branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>lmy766/lmy766.github.com<file_sep>/README.md # lmy766.github.com lmy766 github pages # Test test github pages<file_sep>/js/readfile.js  var fileUrl="./logs/log.txt"; $(document).ready(function(){ $("#b01").click(function(){//比如再按钮的单击事件中 htmlobj=$.ajax({url:fileUrl,async:false});//通过ajax读取test1.txt文本文件。 var strArr=htmlobj.responseText.split(/\r\n/g);//根据回车换行符 var strOut=""; for(var i=0;i<strArr.length;i++){ strOut+=strArr[i]+"<br/>"; } $("#myDiv").html(strOut); }); $('#b02').click(function(){ $(this).attr('disabled','disabled'); $("#myDiv").html("比如再按钮的单击事件中"); // other code }); }); <file_sep>/web/video.js //build in 2016-09-28 var video = document.getElementById("video"); var context = canvas.getContext("2d") var errocb = function () { console.log('sth wrong!'); } if (navigator.getUserMedia) { // 标准的API navigator.getUserMedia({ "video": true }, function (stream) { video.src = stream; video.play(); }, errocb); } else if (navigator.webkitGetUserMedia) { // WebKit 核心的API navigator.webkitGetUserMedia({ "video": true }, function (stream) { video.src = window.webkitURL.createObjectURL(stream); video.play(); }, errocb); } document.getElementById("picture").addEventListener("click", function () { context.drawImage(video, 0, 0, 640, 480); });<file_sep>/js/index.js var data=new Array( "You are being watch.", "The government has a secret system,", "A machine that spies on you every hour of every day.", "I know because I built it.", "I designed the machine to detect acts of terror but it sees everything.", "Vielent crimes involving ordinary people,", "People like you,", "Crimes government considered irrelevant.", "They wouldn't act so I decided I would.", "I work in secret.", "You'll never find me.", "If your number is up,", "I will find you." ); var _index=0; var flag=true;//Is allow print words document.oncontextmenu = function (){ return false;} //ban mouse right button document.touchstart=function(E){E.preventDefault();E.stopPropagation();} window.onload = function(){ // f3('f3').then(f2).then(f1);//promise.js // start();//async.js $("#icon").flicker(700); autoPrint(data[_index],openKey);//输出完成后开启键盘 } function createMenu(){ $('body').GalMenu({ 'menu': 'GalDropDown' }); var items = document.querySelectorAll('.menuItem'); for (var i = 0, l = items.length; i < l; i++) { items[i].style.left = (50 - 35 * Math.cos( - 0.5 * Math.PI - 2 * (1 / l) * i * Math.PI)).toFixed(4) + "%"; items[i].style.top = (50 + 35 * Math.sin( - 0.5 * Math.PI - 2 * (1 / l) * i * Math.PI)).toFixed(4) + "%" } } function openKey(){ document.onkeydown=keydown; document.onmousedown=keydown; } function closeKey(){ document.onkeydown=null; document.onmousedown=null; } function keydown(event){ var e = event || window.event || arguments.callee.caller.arguments[0]; if(e && e.keyCode==13){ // enter if(flag){ _index++; if(_index==data.length){ flag=false; }else{ closeKey(); autoPrint(data[_index],openKey); } } } if (event.button==2){ if(flag){ if(_index>0){ _index--; closeKey(); autoPrint(data[_index],openKey); } }else{ createMenu(); } }else{ if(flag){ _index++; if(_index==data.length){ flag=false; }else{ closeKey(); autoPrint(data[_index],openKey); } } } } $.fn.flicker = function (speed) { var n = 0; var _this = $(this); var timer = function () { if (n % 2 == 0) { _this.show(); } else { _this.hide(); } n++; setTimeout(arguments.callee, speed);//arguments.callee:引用当前正在执行的函数 }; timer(); } function autoPrint(words, callback) { var _this = $("#word"); _this.html(''); if (words.length * 10 < 400) { _this.width(words.length * 10); } else { _this.width(400); } _this.show(); var i = 0; var timer = function () { var current = words.slice(i, i + 1); if (current === '<') { i = words.indexOf('>', i) + 1; } else { i++; } if (i < words.length) { _this.html(words.substring(0, i) + (i & 1 ? '_' : '')); setTimeout(arguments.callee, 100); } else { _this.html(words.substring(0, i)); setTimeout(callback, 100); }; } setTimeout(timer, 1000); }
194812ac7fe405255b98025b2df8c012f11101da
[ "Markdown", "JavaScript" ]
4
Markdown
lmy766/lmy766.github.com
250d7212743c86b6d544cfefdc72a31b60201e7b
605d4aefccb307044b2bb0ae56700405f4fb4862
refs/heads/master
<repo_name>ivoivano/moiazza<file_sep>/admin/libs/utility.lib.php <?php $smarty->assign('tpl_page_title', 'Gestione utility'); # set the current language $_SESSION['lang_id'] = isset($_REQUEST['lang_id']) ? $_REQUEST['lang_id'] : (isset($_SESSION['lang_id']) ? $_SESSION['lang_id'] :'IT'); $smarty->assign('lang_id', $_SESSION['lang_id']); $smarty->assign('lang', lang_get_record($_SESSION['lang_id'])); switch ($_action) { case 'artsection_new': artsection_new($_POST); $_SESSION['artsection_id'] = null; $_SESSION['lang_id'] = null; $smarty->assign('sections', artsection_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_list.tpl')); break; case 'artsection_del': artsection_del($_GET['artsection_id']); $_SESSION['artsection_id'] = null; $_SESSION['lang_id'] = null; $smarty->assign('sections', artsection_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_list.tpl')); break; case 'artsection_sel': $_SESSION['artsection_id'] = $_GET['artsection_id']; $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_record.tpl')); break; case 'artsection_save': if (isset($_POST['submit_save'])) { artsection_save($_SESSION['artsection_id'], $_SESSION['lang_id'], $_POST); $smarty->assign('msg', '...Record salvato con successo...'); } $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_record.tpl')); break; case 'artsectionmedia_del': artsectionmedia_del($_SESSION['artsection_id'], $_GET['artsection_media']); $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_record.tpl')); break; case 'artsectionmedia_add': artsectionmedia_add($_SESSION['artsection_id'], $_POST); $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_record.tpl')); break; case 'artsectionmedia_update': artsectionmedia_update($_SESSION['artsection_id'], $_POST); $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_record.tpl')); break; case 'artsectionfaq_add': artsectionfaq_add($_SESSION['artsection_id'], $_POST); $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_record.tpl')); break; case 'artsectionfaq_sel': $artsectionfaq_sel = artsectionfaq_sel($_SESSION['artsection_id'], $_GET['artsection_faqid']); $smarty->assign('artsectionfaq_sel', $artsectionfaq_sel); $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_record.tpl')); break; case 'artsectionfaq_del': artsectionfaq_del($_SESSION['artsection_id'], $_GET['artsection_faqid']); $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_record.tpl')); break; default: $_SESSION['artsection_id'] = null; $_SESSION['lang_id'] = null; $smarty->assign('sections', artsection_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_utility_list.tpl')); break; } function artsection_get_all($lang_id = 'IT') { global $db; $db->query("SELECT artsection.*, artsectionlang.* FROM artsection INNER JOIN artsectionlang WHERE artsection.artsection_utility = 1 AND artsection.artsection_id = artsectionlang.artsection_id AND artsectionlang.lang_id = '$lang_id' ORDER BY artsection.artsection_utility_order ", SQL_ALL ); $record = $db->record; for($i = 0; $i < count($record); $i++) { $db->query( "SELECT DISTINCT (artsectionlang.lang_id), artsectionlang.artsection_title FROM artsectionlang INNER JOIN artsection INNER JOIN lang WHERE artsection.artsection_id = artsectionlang.artsection_id AND artsection.artsection_id = ".$record[$i]['artsection_id']." AND lang.lang_id = artsectionlang.lang_id ORDER BY lang.lang_order", SQL_ALL ); $record[$i]['artsection_langs'] = $db->record; } return $record; } function artsection_del($artsection_id) { global $db; $db->query("DELETE FROM artsectionlang WHERE artsection_id = $artsection_id", SQL_NONE); $db->query("DELETE FROM artsection WHERE artsection_id = $artsection_id", SQL_NONE); $db->query("DELETE FROM artsectionmedia WHERE artsection_id = $artsection_id", SQL_NONE); $db->query("DELETE FROM artsectionfaq WHERE artsection_id = $artsection_id", SQL_NONE); } function artsection_new($post, $lang_id = 'IT') { global $db; $artsection_name = $post['artsection_name']; $artsection_title = $post['artsection_name']; $artsection_utility_order = $post['artsection_utility_order']; $artsection_type = $post['artsection_type']; $artsection_utility = 1; $artsection_utility_global = 0; $artsection_name = str_replace(" ", "_", $artsection_name); $db->query("INSERT INTO artsection (artsection_name, artsection_status, artsection_type, artsection_utility, artsection_utility_global, artsection_utility_order) VALUES ('$artsection_name', 1, $artsection_type, $artsection_utility, $artsection_utility_global, $artsection_utility_order) ", SQL_NONE); $artsection_id = mysql_insert_id(); if ($artsection_id > 0) { $langs = lang_get_all(); foreach($langs as $l) { $db->query("INSERT INTO artsectionlang (artsection_id, lang_id, artsection_title) VALUES ($artsection_id, '".$l['lang_id']."', '') ", SQL_NONE); } } } function get_icona($ext) { # Icons for files $IconArray = array( "icona_text.gif" => "txt ini xml xsl ini inf cfg log nfo", "icona_html.gif" => "html htm shtml htm", "icona_pdf.gif" => "pdf", "icona_text.gif" => "php php4 php3 phtml phps conf sh shar csh ksh tcl cgi pl js", "icona_image.gif" => "jpeg jpe jpg gif png bmp swf", "icona_word.gif" => "doc", "icona_zip.gif" => "zip tar gz tgz z ace rar arj cab bz2", ); while (list($icon, $types) = each($IconArray)) foreach (explode(" ", $types) as $type) if ($ext == $type) return $icon; return "icon_unknown.gif"; } function artsection_get_record($artsection_id, $lang_id = 'IT') { global $db; $db->query("SELECT artsection.*, artsectionlang.* FROM artsection INNER JOIN artsectionlang WHERE artsectionlang.lang_id = '$lang_id' AND artsection.artsection_id = $artsection_id AND artsectionlang.artsection_id = artsection.artsection_id", SQL_FIRST ); $record = $db->record; $db->query("SELECT artsectionmedia.* FROM artsectionmedia WHERE artsectionmedia.artsection_id = $artsection_id", SQL_ALL); $record['media'] = $db->record; for($i = 0; $i < count($record['media']); $i++) { $filename = $record['media'][$i]['artsection_media']; $ext = substr($filename, strpos($filename, '.') + 1); $record['media'][$i]['icona'] = get_icona($ext); } $db->query("SELECT artsectionfaq.* FROM artsectionfaq WHERE artsectionfaq.artsection_id = $artsection_id ORDER BY artsectionfaq.artsection_faqorder", SQL_ALL); $record['faq'] = $db->record; return $record; } function artsection_save($artsection_id, $lang_id, $post) { global $db; $artsection_name = $post['artsection_name']; $artsection_name = str_replace(" ", "_", $artsection_name); $artsection_text = isset($post['artsection_text']) ? $post['artsection_text'] : ''; $artsection_utility_order = $post['artsection_utility_order']; $artsection_utility_global = $post['artsection_utility_global']; $db->query("UPDATE artsection SET artsection_status=" . $post['artsection_status'] . ", artsection_name='" . $artsection_name . "', artsection_icon='" . $post['artsection_icon'] . "', artsection_utility_order = " . $artsection_utility_order . ", artsection_utility_global = " . $artsection_utility_global . " WHERE artsection_id=$artsection_id", SQL_NONE); $db->query("UPDATE artsectionlang SET artsection_title='" . $post['artsection_title'] . "', artsection_text='" . $artsection_text . "' WHERE artsection_id=$artsection_id AND lang_id='".$lang_id."'", SQL_NONE); return TRUE; } function artsectionmedia_del($artsection_id, $artsection_media) { global $db; $db->query("DELETE FROM artsectionmedia WHERE artsection_id = $artsection_id AND artsection_media = '$artsection_media' ", SQL_NONE); } function artsectionmedia_add($artsection_id, $post) { global $db; if (file_exists($post['file_media'])) { $db->query("INSERT INTO artsectionmedia (artsection_id, artsection_media, artsection_mediadescr, artsection_mediatype) VALUES ($artsection_id, '" . $post['file_media'] . "', '" . $post['artsection_mediadescr'] . "', '" . $post['artsection_mediatype'] . "') ", SQL_NONE); } } function artsectionfaq_add($artsection_id, $post) { global $db; if ($post['artsection_faqid'] == 0) { $db->query("INSERT INTO artsectionfaq (artsection_id, artsection_faqtitle, artsection_faqtext, artsection_faqorder) VALUES ($artsection_id, '" . $post['artsection_faqtitle'] . "', '" . $post['artsection_faqtext'] . "', " . $post['artsection_faqorder'] . ") ", SQL_NONE); } else { $db->query("UPDATE artsectionfaq SET artsection_faqtitle = '" . $post['artsection_faqtitle'] . "', artsection_faqtext = '" . $post['artsection_faqtext'] . "', artsection_faqorder = '" . $post['artsection_faqorder'] . "' WHERE artsection_faqid = " . $post['artsection_faqid'], SQL_NONE); } } function artsectionfaq_sel($artsection_id, $artsection_faqid) { global $db; $db->query("SELECT artsectionfaq.* FROM artsectionfaq WHERE artsectionfaq.artsection_id = $artsection_id AND artsectionfaq.artsection_faqid = $artsection_faqid ", SQL_FIRST); return $db->record; } function artsectionfaq_del($artsection_id, $artsection_faqid) { global $db; $db->query("DELETE FROM artsectionfaq WHERE artsection_id = $artsection_id AND artsection_faqid = $artsection_faqid ", SQL_NONE); } function artsectionmedia_update($artsection_id, $post) { global $db; while (list($key, $value) = each($post['artsection_mediadescr'])) { if (file_exists($post['artsection_media_'.$key])) { $db->query("UPDATE artsectionmedia SET artsection_media = '".$post['artsection_media_'.$key]."', artsection_mediadescr = '".$post['artsection_mediadescr'][$key]."' WHERE artsection_mediaid = $key", SQL_NONE); } } } function lang_get_all() { global $db; $output = array(); $db->query("SELECT * FROM lang ORDER BY lang_order", SQL_ALL); return $db->record; } function lang_get_record($lang_id) { global $db; $db->query("SELECT * FROM lang WHERE lang_id='$lang_id'", SQL_FIRST); return $db->record; } ?> <file_sep>/admin/libs/article.lib.php <?php $smarty->assign('tpl_page_title', 'Gestione articoli'); # set the current language $_SESSION['lang_id'] = isset($_REQUEST['lang_id']) ? $_REQUEST['lang_id'] : (isset($_SESSION['lang_id']) ? $_SESSION['lang_id'] :'IT'); $smarty->assign('lang_id', $_SESSION['lang_id']); $smarty->assign('lang', lang_get_record($_SESSION['lang_id'])); switch ($_action) { case 'art_new': $art_id = art_new($_POST); $_SESSION['art_id'] = $art_id; $smarty->assign('art', $art = art_get_record($_SESSION['art_id'], 'IT')); for($i = 0; $i < count($custom_field); $i++) { $custom_field[$i]['value'] = $art[$custom_field[$i]['name']]; } $smarty->assign('custom_field', $custom_field); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_art_record.tpl')); break; case 'art_sel': $_SESSION['art_id'] = $_GET['art_id']; $smarty->assign('art', $art = art_get_record($_SESSION['art_id'], $_SESSION['lang_id'])); for($i = 0; $i < count($custom_field); $i++) { $custom_field[$i]['value'] = $art[$custom_field[$i]['name']]; } $smarty->assign('custom_field', $custom_field); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_art_record.tpl')); break; case 'art_save': if (isset($_POST['submit_save'])) { art_save($_SESSION['art_id'], $_SESSION['lang_id'], $_POST); $smarty->assign('msg', '...Record salvato con successo...'); } $smarty->assign('art', $art = art_get_record($_SESSION['art_id'], $_SESSION['lang_id'])); for($i = 0; $i < count($custom_field); $i++) { $custom_field[$i]['value'] = $art[$custom_field[$i]['name']]; } $smarty->assign('custom_field', $custom_field); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_art_record.tpl')); break; case 'art_del': art_del($_GET['art_id']); $_SESSION['art_id'] = null; $_SESSION['lang_id'] = null; $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_art_list.tpl')); break; case 'artsection_sel': $_SESSION['artsection_id'] = $_GET['artsection_id']; $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_artsection_record.tpl')); break; case 'artsection_save': if (isset($_POST['submit_save'])) { artsection_save($_SESSION['artsection_id'], $_SESSION['lang_id'], $_POST); $smarty->assign('msg', '...Record salvato con successo...'); } $smarty->assign('artsection', artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_artsection_record.tpl')); break; case 'artsectionmedia_del': artsectionmedia_del($_SESSION['artsection_id'], $_GET['artsection_media']); $smarty->assign('artsection', $artsection_record = artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_artsection_record.tpl')); break; case 'artsectionmedia_add': artsectionmedia_add($_SESSION['artsection_id'], $_POST); $smarty->assign('artsection', $artsection_record = artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_artsection_record.tpl')); break; case 'artsectionmedia_update': artsectionmedia_update($_SESSION['artsection_id'], $_POST); $smarty->assign('artsection', $artsection_record = artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_artsection_record.tpl')); break; case 'artsection_del': artsection_del($_GET['artsection_id'], $_GET['art_id']); $_SESSION['artsection_id'] = null; $smarty->assign('pages', page_get_all(0)); //$smarty->assign('sections', artsection_get_all()); $smarty->assign('utility', artsection_utility_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_art_list.tpl')); break; case 'artsection_new': artsection_new($_POST); # re-load art_list $_SESSION['art_id'] = null; $_SESSION['lang_id'] = null; $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_art_list.tpl')); break; case 'artsection_add': artsection_add($_POST); # re-load art_list $_SESSION['art_id'] = null; $smarty->assign('pages', page_get_all(0)); $smarty->assign('utility', artsection_utility_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_art_list.tpl')); break; case 'artsectionfaq_add': artsectionfaq_add($_SESSION['artsection_id'], $_POST); $smarty->assign('artsection', $artsection_record = artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_artsection_record.tpl')); break; case 'artsectionfaq_sel': $artsectionfaq_sel = artsectionfaq_sel($_SESSION['artsection_id'], $_GET['artsection_faqid']); $smarty->assign('artsectionfaq_sel', $artsectionfaq_sel); $smarty->assign('artsection', $artsection_record = artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_artsection_record.tpl')); break; case 'artsectionfaq_del': artsectionfaq_del($_SESSION['artsection_id'], $_GET['artsection_faqid']); $smarty->assign('artsection', $artsection_record = artsection_get_record($_SESSION['artsection_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_artsection_record.tpl')); break; case 'art_details': $_SESSION['art_id'] = null; $_SESSION['lang_id'] = null; $smarty->assign('art_id_details', $_GET['art_id']); $smarty->assign('pages', page_get_all(0)); //$smarty->assign('sections', artsection_get_all()); $smarty->assign('utility', artsection_utility_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_art_list.tpl')); break; default: $_SESSION['art_id'] = null; $_SESSION['lang_id'] = null; $smarty->assign('pages', page_get_all(0)); $smarty->assign('utility', artsection_utility_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_art_list.tpl')); break; } function art_del($art_id) { global $db; $db->query("DELETE FROM artlang WHERE art_id=" . $art_id, SQL_NONE); $db->query("DELETE FROM art WHERE art_id=" . $art_id, SQL_NONE); $db->query("DELETE FROM art2section WHERE art_id=" . $art_id, SQL_NONE); $db->query("DELETE FROM artlang_custom WHERE art_id=" . $art_id, SQL_NONE); artsection_del_notused(); } function art_new($post) { global $db, $custom_field; $art_name = isset($post['art_name']) ? str_replace(' ', '_', $post['art_name']) : 'Nome_articolo'; $art_title = isset($post['art_name']) ? $post['art_name'] : 'Nome articolo'; $page_id = $post['page_id']; $art_order = isset($post['art_order']) ? $post['art_order'] : 1; $db->query("INSERT INTO art (art_name, page_id, art_order, art_status) VALUES ('$art_name', $page_id, $art_order, " . PAGE_NOT_ACTIVE . ") ", SQL_NONE); $art_id = mysql_insert_id(); $langs = lang_get_all(); foreach($langs as $l) { $db->query("INSERT INTO artlang (art_id, lang_id, art_title) VALUES ($art_id, '".$l['lang_id']."', '')", SQL_NONE); if (count($custom_field) > 0) { $db->query("INSERT INTO artlang_custom (art_id, lang_id) VALUES ($art_id, '".$l['lang_id']."') ", SQL_NONE); } } return $art_id; } function art_save($art_id, $lang_id, $post) { global $db, $custom_field; $art_icon = isset($post['art_icon']) ? $post['art_icon'] : ''; $art_image = isset($post['art_image']) ? $post['art_image'] : ''; $art_image_descr = isset($post['art_image_descr']) ? $post['art_image_descr'] : ''; $art_image_href = isset($post['art_image_href']) ? $post['art_image_href'] : ''; $art_title = isset($post['art_title']) ? $post['art_title'] : ''; $art_subtitle = isset($post['art_subtitle']) ? $post['art_subtitle'] : ''; $art_text = isset($post['art_text']) ? $post['art_text'] : ''; $art_name = isset($post['art_name']) ? str_replace(' ', '_', $post['art_name']) : 'Nome_articolo'; $art_date_start = isset($post['art_date_start']) ? mktime(0,0,0, substr($post['art_date_start'], 3, 2), substr($post['art_date_start'], 0, 2), substr($post['art_date_start'], 6, 4)) : time(); $art_date_end = isset($post['art_date_end']) ? mktime(0,0,0, substr($post['art_date_end'], 3, 2), substr($post['art_date_end'], 0, 2), substr($post['art_date_end'], 6, 4)) : time(); $art_date_end = $art_date_end < $art_date_start ? $art_date_start : $art_date_end; if (isset($post['art_banner'])) { $image_info = getimagesize($post['art_banner']); $art_banner = $post['art_banner']; $art_banner_type = $image_info[2]; } else { $art_banner = ''; $art_banner_type = ''; } if (isset($post['art_vbanner'])) { $image_info = getimagesize($post['art_vbanner']); $art_vbanner = $post['art_vbanner']; $art_vbanner_type = $image_info[2]; } else { $art_vbanner = ''; $art_vbanner_type = ''; } $db->query("UPDATE art SET art_status=" . $post['art_status'] . ", art_name='" . $art_name . "', art_order=" . $post['art_order'] . ", page_id=" . $post['page_id'] . ", art_icon='" . $art_icon . "', art_date_start=" . $art_date_start . ", art_date_end=" . $art_date_end . ", art_banner='" . $art_banner . "', art_vbanner='" . $art_vbanner . "', art_banner_type='" . $art_banner_type . "', art_vbanner_type='" . $art_vbanner_type . "' WHERE art_id=$art_id", SQL_NONE); $db->query("UPDATE artlang SET art_title='" . $art_title . "', art_subtitle='" . $art_subtitle . "', art_text='" . $art_text . "', art_image='" . $art_image . "', art_image_descr='" . $art_image_descr . "', art_image_href='" . $art_image_href . "' WHERE art_id=$art_id AND artlang.lang_id = '".$lang_id."'", SQL_NONE); if (count($custom_field) > 0) { $update_str = ''; foreach($custom_field as $cf) { $update_str .= ($update_str == '' ? '' : ', '); $update_str .= $cf['name']."='".(isset($post[$cf['name']]) ? $post[$cf['name']] : '')."' "; if ($cf['type'] == 'select') { $update_str .= ', '; $cl_record = custom_list_record($post[$cf['name']]); $update_str .= $cf['name']."_icon='".$cl_record['cl_icon']."' "; //print $update_str; } } $db->query("UPDATE artlang_custom SET ".$update_str." WHERE art_id=$art_id AND lang_id = '".$lang_id."'", SQL_NONE); } return TRUE; } function page_get_all($page_id, $output = array(), $level = -1) { global $db; $db->query("SELECT * FROM page WHERE page_parent_id=$page_id ORDER BY page_order", SQL_ALL); $pages = $db->record; foreach ($pages as $p) { $p['level'] = $level + 1; $p = array_merge($p, page_get_record($p['page_id'], 'IT')); $output = array_merge($output, page_get_all($p['page_id'], array($p), $p['level'])); } return $output; } function page_get_record($page_id, $lang_id) { global $db; $db->query( "SELECT page. * , pagelang. * FROM page INNER JOIN pagelang WHERE pagelang.lang_id = '$lang_id' AND page.page_id = pagelang.page_id AND page.page_id = $page_id ORDER BY page_order ", SQL_FIRST ); $record = $db->record; $db->query( "SELECT art.*, artlang.* FROM art INNER JOIN artlang WHERE artlang.lang_id = '$lang_id' AND art.art_id = artlang.art_id AND art.page_id = $page_id ORDER BY art.art_order ", SQL_ALL ); $art = $db->record; for ($i = 0; $i < count($art); $i++) { $art[$i]['artsection'] = art_get_artsection($art[$i]['art_id']); } for($i = 0; $i < count($art); $i++) { $db->query( "SELECT DISTINCT (artlang.lang_id), artlang.art_title FROM artlang INNER JOIN art INNER JOIN lang WHERE art.art_id = artlang.art_id AND art.art_id = ".$art[$i]['art_id']." AND art.page_id = $page_id AND lang.lang_id = artlang.lang_id ORDER BY lang.lang_order", SQL_ALL ); $art[$i]['art_langs'] = $db->record; } $record['art'] = $art; return $record; } function art_get_record($art_id, $lang_id) { global $db, $custom_field; if (count($custom_field) > 0) { $db->query( "SELECT art. * , artlang. *, artlang_custom. * FROM art INNER JOIN artlang INNER JOIN artlang_custom WHERE artlang.lang_id = '$lang_id' AND artlang_custom.lang_id = '$lang_id' AND art.art_id = artlang.art_id AND art.art_id = artlang_custom.art_id AND art.art_id = $art_id ", SQL_FIRST ); } else { $db->query( "SELECT art. * , artlang. * FROM art INNER JOIN artlang WHERE artlang.lang_id = '$lang_id' AND art.art_id = artlang.art_id AND art.art_id = $art_id ", SQL_FIRST ); } $record = $db->record; $record['art_date_start'] = date("d-m-Y", $record['art_date_start']); $record['art_date_end'] = date("d-m-Y", $record['art_date_end']); return $record; } function art_get_artsection($art_id, $lang_id = 'IT') { global $db; $artsection = array(); $db->query("SELECT art2section.* FROM art2section WHERE art_id = " . $art_id . " ORDER BY artsection_order" , SQL_ALL); $art2section = $db->record; $output = array(); foreach($art2section as $a) { $temp = artsection_get_record($a['artsection_id'], $lang_id); if (isset($temp['artsection_id'])) { $temp['artsection_order'] = $a['artsection_order']; array_push($output, $temp); } } return $output; /* for ($x = 0; $x < count($art2section); $x++) { //print "artsection_id".$art2section[$x]['art_id']; $temp = artsection_get_record($art2section[$x]['artsection_id'], $lang_id); if (isset($temp['artsection_id'])) { $temp['artsection_order'] = $art2section[$x]['artsection_order']; } else { $temp['artsection_id'] = $art2section[$x]['artsection_id']; } $art2section[$x] = $temp; } return $art2section; */ } function artsection_get_record($artsection_id, $lang_id = 'IT') { global $db; $db->query("SELECT artsection.*, artsectionlang.* FROM artsection INNER JOIN artsectionlang WHERE artsectionlang.lang_id = '$lang_id' AND artsection.artsection_id = $artsection_id AND artsectionlang.artsection_id = artsection.artsection_id", SQL_FIRST ); $record = $db->record; $db->query( "SELECT DISTINCT (artsectionlang.lang_id), artsectionlang.artsection_title FROM artsectionlang INNER JOIN artsection INNER JOIN lang WHERE artsection.artsection_id = artsectionlang.artsection_id AND artsection.artsection_id = ".$artsection_id." AND lang.lang_id = artsectionlang.lang_id ORDER BY lang.lang_order", SQL_ALL ); $record['artsection_langs'] = $db->record; $db->query("SELECT art2section.artsection_order, art2section.art_id FROM art2section WHERE art2section.artsection_id = $artsection_id", SQL_ALL); $record['art2section'] = $db->record; $db->query("SELECT artsectionmedia.* FROM artsectionmedia WHERE artsectionmedia.artsection_id = $artsection_id ORDER BY artsectionmedia.artsection_mediaorder", SQL_ALL); $record['media'] = $db->record; $db->query("SELECT artsectionfaq.* FROM artsectionfaq WHERE artsectionfaq.artsection_id = $artsection_id ORDER BY artsectionfaq.artsection_faqorder", SQL_ALL); $record['faq'] = $db->record; return $record; } function artsection_get_all() { global $db; $db->query("SELECT artsection.* FROM artsection WHERE artsection.artsection_utility <> 1 ORDER BY artsection.artsection_name ", SQL_ALL ); $record = $db->record; return $record; } function artsection_utility_get_all() { global $db; $db->query("SELECT artsection.* FROM artsection WHERE artsection.artsection_utility = 1 AND artsection.artsection_utility_global <> 1 ORDER BY artsection.artsection_name ", SQL_ALL ); $record = $db->record; return $record; } function artsection_save($artsection_id, $lang_id, $post) { global $db; $artsection_name = $post['artsection_name']; $artsection_name = str_replace(" ", "_", $artsection_name); $artsection_text = isset($post['artsection_text']) ? $post['artsection_text'] : ''; $artsection_order = $post['artsection_order']; $art_id = $post['art_id']; $db->query("UPDATE artsection SET artsection_status=" . $post['artsection_status'] . ", artsection_name='" . $artsection_name . "', artsection_icon='" . $post['artsection_icon'] . "', artsection_hide4end=" . $post['artsection_hide4end'] . " WHERE artsection_id=$artsection_id", SQL_NONE); $db->query("UPDATE artsectionlang SET artsection_title='" . $post['artsection_title'] . "', artsection_subtitle='" . $post['artsection_subtitle'] . "', artsection_text='" . $artsection_text . "' WHERE artsection_id=$artsection_id AND lang_id = '".$lang_id."'", SQL_NONE); $db->query("UPDATE art2section SET art2section.art_id = $art_id, art2section.artsection_order = $artsection_order WHERE artsection_id=$artsection_id", SQL_NONE); return TRUE; } function artsection_del($artsection_id, $art_id) { global $db; $artsection_record = artsection_get_record($artsection_id); if (!isset($artsection_record['artsection_utility']) || $artsection_record['artsection_utility'] == 0) { $db->query("SELECT art2section.* FROM art2section WHERE art2section.artsection_id = $artsection_id", SQL_ALL); $artsection = $db->record; if (count($artsection) == 1) { $db->query("DELETE FROM artsectionlang WHERE artsection_id = $artsection_id", SQL_NONE); $db->query("DELETE FROM artsection WHERE artsection_id = $artsection_id", SQL_NONE); $db->query("DELETE FROM artsectionmedia WHERE artsection_id = $artsection_id", SQL_NONE); $db->query("DELETE FROM artsectionfaq WHERE artsection_id = $artsection_id", SQL_NONE); } } $db->query("DELETE FROM art2section WHERE artsection_id = $artsection_id AND art_id = $art_id", SQL_NONE); } function artsection_del_notused() { global $db; $db->query("SELECT artsection.artsection_id FROM artsection WHERE artsection.artsection_utility = 0", SQL_ALL); $artsection = $db->record; foreach($artsection as $as) { $db->query("SELECT art2section.* FROM art2section WHERE art2section.artsection_id = ".$as['artsection_id'], SQL_ALL); $art2section = $db->record; if (count($art2section) == 0) { $db->query("DELETE FROM artsectionlang WHERE artsection_id = ".$as['artsection_id'], SQL_NONE); $db->query("DELETE FROM artsection WHERE artsection_id = ".$as['artsection_id'], SQL_NONE); $db->query("DELETE FROM artsectionmedia WHERE artsection_id = ".$as['artsection_id'], SQL_NONE); $db->query("DELETE FROM artsectionfaq WHERE artsection_id = ".$as['artsection_id'], SQL_NONE); } } } function artsection_new($post, $lang_id = 'IT') { global $db; $artsection_name = $post['artsection_name']; $artsection_title = $post['artsection_name']; $artsection_order = $post['artsection_order']; $artsection_type = $post['artsection_type']; $artsection_utility = 0; $artsection_utility_global = 0; $art_id = $post['art_id']; $artsection_name = str_replace(" ", "_", $artsection_name); $db->query("INSERT INTO artsection (artsection_name, artsection_status, artsection_type, artsection_utility, artsection_utility_global) VALUES ('$artsection_name', 1, $artsection_type, $artsection_utility, $artsection_utility_global) ", SQL_NONE); $artsection_id = mysql_insert_id(); if ($artsection_id > 0) { $langs = lang_get_all(); foreach($langs as $l) { $db->query("INSERT INTO artsectionlang (artsection_id, lang_id, artsection_title) VALUES ($artsection_id, '".$l['lang_id']."', '') ", SQL_NONE); } $db->query("INSERT INTO art2section (art_id, artsection_id, artsection_order) VALUES ($art_id, $artsection_id, $artsection_order) ", SQL_NONE); } } function artsection_add($post, $lang_id = 'IT') { global $db; $art_id = $post['art_id']; $artsection_id = $post['artsection_id']; $artsection_order = $post['artsection_order']; $db->query("INSERT INTO art2section (art_id, artsection_id, artsection_order) VALUES ($art_id, $artsection_id, $artsection_order) ", SQL_NONE); } function artsectionmedia_del($artsection_id, $artsection_media) { global $db; $db->query("DELETE FROM artsectionmedia WHERE artsection_id = $artsection_id AND artsection_media = '$artsection_media' ", SQL_NONE); } function artsectionmedia_add($artsection_id, $post) { global $db; if (file_exists($post['file_media'])) { $db->query("INSERT INTO artsectionmedia (artsection_id, artsection_media, artsection_mediadescr, artsection_mediatype, artsection_mediaorder) VALUES ($artsection_id, '" . $post['file_media'] . "', '" . $post['artsection_mediadescr'] . "', '" . $post['artsection_mediatype'] . "', " . $post['artsection_mediaorder'] . ") ", SQL_NONE); } } function artsectionfaq_add($artsection_id, $post) { global $db; if ($post['artsection_faqid'] == 0) { $db->query("INSERT INTO artsectionfaq (artsection_id, artsection_faqtitle, artsection_faqtext, artsection_faqorder) VALUES ($artsection_id, '" . $post['artsection_faqtitle'] . "', '" . $post['artsection_faqtext'] . "', " . $post['artsection_faqorder'] . ") ", SQL_NONE); } else { $db->query("UPDATE artsectionfaq SET artsection_faqtitle = '" . $post['artsection_faqtitle'] . "', artsection_faqtext = '" . $post['artsection_faqtext'] . "', artsection_faqorder = '" . $post['artsection_faqorder'] . "' WHERE artsection_faqid = " . $post['artsection_faqid'], SQL_NONE); } } function artsectionfaq_sel($artsection_id, $artsection_faqid) { global $db; $db->query("SELECT artsectionfaq.* FROM artsectionfaq WHERE artsectionfaq.artsection_id = $artsection_id AND artsectionfaq.artsection_faqid = $artsection_faqid ", SQL_FIRST); return $db->record; } function artsectionfaq_del($artsection_id, $artsection_faqid) { global $db; $db->query("DELETE FROM artsectionfaq WHERE artsection_id = $artsection_id AND artsection_faqid = $artsection_faqid ", SQL_NONE); } function artsectionmedia_update($artsection_id, $post) { global $db; while (list($key, $value) = each($post['artsection_mediadescr'])) { if (file_exists($post['artsection_media_'.$key])) { $db->query("UPDATE artsectionmedia SET artsection_media = '".$post['artsection_media_'.$key]."', artsection_mediadescr = '".$post['artsection_mediadescr'][$key]."', artsection_mediaorder = ".$post['artsection_mediaorder'][$key]." WHERE artsection_mediaid = $key", SQL_NONE); } } } function lang_get_all() { global $db; $output = array(); $db->query("SELECT * FROM lang ORDER BY lang_order", SQL_ALL); return $db->record; } function lang_get_record($lang_id) { global $db; $db->query("SELECT * FROM lang WHERE lang_id='$lang_id'", SQL_FIRST); return $db->record; } ?> <file_sep>/admin/libs/login.lib.php <?php $smarty->assign('tpl_page_title', 'Autenticazione utente'); switch ($_action) { case 'logout': $_SESSION['user'] = null; header('Location: admin.php'); break; case 'submit': $username = trim($_POST['username']); $password = md5(trim($_POST['password'])); $db->query("SELECT user.* FROM user WHERE user.user_username = '$username' AND user.user_password = '$<PASSWORD>'", SQL_FIRST); $_SESSION['user'] = $db->record; header('Location: admin.php'); break; default: $smarty->assign('tpl_page', $smarty->fetch('admin_login.tpl')); break; } ?> <file_sep>/admin/libs/page.lib.php <?php $smarty->assign('tpl_page_title', 'Gestione pagine'); $smarty->assign('pages', page_get_all(0)); # set the current language $_SESSION['lang_id'] = isset($_REQUEST['lang_id']) ? $_REQUEST['lang_id'] : (isset($_SESSION['lang_id']) ? $_SESSION['lang_id'] :'IT'); $smarty->assign('lang_id', $_SESSION['lang_id']); $smarty->assign('lang', lang_get_record($_SESSION['lang_id'])); switch ($_action) { case 'page_new': $page_id = page_new($_POST); $_SESSION['page_id'] = $page_id; $smarty->assign('page', page_get_record($_SESSION['page_id'], 'IT')); $smarty->assign('tpl_page', $smarty->fetch('admin_page_record.tpl')); break; case 'page_sel': $_SESSION['page_id'] = $_GET['page_id']; $smarty->assign('page', page_get_record($_SESSION['page_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_page_record.tpl')); break; case 'page_save': if (isset($_POST['submit_save'])) { page_save($_SESSION['page_id'], $_SESSION['lang_id'], $_POST); $smarty->assign('msg', '...Record salvato con successo...'); } $smarty->assign('page', page_get_record($_SESSION['page_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_page_record.tpl')); break; case 'section_new': $section_id = section_new($_POST); $_SESSION['section_id'] = $section_id; $smarty->assign('section', section_get_record($_SESSION['section_id'], 'IT')); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_section_record.tpl')); break; case 'section_sel': $_SESSION['section_id'] = $_GET['section_id']; $smarty->assign('section', section_get_record($_SESSION['section_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_section_record.tpl')); break; case 'section_save': if (isset($_POST['submit_save'])) { section_save($_SESSION['section_id'], $_SESSION['lang_id'], $_POST); $smarty->assign('msg', '...Record salvato con successo...'); } $smarty->assign('section', section_get_record($_SESSION['section_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_section_record.tpl')); break; case 'form_save': if (isset($_POST['submit_save'])) { form_save($_SESSION['section_id'], $_SESSION['lang_id'], $_POST); $smarty->assign('msg3', '...Record salvato con successo...'); } $smarty->assign('section', section_get_record($_SESSION['section_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_section_record.tpl')); break; case 'pagemedia_add': pagemedia_add($_SESSION['page_id'], $_POST); $smarty->assign('page', page_get_record($_SESSION['page_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_page_record.tpl')); break; case 'pagemedia_save': pagemedia_save($_SESSION['page_id'], $_POST); $smarty->assign('page', page_get_record($_SESSION['page_id'], $_SESSION['lang_id'])); $smarty->assign('msg2', '...Record salvato con successo...'); $smarty->assign('tpl_page', $smarty->fetch('admin_page_record.tpl')); break; case 'pagemedia_del': pagemedia_del($_SESSION['page_id'], $_GET['page_media']); $smarty->assign('page', page_get_record($_SESSION['page_id'], $_SESSION['lang_id'])); $smarty->assign('tpl_page', $smarty->fetch('admin_page_record.tpl')); break; case 'page_del': page_del($_GET['page_id']); $_SESSION['page_id'] = null; $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_page_list.tpl')); break; case 'section_del': section_del($_GET['section_id']); $_SESSION['section_id'] = null; $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_page_list.tpl')); break; case 'sectionmedia_add': sectionmedia_add($_SESSION['section_id'], $_POST); $smarty->assign('section', section_get_record($_SESSION['section_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_section_record.tpl')); break; case 'sectionmedia_save': sectionmedia_save($_SESSION['section_id'], $_POST); $smarty->assign('msg2', '...Record salvato con successo...'); $smarty->assign('section', section_get_record($_SESSION['section_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_section_record.tpl')); break; case 'sectionmedia_del': sectionmedia_del($_SESSION['section_id'], $_GET['section_media']); $smarty->assign('section', section_get_record($_SESSION['section_id'], $_SESSION['lang_id'])); $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_section_record.tpl')); break; default: $_SESSION['page_id'] = null; $_SESSION['lang_id'] = null; $smarty->assign('pages', page_get_all(0)); $smarty->assign('tpl_page', $smarty->fetch('admin_page_list.tpl')); break; } function page_del($page_id) { global $db; $db->query("DELETE FROM pagelang WHERE page_id=$page_id" , SQL_NONE); $db->query("DELETE FROM page WHERE page_id=$page_id" , SQL_NONE); $db->query("DELETE FROM sectionlang WHERE section_id IN (SELECT section_id FROM section WHERE page_id=$page_id)" , SQL_NONE); $db->query("DELETE FROM section WHERE page_id=$page_id" , SQL_NONE); $db->query("UPDATE art SET page_id=1 WHERE page_id=$page_id", SQL_NONE); } function section_del($section_id) { global $db; $db->query("DELETE FROM formlang WHERE form_id IN (SELECT form_id FROM section WHERE section_id=$section_id)" , SQL_NONE); $db->query("DELETE FROM form WHERE form_id IN (SELECT form_id FROM section WHERE section_id=$section_id)" , SQL_NONE); $db->query("DELETE FROM sectionlang WHERE section_id=$section_id" , SQL_NONE); $db->query("DELETE FROM section WHERE section_id=$section_id" , SQL_NONE); } function page_save($page_id, $lang_id, $post) { global $db; if (isset($post['page_banner'])) { $image_info = getimagesize($post['page_banner']); $page_banner = $post['page_banner']; $page_banner_type = $image_info[2]; } else { $page_banner = ''; $page_banner_type = ''; } if (isset($post['page_vbanner'])) { $image_info = getimagesize($post['page_vbanner']); $page_vbanner = $post['page_vbanner']; $page_vbanner_type = $image_info[2]; } else { $page_vbanner = ''; $page_vbanner_type = ''; } $page_title = isset($post['page_title']) ? $post['page_title'] : ''; $page_text = isset($post['page_text']) ? $post['page_text'] : ''; $page_vbanner_show = isset($post['page_vbanner_show']) ? intval( $post['page_vbanner_show']) : 0; $page_utility_show = isset($post['page_utility_show']) ? intval( $post['page_utility_show']) : 0; $page_parent_id = isset($post['page_parent_id']) ? intval( $post['page_parent_id']) : 0; $page_order = isset($post['page_order']) ? intval( $post['page_order']) : 0; $page_archive = isset($post['page_archive']) ? intval( $post['page_archive']) : 0; $db->query("UPDATE page SET page_status=" . $post['page_status'] . ", page_name='" . $post['page_name'] . "', page_order=" . $page_order . ", page_menu_flag=" . $post['page_menu_flag'] . ", page_banner='" . $page_banner . "', page_banner_type='" . $page_banner_type . "', page_vbanner='" . $page_vbanner . "', page_vbanner_type='" . $page_vbanner_type . "', page_vbanner_show=" . $page_vbanner_show . ", page_utility_show=" . $page_utility_show . ", page_archive=" . $page_archive . ", page_parent_id = ".$page_parent_id." WHERE page_id=$page_id", SQL_NONE); $db->query("UPDATE pagelang SET page_title='" . $page_title . "', page_text='" . $page_text . "', page_menu='" . $post['page_menu'] . "' WHERE page_id=$page_id AND pagelang.lang_id = '$lang_id'", SQL_NONE); return TRUE; } function page_new($post) { global $db; $page_name = isset($post['page_name']) ? $post['page_name'] : 'Nome pagina'; $page_parent_id = isset($post['page_parent_id']) ? $post['page_parent_id'] : 1; $page_type = isset($post['page_type']) ? $post['page_type'] : PAGE_COMMON; $db->query("INSERT INTO page (page_name, page_parent_id, page_type, page_status) VALUES ('$page_name', $page_parent_id, $page_type, " . PAGE_NOT_ACTIVE . ") ", SQL_NONE); $page_id = mysql_insert_id(); $langs = lang_get_all(); foreach($langs as $l) { $db->query("INSERT INTO pagelang (page_id, lang_id) VALUES ($page_id, '".$l['lang_id']."') ", SQL_NONE); } return $page_id; } function section_new($post) { global $db; $section_name = isset($post['section_name']) ? str_replace(' ', '_', $post['section_name']) : 'Nome_sezione'; $section_title = isset($post['section_name']) ? $post['section_name'] : 'Nome sezione'; $page_id = $post['page_id']; $section_type = isset($post['section_type']) ? $post['section_type'] : 1; $db->query("INSERT INTO section (section_name, page_id, section_type, section_status) VALUES ('$section_name', $page_id, $section_type, " . PAGE_NOT_ACTIVE . ") ", SQL_NONE); $section_id = mysql_insert_id(); $langs = lang_get_all(); foreach($langs as $l) { $db->query("INSERT INTO sectionlang (section_id, lang_id, section_title) VALUES ($section_id, '".$l['lang_id']."', '$section_title') ", SQL_NONE); } return $section_id; } function form_save($section_id, $lang_id, $post) { global $db; if ($post['form_id'] == 0) { $db->query("INSERT INTO form (form_status) values (0)", SQL_NONE); $form_id = mysql_insert_id(); $db->query("INSERT INTO formlang (form_id, lang_id) values ($form_id, '$lang_id')", SQL_NONE); $db->query("UPDATE section SET form_id = $form_id WHERE section_id = $section_id", SQL_NONE); } else { $form_id = $post['form_id']; } $db->query("UPDATE form SET form_mailto='" . $post['form_mailto'] . "', form_field1_type=" . $post['form_field1_type'] . ", form_field2_type=" . $post['form_field2_type'] . ", form_field3_type=" . $post['form_field3_type'] . ", form_field4_type=" . $post['form_field4_type'] . ", form_field5_type=" . $post['form_field5_type'] . " WHERE form_id=" . $form_id, SQL_NONE); $db->query("UPDATE formlang SET form_title='" . $post['form_title'] . "', form_text='" . $post['form_text'] . "', form_note='" . $post['form_note'] . "', form_confirm='" . $post['form_confirm'] . "', form_field1_text='" . $post['form_field1_text'] . "', form_field2_text='" . $post['form_field2_text'] . "', form_field3_text='" . $post['form_field3_text'] . "', form_field4_text='" . $post['form_field4_text'] . "', form_field5_text='" . $post['form_field5_text'] . "', form_submit_button='" . $post['form_submit_button'] . "', form_cancel_button='" . $post['form_cancel_button'] . "' WHERE form_id=" . $form_id ." AND lang_id = '$lang_id'", SQL_NONE); return TRUE; } function section_save($section_id, $lang_id, $post) { global $db; $section_icon = isset($post['section_icon']) ? $post['section_icon'] : ''; $section_title = isset($post['section_title']) ? $post['section_title'] : ''; $section_subtitle = isset($post['section_subtitle']) ? $post['section_subtitle'] : ''; $section_url = isset($post['section_url']) ? $post['section_url'] : ''; $section_text = isset($post['section_text']) ? $post['section_text'] : ''; $section_name = isset($post['section_name']) ? str_replace(' ', '_', $post['section_name']) : 'Nome_sezione'; $db->query("UPDATE section SET section_status=" . $post['section_status'] . ", section_name='" . $section_name . "', section_order=" . $post['section_order'] . ", page_id=" . $post['page_id'] . ", section_icon='" . $section_icon . "' WHERE section_id=$section_id", SQL_NONE); $db->query("UPDATE sectionlang SET section_title='" . $section_title . "', section_subtitle='" . $section_subtitle . "', section_url='" . $section_url . "', section_text='" . $section_text . "' WHERE section_id=$section_id AND sectionlang.lang_id = '$lang_id'", SQL_NONE); return TRUE; } function pagemedia_del($page_id, $page_media) { global $db; $db->query("DELETE FROM pagemedia WHERE page_id = $page_id and page_media = '" . $page_media . "' ", SQL_NONE); } function pagemedia_add($page_id, $post) { global $db; if (file_exists($post['file_media'])) { $db->query("INSERT INTO pagemedia (page_id, page_media, page_mediadescr, page_mediatype) VALUES ($page_id, '" . $post['file_media'] . "', '" . $post['page_mediadescr'] . "', '".$post['page_mediatype']."') ", SQL_NONE); } } function pagemedia_save($page_id, $post) { global $db; for ($i = 0; $i < count($post['page_media']); $i++) { if (file_exists($post['page_media'][$i])) { $db->query("UPDATE pagemedia SET page_mediadescr = '" . $post['page_mediadescr'][$i] . "', page_mediaorder = '" . $post['page_mediaorder'][$i] . "' WHERE page_id = $page_id AND page_media = '" . $post['page_media'][$i] . "'", SQL_NONE); } } } function sectionmedia_del($section_id, $section_media) { global $db; $db->query("DELETE FROM sectionmedia WHERE section_id = $section_id and section_media = '" . $section_media . "' ", SQL_NONE); } function sectionmedia_add($section_id, $post) { global $db; if (file_exists($post['file_media'])) { $db->query("INSERT INTO sectionmedia (section_id, section_media, section_mediadescr, section_mediatype, section_mediaorder) VALUES ($section_id, '" . $post['file_media'] . "', '" . $post['section_mediadescr'] . "', '".$post['section_mediatype']."', '" . $post['section_mediaorder']."')", SQL_NONE); } } function sectionmedia_save($section_id, $post) { global $db; for ($i = 0; $i < count($post['section_media']); $i++) { if (file_exists($post['section_media'][$i])) { $db->query("UPDATE sectionmedia SET section_mediadescr = '" . $post['section_mediadescr'][$i] . "', section_mediaorder = '" . $post['section_mediaorder'][$i] . "' WHERE section_id = $section_id AND section_media = '" . $post['section_media'][$i] . "'", SQL_NONE); } } } function page_get_all($page_id, $output = array(), $level = -1) { global $db; $db->query("SELECT * FROM page WHERE page_parent_id=$page_id ORDER BY page_order", SQL_ALL); $pages = $db->record; foreach ($pages as $p) { $p['level'] = $level + 1; $p = array_merge($p, page_get_record($p['page_id'], 'IT')); $output = array_merge($output, page_get_all($p['page_id'], array($p), $p['level'])); } return $output; } function lang_get_all() { global $db; $output = array(); $db->query("SELECT * FROM lang ORDER BY lang_order", SQL_ALL); return $db->record; } function lang_get_record($lang_id) { global $db; $db->query("SELECT * FROM lang WHERE lang_id='$lang_id'", SQL_FIRST); return $db->record; } function page_get_record($page_id, $lang_id) { global $db; $db->query( "SELECT page. * , pagelang. * FROM page INNER JOIN pagelang WHERE pagelang.lang_id = '$lang_id' AND page.page_id = pagelang.page_id AND page.page_id = $page_id ORDER BY page_order ", SQL_FIRST ); $record = $db->record; $db->query( "SELECT section.*, sectionlang.* FROM section INNER JOIN sectionlang WHERE sectionlang.lang_id = '$lang_id' AND section.section_id = sectionlang.section_id AND section.page_id = $page_id ORDER BY section.section_order ", SQL_ALL ); $record['section'] = $db->record; for($i = 0; $i < count($record['section']); $i++) { $db->query( "SELECT DISTINCT (sectionlang.lang_id), sectionlang.section_title FROM sectionlang INNER JOIN section INNER JOIN lang WHERE section.section_id = sectionlang.section_id AND section.section_id = ".$record['section'][$i]['section_id']." AND section.page_id = $page_id AND lang.lang_id = sectionlang.lang_id ORDER BY lang.lang_order ", SQL_ALL ); $record['section'][$i]['section_langs'] = $db->record; } $db->query( "SELECT pagemedia. * FROM pagemedia WHERE pagemedia.page_id = $page_id ORDER BY pagemedia.page_mediaorder", SQL_ALL ); $record['media'] = $db->record; $db->query( "SELECT DISTINCT (pagelang.lang_id), pagelang.page_title FROM pagelang INNER JOIN lang WHERE pagelang.page_id = $page_id AND pagelang.lang_id = lang.lang_id ORDER BY lang.lang_order", SQL_ALL ); $record['page_langs'] = $db->record; return $record; } function section_get_record($section_id, $lang_id) { global $db; $db->query( "SELECT section. * , sectionlang. * FROM section INNER JOIN sectionlang WHERE sectionlang.lang_id = '$lang_id' AND section.section_id = sectionlang.section_id AND section.section_id = $section_id ", SQL_FIRST ); $record = $db->record; if ($record['section_type'] == 2) { $db->query( "SELECT form.*, formlang.* FROM form INNER JOIN formlang WHERE formlang.lang_id = '$lang_id' AND form.form_id = formlang.form_id AND form.form_id = " . $record['form_id'], SQL_FIRST ); $record['form'] = $db->record; } if ($record['section_type'] == 1 || $record['section_type'] == 4) { $db->query( "SELECT sectionmedia. * FROM sectionmedia WHERE sectionmedia.section_id = $section_id ORDER BY sectionmedia.section_mediaorder", SQL_ALL ); $record['media'] = $db->record; } return $record; } ?> <file_sep>/admin/libs/news.lib.php <?php $smarty->assign('tpl_page_title', 'Gestione news'); # set the current language $_SESSION['lang_id'] = isset($_REQUEST['lang_id']) ? $_REQUEST['lang_id'] : (isset($_SESSION['lang_id']) ? $_SESSION['lang_id'] :'IT'); $smarty->assign('lang_id', $_SESSION['lang_id']); $smarty->assign('lang', lang_get_record($_SESSION['lang_id'])); switch($_action) { case 'news_new': $news_id = news_new($_POST); $_SESSION['news_id'] = $news_id; $smarty->assign('news', news_get_record($_SESSION['news_id'], 'IT')); $smarty->assign('news_list', news_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_news_record.tpl')); break; case 'news_sel': $_SESSION['news_id'] = $_GET['news_id']; $smarty->assign('news', news_get_record($_SESSION['news_id'],$_SESSION['lang_id'])); $smarty->assign('news_list', news_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_news_record.tpl')); break; case 'news_save': if ( isset($_POST['submit_save']) ) { news_save($_SESSION['news_id'], $_SESSION['lang_id'], $_POST); $smarty->assign('msg', '...Record salvato con successo...'); } $smarty->assign('news', news_get_record($_SESSION['news_id'],$_SESSION['lang_id'])); $smarty->assign('news_list', news_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_news_record.tpl')); break; case 'news_del': news_del($_GET['news_id']); $_SESSION['news_id'] = null; $smarty->assign('news_list', news_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_news_list.tpl')); break; default: $_SESSION['page_id'] = null; $smarty->assign('news_list', news_get_all()); $smarty->assign('tpl_page', $smarty->fetch('admin_news_list.tpl')); break; } function news_del($news_id) { global $db; $db->query("DELETE FROM newslang WHERE news_id=$news_id" , SQL_NONE); $db->query("DELETE FROM news WHERE news_id=$news_id" , SQL_NONE); } function lang_get_all() { global $db; $output = array(); $db->query("SELECT * FROM lang ORDER BY lang_order", SQL_ALL); return $db->record; } function news_new($post) { global $db; $news_name = isset($post['news_name']) ? str_replace(' ', '_', $post['news_name']) : 'Nome_sezione'; $page_id = $post['page_id']; $page_id = 0; $news_order = isset($post['news_order']) ? $post['news_order'] : 1; $db->query("INSERT INTO news (news_name, page_id, news_order, news_status) VALUES ('$news_name', $page_id, $news_order, " . PAGE_NOT_ACTIVE . ") ", SQL_NONE); $news_id = mysql_insert_id(); $langs = lang_get_all(); foreach($langs as $l) { $db->query("INSERT INTO newslang (news_id, lang_id, news_title) VALUES ($news_id, '".$l['lang_id']."', '$news_name') ", SQL_NONE); } return $news_id; } function news_save($news_id, $lang_id, $post) { global $db; $news_icon = isset($post['news_icon']) ? $post['news_icon'] : ''; $news_image = isset($post['news_image']) ? $post['news_image'] : ''; $news_image_descr = isset($post['news_image_descr']) ? $post['news_image_descr'] : ''; $news_image_href = isset($post['news_image_href']) ? $post['news_image_href'] : ''; $news_title = isset($post['news_title']) ? $post['news_title'] : ''; $news_subtitle = isset($post['news_subtitle']) ? $post['news_subtitle'] : ''; $news_text = isset($post['news_text']) ? $post['news_text'] : ''; $news_name = isset($post['news_name']) ? str_replace(' ', '_', $post['news_name']) : 'Nome_sezione'; $db->query("UPDATE news SET news_status=".$post['news_status'].", news_name='".$news_name."', news_order=".$post['news_order'].", news_icon='".$news_icon."' WHERE news_id=$news_id", SQL_NONE); $db->query("UPDATE newslang SET news_title='".$news_title."', news_subtitle='".$news_subtitle."', news_text='".$news_text."', news_image='".$news_image."', news_image_descr='".$news_image_descr."', news_image_href='".$news_image_href."' WHERE news_id=$news_id AND newslang.lang_id = '".$lang_id."'", SQL_NONE); return TRUE; } function news_get_all() { global $db; $db->query( "SELECT news.*, newslang.* FROM news INNER JOIN newslang WHERE newslang.lang_id = 'IT' AND news.news_id = newslang.news_id ORDER BY news.news_order ", SQL_ALL ); $news = $db->record; for($i = 0; $i < count($news); $i++) { $db->query( "SELECT DISTINCT (newslang.lang_id), newslang.news_title FROM newslang INNER JOIN news INNER JOIN lang WHERE news.news_id = newslang.news_id AND news.news_id = ".$news[$i]['news_id']." AND lang.lang_id = newslang.lang_id ORDER BY lang.lang_order", SQL_ALL ); $news[$i]['news_langs'] = $db->record; } return $news; } function news_get_record($news_id, $lang_id) { global $db; $db->query( "SELECT news. * , newslang. * FROM news INNER JOIN newslang WHERE newslang.lang_id = '$lang_id' AND news.news_id = newslang.news_id AND news.news_id = $news_id ", SQL_FIRST ); $record = $db->record; return $record; } function lang_get_record($lang_id) { global $db; $db->query("SELECT * FROM lang WHERE lang_id='$lang_id'", SQL_FIRST); return $db->record; } ?> <file_sep>/admin/libs/mediaframe.lib.php <?php $smarty->assign('tpl_page_title', 'Archivio risorse'); /* Memorizza il parent_object */ if (isset($_GET['parent_object'])) $_SESSION['parent_object'] = $_GET['parent_object']; switch ($_action) { case 'folder_sel': $_SESSION['folder'] = $_GET['folder']; break; case 'folder_new': $folder_new_name = MEDIA_DIR . str_replace(" ", "_", $_POST['folder_new_name']); if (!file_exists($folder_new_name)) mkdir($folder_new_name, 0777); break; case 'file_upload': $file_upload_name = MEDIA_DIR . $_SESSION['folder'] . '/' . str_replace(" ", "_", $_FILES['file_upload_name']['name']); if (!file_exists($file_upload_name)) move_uploaded_file($_FILES['file_upload_name']['tmp_name'], $file_upload_name); break; default: break; } $frame = TRUE; if (!isset($_SESSION['folder'])) $_SESSION['folder'] = ''; $smarty->assign('files', get_files($_SESSION['folder'])); $smarty->assign('folders', get_folders()); $smarty->assign('parent_object', $_SESSION['parent_object']); $smarty->assign('tpl_page', $smarty->fetch('admin_mediaframe.tpl')); function get_folders() { $folders = array(); if ($handle = opendir(MEDIA_DIR)) { while (false !== ($file = readdir($handle))) { if (!is_file($file) && $file != '..' && $file != '.') array_push($folders, $file); } closedir($handle); } sort($folders); return $folders; } function get_files($folder) { global $db; $files = array(); if ($handle = opendir(MEDIA_DIR . $folder . '/')) { while (false !== ($filename = readdir($handle))) { $record = array(); $record['file'] = MEDIA_DIR . $folder . '/' . $filename; $record['filename'] = $filename; if (is_file($record['file'])) { $record['ext'] = substr($filename, strrpos($filename, '.') + 1); $record['icona'] = get_icona($record['ext']); $record['dim'] = ($file_info = getimagesize($record['file'])) ? "$file_info[0] x $file_info[1]" : ""; $record['dim'] = ($file_info[0] > 0) ? $record['dim'] : ""; $record['width'] = $file_info[0]; $record['height'] = $file_info[1]; $record['type'] = $file_info[2]; $record['size'] = filesize($record['file']); array_push($files, $record); } } closedir($handle); } return $files; } function get_icona($ext) { # Icons for files $IconArray = array( "icona_text.gif" => "txt ini xml xsl ini inf cfg log nfo", "icona_html.gif" => "html htm shtml htm", "icona_pdf.gif" => "pdf", "icona_text.gif" => "php php4 php3 phtml phps conf sh shar csh ksh tcl cgi pl js", "icona_image.gif" => "jpeg jpe jpg gif png bmp swf", "icona_word.gif" => "doc", "icona_zip.gif" => "zip tar gz tgz z ace rar arj cab bz2", "icona_movies.gif" => "mp4" ); while (list($icon, $types) = each($IconArray)) foreach (explode(" ", $types) as $type) if ($ext == $type) return $icon; return "icona_unknown.gif"; } ?> <file_sep>/admin/libs/link.lib.php <?php $smarty->assign('tpl_page_title', 'Gestione Link'); $link_id = 0; switch ($_action) { case 'link_sel': $link_id = $_GET['link_id']; break; case 'link_new': $link_id = link_new($_POST); break; case 'link_del': link_del($link_id = $_GET['link_id']); break; default: break; } $smarty->assign('link_record', link_get_record($link_id)); $smarty->assign('link_list', link_getall()); $smarty->assign('tpl_page', $smarty->fetch('admin_link_list.tpl')); function link_get_record($link_id) { global $db, $smarty; $output = array(array( 'link_id' => 0, 'link_descr' => '', 'link_value' => '', 'link_icon' => '') ); if ($link_id > 0) { $db->query( "SELECT link.* FROM link WHERE link.link_id = $link_id ", SQL_ALL ); $output = $db->record; } return $output; } function link_del($link_id) { global $db; $db->query("DELETE FROM link WHERE link_id=" . $link_id, SQL_NONE); } function link_new($post) { global $db; $link_id = isset($post['link_id']) ? $post['link_id'] : 0; $link_order = isset($post['link_order']) ? $post['link_order'] : 99; $link_value = isset($post['link_value']) ? $post['link_value'] : ''; $link_descr = isset($post['link_descr']) ? $post['link_descr'] : ''; $link_icon = isset($post['link_icon']) ? $post['link_icon'] : ''; if ($link_id > 0) { $db->query( "UPDATE link SET link_order = $link_order, link_descr = '$link_descr', link_value = '$link_value', link_icon = '$link_icon' WHERE link_id = $link_id", SQL_NONE); } else { $db->query("INSERT INTO link (link_order, link_descr, link_value, link_icon) VALUES ($link_order, '$link_descr', '$link_value', '$link_icon') ", SQL_NONE); $link_id = mysql_insert_id(); } return $link_id; } function link_getall() { global $db, $smarty; $db->query( "SELECT link.* FROM link ORDER BY link_order ", SQL_ALL ); return $db->record; } ?> <file_sep>/admin/libs/custom.lib.php <?php $smarty->assign('tpl_page_title', 'Gestione tabelle'); $cl_id = 0; switch ($_action) { case 'cl_sel': $cl_id = $_GET['cl_id']; break; case 'cl_new': $cl_id = cl_new($_POST); break; case 'cl_del': cl_del($cl_id = $_GET['cl_id']); break; default: break; } $smarty->assign('cl_record', cl_get_record($cl_id)); $smarty->assign('cl_list', cl_getall()); $smarty->assign('cl_types', cl_get_types()); $smarty->assign('tpl_page', $smarty->fetch('admin_custom_list.tpl')); function cl_get_record($cl_id) { global $db, $smarty; $output = array(array('cl_id' => 0, 'cl_type' => '', 'cl_value' => '', 'cl_icon' => '') ); if ($cl_id > 0) { $db->query( "SELECT custom_list.* FROM custom_list WHERE custom_list.cl_id = $cl_id ", SQL_ALL ); $output = $db->record; } return $output; } function cl_del($cl_id) { global $db; $db->query("DELETE FROM custom_list WHERE cl_id=" . $cl_id, SQL_NONE); } function cl_new($post) { global $db; $cl_id = isset($post['cl_id']) ? $post['cl_id'] : 0; $cl_order = isset($post['cl_type']) ? $post['cl_order'] : 99; $cl_type = isset($post['cl_type']) ? $post['cl_type'] : 'xxx'; $cl_value = isset($post['cl_value']) ? $post['cl_value'] : ''; $cl_icon = isset($post['cl_icon']) ? $post['cl_icon'] : ''; if ($cl_id > 0) { $db->query( "SELECT custom_list.* FROM custom_list WHERE cl_id = $cl_id", SQL_FIRST ); $record = $db->record; $db->query( "UPDATE artlang_custom SET ".strtolower($cl_type)." = '$cl_value', ".strtolower($cl_type)."_icon = '$cl_icon' WHERE ".strtolower($cl_type)." = '".$record['cl_value']."'", SQL_NONE); $db->query( "UPDATE custom_list SET cl_order = $cl_order, cl_type = '$cl_type', cl_value = '$cl_value', cl_icon = '$cl_icon' WHERE cl_id = $cl_id", SQL_NONE); } else { $db->query("INSERT INTO custom_list (cl_order, cl_type, cl_value, cl_icon) VALUES ($cl_order, '$cl_type', '$cl_value', '$cl_icon') ", SQL_NONE); $cl_id = mysql_insert_id(); } return $cl_id; } function cl_getall() { global $db, $smarty; $db->query( "SELECT custom_list.* FROM custom_list ORDER BY custom_list.cl_type, cl_order ", SQL_ALL ); return $db->record; } function cl_get_types() { global $db, $smarty; $db->query( "SELECT DISTINCT custom_list.cl_type FROM custom_list ORDER BY custom_list.cl_type", SQL_ALL ); return $db->record; } ?> <file_sep>/admin/libs/common.lib.php <?php $fontfamily_list = array('Verdana', 'Arial', 'Courier', 'Tahoma'); $fontsize_list = array('9px', '10px', '11px', '12px', '13px', '14px', '16px', '18px', '20px'); $menusepsize_list = array('0px', '1px', '2px', '3px'); $smarty->assign('tpl_page_title', 'Configurazione'); switch($_action) { case 'common_save': //if ( isset($_POST['submit_save']) ) { common_save($_POST); css_save(); $smarty->assign('msg', '...Record salvato con successo...'); //} default: break; } $config_group = array('Parametri','Grafica', 'Colonna Sx', 'Colonna Dx', 'Menu','Footer','Pagine', 'Articoli','Cerca'); if (GESTIONE_NEWS == 1) array_push($config_group, 'News'); $config_group = array('Parametri','Aspetto', 'Menu','Footer'); $current_group = isset($_GET['current_group']) ? $_GET['current_group'] : $config_group[0]; $db->query("SELECT config.* FROM config WHERE config.config_group = '$current_group' ORDER BY config_order ", SQL_ALL); $config = $db->record; $smarty->assign('config_group', $config_group); $smarty->assign('current_group', $current_group); $smarty->assign('config', $config); $smarty->assign('fontfamily_list', $fontfamily_list); $smarty->assign('fontsize_list', $fontsize_list); $smarty->assign('menusepsize_list', $menusepsize_list); $smarty->assign('tpl_page', $smarty->fetch('admin_'.$_option.'_record.tpl')); function css_save() { global $db, $smarty; # Load config parameters $db->query("SELECT config.* FROM config WHERE config_css=1", SQL_ALL); $_CONFIG = array(); foreach ($db->record as $r) { $_CONFIG[$r['config_type']] = $r; } $smarty->assign('CONFIG', $_CONFIG); $custom_css = $smarty->fetch('custom_css.tpl'); $fp = fopen (CUSTOM_DIR . "css/custom.css", "w"); fputs($fp, $custom_css); fclose($fp); } function common_save($post) { global $db; while (list($key, $val) = each($post)) { if ($key != 'submit_save') { $k = strtoupper($key); if (strrpos($val, "&euro;")) echo $val; $val = str_replace("€", "&euro;", $val); $val = str_replace("©", "&copy;", $val); $db->query("UPDATE config SET config_value='" . $val . "' WHERE config_type='" . $k . "'", SQL_NONE); } } return TRUE; } ?> <file_sep>/admin/libs/profile.lib.php <?php $smarty->assign('tpl_page_title', 'Profile utente'); switch($_action) { case 'user_save': if ( isset($_POST['submit_save'])) { if ($_POST['user_password'] == $_POST['user_repassword']) { user_save($_POST); $smarty->assign('msg', '...Record salvato con successo...'); } else { $smarty->assign('msg', '...Errore inserimento password...'); } } break; default: break; } $smarty->assign('tpl_page', $smarty->fetch('admin_user_record.tpl')); function user_save($post) { global $db; $db->query("UPDATE user SET user_password='" . md5($post['user_password']) . "' WHERE user_id=" . $_SESSION['user']['user_id'], SQL_NONE); return TRUE; } ?>
45d1009fc171a34d618116693d22f23776fe300f
[ "PHP" ]
10
PHP
ivoivano/moiazza
1ac9f123663cbc7919d8ebba1461da86f62ecc7f
fa87b95346c055a5e92bf214d92c1c8a21a0d80d
refs/heads/master
<file_sep>export default{ api_url: 'http://192.168.127.12:8081', }<file_sep>import React, { PureComponent } from 'react'; import styles from './Login.less'; import { formatMessage,FormattedMessage } from 'umi/locale'; import {connect} from 'dva'; import logo from '../../assets/logo.svg' import banner from '../../assets/banner.svg' import { Row, Col, Button, Tabs, Form, Input,Checkbox } from 'antd' import SelectLang from '@/components/SelectLang'; import {decryptData} from '../../utils/utils' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' const TabPane = Tabs.TabPane; const FormItem=Form.Item; @connect(({loading})=>({ submitting:loading.effects['oauth/login'] })) class Login extends PureComponent { state={ user_name:localStorage.getItem('user_name'), password:<PASSWORD>('password')?<PASSWORD>(localStorage.getItem('password'),'<PASSWORD>'):'' } /** * 登录 */ login=()=>{ const { dispatch, form: { validateFields } } = this.props; validateFields((err,values)=>{ if(!err){ dispatch({ type:'oauth/login', payload:values }) } }) } render() { const {submitting,form:{getFieldDecorator}}=this.props; return ( <div className={styles.container}> <div className={styles.header}> <div className={styles.container}> <div className={styles.logo}> <img src={logo}></img> <span className={styles.title}>React+Koa 后台管理系统</span> </div> <div className={styles.toolbar}> <SelectLang /> </div> </div> </div> <div className={styles.content}> <Row> <Col span={13} offset={2} className={styles.banner}> <img src={banner}></img> <p><FormattedMessage id="login.slogan" /></p> </Col> <Col span={9}> <div className={styles.loginTab}> <Tabs > <TabPane tab={formatMessage({id:'login.tab-account'})} key="1"> <Form className="login-form" ref="loginForm" > <FormItem> {getFieldDecorator('user_name', { initialValue:this.state.user_name, rules: [{ required: true, message: formatMessage({id:'validation.username.required'}) }], })( <Input size="large" prefix={<FontAwesomeIcon icon="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder={formatMessage({id:'login.placeholder.username'})+':admin/testA'} /> )} </FormItem> <FormItem> {getFieldDecorator('password', { initialValue:this.state.password, rules: [{ required: true, message: formatMessage({id:'validation.password.required'}) }], })( <Input size="large" prefix={<FontAwesomeIcon icon="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder={formatMessage({id:'login.placeholder.password'})+':admin/<PASSWORD>'} onPressEnter={this.login}/> )} </FormItem> <FormItem style={{marginBottom:'0'}}> {getFieldDecorator('remember', { valuePropName: 'checked', initialValue: true, })( <Checkbox><FormattedMessage id="login.remember-me"></FormattedMessage></Checkbox> )} <Button size="large" type="primary" onClick={this.login} loading={submitting} style={{width:'100%',marginTop:'10px'}}> <FormattedMessage id="login.btn.login"></FormattedMessage> </Button> </FormItem> </Form> </TabPane> <TabPane tab={formatMessage({id:'login.tab-qrcode'})} key="2"> </TabPane> </Tabs> </div> </Col> </Row> </div> <div className={styles.footer}> <div className={styles.links}> <a href='https://react.docschina.org/' target="_blank" >React</a> <a href='https://ant.design/index-cn' target="_blank" >Ant Design</a> <a href='https://preview.pro.ant.design/user/login' target="_blank" >Ant Design Pro</a> <a href='https://umijs.org/' target="_blank" >UmiJS</a> <a href='https://www.csdn.net' target="_blank" >CSDN</a> </div> <div className={styles.copyright}>Copyright 2018 © zhengxinhong</div> </div> </div> ) } } export default Form.create()(Login);<file_sep>import React, { PureComponent } from 'react' import { connect } from 'dva' import { Form, Input, Radio, Button,message} from 'antd' import { formatMessage, FormattedMessage } from 'umi/locale' import UploadImage from '../../../components/UploadImage' import { regPhone, regNameCn, regNameEn } from '../../../utils/validate' const FormItem = Form.Item @connect(({ app }) => ({ currentUser: app.currentUser, })) @Form.create() class Base extends PureComponent { /**保存 */ handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields(async (err, values) => { if (!err) { const file = values.avatar_file[0] const avatar = file ? file.code : ''; values.avatar_file = file const newUserInfo = Object.assign(this.props.currentUser, values, { avatar: avatar }) const { dispatch } = this.props; await dispatch({ type: 'app/updateCurrentUser', payload: newUserInfo, callback:()=>{ message.success(formatMessage({id:'msg.saved'})) } }) } }) } render() { const { getFieldDecorator } = this.props.form; const { currentUser } = this.props; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 8 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 }, }, }; return ( <div style={{ width: '600px' }}> <h2><FormattedMessage id="menu.setting.base" /></h2> <Form onSubmit={this.handleSubmit}> <FormItem {...formItemLayout} label={formatMessage({ id: 'label.avatar' })}> {getFieldDecorator('avatar_file', { valuePropName: 'fileList', initialValue: currentUser.avatar_file ? [currentUser.avatar_file] : [] })( <UploadImage maxLimit={1} data={{ is_static: true, folder_name: 'avatar', is_thumb: true, }} /> )} </FormItem> <FormItem {...formItemLayout} label={formatMessage({ id: 'label.name-cn' })}> {getFieldDecorator('name_cn', { initialValue: currentUser.name_cn, rules: [ { required: true, whitespace: false, message: formatMessage({ id: 'validation.name-cn.required' }) }, { max: 50, min: 1, pattern: regNameCn, message: formatMessage({ id: 'validation.name-cn' }) } ] })( <Input ></Input> )} </FormItem> <FormItem {...formItemLayout} label={formatMessage({ id: 'label.name-en' })}> {getFieldDecorator('name_en', { initialValue: currentUser.name_en, rules: [ { whitespace: true, message: formatMessage({ id: 'validation.name-en.required' }) }, { max: 50, min: 1, pattern: regNameEn, message: formatMessage({ id: 'validation.name-en' }) } ] })( <Input ></Input> )} </FormItem> <FormItem {...formItemLayout} label={formatMessage({ id: 'label.sex' })}> {getFieldDecorator('sex', { initialValue: currentUser.sex, rules: [{ required: true }] })( <Radio.Group > <Radio value={1}><FormattedMessage id="label.sex.male"/></Radio> <Radio value={2}><FormattedMessage id="label.sex.female"/></Radio> </Radio.Group> )} </FormItem> <FormItem {...formItemLayout} label={formatMessage({ id: 'label.mobile' })}> {getFieldDecorator('mobile', { initialValue: currentUser.mobile, rules: [ { required: true, message: formatMessage({ id: 'validation.mobile.required' }) }, { pattern: regPhone, message: formatMessage({ id: 'validation.mobile' }) } ] })( <Input></Input> )} </FormItem> <FormItem {...formItemLayout} label={formatMessage({ id: 'label.email' })}> {getFieldDecorator('mail', { initialValue: currentUser.mail, rules: [{ type: 'email', message: formatMessage({ id: 'validation.email' }) }] })( <Input></Input> )} </FormItem> <Form.Item wrapperCol={{ span: 12, offset: 6 }} style={{ textAlign: 'center' }} > <Button type="primary" htmlType="submit"><FormattedMessage id="button.save" /></Button> </Form.Item> </Form> </div> ) } } export default Base;<file_sep>import React, { PureComponent, Fragment } from 'react' import { FormattedMessage, formatMessage } from 'umi/locale' import { connect } from 'dva' import { List, Modal, Form, Input,message } from 'antd'; import { regPassword } from '../../../utils/validate' @connect(({ app }) => ({ currentUser: app.currentUser, })) @Form.create() class Security extends PureComponent { state = { modalVisible: false } handleOpenModal = () => { this.setState({ modalVisible: true }) } handleCloseModal = () => { this.props.form.resetFields(); this.setState({ modalVisible: false }) } /**修改密码 */ handUpdatePwd = (e) => { e.preventDefault(); this.props.form.validateFields(async (err, values) => { if (!err) { const { currentUser, dispatch } = this.props; values.user_name = currentUser.user_name dispatch({ type: 'app/updatePassword', payload: values, callback:()=>{ message.success(formatMessage({id:'msg.updated'})) } }) this.handleCloseModal() } }) } getPwdStrength = () => { const { password_strength } = this.props.currentUser; if (password_strength == 3) { return ( <font className="strong"> <FormattedMessage id="setting.security.password.strength.strong" /></font> ) } else if (password_strength == 2) { return ( <font className="medium"> <FormattedMessage id="setting.security.password.strength.medium" /></font> ) } else { return ( <font className="weak"> <FormattedMessage id="setting.security.password.strength.weak" /></font> ) } } getList = () => { const list = [ { title: formatMessage({ id: 'setting.security.password' }, {}), description: ( <Fragment> {formatMessage({ id: 'setting.security.password-description' })}: {this.getPwdStrength()} </Fragment> ), actions: [ <a onClick={this.handleOpenModal}> <FormattedMessage id="label.update" /> </a>, ], }, ] return list; } getModelContent = () => { const { getFieldDecorator } = this.props.form; const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 13 }, }; return ( <Form layout="horizontal" > <Form.Item {...formItemLayout} label={formatMessage({ id: 'setting.security.password.old' })}> {getFieldDecorator('old_password', { rules: [ { required: true, message: formatMessage({ id: 'setting.security.validation.password.required' }) }, { pattern: regPassword, message: formatMessage({ id: 'setting.security.validation.password' }) } ] })( <Input type="password" autoFocus></Input> )} </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({ id: 'setting.security.password.new' })}> {getFieldDecorator('new_password', { initialValue:'', rules: [ { required: true, message: formatMessage({ id: 'setting.security.validation.password.required' }) }, { pattern: regPassword, message: formatMessage({ id: 'setting.security.validation.password' }) } ] })( <Input type="password"></Input> )} </Form.Item> </Form> ) } render() { return ( <Fragment> <h2><FormattedMessage id="menu.setting.security" /></h2> <List itemLayout="horizontal" dataSource={this.getList()} renderItem={item => ( <List.Item actions={item.actions}> <List.Item.Meta title={item.title} description={item.description}></List.Item.Meta> </List.Item> )}> </List> <Modal title={formatMessage({ id: 'setting.security.password.update-title' })} visible={this.state.modalVisible} onCancel={this.handleCloseModal} onOk={this.handUpdatePwd} > {this.getModelContent()} </Modal> </Fragment> ) } } export default Security;<file_sep>export default [ { path: '/login', component: './User/Login' }, { path: '/', component: '../layouts/BasicLayout', routes: [ { path: '/', redirect: '/home' }, { path: '/home', component: './Home' }, { path: '/user/setting', component: './User/Setting/Index', routes: [ { path: '/user/setting', redirect: '/user/setting/base' }, { path: '/user/setting/base', component: './User/Setting/Base' }, { path: '/user/setting/security', component: './User/Setting/Security' }, { path: '/user/setting/personalization', component: './User/Setting/Personalization' }, ] }, { path: '/system', name: 'system', routes: [ { path: '/system/user', name: 'user', component: './System/User' }, { path: '/system/role', component: './System/Role' }, { path: '/system/menu', component: './System/Menu' }, { path: '/system/resource', component: './System/Resource' }, ] } ] } ];<file_sep>import { library } from '@fortawesome/fontawesome-svg-core' import { faGithub } from '@fortawesome/free-brands-svg-icons' //import { faUserEdit, faUserLock,faUserTimes,faUserPlus } from '@fortawesome/free-solid-svg-icons' import { fas } from '@fortawesome/free-solid-svg-icons' library.add(fas,faGithub)<file_sep>import React, { PureComponent } from 'react' import { Menu, Icon } from 'antd'; import { FormattedMessage } from 'umi/locale' import Link from 'umi/link' import { isUrl } from '@/utils/utils'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' const MenuItem = Menu.Item; const SubMenu = Menu.SubMenu; /**获取图标 */ const getIcon = icon => { if (typeof icon === 'string' && isUrl(icon)) { return <img src={icon} alt="icon" style={{ width: '14px', marginRight: '10px' }} />; } if (typeof icon === 'string' && icon) { return <i className="anticon" > <FontAwesomeIcon icon={icon} style={{ marginBottom: '2px' }} /> </i>; } return icon; }; class SiderBaseMenu extends PureComponent { /**获取菜单项 */ getNavMenuItems = (menuData) => { if (!menuData) { return [] } else { return menuData.map(item => this.getSubMenuOrItem(item)) } } /**获取本地化菜单名 */ getLocaleName = (locale) => { return <FormattedMessage id={`menu.${locale}`} /> } /**获取目录菜单或子菜单 */ getSubMenuOrItem = item => { if (item.resource_type != 3) { if (item.children && item.children.length > 0&&item.resource_type!=2) { const { name, icon, path, children, locale } = item return ( <SubMenu title={icon ? (<span>{getIcon(icon)}<span>{this.getLocaleName(locale)}</span></span>) : (name)} key={locale}> {this.getNavMenuItems(children)} </SubMenu> ) } return <MenuItem key={item.path}>{this.getMenuItemPath(item)}</MenuItem> } return null; } /**获取链接菜单 */ getMenuItemPath = (item) => { const { name, locale, path } = item; const icon = getIcon(item.icon); if (/^https?:\/\//.test(path)) { return ( <a href={path} target='_bank'> {icon} <span>{this.getLocaleName(locale)}</span> </a> ); } const { location } = this.props; return ( <Link to={path} replace={path === location.pathname} state={{ title: 'abc' }} > {icon} <span>{this.getLocaleName(locale)}</span> </Link> ) } //获取初始打开的菜单目录 getOpenKeys = (activeKey) => { if (activeKey) { return [activeKey.split('/').slice(0, -1).join('/')] } return [] } render() { const { theme, mode, menuData, navActiveKey } = this.props; return ( <Menu theme={theme} mode={mode} selectedKeys={[navActiveKey]} > {this.getNavMenuItems(menuData)} </Menu> ) } } export default SiderBaseMenu<file_sep>import dva from 'dva'; import createLoading from 'dva-loading'; const runtimeDva = window.g_plugins.mergeConfig('dva'); let app = dva({ history: window.g_history, ...(runtimeDva.config || {}), }); window.g_app = app; app.use(createLoading()); (runtimeDva.plugins || []).forEach(plugin => { app.use(plugin); }); app.model({ namespace: 'app', ...(require('/Users/bruce.zheng/Desktop/test/koa/xinhong-web/src/models/app.js').default) }); app.model({ namespace: 'oauth', ...(require('/Users/bruce.zheng/Desktop/test/koa/xinhong-web/src/models/oauth.js').default) }); app.model({ namespace: 'resource', ...(require('/Users/bruce.zheng/Desktop/test/koa/xinhong-web/src/pages/System/models/resource.js').default) }); app.model({ namespace: 'role', ...(require('/Users/bruce.zheng/Desktop/test/koa/xinhong-web/src/pages/System/models/role.js').default) }); app.model({ namespace: 'user', ...(require('/Users/bruce.zheng/Desktop/test/koa/xinhong-web/src/pages/System/models/user.js').default) }); <file_sep>import React, { PureComponent, Fragment } from 'react'; import TablePage from '../../components/TablePage' import { Button, Input, Select, Tag, Divider, Popconfirm, Form, Modal, Radio, message } from 'antd'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { formatMessage, FormattedMessage } from 'umi/locale' import { connect } from 'dva' import { formatTime } from '../../utils/utils' import { regNameCn, regNameEn, regPhone, regAccount } from '../../utils/validate' import { existAccount, existMobile } from '../../services/user' import Permission from '../../components/Permission' @Form.create() class UserForm extends PureComponent { //保存 handleOk = () => { const { form, handleSave } = this.props; form.validateFieldsAndScroll((err, fieldsValue) => { if (err) return; handleSave(fieldsValue); }) } //验证账号是否已存在 handleExistAccount = async (rule, value, callback) => { const { mode } = this.props; if (mode) { let { code, data } = await existAccount({ user_name: value }); if (!code && data.exist) { callback(formatMessage({ id: 'validation.account.existed' })) } } callback() } //验证手机号是否已存在 handleExistMobile = async (rule, value, callback) => { const { editInfo, mode } = this.props; const params = { mobile: value }; if (!mode) params.id = editInfo.id; let { code, data } = await existMobile(params); if (!code && data.exist) { callback(formatMessage({ id: 'validation.mobile.existed' })) } callback() } render() { const { form: { getFieldDecorator }, handleModalVisible, modalVisible, roleList, mode, editInfo } = this.props; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 7 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 14 }, }, }; return ( <Modal destroyOnClose title={ mode ? <span><FontAwesomeIcon icon="user-plus"></FontAwesomeIcon> <FormattedMessage id="system.user.modal.add" /></span> : <span><FontAwesomeIcon icon="user-edit"></FontAwesomeIcon> <FormattedMessage id="system.user.modal.edit" /></span>} visible={modalVisible} onOk={this.handleOk} onCancel={handleModalVisible} > <Form> <Form.Item {...formItemLayout} label={formatMessage({ id: 'label.account' })}> {getFieldDecorator('user_name', { initialValue: !mode ? editInfo.user_name : '', validateFirst: true, rules: [ { required: true, whitespace: false, message: formatMessage({ id: 'validation.account.required' }) }, { pattern: regAccount, message: formatMessage({ id: 'validation.account' }) }, { validator: this.handleExistAccount } ] })( <Input disabled={!mode}></Input> )} </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({ id: 'label.name-cn' })}> {getFieldDecorator('name_cn', { initialValue: !mode ? editInfo.name_cn : '', rules: [ { required: true, whitespace: false, message: formatMessage({ id: 'validation.name-cn.required' }) }, { max: 50, min: 1, pattern: regNameCn, message: formatMessage({ id: 'validation.name-cn' }) } ] })( <Input></Input> )} </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({ id: 'label.name-en' })}> {getFieldDecorator('name_en', { initialValue: !mode ? editInfo.name_en : '', rules: [ { whitespace: true, message: formatMessage({ id: 'validation.name-en.required' }) }, { max: 50, min: 1, pattern: regNameEn, message: formatMessage({ id: 'validation.name-en' }) } ] })( <Input></Input> )} </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({ id: 'label.sex' })}> {getFieldDecorator('sex', { initialValue: !mode ? editInfo.sex : '', rules: [ { required: true, message: formatMessage({ id: 'validation.sex.required' }) }, ] })( <Radio.Group > <Radio value={1}><FormattedMessage id="label.sex.male" /></Radio> <Radio value={2}><FormattedMessage id="label.sex.female" /></Radio> </Radio.Group> )} </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({ id: 'label.role' })}> {getFieldDecorator('role', { initialValue: !mode ? editInfo.role.map(item => (item.id)) : [], rules: [ { required: true, message: formatMessage({ id: 'validation.role.required' }) }, ] })( <Select mode="multiple"> { roleList.map(item => ( <Select.Option key={item.id} value={item.id}>{item.role_name}</Select.Option> )) } </Select> )} </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({ id: 'label.mobile' })}> {getFieldDecorator('mobile', { initialValue: !mode ? editInfo.mobile : '', validateFirst: true, rules: [ { required: true, message: formatMessage({ id: 'validation.mobile.required' }) }, { pattern: regPhone, message: formatMessage({ id: 'validation.mobile' }) }, { validator: this.handleExistMobile } ] })( <Input></Input> )} </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({ id: 'label.email' })}> {getFieldDecorator('mail', { initialValue: !mode ? editInfo.mail : '', rules: [{ type: 'email', message: formatMessage({ id: 'validation.email' }) }] })( <Input></Input> )} </Form.Item> </Form> </Modal> ) } } @connect(({ user, loading }) => ({ data: user.data, roleList: user.roleList, permission:user.permission, loading: loading.effects['user/getList'] })) class User extends PureComponent { state = { sortedInfo: {},//排序信息 filteredInfo: {},//筛选信息 modalVisible: false, modalMode: true,//弹框模式 true-新增;false-编辑 editInfo: {}, permissionVisible: false, } componentDidMount() { this.initRoleDropList(); } /**绑定子组件 */ bindRef = ref => { this.child = ref } initRoleDropList = () => { const { dispatch } = this.props; dispatch({ type: 'user/getRoleDropList', }) } /**表格排序、筛选变化时触发 */ handleChange = (sorter, filters) => { this.setState({ sortedInfo: { ...sorter }, filteredInfo: { ...filters } }) } /**删除用户 */ handleDelete = (id) => { const { dispatch } = this.props; dispatch({ type: 'user/delete', payload: { id }, callback: () => { message.success(formatMessage({ id: 'msg.deleted' })) } }) } /**禁用或启用用户 */ handleChangeState = (id, status) => { const { dispatch } = this.props; dispatch({ type: 'user/updateState', payload: { id, status: status ? 0 : 1 }, callback: () => { message.success(status ? formatMessage({ id: 'msg.enabled' }) : formatMessage({ id: 'msg.disabled' })) } }) } /**弹框状态 */ handleModalVisible = () => { this.setState({ modalVisible: !this.state.modalVisible, }) } /**打开弹框 model true-新增;false-编辑 */ handleModalOpen = (mode) => { this.setState({ modalMode: mode, modalVisible: !this.state.modalVisible }) } /**修改用户 */ handleEdit = (fieldsValue) => { this.setState({ editInfo: fieldsValue }, () => { this.handleModalOpen(false) }) } /**保存(新增、编辑)用户 */ handleSave = (fieldsValue) => { const { dispatch } = this.props; const { modalMode, editInfo } = this.state; dispatch({ type: modalMode ? 'user/create' : 'user/update', payload: modalMode ? fieldsValue : Object.assign(fieldsValue, { id: editInfo.id }), callback: () => { this.setState({ modalVisible: false }) message.success(modalMode ? formatMessage({ id: 'msg.created' }) : formatMessage({ id: 'msg.updated' })) } }) } handlePermissionModalVisiable = (id,callback) => { this.setState({ assignUserId: id ? id : '', permissionVisible: !this.state.permissionVisible },()=>{ if(callback) callback(); }) } /** * 分配权限 */ handleAssignPermissions = (id) => { const { dispatch} = this.props; dispatch({ type: 'user/getPermission', payload: { id: id }, callback: () => { this.handlePermissionModalVisiable(id,()=>{ const {permission}=this.props; this.child.setCheckedKeys(permission.user.concat(permission.role),permission.role) }); } }) } /**保存权限 */ handleSavePermission=(resource_ids)=>{ const {dispatch}=this.props; dispatch({ type:'user/savePermission', payload:{ id:this.state.assignUserId, resource_list:resource_ids }, callback:()=>{ message.success(formatMessage({id:'msg.saved'})) this.handlePermissionModalVisiable(); } }) } render() { const { data, roleList, loading } = this.props; const { sortedInfo } = this.state; const columns = [{ title: formatMessage({ id: 'label.account' }), key: 'user_name', dataIndex: 'user_name', fixed: true, width: 200, }, { title: formatMessage({ id: 'label.name-cn' }), key: 'name_cn', dataIndex: 'name_cn', fixed: true, width: 120, }, { title: formatMessage({ id: 'label.name-en' }), key: 'name_en', dataIndex: 'name_en', width: 180, }, { title: formatMessage({ id: 'label.status' }), key: 'status', dataIndex: 'status', sorter: true, sortOrder: sortedInfo.columnKey === 'status' && sortedInfo.order, width: 120, render: (text) => (<span>{text == 0 ? <Tag color="green"><FormattedMessage id="label.status.normal" /></Tag> : text == 1 ? <Tag color="red"><FormattedMessage id="label.status.disabled" /></Tag> : <Tag color="grey"><FormattedMessage id="label.status.deleted" /></Tag>}</span>) }, { title: formatMessage({ id: 'label.mobile' }), key: 'mobile', dataIndex: 'mobile', width: 180, }, { title: formatMessage({ id: 'label.role' }), key: 'role', dataIndex: 'role', width: 200, render: (text) => ( <span>{text.map(item => (<Tag key={item.id} >{item.role_name}</Tag>))}</span> ) }, { title: formatMessage({ id: 'label.sex' }), key: 'sex', dataIndex: 'sex', sorter: true, sortOrder: sortedInfo.columnKey === 'sex' && sortedInfo.order, width: 120, render: (text) => (<span>{text == 1 ? <FontAwesomeIcon icon="male" size="lg" color="#0082f3" /> : <FontAwesomeIcon icon="female" size="lg" color="#f98c3d" />}</span>) }, { title: formatMessage({ id: 'label.email' }), key: 'mail', dataIndex: 'mail', width: 200, }, { title: formatMessage({ id: 'label.create-time' }), key: 'create_time', dataIndex: 'create_time', sorter: true, sortOrder: sortedInfo.columnKey === 'create_time' && sortedInfo.order, width: 200, render: (text) => (<span>{formatTime(text)}</span>) }, { title: formatMessage({ id: 'label.operation' }), key: 'operation', fixed: 'right', width: 200, render: (text, record) => ( <div> { record.status !== 2 && !record.is_system ? <span> <a href="javascript:;" onClick={() => this.handleAssignPermissions(record.id)}><FontAwesomeIcon icon="user-shield" /> <FormattedMessage id="label.permissions" /></a> <Divider type="vertical" /> <a href="javascript:;" onClick={() => this.handleEdit(record)}><FontAwesomeIcon icon="edit" /> <FormattedMessage id="label.edit" /></a> <Divider type="vertical" /> { record.status == 1 ? <a href="javascript:;" onClick={() => this.handleChangeState(record.id, record.status)} ><FontAwesomeIcon icon="unlock" /> <FormattedMessage id="label.enable" /></a> : <a href="javascript:;" onClick={() => this.handleChangeState(record.id, record.status)} ><FontAwesomeIcon icon="lock" /> <FormattedMessage id="label.disable" /></a> } <Divider type="vertical" /> <Popconfirm placement="topRight" icon={<FontAwesomeIcon icon="question-circle" className="danger" />} okText={formatMessage({ id: 'button.yes' })} cancelText={formatMessage({ id: 'button.no' })} title={formatMessage({ id: 'system.user.delete.prompt' })} onConfirm={() => this.handleDelete(record.id)}> <a href="javascript:;"><FontAwesomeIcon icon="times" /> <FormattedMessage id="label.delete" /></a> </Popconfirm> </span> : null } </div> ) }]; const buttons = ( <React.Fragment> <Button type="primary" onClick={() => this.handleModalOpen(true)} ><FontAwesomeIcon icon="user-plus" style={{ marginRight: '6px' }} /><FormattedMessage id="button.add" /></Button> </React.Fragment> ) const userFormProps = { mode: this.state.modalMode, editInfo: this.state.editInfo, roleList: roleList, modalVisible: this.state.modalVisible, handleModalVisible: this.handleModalVisible, handleSave: this.handleSave, } return ( <Fragment> <TablePage loading={loading} url="user/getList" data={data} columns={columns} buttons={buttons} rowKey="id" onChange={this.handleChange} > <TablePage.QueryItem label={formatMessage({ id: 'system.user' })} name="user_name"> <Input placeholder={formatMessage({ id: "system.user.placeholder.user" })} /> </TablePage.QueryItem> <TablePage.QueryItem label={<FormattedMessage id="label.status" />} name="status"> <Select placeholder={<FormattedMessage id="placeholder.select" />} allowClear> <Select.Option value="0"><FormattedMessage id="label.status.normal"></FormattedMessage></Select.Option> <Select.Option value="1"><FormattedMessage id="label.status.disabled"></FormattedMessage></Select.Option> <Select.Option value="2"><FormattedMessage id="label.status.deleted"></FormattedMessage></Select.Option> </Select> </TablePage.QueryItem> </TablePage> <UserForm {...userFormProps} ></UserForm> <Permission modalVisible={this.state.permissionVisible} handleModalVisible={this.handlePermissionModalVisiable} triggerRef={this.bindRef} handleSave={this.handleSavePermission} > </Permission> </Fragment> ) } } export default User;<file_sep>import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import styles from './Notification.less' import { formatMessage, FormattedMessage } from 'umi/locale' import { Badge, Popover, Tabs, List, Avatar, Spin } from 'antd'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import classNames from 'classnames' import avatar from '../assets/avatar.svg' const TabPane = Tabs.TabPane; const data = [ { id: '000000001', avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png', title: '你收到了 14 份新周报', datetime: '2017-08-09', type: '通知', }, { id: '000000002', avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png', title: '你推荐的 曲妮妮 已通过第三轮面试', datetime: '2017-08-08', type: '通知', }, { id: '000000003', avatar: 'https://gw.alipayobjects.com/zos/rmsportal/kISTdvpyTAhtGxpovNWd.png', title: '这种模板可以区分多种通知类型', datetime: '2017-08-07', read: true, type: '通知', }, { avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', title: '标题三', read: false, description: '描述描述描述描述描述描述描述描述描述描述', datetime: '一天前', extra: '' }, { avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', title: '标题三', read: false, description: '描述描述描述描述描述描述描述描述描述描述', datetime: '一天前', extra: '' }, { avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', title: '标题三', read: false, description: '描述描述描述描述描述描述描述描述描述描述', datetime: '一天前', extra: '' }, { avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', title: '标题三', read: false, description: '描述描述描述描述描述描述描述描述描述描述', datetime: '一天前', extra: '' }, { avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', title: '标题三', read: false, description: '描述描述描述描述描述描述描述描述描述描述', datetime: '一天前', extra: '' }, ]; class Notification extends PureComponent { getNoticeList = (listData, typeInfo) => { const { emptyImage, emptyText } = typeInfo if (listData.length == 0) { return ( <div className={styles.notFound}> {emptyImage ? <img src={emptyImage} alt="not found" /> : null} <div>{emptyText}</div> </div> ); } return (<div><List className={styles.list} dataSource={listData} renderItem={item => ( <List.Item className={classNames(styles.item, { [styles.read]: item.read })}> <List.Item.Meta className={styles.meta} avatar={<span className={styles.iconElement}><Avatar className={styles.avatar} src={avatar} /></span>} title={ <div className={styles.title}> {item.title} <div className={styles.extra}>{item.extra}</div> </div> } description={ <div> <div className={styles.description} title={item.description}> {item.description} </div> <div className={styles.datetime}>{item.datetime}</div> </div> } /> </List.Item> )}></List> { listData.length > 0 && typeInfo.type != 'all' ? ( <div className={styles.clear}> <FormattedMessage id="home.notification.clear" />{typeInfo.name} </div> ) : null } </div> ) } getNoticeContent = () => { const noticeData = data.slice(0, 4); const messageData = data.slice(0, 5); const eventData = data.slice(0, 6); return ( <Tabs className={styles.tabs}> <TabPane tab={formatMessage({ id: 'home.notification.all' }) + (data.length > 0 ? `(${data.length})` : ``)} key="all"> {this.getNoticeList(data, { type: 'all', name: formatMessage({ id: 'home.notification.all' }), emptyImage: 'https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg', emptyText: formatMessage({ id: 'home.notification.all.empty' }), })} </TabPane> <TabPane tab={formatMessage({ id: 'home.notification.notice' }) + (noticeData.length > 0 ? `(${noticeData.length})` : ``)} key="notice"> {this.getNoticeList(noticeData, { type: 'notice', name: formatMessage({ id: 'home.notification.notice' }), emptyImage: 'https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg', emptyText: formatMessage({ id: 'home.notification.notice.empty' }), })} </TabPane> <TabPane tab={formatMessage({ id: 'home.notification.event' }) + (eventData.length > 0 ? `(${eventData.length})` : ``)} key="event"> {this.getNoticeList(eventData, { type: 'event', name: formatMessage({ id: 'home.notification.event' }), emptyImage: 'https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg', emptyText: formatMessage({ id: 'home.notification.event.empty' }), })} </TabPane> <TabPane tab={formatMessage({ id: 'home.notification.message' }) + (messageData.length > 0 ? `(${messageData.length})` : ``)} key="message"> {this.getNoticeList(messageData, { type: 'message', name: formatMessage({ id: 'home.notification.message' }), emptyImage: 'https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg', emptyText: formatMessage({ id: 'home.notification.message.empty' }), })} </TabPane> </Tabs> ) } render() { const noticeContent = this.getNoticeContent(); const { className } = this.props; return ( <Popover className={className} placement="bottomRight" trigger="click" overlayClassName={styles.popover} content={noticeContent} popupAlign={{ offset: [0, -15] }} > <span> <Badge count={8} overflowCount={99} ><FontAwesomeIcon icon="bell" size="lg" /></Badge> </span> </Popover> ) } } Notification.propTypes = { "className": PropTypes.any, } export default Notification;<file_sep>import React, { PureComponent } from 'react' import { Menu } from 'antd'; import CustomPage from '@/components/CustomPage' import styles from './Index.less' import Link from 'umi/link' import { FormattedMessage } from 'umi/locale' class Setting extends PureComponent { /**菜单切换 */ handleClick=()=>{ } render() { const { children,location } = this.props; return ( <CustomPage> <div className={styles.setting}> <Menu mode="inline" style={{ width: 240 }} defaultSelectedKeys={[location.pathname]} > <Menu.Item key="/user/setting/base"><Link to="/user/setting/base"><FormattedMessage id="menu.setting.base"/></Link></Menu.Item> <Menu.Item key="/user/setting/security"><Link to="/user/setting/security"><FormattedMessage id="menu.setting.security"/></Link></Menu.Item> <Menu.Item key="/user/setting/personalization"><Link to="/user/setting/personalization"><FormattedMessage id="menu.setting.personalization"/></Link></Menu.Item> </Menu> <div className={styles.content} >{ children }</div> </div> </CustomPage> ) } } export default Setting;<file_sep>import routes from './router.config'; export default { plugins: [ ['umi-plugin-react', { antd: true, dva: { hmr: true, }, locale: { enable: true, default: 'zh-CN', baseNavigator: true, }, targets: { ie: 11, }, dynamicImport: { loadingComponent: './components/PageLoading/index', }, // dll: { // include: ['dva', 'dva/router', 'dva/saga'], // exclude: ['@babel/runtime'], // }, // hardSource: true, }] ], routes: routes, theme: { 'primary-color': '#722ED1', }, // externals: { // '@antv/data-set': 'DataSet', // }, outputPath: process.env.BUILD_TYPE == 'docs' ? './docs' : './dist', publicPath: process.env.BUILD_TYPE == 'docs' ? './' : '/', base: process.env.BUILD_TYPE == 'docs' ? './' : '/', cssLoaderOptions: { modules: true, getLocalIdent: (context, localIdentName, localName) => { if ( context.resourcePath.includes('node_modules') || context.resourcePath.includes('global.less') ) { return localName; } const match = context.resourcePath.match(/src(.*)/); if (match && match[1]) { const antdProPath = match[1].replace('.less', ''); const arr = antdProPath .split('/') .map(a => a.replace(/([A-Z])/g, '-$1')) .map(a => a.toLowerCase()); return `zxh${arr.join('-')}-${localName}`.replace(/--/g, '-'); } return localName; }, }, chainWebpack(config, { webpack }) { // code split @ant-design/icons config.module .rule('@ant-design/icons') .include.add(require.resolve('@ant-design/icons/lib/dist')).end() .use('ant-icon') .loader('webpack-ant-icon-loader'); }, manifest: { basePath: '/', }, } <file_sep>import React, { PureComponent, Fragment } from 'react' import { formatMessage,FormattedMessage } from 'umi/locale' import { Radio, Form, Switch } from 'antd' import { connect } from 'dva' @connect(({ app }) => ({ siderStyle: app.siderStyle, navStyle:app.navStyle, colorWeak:app.colorWeak })) class Personalization extends PureComponent { handleChaneSiderStyle = (e) => { const { dispatch } = this.props; dispatch({ type: 'app/setSideStyle', payload: e.target.value }) } handleChaneNavStyle = (e) => { const { dispatch } = this.props; dispatch({ type: 'app/setNavStyle', payload: e.target.value }) } handleChaneColorWeak = (checked) => { const { dispatch } = this.props; dispatch({ type: 'app/setColorWeak', payload: checked }) } render() { const { siderStyle,navStyle,colorWeak } = this.props; const formItemLayout = { labelCol: { lg: { span: 4 }, xl: { span: 3 } }, wrapperCol: { lg: { span: 18 }, xl: { span: 17 } }, }; return ( <Fragment> <h2><FormattedMessage id="menu.setting.personalization" /></h2> <Form> <Form.Item {...formItemLayout} label={formatMessage({id:'setting.personalization.sidebar'})}> <Radio.Group defaultValue={siderStyle} buttonStyle="solid" onChange={this.handleChaneSiderStyle} > <Radio.Button value="dark"><FormattedMessage id="setting.personalization.sidebar.dark" /></Radio.Button> <Radio.Button value="light"><FormattedMessage id="setting.personalization.sidebar.light" /></Radio.Button> </Radio.Group> </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({id:'setting.personalization.navigationbar'})}> <Radio.Group defaultValue={navStyle} buttonStyle="solid" onChange={this.handleChaneNavStyle} > <Radio.Button value="nav"><FormattedMessage id="setting.personalization.navigationbar.tab" /></Radio.Button> <Radio.Button value="breadcrumb"><FormattedMessage id="setting.personalization.navigationbar.breadcrumb" /></Radio.Button> </Radio.Group> </Form.Item> <Form.Item {...formItemLayout} label={formatMessage({id:'setting.personalization.color-weak'})}> <Switch defaultChecked={colorWeak} onChange={this.handleChaneColorWeak}></Switch> </Form.Item> </Form> </Fragment> ) } } export default Personalization;<file_sep>export default { "menu.home":'首页', "menu.system":'系统管理', "menu.system.user":'用户管理', "menu.system.role":'角色管理', "menu.system.menu":'菜单管理', "menu.system.resource":'资源管理', "menu.setting.base":"基本设置", "menu.setting.security":"安全设置", "menu.setting.personalization":"个性化设置", }<file_sep>export default { "menu.home":'首頁', "menu.system":'系統管理', "menu.system.user":'用戶管理', "menu.system.role":'角色管理', "menu.system.menu":'菜單管理', "menu.system.resource":'資源管理', "menu.setting.base":"基本設置", "menu.setting.security":"安全設置", "menu.setting.personalization":"個性化設置", }<file_sep>import React, { PureComponent } from 'react'; import { Layout } from 'antd' import className from 'classnames' import Link from 'umi/link' import styles from './SiderMenu.less' import MenuBase from './SiderMenuBase'; import logo from '../assets/react.svg' const { Sider } = Layout; class SiderMenu extends PureComponent { constructor(props) { super(props) } openMenu=({item, key, keyPath })=>{ console.log(item,key,keyPath) } render() { const { collapsed, onCollapse,theme,menuData} = this.props; return ( <Sider className={className(styles.sider, styles.fixSiderbar,{[styles.light]:theme==='light'})} width={268} collapsible trigger={null} theme={theme} defaultCollapsed={collapsed} collapsed={collapsed} breakpoint="lg" onCollapse={()=>onCollapse} > <div className={styles.logo} id="logo"> <Link to="/"> <img src={logo} alt="logo" /> <h1>Management Sys</h1> </Link> </div> <MenuBase {...this.props} theme={theme} mode="inline" menuData={menuData} > </MenuBase> </Sider> ) } } export default SiderMenu;<file_sep>import React, { PureComponent } from 'react' import { Breadcrumb, Icon } from 'antd' import Link from 'umi/link' import { FormattedMessage } from 'umi/locale' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' class BreadcrumbWrapper extends PureComponent { getBreadcrumbItem = () => { const { breadcrumbList } = this.props; return ( breadcrumbList.map((item, index) => { return ( <Breadcrumb.Item key={item.path}> {item.children || index == breadcrumbList.length - 1 ? <span>{item.name}</span> : <Link to={item.path}>{item.name}</Link>} </Breadcrumb.Item> ) }) ) } render() { const { navActiveKey } = this.props; return ( navActiveKey === '/home' ? null : <Breadcrumb style={{ padding: "9px 15px", background: '#fff' }}> <Breadcrumb.Item key='home'> <Link to="/home"><FontAwesomeIcon icon="home" /> <FormattedMessage id="menu.home" /></Link> </Breadcrumb.Item> {this.getBreadcrumbItem()} </Breadcrumb> ) } } export default BreadcrumbWrapper;
ca0b12520359c44e47e0c0f50fcd456e5e74316d
[ "JavaScript" ]
17
JavaScript
dadawanan/react-admin-web
ca9ee084480ad133ce804cbc20a8f32152cc7bf9
76ad8bc695cda5698335260e0bc1f0721a5de0f2
refs/heads/main
<file_sep>import styled from "styled-components/native"; import colors from "~/styles/colors"; export const Container = styled.View` background-color: ${colors.white}; flex: 1; justify-content: center; align-items: center; `; <file_sep>export default { primaryColor: "#006400", secondaryColor: "#FFA500", inactiveBlack: "#00000044", inactiveWhite: "#FFFFFF44", //Neutrals colors white: "#FFFFFF", black: "#000000", transparent: "#00000000", // status danger: "#DD1111", warning: "#FAA200", info: "#1E90FF", success: "#229922", }; <file_sep>import produce from "immer"; const INITIAL_STATE = { name: "<NAME>", email: "<EMAIL>", loading: false, }; export default function albums(state = INITIAL_STATE, action) { return produce(state, (draft) => { switch (action.type) { case "@user/SIGNIN_REQUEST": { draft.loading = true; break; } } }); } <file_sep>import React from "react"; import { StatusBar } from "react-native"; import { FontAwesome5 } from "@expo/vector-icons"; import { navigationRef } from "~/services/NavigationService"; import colors from "~/styles/colors"; import { NavigationContainer } from "@react-navigation/native"; import { createStackNavigator } from "@react-navigation/stack"; import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; import Payment from "./screens/Payment"; const Stack = createStackNavigator(); const Tab = createBottomTabNavigator(); export default function Routes() { return ( <> <StatusBar backgroundColor={colors.primaryColor} /> <NavigationContainer ref={navigationRef}> <Tab.Navigator initialRouteName="Payment" screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { let iconName; switch (route.name) { case "Payment": { iconName = "donate"; break; } } // You can return any component that you like here! return <FontAwesome5 name={iconName} size={size} color={color} />; }, })} tabBarOptions={{ activeTintColor: colors.secondaryColor, inactiveTintColor: colors.inactiveBlack, }} > <Tab.Screen name="Payment" component={Payment} /> </Tab.Navigator> </NavigationContainer> </> ); } <file_sep>export function signinRequest(email = "", password = "") { return { type: "@user/SIGNIN_REQUEST", payload: { email, password }, }; }
15d80a8ca1bdf169b8c9111af9b96d079f2b17cf
[ "JavaScript" ]
5
JavaScript
fernandosev/PayMeMobile
285f4a5dfbd3c7fd0c094256389d9402ea7bee4b
b36f5ad56455bc0480c03aa702f9fc4161952f81
refs/heads/master
<file_sep>package com.jiangew.service.contacts; import com.jiangew.protobuf.contacts.Contacts; import com.jiangew.protobuf.contacts.Person; import java.io.FileInputStream; /** * 读取 Protobuf 序列化文件 * Author: Jiangew * Date: 30/03/2017 */ public class ListPerson { /** * 打印通讯录中联系人信息 * * @param contacts */ private static void print(Contacts contacts) { for (Person person : contacts.getPeopleList()) { System.out.println("Person Id: " + person.getId()); System.out.println(" Name: " + person.getName()); if (!person.getPhonesList().isEmpty()) { System.out.println(" Email address: " + person.getEmail()); } for (Person.PhoneNumber phoneNumber : person.getPhonesList()) { switch (phoneNumber.getType()) { case MOBILE: System.out.print(" Mobile phone #: "); break; case HOME: System.out.print(" Home phone #: "); break; case WORK: System.out.print(" Work phone #: "); break; } System.out.println(phoneNumber.getNumber()); } } } /** * 加载制定的序列化文件,并输出所有联系人 * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: ListPeople Contacts"); System.exit(-1); } // read the exiting contacts Contacts contacts = Contacts.parseFrom(new FileInputStream(args[0])); print(contacts); } }<file_sep>Protobuf Start Learning ======================= ### Install Protobuf Generate Plugin ```sh brew install protobuf ``` ### Generate Code ```sh protoc -I=. --java_out=src/main/java src/main/proto/contacts.proto ```
6b9db2796b7c32085e083167bab3a67ae8d357c6
[ "Markdown", "Java" ]
2
Java
Jiangew/protobuf-java-learning
634dd4a2db75f60124a2d3ad248dd607ed329ab4
a6cdd91383b8277fc67aa82937dcdeab7289236a
refs/heads/master
<repo_name>loganetherton/dyson<file_sep>/lib/loader.js var _ = require('lodash'), fs = require('fs'), path = require('path'); // Array to hold complete results for each require type var completeResults; var load = function(configDir) { var methods = ['get', 'post', 'put', 'delete', 'patch'], configs = {}, methodDir; /** * Iterate each method and collect the definition objects */ methods.forEach(function(method) { var requireResults = []; methodDir = path.resolve(configDir + '/' + method); requireDir(methodDir); // Require files after they're completely gathered in requireDir() completeResults.map(function(file) { var thisRequire = require(file); requireResults.push(thisRequire); }); configs[method] = _.flatten(requireResults, true); }); return configs; }; /** * Recursively walk through directories synchronously * @param dir * @param done */ var walkSync = function(dir, done) { var results, list, i = 0, file, stat; results = []; try { list = fs.readdirSync(dir); (function next() { // Get next file file = list[i++]; // No more files if (!file) { done(null, results); return results; } // Create file path file = dir + '/' + file; stat = fs.statSync(file); // If it's a directory, go through this process again if (stat && stat.isDirectory()) { walkSync(file, function(err, res) { results = results.concat(res); next(); }); // If not, just } else { results.push(file); next(); } })(); } catch (e) { // One of the directory types doesn't exist. Just skip it. } }; /** * Walk through each top level directory (get, post, etc), find all subdirectories, require all files * @param dir * @returns {Array} */ var requireDir = function(dir) { // Recursively walk through all subdirectories and create collection of necessary files walkSync(dir, function (err, results) { completeResults = results; }); }; module.exports = { load: load };
368ab55e89fb7e173952c599d51b400b049580e1
[ "JavaScript" ]
1
JavaScript
loganetherton/dyson
2e955e4ebc39fe3b844df49454ad8fcaf09ea61e
0f4d6f0e03b2b9da74b6d870583fd28a4f17e87b
refs/heads/master
<repo_name>luobotang/lazy-invoke<file_sep>/index.js var DEFAULT_DELAY_TIME_MS = 50 /* * @param {function} fn * @param {number} [delay=DEFAULT_DELAY_TIME_MS] * @param {Object} [context] - used as `this` when call fn * @returns {function} */ module.exports = function (fn, delay, context) { if (typeof fn !== 'function') { throw new Error('[lazy invoke] fn is not function') } if (arguments.length == 2 && typeof delay !== 'number') { context = delay delay = DEFAULT_DELAY_TIME_MS } else { delay = typeof delay === 'number' ? delay >>> 0 : DEFAULT_DELAY_TIME_MS } var _timer var args var self var invokeFn = function () { _timer = null fn.apply(self, args) } return function () { self = context || this args = arguments if (_timer) { clearTimeout(_timer) } _timer = setTimeout(invokeFn, delay) } }<file_sep>/test.js var LazyInvoke = require('./') function test() { console.log('3 test cases') // 1 - lazy invoke var num = 5 var fn1 = LazyInvoke(function (n) { if (num === n) { console.log('1 - success') } else { console.log('1 - fail') } }) fn1(1) fn1(2) fn1(3) fn1(4) fn1(5) // 2 - context var obj = { name: 'luobo' } var fn2 = LazyInvoke(function () { if (this.name === 'luobo') { console.log('2 - success') } else { console.log('2 - fail') } }, obj) fn2() // 3 - lazy var num3 = 0 var fn3 = LazyInvoke(function () { if (num3 === 1) { console.log('3 - success') } else { console.log('3 - fail') } }, 500) fn3() setTimeout(function () { num3 = 1 }, 200) } test()<file_sep>/README.md # lazy-invoke Invoke a function asynchronously, lazily. ## usage ```hash npm install lazy-invoke ``` ```javascript var LazyInvoke = require('lazy-invoke') var lazyFn = LazyInvoke(function (msg) { console.log(msg) }, 500) lazyFn('hi, 1') lazyFn('hi, 2') lazyFn('hi, 3') lazyFn('hi, 4') lazyFn('hi, 5') // after 500ms, output once: // "hi, 5" ```
e8b85a4d361e0810cf4d6a68091dcfee692c2a02
[ "JavaScript", "Markdown" ]
3
JavaScript
luobotang/lazy-invoke
320e07009843f6c8bd50ad6717ae47e046cad582
cee1e6623d10986b42cd3718d9aea4544f5c4639
refs/heads/master
<repo_name>RobertPastor/calculator<file_sep>/hello/calculator/TestFileFile.py # -*- coding: utf-8 -*- import time import profile from antlr4 import FileStream, CommonTokenStream #from antlr4.PredictionContext import PredictionContextCache #from antlr4.dfa.DFA import DFA #from antlr4.atn.ParserATNSimulator import ParserATNSimulator #from antlr4.tree.Tree import ParseTreeWalker from hello.generated.CalculatorLexer import CalculatorLexer from hello.generated.CalculatorParser import CalculatorParser from ExtendedVisitorFile import ExtendedVisitor from ErrorListenerFile import ThrowingErrorListener class TestFile(object): filePath = "" analysisResult = "" def __init__(self, _filePath, trace=False, _profiling=False): self.filePath = _filePath self.errorsList = [] self.identifierSet = set() self.trace = trace self.analysisDurationSeconds = 0 self.profiling = _profiling def launchProfiling(self): profile.runctx('self.analyseSqlTestFile()', globals(), locals()) def getAnalysisDurationSeconds(self): return self.analysisDurationSeconds def getIdentifierSet(self): return self.identifierSet def getErrorsList(self): return self.errorsList def analyseTestFile(self): try: # measure process time in seconds t0 = time.clock() fileStream = FileStream(fileName=self.filePath, encoding='utf8') lexer = CalculatorLexer(fileStream) commonTokenStream = CommonTokenStream(lexer) parser = CalculatorParser(commonTokenStream) ''' Define new cache ''' #predictionContextCache = PredictionContextCache(); ''' Define new/clean DFA array ''' #decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(parser.atn.decisionToState) ] #parser._interp = ParserATNSimulator(parser, parser.atn, decisionsToDFA, predictionContextCache) #=================================================================== parser.removeErrorListeners() throwingErrorListener = ThrowingErrorListener() parser.addErrorListener(throwingErrorListener) #=================================================================== #if (self.trace): # parser.setTrace(True) ''' try PredictionMode.LL first ''' #parser._interp.predictionMode = PredictionMode.LL #parser.errHandler = BailErrorStrategy() ''' try PredictionMode.SLL ''' #parser._interp.predictionMode = PredictionMode.SLL; ''' parse using entry rule sql_script ''' tree = parser.start() extendedVisitor = ExtendedVisitor() extendedVisitor.visit(tree) variable = extendedVisitor.getFirstVariable() print "First Variable = {variable} --- Result: {result}".format(variable=variable, result=extendedVisitor.getValue(variable)) #=================================================================== # listener = RuleParserListener() # walker = ParseTreeWalker() # walker.walk(listener, tree) # #=================================================================== t1 = time.clock() self.analysisDurationSeconds = t1-t0 self.errorsList = throwingErrorListener.getErrorsList() if len(self.errorsList)>0: print 'Test File - error List = {0}'.format(self.errorsList) # print ' identifiers set = {0}'.format(self.identifierSet) self.analysisResult = "Success" ''' clear cache ''' except Exception as ex: print 'analyseSqlTestFile - exception during parse {filePath} - exception = {ex}'.format(filePath=self.filePath, ex=ex) self.identifierSet = set() self.analysisResult = "Failed" def isSuccess(self): if self.analysisResult == "Success": return True return False def isFailed(self): if self.analysisResult == "Failed": return True return False<file_sep>/gettingstarted/staticfiles/js/generated-javascript/CalculatorParser.js // Generated from Calculator.g4 by ANTLR 4.7.1 // jshint ignore: start var antlr4 = require('antlr4/index'); var CalculatorListener = require('./CalculatorListener').CalculatorListener; var grammarFileName = "Calculator.g4"; var serializedATN = ["\u0003\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964", "\u0003\u0012+\u0004\u0002\t\u0002\u0004\u0003\t\u0003\u0004\u0004\t", "\u0004\u0004\u0005\t\u0005\u0003\u0002\u0003\u0002\u0003\u0002\u0003", "\u0002\u0003\u0002\u0003\u0003\u0003\u0003\u0003\u0004\u0003\u0004\u0003", "\u0004\u0003\u0004\u0003\u0004\u0003\u0004\u0003\u0004\u0003\u0004\u0003", "\u0004\u0003\u0004\u0005\u0004\u001c\n\u0004\u0003\u0004\u0003\u0004", "\u0003\u0004\u0003\u0004\u0003\u0004\u0003\u0004\u0007\u0004$\n\u0004", "\f\u0004\u000e\u0004\'\u000b\u0004\u0003\u0005\u0003\u0005\u0003\u0005", "\u0002\u0003\u0006\u0006\u0002\u0004\u0006\b\u0002\u0005\u0003\u0002", "\f\u000e\u0003\u0002\u0005\u0007\u0003\u0002\b\t\u0002,\u0002\n\u0003", "\u0002\u0002\u0002\u0004\u000f\u0003\u0002\u0002\u0002\u0006\u001b\u0003", "\u0002\u0002\u0002\b(\u0003\u0002\u0002\u0002\n\u000b\u0005\u0006\u0004", "\u0002\u000b\f\u0005\u0004\u0003\u0002\f\r\u0005\u0006\u0004\u0002\r", "\u000e\u0007\u0003\u0002\u0002\u000e\u0003\u0003\u0002\u0002\u0002\u000f", "\u0010\u0007\u0004\u0002\u0002\u0010\u0005\u0003\u0002\u0002\u0002\u0011", "\u0012\b\u0004\u0001\u0002\u0012\u0013\u0007\n\u0002\u0002\u0013\u0014", "\u0005\u0006\u0004\u0002\u0014\u0015\u0007\u000b\u0002\u0002\u0015\u001c", "\u0003\u0002\u0002\u0002\u0016\u0017\t\u0002\u0002\u0002\u0017\u001c", "\u0005\u0006\u0004\u0006\u0018\u001c\u0007\u0011\u0002\u0002\u0019\u001c", "\u0007\u000f\u0002\u0002\u001a\u001c\u0005\b\u0005\u0002\u001b\u0011", "\u0003\u0002\u0002\u0002\u001b\u0016\u0003\u0002\u0002\u0002\u001b\u0018", "\u0003\u0002\u0002\u0002\u001b\u0019\u0003\u0002\u0002\u0002\u001b\u001a", "\u0003\u0002\u0002\u0002\u001c%\u0003\u0002\u0002\u0002\u001d\u001e", "\f\t\u0002\u0002\u001e\u001f\t\u0003\u0002\u0002\u001f$\u0005\u0006", "\u0004\n !\f\b\u0002\u0002!\"\t\u0004\u0002\u0002\"$\u0005\u0006\u0004", "\t#\u001d\u0003\u0002\u0002\u0002# \u0003\u0002\u0002\u0002$\'\u0003", "\u0002\u0002\u0002%#\u0003\u0002\u0002\u0002%&\u0003\u0002\u0002\u0002", "&\u0007\u0003\u0002\u0002\u0002\'%\u0003\u0002\u0002\u0002()\u0007\u0010", "\u0002\u0002)\t\u0003\u0002\u0002\u0002\u0005\u001b#%"].join(""); var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN); var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); }); var sharedContextCache = new antlr4.PredictionContextCache(); var literalNames = [ null, "';'", "'='", "'^'", "'*'", "'/'", "'+'", "'-'", "'('", "')'", "'cos'", "'sin'", "'tan'" ]; var symbolicNames = [ null, null, null, null, null, null, null, null, null, null, "COS", "SIN", "TAN", "PI", "VARIABLE", "INT", "WS" ]; var ruleNames = [ "start", "relop", "expr", "variable" ]; function CalculatorParser (input) { antlr4.Parser.call(this, input); this._interp = new antlr4.atn.ParserATNSimulator(this, atn, decisionsToDFA, sharedContextCache); this.ruleNames = ruleNames; this.literalNames = literalNames; this.symbolicNames = symbolicNames; return this; } CalculatorParser.prototype = Object.create(antlr4.Parser.prototype); CalculatorParser.prototype.constructor = CalculatorParser; Object.defineProperty(CalculatorParser.prototype, "atn", { get : function() { return atn; } }); CalculatorParser.EOF = antlr4.Token.EOF; CalculatorParser.T__0 = 1; CalculatorParser.T__1 = 2; CalculatorParser.T__2 = 3; CalculatorParser.T__3 = 4; CalculatorParser.T__4 = 5; CalculatorParser.T__5 = 6; CalculatorParser.T__6 = 7; CalculatorParser.T__7 = 8; CalculatorParser.T__8 = 9; CalculatorParser.COS = 10; CalculatorParser.SIN = 11; CalculatorParser.TAN = 12; CalculatorParser.PI = 13; CalculatorParser.VARIABLE = 14; CalculatorParser.INT = 15; CalculatorParser.WS = 16; CalculatorParser.RULE_start = 0; CalculatorParser.RULE_relop = 1; CalculatorParser.RULE_expr = 2; CalculatorParser.RULE_variable = 3; function StartContext(parser, parent, invokingState) { if(parent===undefined) { parent = null; } if(invokingState===undefined || invokingState===null) { invokingState = -1; } antlr4.ParserRuleContext.call(this, parent, invokingState); this.parser = parser; this.ruleIndex = CalculatorParser.RULE_start; this.op = null; // RelopContext return this; } StartContext.prototype = Object.create(antlr4.ParserRuleContext.prototype); StartContext.prototype.constructor = StartContext; StartContext.prototype.expr = function(i) { if(i===undefined) { i = null; } if(i===null) { return this.getTypedRuleContexts(ExprContext); } else { return this.getTypedRuleContext(ExprContext,i); } }; StartContext.prototype.relop = function() { return this.getTypedRuleContext(RelopContext,0); }; StartContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterStart(this); } }; StartContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitStart(this); } }; CalculatorParser.StartContext = StartContext; CalculatorParser.prototype.start = function() { var localctx = new StartContext(this, this._ctx, this.state); this.enterRule(localctx, 0, CalculatorParser.RULE_start); try { this.enterOuterAlt(localctx, 1); this.state = 8; this.expr(0); this.state = 9; localctx.op = this.relop(); this.state = 10; this.expr(0); this.state = 11; this.match(CalculatorParser.T__0); } catch (re) { if(re instanceof antlr4.error.RecognitionException) { localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return localctx; }; function RelopContext(parser, parent, invokingState) { if(parent===undefined) { parent = null; } if(invokingState===undefined || invokingState===null) { invokingState = -1; } antlr4.ParserRuleContext.call(this, parent, invokingState); this.parser = parser; this.ruleIndex = CalculatorParser.RULE_relop; return this; } RelopContext.prototype = Object.create(antlr4.ParserRuleContext.prototype); RelopContext.prototype.constructor = RelopContext; RelopContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterRelop(this); } }; RelopContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitRelop(this); } }; CalculatorParser.RelopContext = RelopContext; CalculatorParser.prototype.relop = function() { var localctx = new RelopContext(this, this._ctx, this.state); this.enterRule(localctx, 2, CalculatorParser.RULE_relop); try { this.enterOuterAlt(localctx, 1); this.state = 13; this.match(CalculatorParser.T__1); } catch (re) { if(re instanceof antlr4.error.RecognitionException) { localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return localctx; }; function ExprContext(parser, parent, invokingState) { if(parent===undefined) { parent = null; } if(invokingState===undefined || invokingState===null) { invokingState = -1; } antlr4.ParserRuleContext.call(this, parent, invokingState); this.parser = parser; this.ruleIndex = CalculatorParser.RULE_expr; return this; } ExprContext.prototype = Object.create(antlr4.ParserRuleContext.prototype); ExprContext.prototype.constructor = ExprContext; ExprContext.prototype.copyFrom = function(ctx) { antlr4.ParserRuleContext.prototype.copyFrom.call(this, ctx); }; function VarExprContext(parser, ctx) { ExprContext.call(this, parser); this.name = null; // VariableContext; ExprContext.prototype.copyFrom.call(this, ctx); return this; } VarExprContext.prototype = Object.create(ExprContext.prototype); VarExprContext.prototype.constructor = VarExprContext; CalculatorParser.VarExprContext = VarExprContext; VarExprContext.prototype.variable = function() { return this.getTypedRuleContext(VariableContext,0); }; VarExprContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterVarExpr(this); } }; VarExprContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitVarExpr(this); } }; function PiExprContext(parser, ctx) { ExprContext.call(this, parser); ExprContext.prototype.copyFrom.call(this, ctx); return this; } PiExprContext.prototype = Object.create(ExprContext.prototype); PiExprContext.prototype.constructor = PiExprContext; CalculatorParser.PiExprContext = PiExprContext; PiExprContext.prototype.PI = function() { return this.getToken(CalculatorParser.PI, 0); }; PiExprContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterPiExpr(this); } }; PiExprContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitPiExpr(this); } }; function OpExprContext(parser, ctx) { ExprContext.call(this, parser); this.left = null; // ExprContext; this.op = null; // Token; this.right = null; // ExprContext; ExprContext.prototype.copyFrom.call(this, ctx); return this; } OpExprContext.prototype = Object.create(ExprContext.prototype); OpExprContext.prototype.constructor = OpExprContext; CalculatorParser.OpExprContext = OpExprContext; OpExprContext.prototype.expr = function(i) { if(i===undefined) { i = null; } if(i===null) { return this.getTypedRuleContexts(ExprContext); } else { return this.getTypedRuleContext(ExprContext,i); } }; OpExprContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterOpExpr(this); } }; OpExprContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitOpExpr(this); } }; function TrigExprContext(parser, ctx) { ExprContext.call(this, parser); this.op = null; // Token; this.right = null; // ExprContext; ExprContext.prototype.copyFrom.call(this, ctx); return this; } TrigExprContext.prototype = Object.create(ExprContext.prototype); TrigExprContext.prototype.constructor = TrigExprContext; CalculatorParser.TrigExprContext = TrigExprContext; TrigExprContext.prototype.expr = function() { return this.getTypedRuleContext(ExprContext,0); }; TrigExprContext.prototype.COS = function() { return this.getToken(CalculatorParser.COS, 0); }; TrigExprContext.prototype.SIN = function() { return this.getToken(CalculatorParser.SIN, 0); }; TrigExprContext.prototype.TAN = function() { return this.getToken(CalculatorParser.TAN, 0); }; TrigExprContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterTrigExpr(this); } }; TrigExprContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitTrigExpr(this); } }; function AtomExprContext(parser, ctx) { ExprContext.call(this, parser); this.atom = null; // Token; ExprContext.prototype.copyFrom.call(this, ctx); return this; } AtomExprContext.prototype = Object.create(ExprContext.prototype); AtomExprContext.prototype.constructor = AtomExprContext; CalculatorParser.AtomExprContext = AtomExprContext; AtomExprContext.prototype.INT = function() { return this.getToken(CalculatorParser.INT, 0); }; AtomExprContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterAtomExpr(this); } }; AtomExprContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitAtomExpr(this); } }; function ParenExprContext(parser, ctx) { ExprContext.call(this, parser); ExprContext.prototype.copyFrom.call(this, ctx); return this; } ParenExprContext.prototype = Object.create(ExprContext.prototype); ParenExprContext.prototype.constructor = ParenExprContext; CalculatorParser.ParenExprContext = ParenExprContext; ParenExprContext.prototype.expr = function() { return this.getTypedRuleContext(ExprContext,0); }; ParenExprContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterParenExpr(this); } }; ParenExprContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitParenExpr(this); } }; CalculatorParser.prototype.expr = function(_p) { if(_p===undefined) { _p = 0; } var _parentctx = this._ctx; var _parentState = this.state; var localctx = new ExprContext(this, this._ctx, _parentState); var _prevctx = localctx; var _startState = 4; this.enterRecursionRule(localctx, 4, CalculatorParser.RULE_expr, _p); var _la = 0; // Token type try { this.enterOuterAlt(localctx, 1); this.state = 25; this._errHandler.sync(this); switch(this._input.LA(1)) { case CalculatorParser.T__7: localctx = new ParenExprContext(this, localctx); this._ctx = localctx; _prevctx = localctx; this.state = 16; this.match(CalculatorParser.T__7); this.state = 17; this.expr(0); this.state = 18; this.match(CalculatorParser.T__8); break; case CalculatorParser.COS: case CalculatorParser.SIN: case CalculatorParser.TAN: localctx = new TrigExprContext(this, localctx); this._ctx = localctx; _prevctx = localctx; this.state = 20; localctx.op = this._input.LT(1); _la = this._input.LA(1); if(!((((_la) & ~0x1f) == 0 && ((1 << _la) & ((1 << CalculatorParser.COS) | (1 << CalculatorParser.SIN) | (1 << CalculatorParser.TAN))) !== 0))) { localctx.op = this._errHandler.recoverInline(this); } else { this._errHandler.reportMatch(this); this.consume(); } this.state = 21; localctx.right = this.expr(4); break; case CalculatorParser.INT: localctx = new AtomExprContext(this, localctx); this._ctx = localctx; _prevctx = localctx; this.state = 22; localctx.atom = this.match(CalculatorParser.INT); break; case CalculatorParser.PI: localctx = new PiExprContext(this, localctx); this._ctx = localctx; _prevctx = localctx; this.state = 23; this.match(CalculatorParser.PI); break; case CalculatorParser.VARIABLE: localctx = new VarExprContext(this, localctx); this._ctx = localctx; _prevctx = localctx; this.state = 24; localctx.name = this.variable(); break; default: throw new antlr4.error.NoViableAltException(this); } this._ctx.stop = this._input.LT(-1); this.state = 35; this._errHandler.sync(this); var _alt = this._interp.adaptivePredict(this._input,2,this._ctx) while(_alt!=2 && _alt!=antlr4.atn.ATN.INVALID_ALT_NUMBER) { if(_alt===1) { if(this._parseListeners!==null) { this.triggerExitRuleEvent(); } _prevctx = localctx; this.state = 33; this._errHandler.sync(this); var la_ = this._interp.adaptivePredict(this._input,1,this._ctx); switch(la_) { case 1: localctx = new OpExprContext(this, new ExprContext(this, _parentctx, _parentState)); localctx.left = _prevctx; this.pushNewRecursionContext(localctx, _startState, CalculatorParser.RULE_expr); this.state = 27; if (!( this.precpred(this._ctx, 7))) { throw new antlr4.error.FailedPredicateException(this, "this.precpred(this._ctx, 7)"); } this.state = 28; localctx.op = this._input.LT(1); _la = this._input.LA(1); if(!((((_la) & ~0x1f) == 0 && ((1 << _la) & ((1 << CalculatorParser.T__2) | (1 << CalculatorParser.T__3) | (1 << CalculatorParser.T__4))) !== 0))) { localctx.op = this._errHandler.recoverInline(this); } else { this._errHandler.reportMatch(this); this.consume(); } this.state = 29; localctx.right = this.expr(8); break; case 2: localctx = new OpExprContext(this, new ExprContext(this, _parentctx, _parentState)); localctx.left = _prevctx; this.pushNewRecursionContext(localctx, _startState, CalculatorParser.RULE_expr); this.state = 30; if (!( this.precpred(this._ctx, 6))) { throw new antlr4.error.FailedPredicateException(this, "this.precpred(this._ctx, 6)"); } this.state = 31; localctx.op = this._input.LT(1); _la = this._input.LA(1); if(!(_la===CalculatorParser.T__5 || _la===CalculatorParser.T__6)) { localctx.op = this._errHandler.recoverInline(this); } else { this._errHandler.reportMatch(this); this.consume(); } this.state = 32; localctx.right = this.expr(7); break; } } this.state = 37; this._errHandler.sync(this); _alt = this._interp.adaptivePredict(this._input,2,this._ctx); } } catch( error) { if(error instanceof antlr4.error.RecognitionException) { localctx.exception = error; this._errHandler.reportError(this, error); this._errHandler.recover(this, error); } else { throw error; } } finally { this.unrollRecursionContexts(_parentctx) } return localctx; }; function VariableContext(parser, parent, invokingState) { if(parent===undefined) { parent = null; } if(invokingState===undefined || invokingState===null) { invokingState = -1; } antlr4.ParserRuleContext.call(this, parent, invokingState); this.parser = parser; this.ruleIndex = CalculatorParser.RULE_variable; return this; } VariableContext.prototype = Object.create(antlr4.ParserRuleContext.prototype); VariableContext.prototype.constructor = VariableContext; VariableContext.prototype.VARIABLE = function() { return this.getToken(CalculatorParser.VARIABLE, 0); }; VariableContext.prototype.enterRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.enterVariable(this); } }; VariableContext.prototype.exitRule = function(listener) { if(listener instanceof CalculatorListener ) { listener.exitVariable(this); } }; CalculatorParser.VariableContext = VariableContext; CalculatorParser.prototype.variable = function() { var localctx = new VariableContext(this, this._ctx, this.state); this.enterRule(localctx, 6, CalculatorParser.RULE_variable); try { this.enterOuterAlt(localctx, 1); this.state = 38; this.match(CalculatorParser.VARIABLE); } catch (re) { if(re instanceof antlr4.error.RecognitionException) { localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return localctx; }; CalculatorParser.prototype.sempred = function(localctx, ruleIndex, predIndex) { switch(ruleIndex) { case 2: return this.expr_sempred(localctx, predIndex); default: throw "No predicate with index:" + ruleIndex; } }; CalculatorParser.prototype.expr_sempred = function(localctx, predIndex) { switch(predIndex) { case 0: return this.precpred(this._ctx, 7); case 1: return this.precpred(this._ctx, 6); default: throw "No predicate with index:" + predIndex; } }; exports.CalculatorParser = CalculatorParser; <file_sep>/hello/generated/CalculatorLexer.py # Generated from Calculator.g4 by ANTLR 4.7.1 # encoding: utf-8 from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2") buf.write(u"\22k\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write(u"\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t") buf.write(u"\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22") buf.write(u"\4\23\t\23\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3") buf.write(u"\7\3\7\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\13\3\13\3") buf.write(u"\f\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\16\3\16\3\16\3\17\3") buf.write(u"\17\7\17K\n\17\f\17\16\17N\13\17\3\20\5\20Q\n\20\3\21") buf.write(u"\3\21\5\21U\n\21\3\22\6\22X\n\22\r\22\16\22Y\3\22\5\22") buf.write(u"]\n\22\3\22\7\22`\n\22\f\22\16\22c\13\22\3\23\6\23f\n") buf.write(u"\23\r\23\16\23g\3\23\3\23\2\2\24\3\3\5\4\7\5\t\6\13\7") buf.write(u"\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\35\20\37\2") buf.write(u"!\2#\21%\22\3\2\6\4\2RRrr\4\2KKkk\5\2C\\aac|\5\2\13\f") buf.write(u"\17\17\"\"\2n\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t") buf.write(u"\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3") buf.write(u"\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3") buf.write(u"\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2#\3\2\2\2\2%\3\2\2") buf.write(u"\2\3\'\3\2\2\2\5)\3\2\2\2\7+\3\2\2\2\t-\3\2\2\2\13/\3") buf.write(u"\2\2\2\r\61\3\2\2\2\17\63\3\2\2\2\21\65\3\2\2\2\23\67") buf.write(u"\3\2\2\2\259\3\2\2\2\27=\3\2\2\2\31A\3\2\2\2\33E\3\2") buf.write(u"\2\2\35H\3\2\2\2\37P\3\2\2\2!T\3\2\2\2#W\3\2\2\2%e\3") buf.write(u"\2\2\2\'(\7=\2\2(\4\3\2\2\2)*\7?\2\2*\6\3\2\2\2+,\7`") buf.write(u"\2\2,\b\3\2\2\2-.\7,\2\2.\n\3\2\2\2/\60\7\61\2\2\60\f") buf.write(u"\3\2\2\2\61\62\7-\2\2\62\16\3\2\2\2\63\64\7/\2\2\64\20") buf.write(u"\3\2\2\2\65\66\7*\2\2\66\22\3\2\2\2\678\7+\2\28\24\3") buf.write(u"\2\2\29:\7e\2\2:;\7q\2\2;<\7u\2\2<\26\3\2\2\2=>\7u\2") buf.write(u"\2>?\7k\2\2?@\7p\2\2@\30\3\2\2\2AB\7v\2\2BC\7c\2\2CD") buf.write(u"\7p\2\2D\32\3\2\2\2EF\t\2\2\2FG\t\3\2\2G\34\3\2\2\2H") buf.write(u"L\5\37\20\2IK\5!\21\2JI\3\2\2\2KN\3\2\2\2LJ\3\2\2\2L") buf.write(u"M\3\2\2\2M\36\3\2\2\2NL\3\2\2\2OQ\t\4\2\2PO\3\2\2\2Q") buf.write(u" \3\2\2\2RU\5\37\20\2SU\4\62;\2TR\3\2\2\2TS\3\2\2\2U") buf.write(u"\"\3\2\2\2VX\4\62;\2WV\3\2\2\2XY\3\2\2\2YW\3\2\2\2YZ") buf.write(u"\3\2\2\2Z\\\3\2\2\2[]\7\60\2\2\\[\3\2\2\2\\]\3\2\2\2") buf.write(u"]a\3\2\2\2^`\4\62;\2_^\3\2\2\2`c\3\2\2\2a_\3\2\2\2ab") buf.write(u"\3\2\2\2b$\3\2\2\2ca\3\2\2\2df\t\5\2\2ed\3\2\2\2fg\3") buf.write(u"\2\2\2ge\3\2\2\2gh\3\2\2\2hi\3\2\2\2ij\b\23\2\2j&\3\2") buf.write(u"\2\2\n\2LPTY\\ag\3\b\2\2") return buf.getvalue() class CalculatorLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] T__0 = 1 T__1 = 2 T__2 = 3 T__3 = 4 T__4 = 5 T__5 = 6 T__6 = 7 T__7 = 8 T__8 = 9 COS = 10 SIN = 11 TAN = 12 PI = 13 VARIABLE = 14 INT = 15 WS = 16 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ u"DEFAULT_MODE" ] literalNames = [ u"<INVALID>", u"';'", u"'='", u"'^'", u"'*'", u"'/'", u"'+'", u"'-'", u"'('", u"')'", u"'cos'", u"'sin'", u"'tan'" ] symbolicNames = [ u"<INVALID>", u"COS", u"SIN", u"TAN", u"PI", u"VARIABLE", u"INT", u"WS" ] ruleNames = [ u"T__0", u"T__1", u"T__2", u"T__3", u"T__4", u"T__5", u"T__6", u"T__7", u"T__8", u"COS", u"SIN", u"TAN", u"PI", u"VARIABLE", u"VALID_ID_START", u"VALID_ID_CHAR", u"INT", u"WS" ] grammarFileName = u"Calculator.g4" def __init__(self, input=None, output=sys.stdout): super(CalculatorLexer, self).__init__(input, output=output) self.checkVersion("4.7.1") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None <file_sep>/hello/generated/CalculatorVisitor.py # Generated from Calculator.g4 by ANTLR 4.7.1 from antlr4 import * # This class defines a complete generic visitor for a parse tree produced by CalculatorParser. class CalculatorVisitor(ParseTreeVisitor): # Visit a parse tree produced by CalculatorParser#start. def visitStart(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#relop. def visitRelop(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#varExpr. def visitVarExpr(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#PiExpr. def visitPiExpr(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#opExpr. def visitOpExpr(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#trigExpr. def visitTrigExpr(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#atomExpr. def visitAtomExpr(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#parenExpr. def visitParenExpr(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#variable. def visitVariable(self, ctx): return self.visitChildren(ctx) <file_sep>/hello/calculator/MainAll.py ''' Created on Jun 2, 2016 @author: t0007330 ''' import os import glob import xlsxwriter import time from datetime import datetime from TestFileFile import TestFile def getTestsFiles(): path = os.path.realpath(r'..\TestsFiles') #path = os.path.realpath(r'..\SqlTestsFiles') print '=================== get Tests files in ' + path for filePath in glob.glob(path+'\\*.txt'): yield filePath if __name__ == '__main__': TestFiles = [] # measure process time t0 = time.clock() for filePath in getTestsFiles(): print ' ------------------------------------------------- ' print filePath testFile = TestFile(filePath, trace=True) testFile.analyseTestFile() #resume = raw_input("Voulez-vous continuez - n=non - : ") resume = 'o' if (resume == 'n') or (resume == 'N'): break TestFiles.append(testFile) print ' ------------------------------------------------- ' # measure process time t1 = time.clock() fileName = 'analysisResults' + '-{0}'.format(datetime.now().strftime("%d-%b-%Y-%Hh%Mm%S")) + '.xlsx' workbook = xlsxwriter.Workbook(fileName) resultsWorkSheet = workbook.add_worksheet('Results') col = 0 for cellName in ['Id', 'path', 'result', 'identifiers', 'nbIdentifiers', 'errors' , 'nbErrors','analysis duration (seconds)']: resultsWorkSheet.write_string(row=0, col=col, string=cellName) col += 1 countOfFailedAnalysis = 0 countOfParsedWithErrors = 0 counter = 1 for testFile in TestFiles: print 'id = {0} - file path = {1} - analysis results = {2}'.format(counter, testFile.filePath, testFile.analysisResult) print 'id = {0} - error list = {1}'.format(testFile.filePath, testFile.getErrorsList()) #print 'id = {0} - identifiers set = {1}'.format(testFile.filePath, testFile.getIdentifierSet()) resultsWorkSheet.write_number(row=counter, col=0, number=(counter) ) resultsWorkSheet.write_string(row=counter, col=1, string=testFile.filePath ) resultsWorkSheet.write_string(row=counter, col=2, string=testFile.analysisResult ) if testFile.isFailed(): countOfFailedAnalysis += 1 resultsWorkSheet.write_string(row=counter, col=3, string=repr(sorted(testFile.getIdentifierSet())) ) resultsWorkSheet.write_number(row=counter, col=4, number=(len(testFile.getIdentifierSet())) ) resultsWorkSheet.write_string(row=counter, col=5, string=repr(sorted(testFile.getErrorsList())) ) resultsWorkSheet.write_number(row=counter, col=6, number=(len(testFile.getErrorsList())) ) resultsWorkSheet.write_number(row=counter, col=7, number=(testFile.getAnalysisDurationSeconds()) ) if len(testFile.errorsList): countOfParsedWithErrors += 1 counter += 1 readMeWorksheet = workbook.add_worksheet('ReadMe') readMeWorksheet.write_string(row=0, col=0 , string='Export Date') readMeWorksheet.write_string(row=0, col=1 , string='{0}'.format(datetime.now().strftime("%d-%b-%Y-%Hh%Mm%S")) ) readMeWorksheet.write_string(row=1, col=0 , string='number of analysed files' ) readMeWorksheet.write_number(row=1, col=1 , number=(counter) ) readMeWorksheet.write_string(row=2, col=0 , string='number of failed analysis' ) readMeWorksheet.write_number(row=2, col=1 , number=(countOfFailedAnalysis) ) readMeWorksheet.write_string(row=3, col=0 , string='number of parsed SQL with errors' ) readMeWorksheet.write_number(row=3, col=1 , number=(countOfParsedWithErrors) ) readMeWorksheet.write_string(row=4, col=0 , string='Analysis duration (seconds)' ) readMeWorksheet.write_number(row=4, col=1 , number=(t1-t0) ) readMeWorksheet.write_string(row=5, col=0 , string='Analysis duration (minutes)' ) readMeWorksheet.write_number(row=5, col=1 , number=((t1-t0)/60.) ) workbook.close()<file_sep>/hello/calculator/ExtendedVisitorFile.py # coding: utf8 ''' Created on 2 janv. 2018 @author: t0007330 ''' import math from hello.generated.CalculatorVisitor import CalculatorVisitor from hello.generated.CalculatorParser import CalculatorParser class ExtendedVisitor(CalculatorVisitor): variables = {} histories = [] relationalOperator = '' def __init__(self): self.variables = {} self.histories = [] def storeHistory(self, history): print history self.histories.append(history) def getHistories(self): return self.histories def storeResult(self, result): if len(self.variables.keys())>0: for variable in self.variables.keys(): self.storeHistory('variable {variable} with result= {result}'.format(result=result, variable=variable)) self.variables[variable] = result print self.variables def getFirstVariable(self): return self.getVariable(1) def getVariable(self, variableIndex): count = 1 if len(self.variables.keys())>0: for key in self.variables.keys(): if (count == variableIndex): return key self.storeHistory('Visitor - getVariable - no variable found!!!') return 'no variable found' def getValue(self, variable): if len(self.variables.keys())>0: for key in self.variables.keys(): if (key == variable): return self.variables[key] return 0.0 def visitStart(self , ctx): assert isinstance(ctx, CalculatorParser.StartContext) return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#relop. def visitRelop(self, ctx): assert isinstance(ctx, CalculatorParser.RelopContext) self.relationalOperator = ctx.getText() self.storeHistory('Relational Operator is "{0}"'.format(self.relationalOperator)) return self.visitChildren(ctx) # Visit a parse tree produced by CalculatorParser#varExpr. def visitVarExpr(self, ctx): assert isinstance(ctx, CalculatorParser.VarExprContext) variable = ctx.name.getText() self.variables[str(variable)] = 0.0 self.storeHistory( 'Variable is {variable}'.format(variable=variable)) return self.visitChildren(ctx) def visitOpExpr(self, ctx): assert isinstance(ctx, CalculatorParser.OpExprContext) left = self.visit(ctx.left) right = self.visit(ctx.right) op = ctx.op.text; self.storeHistory( 'Operator is {op}'.format(op=op) ) if str(op).startswith('^'): result = math.pow(left, right) self.storeHistory( 'Expression is {0} -- result is {1}'.format(ctx.getText(), result) ) self.storeResult(result) return result if str(op).startswith('*'): result = left*right self.storeHistory( 'Expression is {0} -- result is {1}'.format(ctx.getText(), result) ) self.storeResult(result) return result if str(op).startswith('/'): result = 0.0 if (right == 0.0): self.storeHistory( 'Error - Division per Zero' ) else: result = left/right self.storeHistory( 'Expression is {0} -- result is {1}'.format(ctx.getText(), result) ) self.storeResult(result) return result if str(op).startswith('+'): result = left+right self.storeHistory( 'Expression is {0} -- result is {1}'.format(ctx.getText(), result) ) self.storeResult(result) return result if str(op).startswith('-'): result = left-right self.storeHistory( 'Expression is {0} -- result is {1}'.format(ctx.getText(), result) ) self.storeResult(result) return result self.storeHistory("Extended Visitor - Unknown operator " + op) raise Exception("Unknown operator " + op); # Visit a parse tree produced by CalculatorParser#trigExpr. def visitTrigExpr(self, ctx): assert isinstance(ctx, CalculatorParser.TrigExprContext) op = ctx.op.text; right = self.visit(ctx.right) if str(op).startswith('cos'): result = math.cos(right) self.storeHistory( 'Expression is {0} - value is in radians - result is {1}'.format(ctx.getText(), result) ) self.storeResult(result) return result if str(op).startswith('sin'): result = math.sin(right) self.storeHistory( 'Expression is {0} - value is in radians - result is {1}'.format(ctx.getText(), result) ) self.storeResult(result) return result if str(op).startswith('cos'): result = math.tan(right) self.storeHistory( 'Expression is {0} - value is in radians - result is {1}'.format(ctx.getText(), result) ) self.storeResult(result) return result self.storeHistory( 'Unknown trigonometric operator!' ) raise 'Extended Visitor - Opérateur trigonometrique inconnu' return self.visitChildren(ctx) def visitAtomExpr(self, ctx): assert isinstance(ctx, CalculatorParser.AtomExprContext) #self.storeHistory('atom expression -- result is {0}'.format( float(ctx.getText()) ) ) #self.storeResult(float(ctx.getText())) return float(ctx.getText()) def visitParenExpr(self, ctx): assert isinstance(ctx, CalculatorParser.ParenExprContext) return self.visit(ctx.expr()) # Visit a parse tree produced by CalculatorParser#PiExpr. def visitPiExpr(self, ctx): result = math.pi return result <file_sep>/hello/calculator/Main.py ''' Created on 2 janv. 2018 @author: t0007330 ''' import json from antlr4 import InputStream from antlr4 import CommonTokenStream #from antlr4.tree import Trees from hello.generated.CalculatorLexer import CalculatorLexer from hello.generated.CalculatorParser import CalculatorParser from ExtendedVisitorFile import ExtendedVisitor from TreesSubClassFile import SubTrees if __name__ == '__main__': print ' ------------------- start ------------------' expression = "y = 2 * (3 + 4)" #expression = " (3.1 * 9.2) + (5.5 * 7.2)" #expression = " 2 ^ 3" expression = " y = (3.1 * 9.2) + (5.5 / 7.2) ;" arraySplit = str(expression).strip().split(';'); for index in range(len(arraySplit)-1): #print index #print '=============== ' statement = str(arraySplit[index]).strip() statement = statement + ';' print ' =========== statement = {statement} ==============='.format(statement=statement) print 'index = {index} - expression= {statement}'.format(index=index, statement=statement) if (str(statement).strip() != ';'): inputStream = InputStream(statement) print inputStream lexer = CalculatorLexer(inputStream) commonTokenStream = CommonTokenStream(lexer) parser = CalculatorParser(commonTokenStream) tree = parser.start() extendedVisitor = ExtendedVisitor() result = extendedVisitor.visit(tree) # check that there is at least one variable #ruleNames = ['start','relop', 'expr', 'variable'] subTree = SubTrees() obj = dict() obj = subTree.toJson(obj=obj, t=tree, ruleNames=None, recog=parser) print json.dumps(obj) if (extendedVisitor.getFirstVariable()): variable = extendedVisitor.getFirstVariable() print 'variable = {variable}'.format(variable=variable) print 'expression= {variable} - result= {value}'.format(variable=variable, value=extendedVisitor.getValue(variable)) print '-------------------- end --------------------------'<file_sep>/hello/generated/CalculatorListener.py # Generated from Calculator.g4 by ANTLR 4.7.1 from antlr4 import * # This class defines a complete listener for a parse tree produced by CalculatorParser. class CalculatorListener(ParseTreeListener): # Enter a parse tree produced by CalculatorParser#start. def enterStart(self, ctx): pass # Exit a parse tree produced by CalculatorParser#start. def exitStart(self, ctx): pass # Enter a parse tree produced by CalculatorParser#relop. def enterRelop(self, ctx): pass # Exit a parse tree produced by CalculatorParser#relop. def exitRelop(self, ctx): pass # Enter a parse tree produced by CalculatorParser#varExpr. def enterVarExpr(self, ctx): pass # Exit a parse tree produced by CalculatorParser#varExpr. def exitVarExpr(self, ctx): pass # Enter a parse tree produced by CalculatorParser#PiExpr. def enterPiExpr(self, ctx): pass # Exit a parse tree produced by CalculatorParser#PiExpr. def exitPiExpr(self, ctx): pass # Enter a parse tree produced by CalculatorParser#opExpr. def enterOpExpr(self, ctx): pass # Exit a parse tree produced by CalculatorParser#opExpr. def exitOpExpr(self, ctx): pass # Enter a parse tree produced by CalculatorParser#trigExpr. def enterTrigExpr(self, ctx): pass # Exit a parse tree produced by CalculatorParser#trigExpr. def exitTrigExpr(self, ctx): pass # Enter a parse tree produced by CalculatorParser#atomExpr. def enterAtomExpr(self, ctx): pass # Exit a parse tree produced by CalculatorParser#atomExpr. def exitAtomExpr(self, ctx): pass # Enter a parse tree produced by CalculatorParser#parenExpr. def enterParenExpr(self, ctx): pass # Exit a parse tree produced by CalculatorParser#parenExpr. def exitParenExpr(self, ctx): pass # Enter a parse tree produced by CalculatorParser#variable. def enterVariable(self, ctx): pass # Exit a parse tree produced by CalculatorParser#variable. def exitVariable(self, ctx): pass <file_sep>/gettingstarted/staticfiles/js/generated-javascript/index.js // define the Calculator functions //console.log("generated-javascript -- index.js -- start"); exports.CalculatorLexer = require('generated-javascript/CalculatorLexer').CalculatorLexer; exports.CalculatorParser = require('generated-javascript/CalculatorParser').CalculatorParser; exports.CalculatorListener = require('generated-javascript/CalculatorListener').CalculatorListener; //console.log("generated-javascript -- index.js -- end"); <file_sep>/gettingstarted/staticfiles/js/generated-javascript/CalculatorListener.d9bf18130381.js // Generated from Calculator.g4 by ANTLR 4.7.1 // jshint ignore: start var antlr4 = require('antlr4/index'); // This class defines a complete listener for a parse tree produced by CalculatorParser. function CalculatorListener() { antlr4.tree.ParseTreeListener.call(this); return this; } CalculatorListener.prototype = Object.create(antlr4.tree.ParseTreeListener.prototype); CalculatorListener.prototype.constructor = CalculatorListener; // Enter a parse tree produced by CalculatorParser#start. CalculatorListener.prototype.enterStart = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#start. CalculatorListener.prototype.exitStart = function(ctx) { }; // Enter a parse tree produced by CalculatorParser#relop. CalculatorListener.prototype.enterRelop = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#relop. CalculatorListener.prototype.exitRelop = function(ctx) { }; // Enter a parse tree produced by CalculatorParser#varExpr. CalculatorListener.prototype.enterVarExpr = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#varExpr. CalculatorListener.prototype.exitVarExpr = function(ctx) { }; // Enter a parse tree produced by CalculatorParser#PiExpr. CalculatorListener.prototype.enterPiExpr = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#PiExpr. CalculatorListener.prototype.exitPiExpr = function(ctx) { }; // Enter a parse tree produced by CalculatorParser#opExpr. CalculatorListener.prototype.enterOpExpr = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#opExpr. CalculatorListener.prototype.exitOpExpr = function(ctx) { }; // Enter a parse tree produced by CalculatorParser#trigExpr. CalculatorListener.prototype.enterTrigExpr = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#trigExpr. CalculatorListener.prototype.exitTrigExpr = function(ctx) { }; // Enter a parse tree produced by CalculatorParser#atomExpr. CalculatorListener.prototype.enterAtomExpr = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#atomExpr. CalculatorListener.prototype.exitAtomExpr = function(ctx) { }; // Enter a parse tree produced by CalculatorParser#parenExpr. CalculatorListener.prototype.enterParenExpr = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#parenExpr. CalculatorListener.prototype.exitParenExpr = function(ctx) { }; // Enter a parse tree produced by CalculatorParser#variable. CalculatorListener.prototype.enterVariable = function(ctx) { }; // Exit a parse tree produced by CalculatorParser#variable. CalculatorListener.prototype.exitVariable = function(ctx) { }; exports.CalculatorListener = CalculatorListener;<file_sep>/hello/generated/CalculatorParser.py # Generated from Calculator.g4 by ANTLR 4.7.1 # encoding: utf-8 from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3") buf.write(u"\22+\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\3\2\3\2\3\2\3\2") buf.write(u"\3\2\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4") buf.write(u"\5\4\34\n\4\3\4\3\4\3\4\3\4\3\4\3\4\7\4$\n\4\f\4\16\4") buf.write(u"\'\13\4\3\5\3\5\3\5\2\3\6\6\2\4\6\b\2\5\3\2\f\16\3\2") buf.write(u"\5\7\3\2\b\t\2,\2\n\3\2\2\2\4\17\3\2\2\2\6\33\3\2\2\2") buf.write(u"\b(\3\2\2\2\n\13\5\6\4\2\13\f\5\4\3\2\f\r\5\6\4\2\r\16") buf.write(u"\7\3\2\2\16\3\3\2\2\2\17\20\7\4\2\2\20\5\3\2\2\2\21\22") buf.write(u"\b\4\1\2\22\23\7\n\2\2\23\24\5\6\4\2\24\25\7\13\2\2\25") buf.write(u"\34\3\2\2\2\26\27\t\2\2\2\27\34\5\6\4\6\30\34\7\21\2") buf.write(u"\2\31\34\7\17\2\2\32\34\5\b\5\2\33\21\3\2\2\2\33\26\3") buf.write(u"\2\2\2\33\30\3\2\2\2\33\31\3\2\2\2\33\32\3\2\2\2\34%") buf.write(u"\3\2\2\2\35\36\f\t\2\2\36\37\t\3\2\2\37$\5\6\4\n !\f") buf.write(u"\b\2\2!\"\t\4\2\2\"$\5\6\4\t#\35\3\2\2\2# \3\2\2\2$\'") buf.write(u"\3\2\2\2%#\3\2\2\2%&\3\2\2\2&\7\3\2\2\2\'%\3\2\2\2()") buf.write(u"\7\20\2\2)\t\3\2\2\2\5\33#%") return buf.getvalue() class CalculatorParser ( Parser ): grammarFileName = "Calculator.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ u"<INVALID>", u"';'", u"'='", u"'^'", u"'*'", u"'/'", u"'+'", u"'-'", u"'('", u"')'", u"'cos'", u"'sin'", u"'tan'" ] symbolicNames = [ u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"COS", u"SIN", u"TAN", u"PI", u"VARIABLE", u"INT", u"WS" ] RULE_start = 0 RULE_relop = 1 RULE_expr = 2 RULE_variable = 3 ruleNames = [ u"start", u"relop", u"expr", u"variable" ] EOF = Token.EOF T__0=1 T__1=2 T__2=3 T__3=4 T__4=5 T__5=6 T__6=7 T__7=8 T__8=9 COS=10 SIN=11 TAN=12 PI=13 VARIABLE=14 INT=15 WS=16 def __init__(self, input, output=sys.stdout): super(CalculatorParser, self).__init__(input, output=output) self.checkVersion("4.7.1") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class StartContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(CalculatorParser.StartContext, self).__init__(parent, invokingState) self.parser = parser self.op = None # RelopContext def expr(self, i=None): if i is None: return self.getTypedRuleContexts(CalculatorParser.ExprContext) else: return self.getTypedRuleContext(CalculatorParser.ExprContext,i) def relop(self): return self.getTypedRuleContext(CalculatorParser.RelopContext,0) def getRuleIndex(self): return CalculatorParser.RULE_start def enterRule(self, listener): if hasattr(listener, "enterStart"): listener.enterStart(self) def exitRule(self, listener): if hasattr(listener, "exitStart"): listener.exitStart(self) def accept(self, visitor): if hasattr(visitor, "visitStart"): return visitor.visitStart(self) else: return visitor.visitChildren(self) def start(self): localctx = CalculatorParser.StartContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_start) try: self.enterOuterAlt(localctx, 1) self.state = 8 self.expr(0) self.state = 9 localctx.op = self.relop() self.state = 10 self.expr(0) self.state = 11 self.match(CalculatorParser.T__0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class RelopContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(CalculatorParser.RelopContext, self).__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return CalculatorParser.RULE_relop def enterRule(self, listener): if hasattr(listener, "enterRelop"): listener.enterRelop(self) def exitRule(self, listener): if hasattr(listener, "exitRelop"): listener.exitRelop(self) def accept(self, visitor): if hasattr(visitor, "visitRelop"): return visitor.visitRelop(self) else: return visitor.visitChildren(self) def relop(self): localctx = CalculatorParser.RelopContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_relop) try: self.enterOuterAlt(localctx, 1) self.state = 13 self.match(CalculatorParser.T__1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(CalculatorParser.ExprContext, self).__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return CalculatorParser.RULE_expr def copyFrom(self, ctx): super(CalculatorParser.ExprContext, self).copyFrom(ctx) class VarExprContext(ExprContext): def __init__(self, parser, ctx): # actually a CalculatorParser.ExprContext) super(CalculatorParser.VarExprContext, self).__init__(parser) self.name = None # VariableContext self.copyFrom(ctx) def variable(self): return self.getTypedRuleContext(CalculatorParser.VariableContext,0) def enterRule(self, listener): if hasattr(listener, "enterVarExpr"): listener.enterVarExpr(self) def exitRule(self, listener): if hasattr(listener, "exitVarExpr"): listener.exitVarExpr(self) def accept(self, visitor): if hasattr(visitor, "visitVarExpr"): return visitor.visitVarExpr(self) else: return visitor.visitChildren(self) class PiExprContext(ExprContext): def __init__(self, parser, ctx): # actually a CalculatorParser.ExprContext) super(CalculatorParser.PiExprContext, self).__init__(parser) self.copyFrom(ctx) def PI(self): return self.getToken(CalculatorParser.PI, 0) def enterRule(self, listener): if hasattr(listener, "enterPiExpr"): listener.enterPiExpr(self) def exitRule(self, listener): if hasattr(listener, "exitPiExpr"): listener.exitPiExpr(self) def accept(self, visitor): if hasattr(visitor, "visitPiExpr"): return visitor.visitPiExpr(self) else: return visitor.visitChildren(self) class OpExprContext(ExprContext): def __init__(self, parser, ctx): # actually a CalculatorParser.ExprContext) super(CalculatorParser.OpExprContext, self).__init__(parser) self.left = None # ExprContext self.op = None # Token self.right = None # ExprContext self.copyFrom(ctx) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(CalculatorParser.ExprContext) else: return self.getTypedRuleContext(CalculatorParser.ExprContext,i) def enterRule(self, listener): if hasattr(listener, "enterOpExpr"): listener.enterOpExpr(self) def exitRule(self, listener): if hasattr(listener, "exitOpExpr"): listener.exitOpExpr(self) def accept(self, visitor): if hasattr(visitor, "visitOpExpr"): return visitor.visitOpExpr(self) else: return visitor.visitChildren(self) class TrigExprContext(ExprContext): def __init__(self, parser, ctx): # actually a CalculatorParser.ExprContext) super(CalculatorParser.TrigExprContext, self).__init__(parser) self.op = None # Token self.right = None # ExprContext self.copyFrom(ctx) def expr(self): return self.getTypedRuleContext(CalculatorParser.ExprContext,0) def COS(self): return self.getToken(CalculatorParser.COS, 0) def SIN(self): return self.getToken(CalculatorParser.SIN, 0) def TAN(self): return self.getToken(CalculatorParser.TAN, 0) def enterRule(self, listener): if hasattr(listener, "enterTrigExpr"): listener.enterTrigExpr(self) def exitRule(self, listener): if hasattr(listener, "exitTrigExpr"): listener.exitTrigExpr(self) def accept(self, visitor): if hasattr(visitor, "visitTrigExpr"): return visitor.visitTrigExpr(self) else: return visitor.visitChildren(self) class AtomExprContext(ExprContext): def __init__(self, parser, ctx): # actually a CalculatorParser.ExprContext) super(CalculatorParser.AtomExprContext, self).__init__(parser) self.atom = None # Token self.copyFrom(ctx) def INT(self): return self.getToken(CalculatorParser.INT, 0) def enterRule(self, listener): if hasattr(listener, "enterAtomExpr"): listener.enterAtomExpr(self) def exitRule(self, listener): if hasattr(listener, "exitAtomExpr"): listener.exitAtomExpr(self) def accept(self, visitor): if hasattr(visitor, "visitAtomExpr"): return visitor.visitAtomExpr(self) else: return visitor.visitChildren(self) class ParenExprContext(ExprContext): def __init__(self, parser, ctx): # actually a CalculatorParser.ExprContext) super(CalculatorParser.ParenExprContext, self).__init__(parser) self.copyFrom(ctx) def expr(self): return self.getTypedRuleContext(CalculatorParser.ExprContext,0) def enterRule(self, listener): if hasattr(listener, "enterParenExpr"): listener.enterParenExpr(self) def exitRule(self, listener): if hasattr(listener, "exitParenExpr"): listener.exitParenExpr(self) def accept(self, visitor): if hasattr(visitor, "visitParenExpr"): return visitor.visitParenExpr(self) else: return visitor.visitChildren(self) def expr(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = CalculatorParser.ExprContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 4 self.enterRecursionRule(localctx, 4, self.RULE_expr, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 25 self._errHandler.sync(self) token = self._input.LA(1) if token in [CalculatorParser.T__7]: localctx = CalculatorParser.ParenExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 16 self.match(CalculatorParser.T__7) self.state = 17 self.expr(0) self.state = 18 self.match(CalculatorParser.T__8) pass elif token in [CalculatorParser.COS, CalculatorParser.SIN, CalculatorParser.TAN]: localctx = CalculatorParser.TrigExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 20 localctx.op = self._input.LT(1) _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CalculatorParser.COS) | (1 << CalculatorParser.SIN) | (1 << CalculatorParser.TAN))) != 0)): localctx.op = self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 21 localctx.right = self.expr(4) pass elif token in [CalculatorParser.INT]: localctx = CalculatorParser.AtomExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 22 localctx.atom = self.match(CalculatorParser.INT) pass elif token in [CalculatorParser.PI]: localctx = CalculatorParser.PiExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 23 self.match(CalculatorParser.PI) pass elif token in [CalculatorParser.VARIABLE]: localctx = CalculatorParser.VarExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 24 localctx.name = self.variable() pass else: raise NoViableAltException(self) self._ctx.stop = self._input.LT(-1) self.state = 35 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx self.state = 33 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,1,self._ctx) if la_ == 1: localctx = CalculatorParser.OpExprContext(self, CalculatorParser.ExprContext(self, _parentctx, _parentState)) localctx.left = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 27 if not self.precpred(self._ctx, 7): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 7)") self.state = 28 localctx.op = self._input.LT(1) _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CalculatorParser.T__2) | (1 << CalculatorParser.T__3) | (1 << CalculatorParser.T__4))) != 0)): localctx.op = self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 29 localctx.right = self.expr(8) pass elif la_ == 2: localctx = CalculatorParser.OpExprContext(self, CalculatorParser.ExprContext(self, _parentctx, _parentState)) localctx.left = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 30 if not self.precpred(self._ctx, 6): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 6)") self.state = 31 localctx.op = self._input.LT(1) _la = self._input.LA(1) if not(_la==CalculatorParser.T__5 or _la==CalculatorParser.T__6): localctx.op = self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 32 localctx.right = self.expr(7) pass self.state = 37 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class VariableContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(CalculatorParser.VariableContext, self).__init__(parent, invokingState) self.parser = parser def VARIABLE(self): return self.getToken(CalculatorParser.VARIABLE, 0) def getRuleIndex(self): return CalculatorParser.RULE_variable def enterRule(self, listener): if hasattr(listener, "enterVariable"): listener.enterVariable(self) def exitRule(self, listener): if hasattr(listener, "exitVariable"): listener.exitVariable(self) def accept(self, visitor): if hasattr(visitor, "visitVariable"): return visitor.visitVariable(self) else: return visitor.visitChildren(self) def variable(self): localctx = CalculatorParser.VariableContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_variable) try: self.enterOuterAlt(localctx, 1) self.state = 38 self.match(CalculatorParser.VARIABLE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx def sempred(self, localctx, ruleIndex, predIndex): if self._predicates == None: self._predicates = dict() self._predicates[2] = self.expr_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def expr_sempred(self, localctx, predIndex): if predIndex == 0: return self.precpred(self._ctx, 7) if predIndex == 1: return self.precpred(self._ctx, 6) <file_sep>/gettingstarted/staticfiles/js/generated-javascript/CalculatorLexer.js // Generated from Calculator.g4 by ANTLR 4.7.1 // jshint ignore: start var antlr4 = require('antlr4/index'); var serializedATN = ["\u0003\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964", "\u0002\u0012k\b\u0001\u0004\u0002\t\u0002\u0004\u0003\t\u0003\u0004", "\u0004\t\u0004\u0004\u0005\t\u0005\u0004\u0006\t\u0006\u0004\u0007\t", "\u0007\u0004\b\t\b\u0004\t\t\t\u0004\n\t\n\u0004\u000b\t\u000b\u0004", "\f\t\f\u0004\r\t\r\u0004\u000e\t\u000e\u0004\u000f\t\u000f\u0004\u0010", "\t\u0010\u0004\u0011\t\u0011\u0004\u0012\t\u0012\u0004\u0013\t\u0013", "\u0003\u0002\u0003\u0002\u0003\u0003\u0003\u0003\u0003\u0004\u0003\u0004", "\u0003\u0005\u0003\u0005\u0003\u0006\u0003\u0006\u0003\u0007\u0003\u0007", "\u0003\b\u0003\b\u0003\t\u0003\t\u0003\n\u0003\n\u0003\u000b\u0003\u000b", "\u0003\u000b\u0003\u000b\u0003\f\u0003\f\u0003\f\u0003\f\u0003\r\u0003", "\r\u0003\r\u0003\r\u0003\u000e\u0003\u000e\u0003\u000e\u0003\u000f\u0003", "\u000f\u0007\u000fK\n\u000f\f\u000f\u000e\u000fN\u000b\u000f\u0003\u0010", "\u0005\u0010Q\n\u0010\u0003\u0011\u0003\u0011\u0005\u0011U\n\u0011\u0003", "\u0012\u0006\u0012X\n\u0012\r\u0012\u000e\u0012Y\u0003\u0012\u0005\u0012", "]\n\u0012\u0003\u0012\u0007\u0012`\n\u0012\f\u0012\u000e\u0012c\u000b", "\u0012\u0003\u0013\u0006\u0013f\n\u0013\r\u0013\u000e\u0013g\u0003\u0013", "\u0003\u0013\u0002\u0002\u0014\u0003\u0003\u0005\u0004\u0007\u0005\t", "\u0006\u000b\u0007\r\b\u000f\t\u0011\n\u0013\u000b\u0015\f\u0017\r\u0019", "\u000e\u001b\u000f\u001d\u0010\u001f\u0002!\u0002#\u0011%\u0012\u0003", "\u0002\u0006\u0004\u0002RRrr\u0004\u0002KKkk\u0005\u0002C\\aac|\u0005", "\u0002\u000b\f\u000f\u000f\"\"\u0002n\u0002\u0003\u0003\u0002\u0002", "\u0002\u0002\u0005\u0003\u0002\u0002\u0002\u0002\u0007\u0003\u0002\u0002", "\u0002\u0002\t\u0003\u0002\u0002\u0002\u0002\u000b\u0003\u0002\u0002", "\u0002\u0002\r\u0003\u0002\u0002\u0002\u0002\u000f\u0003\u0002\u0002", "\u0002\u0002\u0011\u0003\u0002\u0002\u0002\u0002\u0013\u0003\u0002\u0002", "\u0002\u0002\u0015\u0003\u0002\u0002\u0002\u0002\u0017\u0003\u0002\u0002", "\u0002\u0002\u0019\u0003\u0002\u0002\u0002\u0002\u001b\u0003\u0002\u0002", "\u0002\u0002\u001d\u0003\u0002\u0002\u0002\u0002#\u0003\u0002\u0002", "\u0002\u0002%\u0003\u0002\u0002\u0002\u0003\'\u0003\u0002\u0002\u0002", "\u0005)\u0003\u0002\u0002\u0002\u0007+\u0003\u0002\u0002\u0002\t-\u0003", "\u0002\u0002\u0002\u000b/\u0003\u0002\u0002\u0002\r1\u0003\u0002\u0002", "\u0002\u000f3\u0003\u0002\u0002\u0002\u00115\u0003\u0002\u0002\u0002", "\u00137\u0003\u0002\u0002\u0002\u00159\u0003\u0002\u0002\u0002\u0017", "=\u0003\u0002\u0002\u0002\u0019A\u0003\u0002\u0002\u0002\u001bE\u0003", "\u0002\u0002\u0002\u001dH\u0003\u0002\u0002\u0002\u001fP\u0003\u0002", "\u0002\u0002!T\u0003\u0002\u0002\u0002#W\u0003\u0002\u0002\u0002%e\u0003", "\u0002\u0002\u0002\'(\u0007=\u0002\u0002(\u0004\u0003\u0002\u0002\u0002", ")*\u0007?\u0002\u0002*\u0006\u0003\u0002\u0002\u0002+,\u0007`\u0002", "\u0002,\b\u0003\u0002\u0002\u0002-.\u0007,\u0002\u0002.\n\u0003\u0002", "\u0002\u0002/0\u00071\u0002\u00020\f\u0003\u0002\u0002\u000212\u0007", "-\u0002\u00022\u000e\u0003\u0002\u0002\u000234\u0007/\u0002\u00024\u0010", "\u0003\u0002\u0002\u000256\u0007*\u0002\u00026\u0012\u0003\u0002\u0002", "\u000278\u0007+\u0002\u00028\u0014\u0003\u0002\u0002\u00029:\u0007e", "\u0002\u0002:;\u0007q\u0002\u0002;<\u0007u\u0002\u0002<\u0016\u0003", "\u0002\u0002\u0002=>\u0007u\u0002\u0002>?\u0007k\u0002\u0002?@\u0007", "p\u0002\u0002@\u0018\u0003\u0002\u0002\u0002AB\u0007v\u0002\u0002BC", "\u0007c\u0002\u0002CD\u0007p\u0002\u0002D\u001a\u0003\u0002\u0002\u0002", "EF\t\u0002\u0002\u0002FG\t\u0003\u0002\u0002G\u001c\u0003\u0002\u0002", "\u0002HL\u0005\u001f\u0010\u0002IK\u0005!\u0011\u0002JI\u0003\u0002", "\u0002\u0002KN\u0003\u0002\u0002\u0002LJ\u0003\u0002\u0002\u0002LM\u0003", "\u0002\u0002\u0002M\u001e\u0003\u0002\u0002\u0002NL\u0003\u0002\u0002", "\u0002OQ\t\u0004\u0002\u0002PO\u0003\u0002\u0002\u0002Q \u0003\u0002", "\u0002\u0002RU\u0005\u001f\u0010\u0002SU\u00042;\u0002TR\u0003\u0002", "\u0002\u0002TS\u0003\u0002\u0002\u0002U\"\u0003\u0002\u0002\u0002VX", "\u00042;\u0002WV\u0003\u0002\u0002\u0002XY\u0003\u0002\u0002\u0002Y", "W\u0003\u0002\u0002\u0002YZ\u0003\u0002\u0002\u0002Z\\\u0003\u0002\u0002", "\u0002[]\u00070\u0002\u0002\\[\u0003\u0002\u0002\u0002\\]\u0003\u0002", "\u0002\u0002]a\u0003\u0002\u0002\u0002^`\u00042;\u0002_^\u0003\u0002", "\u0002\u0002`c\u0003\u0002\u0002\u0002a_\u0003\u0002\u0002\u0002ab\u0003", "\u0002\u0002\u0002b$\u0003\u0002\u0002\u0002ca\u0003\u0002\u0002\u0002", "df\t\u0005\u0002\u0002ed\u0003\u0002\u0002\u0002fg\u0003\u0002\u0002", "\u0002ge\u0003\u0002\u0002\u0002gh\u0003\u0002\u0002\u0002hi\u0003\u0002", "\u0002\u0002ij\b\u0013\u0002\u0002j&\u0003\u0002\u0002\u0002\n\u0002", "LPTY\\ag\u0003\b\u0002\u0002"].join(""); var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN); var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); }); function CalculatorLexer(input) { antlr4.Lexer.call(this, input); this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache()); return this; } CalculatorLexer.prototype = Object.create(antlr4.Lexer.prototype); CalculatorLexer.prototype.constructor = CalculatorLexer; Object.defineProperty(CalculatorLexer.prototype, "atn", { get : function() { return atn; } }); CalculatorLexer.EOF = antlr4.Token.EOF; CalculatorLexer.T__0 = 1; CalculatorLexer.T__1 = 2; CalculatorLexer.T__2 = 3; CalculatorLexer.T__3 = 4; CalculatorLexer.T__4 = 5; CalculatorLexer.T__5 = 6; CalculatorLexer.T__6 = 7; CalculatorLexer.T__7 = 8; CalculatorLexer.T__8 = 9; CalculatorLexer.COS = 10; CalculatorLexer.SIN = 11; CalculatorLexer.TAN = 12; CalculatorLexer.PI = 13; CalculatorLexer.VARIABLE = 14; CalculatorLexer.INT = 15; CalculatorLexer.WS = 16; CalculatorLexer.prototype.channelNames = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" ]; CalculatorLexer.prototype.modeNames = [ "DEFAULT_MODE" ]; CalculatorLexer.prototype.literalNames = [ null, "';'", "'='", "'^'", "'*'", "'/'", "'+'", "'-'", "'('", "')'", "'cos'", "'sin'", "'tan'" ]; CalculatorLexer.prototype.symbolicNames = [ null, null, null, null, null, null, null, null, null, null, "COS", "SIN", "TAN", "PI", "VARIABLE", "INT", "WS" ]; CalculatorLexer.prototype.ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8", "COS", "SIN", "TAN", "PI", "VARIABLE", "VALID_ID_START", "VALID_ID_CHAR", "INT", "WS" ]; CalculatorLexer.prototype.grammarFileName = "Calculator.g4"; exports.CalculatorLexer = CalculatorLexer; <file_sep>/requirements.txt dj-database-url==0.4.0 Django==1.9.2 gunicorn==19.4.5 psycopg2==2.7.1 whitenoise==2.0.6 pytz==2016.4 <file_sep>/hello/calculator/ErrorListenerFile.py ''' Created on Jun 27, 2016 @author: t0007330 ''' from antlr4.error.ErrorListener import ErrorListener class ThrowingErrorListener(ErrorListener): errorsList = [] def __init__(self): self.errorsList = [] def getErrorsList(self): return self.errorsList def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e): errorMsg = 'syntaxError - symbol= {offendingSymbol}'.format(offendingSymbol=offendingSymbol) errorMsg += ' - line= {line}'.format(line=line) errorMsg += ' : {column}'.format(column=column) errorMsg += ' {msg}'.format(msg=msg) self.errorsList.append(errorMsg) # def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs): # errorMsg = 'report Ambiguity dfa= {dfa}'.format(dfa=str(dfa)[:50]) # errorMsg += ' - startIndex= {startIndex}'.format(startIndex=startIndex) # errorMsg += ' : {stopIndex}'.format(stopIndex=stopIndex) # errorMsg += ' {exact}'.format(exact=exact) # self.errorsList.append(errorMsg) # def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs): # errorMsg = 'report AttemptingFullContext dfa= {dfa}'.format(dfa=dfa) # errorMsg += ' - startIndex= {startIndex}'.format(startIndex=startIndex) # errorMsg += ' : {stopIndex}'.format(stopIndex=stopIndex) # errorMsg += ' {conflictingAlts}'.format(conflictingAlts=conflictingAlts) # self.errorsList.append(errorMsg) # def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs): # errorMsg = 'report Context Sensitivity dfa= {dfa}'.format(dfa=dfa) # errorMsg += ' - startIndex= {startIndex}'.format(startIndex=startIndex) # errorMsg += ' : {stopIndex}'.format(stopIndex=stopIndex) # errorMsg += ' {prediction}'.format(prediction=prediction) # self.errorsList.append(errorMsg)<file_sep>/hello/views.py from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from hello.models import Greeting encoding = 'utf-8' import json from antlr4 import InputStream from antlr4 import CommonTokenStream from hello.generated.CalculatorLexer import CalculatorLexer from hello.generated.CalculatorParser import CalculatorParser from hello.calculator.ExtendedVisitorFile import ExtendedVisitor from hello.calculator.TreesSubClassFile import SubTrees # Create your views here. def index(request): # return HttpResponse('Hello from Python!') return render(request, 'index.html') def db(request): greeting = Greeting() greeting.save() greetings = Greeting.objects.all() return render(request, 'db.html', {'greetings': greetings}) @csrf_exempt def compute(request): print 'calculator compute = {user}'.format(user=request.user) if request.method == 'POST': print 'method is POST {0}'.format(request.POST) ''' results and histories are dictionnaries with results for each variable ''' results = dict() histories = dict() jsonDumps = dict() try: expression = request.POST['data'] arraySplit = str(expression).strip().split(';'); for index in range(len(arraySplit)-1): #print index #print '=============== ' statement = str(arraySplit[index]).strip() statement = statement + ';' statement = str(statement).strip() print ' =========== {statement} ==============='.format(statement=statement) print 'index = {index} - expression= {statement}'.format(index=index, statement=statement) if (statement != ';'): #print 'received line to compute= ' + line inputStream = InputStream(statement) lexer = CalculatorLexer(inputStream) commonTokenStream = CommonTokenStream(lexer) parser = CalculatorParser(commonTokenStream) tree = parser.start() extendedVisitor = ExtendedVisitor() extendedVisitor.visit(tree) variable = extendedVisitor.getFirstVariable() result = extendedVisitor.getValue(variable) results[str(variable)] = result ''' build a json output that will be converted with library d3 in a tree ''' subTree = SubTrees() obj = dict() obj = subTree.toJson(obj=obj, t=tree, ruleNames=None, recog=parser) print json.dumps(obj) jsonDumps[str(variable)] = json.dumps(obj) ''' define an history table for each variable ''' histories[str(variable)] = [] print 'statement=> {statement} - variable=> {variable} - result=> {result}'.format(statement=statement, variable=variable, result=result) for history in extendedVisitor.getHistories(): histories[str(variable)].append(history); ok = True response_data = { 'ok': ok, 'results' : results, 'histories': histories, 'jsonDumps': jsonDumps, 'exception': "" } except Exception as ex: print 'views - compute - exception= {ex}'.format(ex=ex) ok = False response_data = { 'ok': ok, 'results' : {}, 'histories': {}, 'jsonDumps': {}, 'exception': str(ex) } return HttpResponse(json.dumps(response_data, encoding=encoding), content_type="application/json") <file_sep>/hello/calculator/TreesSubClassFile.py ''' Created on 21 janv. 2018 @author: <NAME> ''' from io import StringIO from antlr4.tree.Trees import Trees from antlr4.Utils import escapeWhitespace class SubTrees(Trees): @classmethod def toJson(cls, obj, t, ruleNames=None, recog=None): if recog is not None: ruleNames = recog.ruleNames s = escapeWhitespace(cls.getNodeText(t, ruleNames), False) #print s if t.getChildCount()==0: return {"name": s} with StringIO() as buf: buf.write(u"(") obj = dict() obj['name'] = s obj['children'] = [] #buf.write(s) #buf.write(u' ') for i in range(0, t.getChildCount()): if i > 0: pass #buf.write(u' ') #print t.getChildCount() #buf.write(listElements) obj['children'].append(cls.toJson(obj, t.getChild(i), ruleNames)) #buf.write(u")") #return buf.getvalue() return (obj)<file_sep>/README.md # Integrating antlr4, the ace web editor, d3 in Django January 2018 ## Overview For a language dedicated editor, the state of art is to combine syntax highlighting, syntax and semantic checks. In this development we want to have all three features available at the same time for instance in a browser. Coupled to an additional code completion capability and our editor would be the smartest tool to use on a daily basis. ## What is it about? The overall purpose of the tool is to propose a basic algebraic calculator. We will describe later the minimal features of this implementation but one key requirement would allow for this tool to return results and more over return the sequence of intermediate commutations in order for the student to understand precedence between the main additive and multiplicative operations. Another nice feature would be to show to the end user the abstract Syntax tree (as a representation of the input expression) as a way to visualize its algebraic expression, taking into account the effect of braces or the results of applying operators precedence. ## Who is our end user? The very first end user is an undergraduate student facing difficulties while understanding and solving complex algebraic expressions. See https://en.m.wikipedia.org/wiki/Algebraic_expression ## Goal Provide a minimal web application which could be deployed for instance in heroku https://www.heroku.com and hence be accessible over the internet. ## Credits - Reference Post The base for this post and the relevant code development was inspired by the following post: https://github.com/antlr/antlr4/blob/master/doc/ace-javascript-target.md ## Ace Front End Ace https://ace.c9.io/ is a high performance code editor. Ace has a large base of supported language such as JavaScript, html, CSS and more. Ace is written in JavaScript and hence integrates straight within a browser. Ace has token highlighting features, syntax checks and more such code folding... Ace needs a theme for its cosmetics and a so called “mode” to manage all the syntax highlighting and the annotations (error messages) provided to the user. The “mode” interacts with a “worker”. This worker runs in its own environment. The worker is independent of the user input loop running. As described in the reference post, the antlr4 part lies in the worker environment. The following picture is taken from the reference post. ![Ace-Architecture](https://github.com/RobertPastor/calculator/blob/master/hello/static/images/Ace-architecture.png) ## Web Framework We chose to work with Django https://www.djangoproject.com/ as we did already deploy a Django website within heroku. Until now our Django site doesn't have any models and hence a lighter solution should suffice. The server side covers only the computation part (providing computation results). It could be extended to provide a graphical view of an algebraic expression as the one provided by the antlr4 test-rig (alias grun). ## Worker and antlr4 Integration Antlr4 has various targets. In this development, we used both a python 2 target for the Django view (on the server side) and a JavaScript target for the part of the worker responsible for sending annotations to the ace "mode". We started with the latest JavaScript worker and as described in the reference post, we modified the OnUpdate function to allow our JavaScript antlr4 instance to retrieve syntax check messages. In order to integrate the antlr4 code (with the worker) we need a module loader feature compatible with the one expected by antlr4. We used the Smoothie module loader available from here: https://github.com/letorbi/smoothie/blob/master/standalone/require.js All recurrent logic, such as running the lexer and spending annotations is bound in the OnUpdate function of the worker. The initialization part, the one responsible for loading dynamically the antlr4 environment, is added to the worker and triggered once. ## Antlr4 initialization within the worker The following code is the antlr4 initialization code that sits inside the worker. It is called once at worker initialization. In the following code, please note that the initialization function is self-invoking. It will be run only once at startup. We use the requirePath feature of the Smoothie require module loader to take into account our static javascript folder in the code tree. Finally we use the window.location.origin to get the site http address. This should retrieve either with the localhost and inside the target heroku server. ``` var antlr4; var CalculatorLanguage; var AnnotatingListener; var AnnotatingConsoleListener; var ace_require; // self invoking antlr4 initialisation function (function () { console.log('init antlr4'); try { ace_require = require; window.require = undefined; //console.log('worker - validate - require is now undefined '); //console.log('window location origin= ' + window.location.origin); window.Smoothie = { 'requirePath': ['/static/js/'] }; // using import scripts : please provide the full path importScripts(window.location.origin + "/static/js/smoothie-require.js"); //console.log('worker -- init -- require for antlr4 is loaded'); antlr4 = window.require('antlr4/index'); //console.log('worker -- init -- antlr4 is loaded'); CalculatorLanguage = window.require("generated-javascript/index"); //console.log('worker -- init -- generated javascript calculator index loaded'); // this is the lexer error listener AnnotatingListener = window.require("annotating-error-listener"); //console.log('worker -- init -- annotating error listener loaded'); // this is the parser error listener AnnotatingConsoleListener = window.require("annotating-console-error-listener"); //console.log('worker -- init -- annotating console error listener loaded'); } catch (e) { console.log('worker -- init -- error= ' + String(e)); } finally { require = ace_require; } } )(); ``` ## Antlr4 annotations generation within the worker The following code shows the modifications made to the OnUpdate function of the worker. Please note the two error listeners, one attached to the lexer and one attached to the parser. ``` this.onUpdate = function() { var value = this.doc.getValue(); value = value.replace(/^#!.*\n/, "\n"); if (!value) { return this.sender.emit("annotate", []); } var stream = antlr4.CharStreams.fromString(value); //console.log('worker -- stream initialized'); var lexer = new CalculatorLanguage.CalculatorLexer(stream); //console.log('worker -- Calculator Lexer initialized'); var tokens = new antlr4.CommonTokenStream(lexer); //console.log ('worker -- validate -- Token Stream ready'); var parser = new CalculatorLanguage.CalculatorParser(tokens); var lexerAnnotations = []; var parserAnnotations = []; var lexerListener = new AnnotatingListener.AnnotatingErrorListener(lexerAnnotations); var parserListener = new AnnotatingConsoleListener.AnnotatingConsoleErrorListener(parserAnnotations); // need to remove previous listener otherwise they will be still active lexer.removeErrorListeners(); lexer.addErrorListener(lexerListener) parser.removeErrorListeners(); parser.addErrorListener(parserListener); // start is the main entry rule of the grammar parser.start(); // group annotations var annotations = []; lexerAnnotations.forEach( function (annotation) { //console.log(annotation); annotations.push(annotation); }); parserAnnotations.forEach( function (annotation) { //console.log(annotation); annotations.push(annotation); }); // send annotations from the worker back to the mode this.sender.emit("annotate", annotations); }; ``` ## Antlr4 and Django integration One would be confused by having both antlr4 JavaScript code generated from the grammar (running in the browser and tightly coupled with the ace worker) and antlr4 python code generated by the same grammar and computing the end results of an algebraic expression in the Django server. Warning: inside our Django code tree, please note that the antlr4 python target code must be at the higher python package level. This python target code must have the same version as the antlr4 jar code used to generate the code from the grammar. This is done to avoid a strange incompatibility error raised by antlr4 when it is comparing both embedded versions. ![code-tree](https://github.com/RobertPastor/calculator/blob/master/hello/static/images/Calculator-Code-Tree.png) ## Antlr4 Grammar The grammar is able to cope with multiple expressions. The antlr4 visitor code closes the gap between these expressions and reports the result of a variable in one expression to the next expression. ``` grammar Calculator; start : expr op=relop expr ';'; relop : '=' | '>' | '<'; expr : left=expr op=('^'|'*'|'/') right=expr #opExpr | left=expr op=('+'|'-') right=expr #opExpr | '(' expr ')' #parenExpr | op=(COS|SIN|TAN) right=expr #trigExpr | atom=INT #atomExpr | PI #PiExpr | name=variable #varExpr ; COS : 'cos'; SIN : 'sin'; TAN : 'tan'; PI : [Pp][Ii]; variable : VARIABLE; VARIABLE : VALID_ID_START VALID_ID_CHAR* ; fragment VALID_ID_START : ('a' .. 'z') | ('A' .. 'Z') | '_' ; fragment VALID_ID_CHAR : VALID_ID_START | ('0' .. '9') ; INT : ('0'..'9')+ ('.')? ('0'..'9')* ; WS : [ \t\r\n]+ -> skip ; ``` ## Examples of Lexer and Parser Annotations Annotations appear in the ace "gutter". The annotation text pops up when the user move the mouse over the annotation in the gutter. ![parser-error](https://github.com/RobertPastor/calculator/blob/master/hello/static/images/parser-error.png) ![lexer-error](https://github.com/RobertPastor/calculator/blob/master/hello/static/images/lexer-error.png) ![token-error](https://github.com/RobertPastor/calculator/blob/master/hello/static/images/token-recognition-error.png) ## Regressions Testing In order to verify non regression, there is a folder dedicated to unit tests files, a Main python module to test one grammar pattern and a MainAll module to run all the test files. These regression tests have to be run each time the grammar is changed. An improvement would be to define the expected results. ## Calculator Visitor The visitor aims at returning both intermediate results obtained when parsing an operator and final results as the results of the assignment operator. In order to deal with several expressions, the variables are stored in a python dictionary with the name of the variable as a key and the result as the value. ## A syntax tree The following tree is generated using the d3 library https://github.com/d3/d3 The antlr4 Trees toStringTree function has been derived to produce a JSON object with names and children as expected by d3. The tree represents the following statement: y = (3.1 * 9.2) + (5.5 / 7.2) ; ![syntaxtree](https://github.com/RobertPastor/calculator/blob/master/hello/static/images/d3.org.syntaxTree.png) ## Deployment on Heroku see the application deployed on heroku (free restricted dyno). https://algebraic-calculator.herokuapp.com/ ## Github code branch The code available in github https://github.com/RobertPastor/calculator/ . It has following dependencies: Python version is 2.7.7 Django version is 1.9.3 Ace version is 1.2.9 Smoothie require version is … Antlr4 version is 4.7.1 If one would start again from scratch from the getting started Django code provided as an example by heroku, he would have to change little code to make it work again. ## Documentation For more information about using Python on Heroku, see these Dev Center articles: - [Python on Heroku](https://devcenter.heroku.com/categories/python)
f3d7745c26823447992482a8b8b80dde7b2f234f
[ "JavaScript", "Python", "Text", "Markdown" ]
17
Python
RobertPastor/calculator
59ad441455c8540c2099e09fed1bada876cca9db
0066bf190c0c3b0c3c3d5ae0380b75a81455a239
refs/heads/master
<repo_name>Miroku87/reboot-docker<file_sep>/client/app/scripts/controllers/LiveEventsManager.js /** * Created by Miroku on 11/03/2018. */ var LiveEventsManager = function () { return { init: function () { window.localStorage.removeItem("evento_mod_id"); this.setListeners(); this.recuperaInfoUtente(); this.recuperaUltimoEvento(); this.impostaTabellaPgIscritti("prossimo"); this.impostaTabellaPgIscritti("precedente"); this.impostaTabellaEventiPreparati(); }, mostraModalIscrizione: function () { EventSigning.showModal(); }, disiscriviPg: function (evid, pgid, quando) { Utils.requestData( Constants.API_POST_DISISCRIZIONE, "POST", { evid: evid, pgid: pgid }, "Personaggio disiscritto con successo.", null, this["pg_" + quando].ajax.reload.bind(this, null, false) ); }, confermaDisiscriviPg: function (e) { var t = $(e.target); Utils.showConfirm("Vuoi veramente disiscrivere <strong>" + t.attr("data-nome") + "</strong>?", this.disiscriviPg.bind(this, t.attr("data-evid"), t.attr("data-id"), t.attr("data-quando"))); }, inviaModificaNoteIscrizione: function (id, evid, quando, e) { Utils.requestData( Constants.API_POST_EDIT_ISCRIZIONE, "POST", { evid: evid, pgid: id, modifiche: { note_iscrizione: $("#modal_note_iscrizione").find("#note_iscrizione").val() } }, "Note modificate con successo.", null, function () { Utils.resetSubmitBtn(); this["pg_" + quando].ajax.reload(null, true); }.bind(this) ); }, mostraModalNoteIscrizione: function (evid, pgid, quando, nomepg, nomegioc, data) { $("#modal_note_iscrizione").find("#nome_pg").text(nomepg); $("#modal_note_iscrizione").find("#nome_giocatore").text(nomegioc); $("#modal_note_iscrizione").find("#note_iscrizione").val(data.result); $("#modal_note_iscrizione").find("#btn_invia_mods").unbind("click", this.inviaModificaNoteIscrizione.bind(this)); $("#modal_note_iscrizione").find("#btn_invia_mods").click(this.inviaModificaNoteIscrizione.bind(this, pgid, evid, quando)); $("#modal_note_iscrizione").modal({ drop: "static" }); }, recuperaVecchieNoteIscrizione: function (e) { var t = $(e.target); Utils.requestData( Constants.API_GET_NOTE_ISCRITTO, "GET", { id_ev: t.attr("data-evid"), id_pg: t.attr("data-id") }, this.mostraModalNoteIscrizione.bind(this, t.attr("data-evid"), t.attr("data-id"), t.attr("data-quando"), t.attr("data-nome"), t.attr("data-utente")) ); }, modificaPagataIscrizione: function (e) { var t = $(e.target); t.attr("disabled", true); Utils.requestData( Constants.API_POST_EDIT_ISCRIZIONE, "POST", { evid: t.attr("data-evid"), pgid: t.attr("data-id"), mods: { pagato_iscrizione: t.is(":checked") ? 1 : 0 } }, function () { t.attr("disabled", false); this["pg_" + t.attr("data-quando")].ajax.reload(null, false); }.bind(this) ); }, modificaPartecipazione: function (e) { var t = $(e.target); t.attr("disabled", true); Utils.requestData( Constants.API_POST_EDIT_ISCRIZIONE, "POST", { evid: t.attr("data-evid"), pgid: t.attr("data-id"), mods: { ha_partecipato_iscrizione: t.is(":checked") ? 1 : 0 } }, function () { t.attr("disabled", false); this["pg_" + t.attr("data-quando")].ajax.reload(null, false); }.bind(this) ); }, creaCheckBoxPagato: function (data, type, row) { var checked = data === "1" ? "checked" : "", checkbox = "<div class='checkbox icheck'>" + "<input type='checkbox' " + "class='inizialmente-nascosto modificaIscrizionePG_pagato_iscrizione_proprio modificaIscrizionePG_pagato_iscrizione_altri' " + "data-id='" + row.personaggi_id_personaggio + "' " + "data-evid='" + row.id_evento + "' " + "data-quando='" + row.quando + "' " + "" + checked + ">" + "</div>", pagato = data === "1" ? "S&igrave;" : "No", output = Utils.controllaPermessiUtente(this.user_info, ["modificaIscrizionePG_pagato_iscrizione_proprio", "modificaIscrizionePG_pagato_iscrizione_altri"]) ? checkbox : pagato; return output; }, creaCheckBoxPartecipazione: function (data, type, row) { var checked = data === "1" ? "checked" : "", checkbox = "<div class='checkbox icheck'>" + "<input type='checkbox' " + "class='inizialmente-nascosto modificaIscrizionePG_ha_partecipato_iscrizione_altri' " + "data-id='" + row.personaggi_id_personaggio + "' " + "data-evid='" + row.id_evento + "' " + "data-quando='" + row.quando + "' " + "" + checked + ">" + "</div>", pagato = data === "1" ? "S&igrave;" : "No", output = Utils.controllaPermessiUtente(this.user_info, ["modificaIscrizionePG_ha_partecipato_iscrizione_altri"]) ? checkbox : pagato; return output; }, renderAzioniPgIscritti: function (data, type, row) { var pulsanti = ""; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto modificaIscrizionePG_note_iscrizione_proprio modificaIscrizionePG_note_iscrizione_altri' " + "data-id='" + row.personaggi_id_personaggio + "' " + "data-evid='" + row.id_evento + "' " + "data-nome='" + row.nome_personaggio + "' " + "data-utente='" + row.nome_completo + "' " + "data-quando='" + row.quando + "' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Modifica Note'><i class='fa fa-pencil'></i></button>"; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto disiscriviPG_altri disiscriviPG_proprio' " + "data-id='" + row.personaggi_id_personaggio + "' " + "data-evid='" + row.id_evento + "' " + "data-nome='" + row.nome_personaggio + "' " + "data-quando='" + row.quando + "' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Disiscrivi PG'><i class='fa fa-remove'></i></button>"; return pulsanti; }, setPGTableListeners: function (quando) { AdminLTEManager.controllaPermessi(); $('#pg_' + quando).find("td [data-toggle='tooltip']").tooltip("destroy"); $('#pg_' + quando).find("td [data-toggle='tooltip']").tooltip(); $('#pg_' + quando).find("td [data-toggle='popover']").popover("destroy"); $('#pg_' + quando).find("td [data-toggle='popover']").popover({ trigger: Utils.isDeviceMobile() ? 'click' : 'hover', placement: 'top', container: 'body', html: true }); $('#pg_' + quando).find('input[type="checkbox"]').iCheck("destroy"); $('#pg_' + quando).find('input[type="checkbox"]').iCheck({ checkboxClass: 'icheckbox_square-blue' }); $('#pg_' + quando).find("td input.modificaIscrizionePG_pagato_iscrizione_altri").unbind("ifChanged", this.modificaPagataIscrizione.bind(this)); $('#pg_' + quando).find("td input.modificaIscrizionePG_pagato_iscrizione_altri").on("ifChanged", this.modificaPagataIscrizione.bind(this)); $('#pg_' + quando).find("td button.modificaIscrizionePG_note_iscrizione_altri").unbind("click", this.recuperaVecchieNoteIscrizione.bind(this)); $('#pg_' + quando).find("td button.modificaIscrizionePG_note_iscrizione_altri").click(this.recuperaVecchieNoteIscrizione.bind(this)); $('#pg_' + quando).find("td button.disiscriviPG_altri").unbind("click", this.confermaDisiscriviPg.bind(this)); $('#pg_' + quando).find("td button.disiscriviPG_altri").click(this.confermaDisiscriviPg.bind(this)); if (quando === "precedente") { $('#pg_' + quando).find("td input.modificaIscrizionePG_ha_partecipato_iscrizione_altri").unbind("ifChanged", this.modificaPartecipazione.bind(this)); $('#pg_' + quando).find("td input.modificaIscrizionePG_ha_partecipato_iscrizione_altri").on("ifChanged", this.modificaPartecipazione.bind(this)); } }, impostaTabellaPgIscritti: function (quando) { var columns = [], permessi_avan = Utils.controllaPermessiUtente(this.user_info, ["recuperaListaIscrittiAvanzato"]), url = permessi_avan ? Constants.API_GET_INFO_ISCRITTI_AVANZATE : Constants.API_GET_INFO_ISCRITTI_BASE; if (!permessi_avan) return false; columns.push({ title: "ID", data: "personaggi_id_personaggio" }); columns.push({ title: "Nome Personaggio", data: "nome_personaggio" }); columns.push({ title: "<NAME>", data: "nome_completo" }); if (quando === "prossimo") { columns.push({ title: "Classi Civili", data: "classi_civili", render: $.fn.dataTable.render.ellipsis(20, true, false) }); columns.push({ title: "Classi Militari", data: "classi_militari", render: $.fn.dataTable.render.ellipsis(20, true, false) }); } if (permessi_avan) columns.push({ title: "Pagato", data: "pagato_iscrizione", render: this.creaCheckBoxPagato.bind(this) }); if (Utils.controllaPermessiUtente(this.user_info, ["modificaIscrizionePG_pagato_iscrizione_proprio", "modificaIscrizionePG_pagato_iscrizione_altri"])) columns.push({ title: "Tipo Pagamento", data: "tipo_pagamento_iscrizione" }); if (quando === "precedente" && Utils.controllaPermessiUtente(this.user_info, ["modificaIscrizionePG_ha_partecipato_iscrizione_altri"])) columns.push({ title: "Ha Partecipato", data: "ha_partecipato_iscrizione", render: this.creaCheckBoxPartecipazione.bind(this) }); if (permessi_avan) columns.push({ title: "Note", data: "note_iscrizione", render: $.fn.dataTable.render.ellipsis(20, true, false) }); if (Utils.controllaPermessiUtente(this.user_info, ["disiscriviPG_altri", "disiscriviPG_proprio", "modificaIscrizionePG_note_iscrizione_proprio", "modificaIscrizionePG_note_iscrizione_altri"], false)) { columns.push({ title: "Azioni", render: this.renderAzioniPgIscritti.bind(this) }); } this["pg_" + quando] = $('#pg_' + quando) .on("error.dt", this.erroreDataTable.bind(this)) .on("draw.dt", this.setPGTableListeners.bind(this, quando)) .DataTable({ language: Constants.DATA_TABLE_LANGUAGE, ajax: function (data, callback) { Utils.requestData( url, "GET", $.extend(data, { quando: quando }), function (data) { var button = $('#pg_' + quando).parents(".box-body").find(".btn-group > button"); if (data.data.length > 0 && data.data[0].punti_assegnati_evento === "0") button.attr("data-evid", data.data[0].id_evento); else if (data.data.length > 0 && data.data[0].punti_assegnati_evento === "1") { button.attr("disabled", true); button.html("<i class='fa fa-edit'></i><br>Punti gi&agrave; assegnati") } callback(data); }.bind(this) ); }.bind(this), columns: columns, order: [ [0, 'desc'] ] }); }, eliminaEvento: function (id) { Utils.requestData( Constants.API_POST_DEL_EVENTO, "POST", { id_ev: id }, "L'evento &egrave; stato completamente rimosso dal database e tutte le iscrizioni perse.", null, Utils.reloadPage ); }, confermaEliminaEvento: function (e) { var t = $(e.target); Utils.showConfirm("Sicuro di voler eliminare questo evento? Tutti i suoi dati e le iscrizioni dei PG andranno <strong>perse per sempre</strong>.", this.eliminaEvento.bind(this, t.attr("data-id"))); }, mostraAnteprima: function (d) { this.riempiCampiEvento(d.result, "anteprima"); }, mostraAnteprimaMessaggio: function (e) { Utils.requestData( Constants.API_GET_EVENTO, "GET", { id: $(e.target).attr("data-id") }, this.mostraAnteprima.bind(this) ); if (parseInt($(e.target).attr("data-pubblico"), 10) === 1 && Utils.controllaPermessiUtente(this.user_info, ["ritiraEvento"], true)) { $("#modal_anteprima_evento").find("#btn_pubblica").hide(); $("#modal_anteprima_evento").find("#btn_ritira").show(); $("#modal_anteprima_evento").find("#btn_ritira").attr("data-id", $(e.target).attr("data-id")); } $("#modal_anteprima_evento").find("#btn_modifica").attr("data-evid", $(e.target).attr("data-id")); $("#modal_anteprima_evento").find("#btn_pubblica").attr("data-id", $(e.target).attr("data-id")); $("#modal_anteprima_evento").find("#iscrivi_pg").attr("disabled", true); $("#modal_anteprima_evento").modal({ drop: "static" }); }, renderPubblicoEvento: function (data, type, row) { return parseInt(data, 10) === 1 ? "S&igrave;" : "No"; }, impostaLinkAnteprima: function (data, type, row) { return "<a class='btn_anteprima_evento' data-id='" + row.id_evento + "' data-pubblico='" + row.pubblico_evento + "'>" + data + "</a>"; }, creaPulsantiAzioniEvento: function (data, type, row) { var pulsanti = ""; if (parseInt(row.pubblico_evento, 10) === 1) { pulsanti += "<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto ritiraEvento' " + "data-id='" + row.id_evento + "' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Ritira Evento'><i class='fa fa-remove'></i></button>"; } pulsanti += "<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto modificaEvento' " + "data-evid='" + row.id_evento + "' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Modifica Evento'><i class='fa fa-pencil'></i></button>"; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto eliminaEvento' " + "data-id='" + row.id_evento + "' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Elimina Evento'><i class='fa fa-trash'></i></button>"; return pulsanti; }, setGridListeners: function () { AdminLTEManager.controllaPermessi(); $("td [data-toggle='tooltip']").tooltip("destroy"); $("td [data-toggle='tooltip']").tooltip(); $("td [data-toggle='popover']").popover("destroy"); $("td [data-toggle='popover']").popover({ trigger: Utils.isDeviceMobile() ? 'click' : 'hover', placement: 'top', container: '#lista_eventi', html: true }); $("td > a.btn_anteprima_evento").unbind("click", this.mostraAnteprimaMessaggio.bind(this)); $("td > a.btn_anteprima_evento").click(this.mostraAnteprimaMessaggio.bind(this)); $("td > button.eliminaEvento").unbind("click", this.confermaEliminaEvento.bind(this)); $("td > button.eliminaEvento").click(this.confermaEliminaEvento.bind(this)); $("td > button.ritiraEvento").unbind("click", this.confermaRitiraEvento.bind(this)); $("td > button.ritiraEvento").click(this.confermaRitiraEvento.bind(this)); $("td > button.modificaEvento").unbind("click", this.vaiAModificaEvento.bind(this)); $("td > button.modificaEvento").click(this.vaiAModificaEvento.bind(this)); }, erroreDataTable: function (e, settings, techNote, message) { if (!settings.jqXHR || !settings.jqXHR.responseText) { console.log(message); return false; } var real_error = settings.jqXHR.responseText.replace(/^([\S\s]*?)\{"[\S\s]*/i, "$1"); real_error = real_error.replace("\n", "<br>"); Utils.showError(real_error); }, impostaTabellaEventiPreparati: function (d) { if (!Utils.controllaPermessiUtente(this.user_info, ["recuperaListaEventi"])) return false; var columns = []; columns.push({ data: "nome_completo" }); columns.push({ data: "pubblico_evento", render: this.renderPubblicoEvento.bind(this) }); columns.push({ data: "titolo_evento", render: this.impostaLinkAnteprima.bind(this) }); columns.push({ data: "data_inizio_evento" }); columns.push({ data: "ora_inizio_evento" }); columns.push({ data: "data_fine_evento" }); columns.push({ data: "ora_fine_evento" }); columns.push({ data: "luogo_evento", render: $.fn.dataTable.render.ellipsis(20, true, false) }); columns.push({ data: "costo_evento" }); columns.push({ data: "costo_maggiorato_evento" }); columns.push({ data: "note_evento", render: $.fn.dataTable.render.ellipsis(20, true, false) }); columns.push({ data: "azioni", render: this.creaPulsantiAzioniEvento.bind(this), className: 'inizialmente-nascosto visualizza_pagina_crea_evento pubblicaEvento eliminaEvento ritiraEvento', orderable: false }); this.tabella_eventi = $('#eventi') .on("error.dt", this.erroreDataTable.bind(this)) .on("draw.dt", this.setGridListeners.bind(this)) .DataTable({ language: Constants.DATA_TABLE_LANGUAGE, ajax: function (data, callback) { Utils.requestData( Constants.API_GET_LISTA_EVENTI, "GET", data, callback ); }, columns: columns, order: [ [3, 'desc'] ] }); }, riempiCampiEvento: function (data, suffisso_id) { var suf = typeof suffisso_id === "undefined" ? "" : "_" + suffisso_id; $("#titolo_evento" + suf).text(data.titolo_evento); $("#data_inizio_evento" + suf).text(data.data_inizio_evento_it); $("#ora_inizio_evento" + suf).text(data.ora_inizio_evento.replace(/:00$/, "")); $("#data_fine_evento" + suf).text(data.data_fine_evento_it); $("#ora_fine_evento" + suf).text(data.ora_fine_evento.replace(/:00$/, "")); $("#luogo_evento" + suf).text(data.luogo_evento); $("#costo_evento" + suf).html(data.costo_evento + "&euro;"); $("#costo_maggiorato_evento" + suf).html(data.costo_maggiorato_evento + "&euro;"); $("#note_evento" + suf).html(data.note_evento); }, mostraDati: function (d) { var data = d.result; if (data && Object.keys(data).length > 0) { this.id_evento = data.id_evento; this.luogo_evento = data.luogo_evento; this.riempiCampiEvento(data); $("#info_prossimo_evento").removeClass("inizialmente-nascosto"); $("#info_prossimo_evento").show(); //$("#partecipanti_evento").removeClass("inizialmente-nascosto"); //$("#partecipanti_evento").show(); } else { $("#no_evento").removeClass("inizialmente-nascosto"); $("#no_evento").show(400); } }, recuperaUltimoEvento: function () { Utils.requestData( Constants.API_GET_EVENTO, "GET", "", this.mostraDati.bind(this) ); }, vaiAModificaEvento: function (e) { var t = $(e.target); window.localStorage.setItem("evento_mod_id", t.attr("data-evid")); Utils.redirectTo(Constants.CREA_EVENTO_PAGE); }, pubblicaEvento: function (id) { Utils.requestData( Constants.API_POST_PUBBLICA_EVENTO, "POST", { id_ev: id }, "Ora l'evento &egrave; visibile a tutti i giocatori e sar&agrave; possibile iscriversi.", null, Utils.reloadPage ); }, confermaPubblicaEvento: function (e) { Utils.showConfirm("Sicuro di voler pubblicare questo evento? In caso affermativo gli utenti potranno iniziare subito a iscrivere i loro PG.", this.pubblicaEvento.bind(this, $(e.target).attr("data-id"))); }, ritiraEvento: function (id) { Utils.requestData( Constants.API_POST_RITIRA_EVENTO, "POST", { id_ev: id }, "L'evento non &egrave; pi&ugrave; visibile ai giocatori e non sar&agrave; possibile iscriversi.", null, Utils.reloadPage ); }, confermaRitiraEvento: function (e) { Utils.showConfirm("Sicuro di voler ritirare questo evento?", this.ritiraEvento.bind(this, $(e.target).attr("data-id"))); }, recuperaInfoUtente: function () { this.user_info = JSON.parse(window.localStorage.getItem("user")); }, puntiInviati: function (idev) { Utils.requestData( Constants.API_POST_PUNTI_EVENTO, "POST", { idev: idev }, Utils.redirectTo.bind(this, Constants.MAIN_PAGE) ); }, mostraModalPunteggio: function (data) { var data = data.data, ids = data.map(function (el) { return el.personaggi_id_personaggio; }), nomi = data.map(function (el) { return el.nome_personaggio; }), titolo_evento = data[0].titolo_evento, id_evento = data[0].id_evento; PointsManager.impostaModal({ pg_ids: ids, nome_personaggi: nomi, note_azione: "partecipazione evento " + titolo_evento + " [ID: " + id_evento + "]", onSuccess: this.puntiInviati.bind(this, data.id_evento) }); }, modificaPuntiAiPartecipanti: function (e) { var t = $(e.target); Utils.requestData( Constants.API_GET_PARTECIPANTI_EVENTO, "POST", { idev: t.attr("data-evid") }, this.mostraModalPunteggio.bind(this) ); }, modificaCreditoPG: function (e) { var users = { ids: [], names: [] }; this.pg_precedente.rows().every(function (rowIdx, tableLoop, rowLoop) { var data = this.data(); if (parseInt(data.ha_partecipato_iscrizione, 10) === 1) { users.ids.push(data.personaggi_id_personaggio); users.names.push(data.nome_personaggio); } }); CreditManager.impostaModal({ pg_ids: users.ids, nome_personaggi: users.names, onSuccess: this.pg_precedente.ajax.reload.bind(this, null, false), valore_min: 0 }); }, vaiAPaginaStampaCartellini: function (data) { $(".modal").modal("hide"); var pg_da_stampare = data.data.reduce(function (prev, el) { prev.schede_pg[el.personaggi_id_personaggio] = 1; return prev; }, { schede_pg: {} }); window.localStorage.setItem("cartellini_da_stampare", JSON.stringify(pg_da_stampare)); window.open(Constants.STAMPA_CARTELLINI_PAGE, "Stampa Cartellini"); }, stampaCartellini: function () { Utils.showLoading("Scarico gli id dei personaggi iscritti..."); Utils.requestData( Constants.API_GET_INFO_ISCRITTI_BASE, "GET", "draw=1&columns=&order=&start=0&length=999&search=&quando=prossimo", this.vaiAPaginaStampaCartellini.bind(this) ); }, vaiAPaginaStampaIscrizioni: function (e) { var t = $(e.target); window.localStorage.setItem("da_stampare", t.attr("data-evid")); window.open(Constants.STAMPA_ISCRITTI_PAGE, "Stampa Lista Iscritti"); }, setListeners: function () { $("[data-toggle='tooltip']").tooltip("destroy"); $("[data-toggle='tooltip']").tooltip(); $("#btn_visualizza_pagina_crea_evento").click(Utils.redirectTo.bind(this, Constants.CREA_EVENTO_PAGE)); $("#btn_pubblica").click(this.confermaPubblicaEvento.bind(this)); $("#btn_modifica").click(this.vaiAModificaEvento.bind(this)); $("#btn_ritira").click(this.confermaRitiraEvento.bind(this)); $("#iscrivi_pg").click(this.mostraModalIscrizione.bind(this)); $("#btn_modificaPG_px_personaggio").click(this.modificaPuntiAiPartecipanti.bind(this)); $("#btn_stampaCartelliniPG").click(this.stampaCartellini.bind(this)); $("#btn_stampaIscrizioniPg").click(this.vaiAPaginaStampaIscrizioni.bind(this)); $("#btn_modificaPG_credito_personaggio").click(this.modificaCreditoPG.bind(this)); } }; }(); $(function () { LiveEventsManager.init(); });<file_sep>/server/src/classes/DatabaseBridge.class.php <?php $path = $_SERVER['DOCUMENT_ROOT']."/"; include_once($path."classes/APIException.class.php"); include_once($path."config/config.inc.php"); class DatabaseBridge extends PDO { public function __construct() { } public function __destruct() { } private function connect() { global $DB_DATA; $dns = $DB_DATA["DB_DRIVER"] . ':host=' . $DB_DATA["DB_HOST"] . ';dbname=' . $DB_DATA["DB_NAME"] . ';charset=utf8'; try { $connection = new PDO( $dns, $DB_DATA["DB_USER"], $DB_DATA["DB_PASS"] ); $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $connection->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false ); $connection->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'" ); } catch (PDOException $e) { die( "{\"status\":\"error\", \"message\":\"".$e->getMessage()."\"}" ); } return $connection; } /** * @param string $query * @param Array $params * @param bool $to_json * @return array|bool|string * @throws Exception */ public function doQuery( $query, $params, $to_json = True ) { global $DB_ERR_DELIMITATORE; if( !is_array( $params ) ) throw new APIException("$query<br><br>I parametri passati devono essere sotto forma di array di traduzione PDO. Il valore passato non lo è: ".$params, APIException::$DATABASE_ERROR); $query = str_replace("\n","",$query); $query = str_replace("\r","",$query); $query = preg_replace("/\s+/"," ",$query); try { $conn = $this->connect(); $stmnt = $conn->prepare($query); $stmnt->execute($params); // $stmnt->debugDumpParams(); if ($stmnt->columnCount() !== 0) $result = $stmnt->fetchAll(PDO::FETCH_ASSOC); else if ($stmnt->columnCount() === 0 && $conn->lastInsertId() !== 0) { $result = $conn->lastInsertId(); $to_json = False; } else if ($stmnt->columnCount() === 0 && $conn->lastInsertId() === 0) { $result = True; $to_json = False; } $stmnt->closeCursor(); // this is not even required $stmnt = null; // doing this is mandatory for connection to get closed $conn = null; if ($result && !$to_json) return $result; else if ($result && $to_json) return json_encode($result); } catch( Exception $e ) { throw new APIException($e->getCode().$DB_ERR_DELIMITATORE.$query."<br>".$e->getMessage(),APIException::$DATABASE_ERROR); } } public function doMultipleManipulations( $query, $params, $to_json = True ) { if( !is_array( $params ) || ( is_array( $params ) && !is_array( $params[0] ) ) ) throw new APIException("I parametri passati devono essere sotto forma di array di traduzione PDO a due dimensioni.", APIException::$DATABASE_ERROR); try { $conn = $this->connect(); $stmnt = $conn->prepare( $query ); foreach( $params as $p ) $stmnt->execute( $p ); $stmnt->closeCursor(); // this is not even required $stmnt = null; // doing this is mandatory for connection to get closed $conn = null; return True; } catch( Exception $e ) { throw new APIException(str_replace("\n","",$query )."<br>".$e->getMessage(), APIException::$DATABASE_ERROR); } } } <file_sep>/client/app/scripts/controllers/GrantsManager.js /** * Created by Miroku on 11/03/2018. */ var GrantsManager = function () { return { init: function () { this.user_info = JSON.parse( window.localStorage.getItem("user") ); this.setListeners(); if( Utils.controllaPermessiUtente( this.user_info, ["creaRuolo","eliminaRuolo","associaPermessi"], true ) ) { this.recuperaListaPermessi(); this.recuperaListaPermessiDeiRuoli(); } if( Utils.controllaPermessiUtente( this.user_info, ["recuperaRuoli"], true ) ) this.recuperaRuoli(); }, inserisciNuovoRuolo: function( ) { var nome = $("#nome_nuovo_ruolo").val(); Utils.requestData( Constants.API_POST_CREA_RUOLO, "POST", { nome: nome }, "Il nuovo ruolo <strong>"+nome+"</strong> &egrave; stato creato correttamente.<br>Ora potrai associargli dei permessi.", null, Utils.reloadPage ); }, salvaPermessiDeiRuoli: function( data ) { this.permessi_dei_ruoli = data.result; }, recuperaListaPermessiDeiRuoli: function() { Utils.requestData( Constants.API_GET_PERMESSI_DEI_RUOLI, "GET", {}, this.salvaPermessiDeiRuoli.bind(this) ); }, impostaModalPermessi: function( data ) { var res = data.result; for( var r in res ) { var p = res[r], tr = $("<tr></tr>"), cbox = $("<div class='checkbox icheck'>" + "<input type='checkbox' " + "class='permesso-cbox' " + "name='permessi["+ p.nome_grant+"]'>" + "</div>"); tr.append( $("<td></td>").append(cbox) ); tr.append( $("<td></td>").text(p.nome_grant) ); tr.append( $("<td></td>").text(p.descrizione_grant) ); $("#tabella_associazioni").find("tbody").append(tr); } $( 'input[type="checkbox"]' ).iCheck("destroy"); $( 'input[type="checkbox"]' ).iCheck( { checkboxClass : 'icheckbox_square-blue' } ); }, recuperaListaPermessi: function() { Utils.requestData( Constants.API_GET_PERMESSI, "GET", {}, this.impostaModalPermessi.bind(this) ); }, eliminaRuolo: function( nome ) { if( nome === Constants.RUOLO_ADMIN ) { Utils.showError("Non puoi eliminare il ruolo "+Constants.RUOLO_ADMIN); return; } var nuovo_ruolo = $("#modal_nuovo_ruolo").find("select").val(); if( parseInt( nuovo_ruolo, 10 ) === -1 ) { Utils.showError("Devi scegliere un ruolo sostitutivo"); return; } Utils.requestData( Constants.API_POST_DEL_RUOLO, "POST", { ruolo: nome, sostituto: nuovo_ruolo }, "Ruolo rimosso con successo.", null, Utils.reloadPage ); }, chiediNuovoRuolo: function( nome ) { $('.modal').modal('hide'); $("#nuovo_ruolo").find("option[value='"+nome+"']").attr("disabled",true); $("#modal_nuovo_ruolo").find("#ruolo_del").text(nome); $("#modal_nuovo_ruolo").find("#scegli_ruolo").unbind("click"); $("#modal_nuovo_ruolo").find("#scegli_ruolo").click(this.eliminaRuolo.bind(this,nome)); $("#modal_nuovo_ruolo").modal({drop:"static"}); }, confermaEliminazioneRuolo: function( e ) { var t = $(e.target); if( t.attr("data-nome") === Constants.RUOLO_ADMIN ) { Utils.showError("Non puoi eliminare il ruolo di <strong>admin</strong>"); return; } Utils.showConfirm("Sicuro di voler eliminare questo ruolo?<br>Tutti i permessi associati verranno persi.", this.chiediNuovoRuolo.bind(this, t.attr("data-nome"))); }, spuntaCheckboxPermessi: function( ruolo ) { $("#modal_scegli_permessi").find("input[type='checkbox']").prop("checked",false); $("#modal_scegli_permessi").find("input[type='checkbox']").iCheck('update'); if( this.permessi_dei_ruoli[ruolo] ) { for( var pdr in this.permessi_dei_ruoli[ruolo] ) { var p = this.permessi_dei_ruoli[ruolo][pdr], box = $("#modal_scegli_permessi").find("input[type='checkbox'][name='permessi["+p+"]']"); box.prop("checked",true); box.iCheck('update'); } } }, copiaPermessi: function( e ) { var t = $(e.target), ruolo = t.val(); this.spuntaCheckboxPermessi(ruolo); }, inviaAssociazioni: function( e ) { var t = $(e.target), nome = t.attr("data-ruolo"), data = "ruolo="+nome+"&"+ $("#modal_scegli_permessi").find("input[type='checkbox']").serialize(); Utils.requestData( Constants.API_POST_ASSOCIA_PERMESSI, "POST", data, "Permessi aggiornati con successo.", null, Utils.reloadPage ); }, mostraModalAssociazione: function( e ) { var t = $(e.target), nome = t.attr("data-nome"); if( t.attr("data-nome") === Constants.RUOLO_ADMIN ) { Utils.showError("Non puoi modificare il ruolo di <strong>admin</strong>"); return; } this.spuntaCheckboxPermessi(nome); $("#modal_scegli_permessi").find("#lista_ruoli_copia").val(-1); $("#modal_scegli_permessi").find("#lista_ruoli_copia").unbind("change"); $("#modal_scegli_permessi").find("#lista_ruoli_copia").change( this.copiaPermessi.bind(this) ); $("#modal_scegli_permessi").find("#invia_associazioni").attr("data-ruolo",nome); $("#modal_scegli_permessi").find("#invia_associazioni").unbind("click"); $("#modal_scegli_permessi").find("#invia_associazioni").click( this.inviaAssociazioni.bind(this) ); $("#modal_scegli_permessi").find("#ruolo_ass").text(nome); $("#modal_scegli_permessi").modal({drop:"static"}); }, tabellaPronta: function() { AdminLTEManager.controllaPermessi(); this.setTooltip(); $("td button.eliminaRuolo").unbind("click",this.confermaEliminazioneRuolo.bind(this)); $("td button.eliminaRuolo").click(this.confermaEliminazioneRuolo.bind(this)); $("td button.associaPermessi").unbind("click",this.mostraModalAssociazione.bind(this)); $("td button.associaPermessi").click(this.mostraModalAssociazione.bind(this)); $("td a.nome-ruolo").unbind("click",this.mostraModalAssociazione.bind(this)); $("td a.nome-ruolo").click(this.mostraModalAssociazione.bind(this)); }, mostraRuoli: function( data ) { var res = data.result, count = 0; this.ruoli = []; var elimina_btn = $("<button type='button' " + "class='btn btn-xs btn-default eliminaRuolo' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Elimina Ruolo'><i class='fa fa-trash-o'></i></button>"), associa_btn = $("<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto associaPermessi recuperaPermessiDeiRuoli' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Associa Permessi'><i class='fa fa-pencil'></i></button>"); for( var r in res ) { this.ruoli.push(res[r].nome_ruolo); var tr = $("<tr></tr>"), nome = Utils.controllaPermessiUtente(this.user_info, ["associaPermessi","recuperaPermessiDeiRuoli"], false) ? "<a class='nome-ruolo' data-nome='"+res[r].nome_ruolo+"'>"+res[r].nome_ruolo+"</a>" : res[r].nome_ruolo, azioni = $("<td></td>"); azioni.append( associa_btn.clone().attr("data-nome",res[r].nome_ruolo) ); azioni.append( elimina_btn.clone().attr("data-nome",res[r].nome_ruolo) ); tr.append("<td>"+(++count)+"</td>"); tr.append("<td>"+nome+"</td>"); tr.append("<td>"+res[r].numero_grants+"</td>"); tr.append( azioni ); $("#tabella_ruoli").find("tbody").append(tr); $("#nuovo_ruolo").append("<option value='"+res[r].nome_ruolo+"'>"+res[r].nome_ruolo+"</option>"); $("#ruolo_giocatore").append("<option value='"+res[r].nome_ruolo+"'>"+res[r].nome_ruolo+"</option>"); $("#lista_ruoli_copia").append("<option value='"+res[r].nome_ruolo+"'>"+res[r].nome_ruolo+"</option>"); } setTimeout( this.tabellaPronta.bind(this), 100 ); }, recuperaRuoli: function() { Utils.requestData( Constants.API_GET_RUOLI, "GET", {}, this.mostraRuoli.bind(this) ); }, setTooltip: function() { $( "td [data-toggle='tooltip']" ).tooltip("destroy"); $( "td [data-toggle='tooltip']" ).tooltip(); }, setListeners: function() { this.setTooltip(); $("#btn_nome_nuovo_ruolo").click(this.inserisciNuovoRuolo.bind(this)); } }; }(); $(function () { GrantsManager.init(); });<file_sep>/server/src/classes/TransactionManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT']."/"; include_once($path."classes/APIException.class.php"); include_once($path."classes/UsersManager.class.php"); include_once($path."classes/DatabaseBridge.class.php"); include_once($path."classes/SessionManager.class.php"); include_once($path."classes/CharactersManager.class.php"); include_once($path."classes/Utils.class.php"); include_once($path."config/constants.php"); class TransactionManager { protected $idev_in_corso; protected $session; protected $character_manager; protected $db; public function __construct($char_manager, $idev_in_corso = NULL) { $this->idev_in_corso = $idev_in_corso; $this->character_manager = $char_manager; $this->db = new DatabaseBridge(); $this->session = SessionManager::getInstance(); } public function __destruct() { } public function inserisciTransazione( $id_debitore, $importo, $id_creditore, $note = NULL, $id_acq_comp = NULL ) { global $INFINITE_MONEY_PGS; UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); if( !in_array($id_debitore, $INFINITE_MONEY_PGS) && $this->character_manager->recuperaCredito( $id_debitore ) < $importo ) throw new APIException("Non hai abbastanza Bit per completare l'operzione."); $params = [ ":pgdeb" => $id_debitore, ":importo" => $importo ]; if( isset($id_creditore) ) { $cred_macro = ":pgcred"; $params[$cred_macro] = $id_creditore; } else throw new APIException("Impossibile inserire una transazione senza indicare l'id del creditore."); if( isset($note) ) { $note_macro = ":note"; $params[$note_macro] = $note; } else $note_macro = "NULL"; if( isset($id_acq_comp) ) { $id_acq_comp_macro = ":idacqcomp"; $params[$id_acq_comp_macro] = $id_acq_comp; } else $id_acq_comp_macro = "NULL"; $sql_ins = "INSERT INTO transazioni_bit (debitore_transazione, creditore_transazione, importo_transazione, note_transazione, id_acquisto_componente) VALUES (:pgdeb,$cred_macro,:importo,$note_macro,$id_acq_comp_macro)"; $this->db->doQuery( $sql_ins, $params, False ); $output = ["status" => "ok", "result" => true]; return json_encode($output); } public function inserisciTransazioneMolti( $importo, $note, $creditori = [], $debitore = 1 ) { foreach( $creditori as $cc ) $this->inserisciTransazione( $debitore, $importo, $cc, $note ); $output = ["status" => "ok", "result" => true]; return json_encode($output); } public function compraComponenti( $ids_qty ) { global $SCONTO_MERCATO; global $QTA_PER_SCONTO_MERCATO; global $INFINITE_MONEY_PGS; UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); if( !isset($this->session->pg_loggato) ) throw new APIException("Devi essere loggato con un personaggio per compiere questa operazione."); if( !isset($ids_qty) || count($ids_qty) === 0 ) throw new APIException( "Non ci sono articoli nel carrello." ); $ids = array_keys($ids_qty); $marcatori = str_repeat("?, ", count($ids) - 1) . "?"; $sql = "SELECT id_componente ,costo_attuale_componente FROM componenti_crafting WHERE id_componente IN ($marcatori)"; $risultati = $this->db->doQuery($sql, $ids, False); $totale = 0; $sconto = 0; $sconto_txt = ""; $params_comp = []; foreach( $risultati as $componente ) { $qty = (int)$ids_qty[$componente["id_componente"]]; $totale += (int)$componente["costo_attuale_componente"] * $qty; for ( $q = 0; $q < $qty; $q++ ) $params_comp[] = [ ":idpg" => $this->session->pg_loggato["id_personaggio"], ":idcomp" => $componente["id_componente"], ":costo" => (int)$componente["costo_attuale_componente"] ]; } if( count( $ids ) % $QTA_PER_SCONTO_MERCATO === 0 ) { $sconto = ($SCONTO_MERCATO / 100); $totale = $totale - ( $totale * $sconto ); } if( !in_array($this->session->pg_loggato["id_personaggio"], $INFINITE_MONEY_PGS) && $this->character_manager->recuperaCredito( $this->session->pg_loggato["id_personaggio"] ) < $totale ) throw new APIException("Non hai abbastanza Bit per completare l'operazione."); $sql_acq_comp = "INSERT INTO componenti_acquistati (cliente_acquisto, id_componente_acquisto, importo_acquisto) VALUES (:idpg, :idcomp, :costo)"; foreach ($params_comp as $p) { if( $sconto > 0 ) { $sconto_txt = " Sconto del $SCONTO_MERCATO%. Prezzo pieno " . $p[":costo"] . " Bit."; $p[":costo"] = $p[":costo"] - ( $p[":costo"] * $sconto ); } $id_acq_com = $this->db->doQuery( $sql_acq_comp, $p, False ); $this->inserisciTransazione( $p[":idpg"], $p[":costo"], 1, "Acquisto componente ".$p[":idcomp"]." dal RavShop.".$sconto_txt, $id_acq_com ); } $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function compraOggetti( $ids_qty ) { global $SCONTO_MERCATO; global $QTA_PER_SCONTO_MERCATO; global $INFINITE_MONEY_PGS; UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); if( !isset($this->session->pg_loggato) ) throw new APIException("Devi essere loggato con un personaggio per compiere questa operazione."); if( !isset($ids_qty) || count($ids_qty) === 0 ) throw new APIException( "Non ci sono articoli nel carrello." ); $ids = array_keys($ids_qty); $marcatori = str_repeat("?, ", count($ids) - 1) . "?"; $sql = "SELECT id_ricetta ,nome_ricetta ,costo_attuale_ricetta ,disponibilita_ravshop_ricetta FROM ricette WHERE id_ricetta IN ($marcatori)"; $risultati = $this->db->doQuery($sql, $ids, False); $totale = 0; $sconto = 0; $sconto_txt = ""; $params_comp = []; $params_qty = []; foreach( $risultati as $oggetto ) { $qty = (int)$ids_qty[$oggetto["id_ricetta"]]; if( (int)$oggetto["disponibilita_ravshop_ricetta"] < $qty ) throw new APIException("Siamo spiacenti, ma le quantit&agrave; richieste per l'oggetto $oggetto[nome_ricetta] (#$oggetto[id_ricetta]) non sono disponibili."); $totale += (int)$oggetto["costo_attuale_ricetta"] * $qty; for ( $q = 0; $q < $qty; $q++ ) $params_comp[] = [ ":idpg" => $this->session->pg_loggato["id_personaggio"], ":idcomp" => $oggetto["id_ricetta"], ":nome" => $oggetto["nome_ricetta"], ":costo" => (int)$oggetto["costo_attuale_ricetta"] ]; $params_qty[] = [":qty" => $qty, ":idric" => $oggetto["id_ricetta"]]; } // if( count( $ids ) % $QTA_PER_SCONTO_MERCATO === 0 ) // { // $sconto = ($SCONTO_MERCATO / 100); // $totale = $totale - ( $totale * $sconto ); // } if( !in_array($this->session->pg_loggato["id_personaggio"], $INFINITE_MONEY_PGS) && $this->character_manager->recuperaCredito( $this->session->pg_loggato["id_personaggio"] ) < $totale ) throw new APIException("Non hai abbastanza Bit per completare l'operazione."); foreach ($params_comp as $p) { if( $sconto > 0 ) { $sconto_txt = " Sconto del $SCONTO_MERCATO%. Prezzo pieno " . $p[":costo"] . " Bit."; $p[":costo"] = $p[":costo"] - ( $p[":costo"] * $sconto ); } $this->inserisciTransazione( $p[":idpg"], $p[":costo"], 1, "Acquisto oggetto ".$p[":nome"]." (#".$p[":idcomp"].") dal RavShop.".$sconto_txt ); } foreach ($params_qty as $q) $this->db->doQuery("UPDATE ricette SET disponibilita_ravshop_ricetta = disponibilita_ravshop_ricetta - :qty WHERE id_ricetta = :idric", $q, False ); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function recuperaInfoBanca( ) { if( !isset( $this->session->pg_loggato["id_personaggio"] ) ) throw new APIException("Devi essere loggato con un personaggio per eseguire questa operazione.", APIException::$PG_LOGIN_ERROR ); UsersManager::operazionePossibile( $this->session, __FUNCTION__, $this->session->pg_loggato["id_personaggio"] ); $sql_check = "SELECT ( SELECT SUM( COALESCE( u.importo, 0 ) ) as credito FROM ( SELECT SUM( COALESCE( importo_transazione, 0 ) ) as importo, creditore_transazione as pg FROM transazioni_bit GROUP BY creditore_transazione UNION ALL SELECT ( SUM( COALESCE( importo_transazione, 0 ) ) * -1 ) as importo, debitore_transazione as pg FROM transazioni_bit GROUP BY debitore_transazione ) as u WHERE pg = :idpg ) AS credito_personaggio, ( SELECT COALESCE( SUM(importo_transazione), 0 ) FROM transazioni_bit WHERE YEAR(data_transazione) = YEAR(NOW()) AND creditore_transazione = :idpg ) as entrate_anno_personaggio, ( SELECT COALESCE( SUM(importo_transazione), 0 ) FROM transazioni_bit WHERE YEAR(data_transazione) = YEAR(NOW()) AND debitore_transazione = :idpg ) as uscite_anno_personaggio"; $ris_check = $this->db->doQuery( $sql_check, [ ":idpg" => $this->session->pg_loggato["id_personaggio"] ], False ); $output = [ "status" => "ok", "result" => $ris_check[0] ]; return json_encode($output); } public function recuperaMovimenti( $draw, $columns, $order, $start, $length, $search, $tutti = False ) { $tutti = (bool)$tutti; if( !$tutti && !isset( $this->session->pg_loggato["id_personaggio"] ) ) throw new APIException("Devi essere loggato con un personaggio per eseguire questa operazione.", APIException::$PG_LOGIN_ERROR ); if( $tutti ) $pgid = -1; else $pgid = $this->session->pg_loggato["id_personaggio"]; UsersManager::operazionePossibile( $this->session, __FUNCTION__, $pgid ); $filter = False; $where = $tutti ? [] : [ "( t.debitore_transazione = :pgid OR t.creditore_transazione = :pgid )" ]; $params = $tutti ? [] : [ ":pgid" => $pgid ]; $sql_tipo = $tutti ? "" : ", IF( tb.creditore_transazione = :pgid, 'entrata', 'uscita' ) as tipo_transazione"; $order_str = ""; $field_map = [ "datait_transazione" => "data_transazione" ]; if (isset($search) && isset($search["value"]) && $search["value"] != "") { $filter = True; $params[":search"] = "%$search[value]%"; $where[] = " ( t.nome_creditore LIKE :search OR t.nome_debitore LIKE :search OR t.tipo_transazione LIKE :search OR t.note_transazione LIKE :search OR t.datait_transazione LIKE :search )"; } if( isset( $order ) && count($order) > 0 ) { $order_by_field = $columns[$order[0]["column"]]["data"]; $order_by_field = !isset( $field_map[$order_by_field] ) ? $order_by_field : $field_map[$order_by_field]; $order_by_dir = $order[0]["dir"]; $order_str = "ORDER BY t." . $order_by_field . " " . $order_by_dir; } if (count($where) > 0) $where = "WHERE " . implode(" AND ", $where); else $where = ""; $query_ric = "SELECT * FROM ( SELECT tb.*, DATE_FORMAT( tb.data_transazione, '%d/%m/%Y %H:%i:%s' ) as datait_transazione, IF( tb.id_acquisto_componente IS NOT NULL, 'RavShop', pgc.nome_personaggio ) as nome_creditore, pgd.nome_personaggio as nome_debitore $sql_tipo FROM transazioni_bit AS tb LEFT OUTER JOIN personaggi AS pgc ON pgc.id_personaggio = tb.creditore_transazione JOIN personaggi AS pgd ON pgd.id_personaggio = tb.debitore_transazione ) AS t $where $order_str"; $risultati = $this->db->doQuery($query_ric, $params, False); $totale = count($risultati); if (count($risultati) > 0) $risultati = array_splice($risultati, $start, $length); else $risultati = array(); $output = array( "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => $totale, "recordsFiltered" => $filter ? count($risultati) : $totale, "data" => $risultati ); return json_encode($output); } } <file_sep>/client/app/scripts/controllers/EventCreateManager.js /** * Created by Miroku on 11/03/2018. */ var EventCreateManager = function() { return { init: function() { this.setListeners(); this.analizzaAzione(); }, mostraTimePicker: function() { $(this).timepicker('showWidget'); }, mostraDati: function(d) { var data = d.result; $("#titolo").val(data.titolo_evento); $("#data_inizio").val(data.data_inizio_evento_it); $("#ora_inizio").val(data.ora_inizio_evento.replace(/:00$/, "")); $("#data_fine").val(data.data_fine_evento_it); $("#ora_fine").val(data.ora_fine_evento.replace(/:00$/, "")); $("#luogo").val(data.luogo_evento); $("#costo").val(data.costo_evento); $("#costo_maggiorato").val(data.costo_maggiorato_evento); $("#note").val(data.note_evento.replace(/<br>/g, "\r").replace(/<br \/>/g, "\r")); }, inviaDatiEvento: function() { var data = {}, url = Constants.API_POST_EVENTO, mex = "Evento inserito correttamente.<br>Ricordati che non è ancora pubblico e che pu&ograve; essere modificato."; if (this.evento_mod_id) { window.localStorage.removeItem("azione_evento"); url = Constants.API_POST_MOD_EVENTO; mex = "Evento modificato correttamente.<br>Ricordati che non è ancora pubblico e che pu&ograve; essere modificato." data.id = this.evento_mod_id; } data.titolo = $("#titolo").val(); data.data_inizio = $("#data_inizio").val(); data.ora_inizio = $("#ora_inizio").val(); data.data_fine = $("#data_fine").val(); data.ora_fine = $("#ora_fine").val(); data.luogo = $("#luogo").val(); data.costo = $("#costo").val() || 0; data.costo_magg = $("#costo_maggiorato").val() || 0; data.note = $("#note").val(); Utils.requestData( url, "POST", data, mex, null, Utils.redirectTo.bind(this, Constants.EVENTI_PAGE) ); }, checkInputData: function() { var titolo = $("#titolo").val(), data_inizio = $("#data_inizio").val(), ora_inizio = $("#ora_inizio").val(), data_fine = $("#data_fine").val(), ora_fine = $("#ora_fine").val(), luogo = $("#luogo").val(), costo = $("#costo").val(), costo_magg = $("#costo_maggiorato").val(), note = $("#note").val(), d_inizio_ts = 0, d_fine_ts = 0, error = ""; if (!titolo || Utils.soloSpazi(titolo)) error += "<li>Il campo Titolo non pu&ograve; essere lasciato vuoto.</li>"; if (!data_inizio || Utils.soloSpazi(data_inizio)) error += "<li>Il campo Data Inizio non pu&ograve; essere lasciato vuoto.</li>"; else { var data_spl = data_inizio.split("/"); d_inizio_ts = new Date(data_spl[2], parseInt(data_spl[1], 10) - 1, data_spl[0]).getTime(); } if (!ora_inizio || Utils.soloSpazi(ora_inizio)) error += "<li>Il campo Ora Inizio non pu&ograve; essere lasciato vuoto.</li>"; if (!data_fine || Utils.soloSpazi(data_fine)) error += "<li>Il campo Data Fine non pu&ograve; essere lasciato vuoto.</li>"; else { var data_spl = data_fine.split("/"); d_fine_ts = new Date(data_spl[2], parseInt(data_spl[1], 10) - 1, data_spl[0]).getTime(); } if (!ora_fine || Utils.soloSpazi(ora_fine)) error += "<li>Il campo Ora Fine non pu&ograve; essere lasciato vuoto.</li>"; if (costo && !Utils.soloSpazi(costo) && !/^\d+(\.\d+)?$/.test(costo)) error += "<li>Il campo Costo pu&ograve; contenere solo numeri.</li>"; if (costo_magg && Utils.soloSpazi(costo_magg) && !/^\d+$/.test(costo_magg)) error += "<li>Il campo Costo Maggiorato pu&ograve; contenere solo numeri.</li>"; if (!luogo || Utils.soloSpazi(luogo)) error += "<li>Il campo Luogo non pu&ograve; essere lasciato vuoto.</li>"; if (d_fine_ts !== 0 && d_inizio_ts !== 0 && d_fine_ts < d_inizio_ts) error += "<li>La data di fine non pu&ograve; essere prima di quella d'inizio.</li>" return error; }, checkForWarnings: function() { var costo = $("#costo").val(), costo_magg = $("#costo_maggiorato").val(), note = $("#note").val(), warning = ""; if (!costo || Utils.soloSpazi(costo) || parseInt(costo, 10) === 0) warning += "<li>Il campo Costo non &egrave; stato riempito.</li>"; if (!costo_magg || Utils.soloSpazi(costo_magg) || parseInt(costo, 10) === 0) warning += "<li>Il campo Costo Maggiorato non &egrave; stato riempito.</li>"; if (!note || Utils.soloSpazi(note)) warning += "<li>Il campo Dettagli non &egrave; stato riempito.</li>"; return warning; }, controllaDatiEvento: function() { var errors = this.checkInputData(), warnings = this.checkForWarnings(); if (errors) { Utils.showError("Sono stati rilevati i seguenti errori:<ul>" + errors + "</ul>"); return false; } if (warnings) Utils.showConfirm("Sono state rilevate queste anomalie:<ul>" + warnings + "</ul>Vuoi proseguire lo stesso?", this.inviaDatiEvento.bind(this), false); else this.inviaDatiEvento(); }, analizzaAzione: function() { this.evento_mod_id = window.localStorage.getItem("evento_mod_id"); if (this.evento_mod_id) { $("#invia_evento").text("Modifica Evento"); Utils.requestData( Constants.API_GET_EVENTO, "GET", { id: this.evento_mod_id }, this.mostraDati.bind(this) ); } }, setListeners: function() { $('[data-provide="timepicker"]').focus(this.mostraTimePicker); $("#invia_evento").click(this.controllaDatiEvento.bind(this)); $("#indietro").click(Utils.redirectTo.bind(this, Constants.EVENTI_PAGE)); } }; }(); $(function() { EventCreateManager.init(); });<file_sep>/client/app/scripts/controllers/MessagingManager.js /** * Created by Miroku on 03/03/2018. */ var MessaggingManager = function () { return { init: function () { this.user_info = JSON.parse( window.localStorage.getItem( "user" ) ); this.pg_info = window.localStorage.getItem( "logged_pg" ); this.pg_info = this.pg_info ? JSON.parse( this.pg_info ) : null; this.visibile_ora = this.sezioneIniziale(); this.vaiA( this.visibile_ora, true ); this.setListeners(); this.recuperaDatiPropriPG(); this.controllaStorage(); this.mostraMessaggi(); }, sezioneIniziale: function () { return typeof this.user_info.pg_da_loggare !== "undefined" ? $( "#lista_ig" ) : $( "#lista_fg" ); }, erroreDataTable: function ( e, settings, techNote, message ) { if ( !settings.jqXHR.responseText ) return false; var real_error = settings.jqXHR.responseText.replace( /^([\S\s]*?)\{"[\S\s]*/i, "$1" ); real_error = real_error.replace( "\n", "<br>" ); Utils.showError( real_error ); }, risettaMessaggio: function () { this.id_destinatario = null; this.conversazione_in_lettura = null; $( ".form-destinatario" ).first().find( ".nome-destinatario" ).val( "" ); $( ".form-destinatario" ).first().find( ".nome-destinatario" ).attr( "disabled", false ); $( ".form-destinatario" ).first().find( ".controlli-destinatario" ).show(); $( "#messaggio" ).val( "" ); $( "#messaggio" ).attr( "disabled", false ); $( "#oggetto" ).val( "" ); $( "#oggetto" ).attr( "disabled", false ); $( "#tipo_messaggio" ).attr( "disabled", false ); $( "#invia_messaggio" ).attr( "disabled", true ); //this.inserisciMittente(); }, aggiungiDestinatarioInArray: function ( input_elem, id ) { var index = $( ".form-destinatario" ).index( $( input_elem ).parents( ".form-destinatario" ) ); if ( !( this.id_destinatari instanceof Array ) ) this.id_destinatari = []; if ( this.id_destinatari.indexOf( id ) === -1 && !/^\s*$/.test( id ) ) this.id_destinatari[index] = id; }, rimuoviDestinatarioInArray: function ( input_elem ) { var index = $( ".form-destinatario" ).index( $( input_elem ).parents( ".form-destinatario" ) ); if ( this.id_destinatari instanceof Array && this.id_destinatari[index] ) this.id_destinatari.splice( index, 1 ); }, destinatarioSelezionato: function ( event, ui ) { console.log(ui.item.real_value); this.aggiungiDestinatarioInArray( event.target, ui.item.real_value ); $( "#invia_messaggio" ).attr( "disabled", false ); }, scrittoSuDestinatario: function ( e, ui ) { var scritta = $( e.target ).val().substr( 1 ), index_dest = $( ".form-destinatario" ).index( $( e.target ).parents( ".form-destinatario" ) ); if ( this.id_destinatari && this.id_destinatari[index_dest] ) this.id_destinatari[index_dest] = null; if ( $( "#tipo_messaggio" ).val() === "ig" && $( e.target ).val().substr( 0, 1 ) === "#" && /^\d+$/.test( scritta ) && scritta !== "" ) { this.aggiungiDestinatarioInArray( e.target, scritta ); $( "#invia_messaggio" ).attr( "disabled", false ); } //else if ( $("#tipo_messaggio").val() === "ig" && $(e.target).val().substr(0,1) !== "#" ) // $("#invia_messaggio").attr("disabled",true); }, selezionatoDestinatario: function ( e, ui ) { //if( !ui.item && $("#tipo_messaggio").val() !== "ig" && $(e.target).val().substr(0,1) !== "#" ) // $("#invia_messaggio").attr("disabled",true); }, inserisciMittente: function () { if ( $( "#tipo_messaggio" ).val() === "ig" ) this.renderizzaMenuMittenteIG(); else if ( $( "#tipo_messaggio" ).val() === "fg" ) this.renderizzaMenuMittenteFG(); }, resettaInputDestinatari: function () { $( ".form-destinatario:not(:first)" ).remove(); $( ".form-destinatario" ).first().find( ".nome-destinatario" ).val( "" ); }, cambiaListaDestinatari: function ( e ) { this.id_destinatari = []; this.resettaInputDestinatari(); $( "#invia_messaggio" ).attr( "disabled", true ); this.inserisciMittente(); }, recuperaDestinatariAutofill: function ( req, res ) { var url = $( "#tipo_messaggio" ).val() === "ig" ? Constants.API_GET_DESTINATARI_IG : Constants.API_GET_DESTINATARI_FG; //var url = Constants.API_GET_DESTINATARI_IG; Utils.requestData( url, "GET", { term: req.term }, function ( data ) { var dati = data.results.filter( function ( el ) { return el.real_value !== $( "#mittente" ).val(); } ); res( dati ); } ); }, rimuoviAutocompleteDestinatario: function () { if ( $( ".form-destinatario" ).find( ".nome-destinatario" ).data( 'autocomplete' ) ) { $( ".form-destinatario" ).find( ".nome-destinatario" ).autocomplete( "destroy" ); $( ".form-destinatario" ).find( ".nome-destinatario" ).removeData( 'autocomplete' ); } }, impostaAutocompleteDestinatario: function () { this.rimuoviAutocompleteDestinatario(); $( ".form-destinatario" ).find( ".nome-destinatario" ).autocomplete( { autoFocus: true, select: this.destinatarioSelezionato.bind( this ), search: this.scrittoSuDestinatario.bind( this ), change: this.selezionatoDestinatario.bind( this ), source: this.recuperaDestinatariAutofill.bind( this ) } ); }, rispondiAMessaggio: function () { var pgs = this.conversazione_in_lettura[0].tipo_messaggio === "ig" ? this.info_propri_pg.map( function ( el ) { return el.id_personaggio } ) : [this.user_info.email_giocatore]; if ( pgs.indexOf( this.conversazione_in_lettura[0].id_mittente ) === -1 && pgs.indexOf( this.conversazione_in_lettura[0].id_destinatario ) === -1 ) { var attore = this.conversazione_in_lettura[0].tipo_messaggio === "fg" ? "l'utente" : "il personaggio"; Utils.showError( "Non puoi rispondere con " + attore + " attualmente loggato." ); return null; } this.vaiA( $( "#scrivi_messaggio" ), false ) }, annullaInvio: function () { if ( this.conversazione_in_lettura ) this.tornaAConversazione(); else this.vaiA( this.sezioneIniziale(), true ); }, impostaInterfacciaScrittura: function () { var default_type = "fg"; if ( this.user_info && this.user_info.pg_da_loggare ) default_type = "ig"; $( "#tipo_messaggio" ).val( default_type ); this.impostaControlliDestinatari(); $( "#tipo_messaggio" ).unbind( "change" ).change( this.cambiaListaDestinatari.bind( this ) ); $( "#invia_messaggio" ).unbind( "click" ).click( this.inviaMessaggio.bind( this ) ); $( "#risetta_messaggio" ).unbind( "click" ).click( this.annullaInvio.bind( this ) ); if ( this.conversazione_in_lettura ) { default_type = this.conversazione_in_lettura[0].tipo_messaggio; var attori = this.trovaRuoliInConversazione( default_type, this.conversazione_in_lettura ); this.id_destinatari = [attori.id_destinatario]; $( "#tipo_messaggio" ).val( this.conversazione_in_lettura[0].tipo_messaggio ) $( "#tipo_messaggio" ).attr( "disabled", true ); $( ".form-destinatario" ).first().find( ".nome-destinatario" ).val( " A: " + attori.nome_destinatario ); $( ".form-destinatario" ).first().find( ".nome-destinatario" ).attr( "disabled", true ); $( ".form-destinatario" ).first().find( ".controlli-destinatario" ).hide(); if ( this.conversazione_in_lettura[0].oggetto_messaggio ) { var oggetto_decodificato = decodeURIComponent( this.conversazione_in_lettura[0].oggetto_messaggio ); $( "#oggetto" ).val( " Re: " + oggetto_decodificato.replace( /^\s*?re:\s?/i, "" ) ); $( "#oggetto" ).attr( "disabled", true ); } $( "#invia_messaggio" ).attr( "disabled", false ); } this.inserisciMittente(); }, liberaSpazioMessaggio: function () { $( "#oggetto_messaggio" ).text( "" ); $( "#mittente_messaggio" ).text( "" ); $( "#destinatario_messaggio" ).text( "" ); $( "#data_messaggio" ).text( "" ); $( "#corpo_messaggio" ).text( "" ); }, mostraConversazione: function ( dati ) { this.conversazione_in_lettura = dati; $( ".message-container" ).not( "#template_messaggio" ).remove(); for ( var d in dati ) { var nodo_mex = $( "#template_messaggio" ).clone(), testo_mex = decodeURIComponent( dati[d].testo_messaggio ).replace( /\n/g, "<br>" ), testo_ogg = decodeURIComponent( dati[d].oggetto_messaggio ).replace( /Re:\s?/g, "" ); if ( parseInt( d, 10 ) === 0 ) nodo_mex.find( ".oggetto-messaggio" ).text( testo_ogg ); nodo_mex.removeClass( "hidden" ); nodo_mex.attr( "id", "" ); nodo_mex.find( ".mittente-messaggio" ).text( dati[d].nome_mittente ); nodo_mex.find( ".destinatario-messaggio" ).text( dati[d].nome_destinatario ); nodo_mex.find( ".data-messaggio" ).text( dati[d].data_messaggio ); nodo_mex.find( ".corpo-messaggio" ).html( testo_mex ); $( "#template_messaggio" ).parent().append( nodo_mex ); } }, leggiMessaggio: function ( e ) { var target = $( e.target ); this.recuperaConversazione( target.attr( "data-id" ), target.attr( "data-tipo" ) ); this.vaiA( $( "#leggi_messaggio" ), false, e ); }, formattaNonLetti: function ( data, type, row ) { var asterisk = ""; if ( data.substr( 0, 2 ) === "<a" ) asterisk = "<i class='fa fa-asterisk'></i> "; return parseInt( row.letto_messaggio, 10 ) === 0 ? "<strong>" + asterisk + data + "</strong>" : data; }, formattaOggettoMessaggio: function ( data, type, row ) { return this.formattaNonLetti( "<a href='#' " + "class='link-messaggio' " + "data-id='" + row.id_conversazione + "' " + "data-tipo='" + row.tipo_messaggio + "' " + "data-casella='" + row.casella_messaggio + "'>" + decodeURIComponent( data ) + "</a>", type, row ); }, tabellaDisegnata: function ( e ) { $( ".link-messaggio" ).unbind( "click" ); $( ".link-messaggio" ).click( this.leggiMessaggio.bind( this ) ); }, aggiornaDati: function () { if ( this.tab_fg ) this.tab_fg.ajax.reload( null, true ); if ( this.tab_inviati_fg ) this.tab_inviati_fg.ajax.reload( null, true ); if ( this.tab_ig ) this.tab_ig.ajax.reload( null, true ); if ( this.tab_inviati_ig ) this.tab_inviati_ig.ajax.reload( null, true ); }, mostraMessaggi: function () { if ( this.user_info && !( this.user_info.pg_da_loggare && typeof this.user_info.event_id !== "undefined" ) ) $( "#sezioni" ).find( "li:first-child" ).removeClass( "inizialmente-nascosto" ).show(); $( "#sezioni" ).find( "li:last-child" ).removeClass( "inizialmente-nascosto" ).show(); if ( this.user_info && this.user_info.pg_da_loggare && typeof this.user_info.event_id !== "undefined" ) { $( "#sezioni" ).find( ".nome_sezione" ).text( "Caselle" ); $( "#tipo_messaggio" ).val( "ig" ).hide(); // this.recuperaDestinatariAutofill.bind(this,"ig"); } this.tab_fg = this.creaDataTable.call( this, 'lista_fg_table', Constants.API_GET_MESSAGGI, { tipo: "fg" } ); this.tab_ig = this.creaDataTable.call( this, 'lista_ig_table', Constants.API_GET_MESSAGGI, { tipo: "ig" } ); }, tornaAConversazione: function () { this.mostraConversazione( this.conversazione_in_lettura ) this.vaiA( $( "#leggi_messaggio" ), false ); }, trovaRuoliInConversazione: function ( tipo_conv, conversazione ) { if ( tipo_conv === "fg" ) { if ( !conversazione ) return { id_mittente: this.user_info.email_giocatore, nome_mittente: this.user_info.nome_giocatore, id_destinatario: null, nome_destinatario: null } if ( conversazione[0].id_mittente === this.user_info.email_giocatore ) return { id_mittente: conversazione[0].id_mittente, nome_mittente: conversazione[0].nome_mittente, id_destinatario: conversazione[0].id_destinatario, nome_destinatario: conversazione[0].nome_destinatario } else return { id_mittente: conversazione[0].id_destinatario, nome_mittente: conversazione[0].nome_destinatario, id_destinatario: conversazione[0].id_mittente, nome_destinatario: conversazione[0].nome_mittente } } else if ( tipo_conv === "ig" ) { var pgids = this.info_propri_pg.map( function ( el ) { return el.id_personaggio } ), attori; if ( !conversazione && !this.pg_info ) return { id_mittente: null, nome_mittente: null, id_destinatario: null, nome_destinatario: null } else if ( !conversazione && this.pg_info ) return { id_mittente: this.pg_info.id_personaggio, nome_mittente: this.pg_info.nome_personaggio, id_destinatario: null, nome_destinatario: null } attori = [conversazione[0].id_mittente, conversazione[0].id_destinatario] if ( !this.pg_info || ( this.pg_info && attori.indexOf( this.pg_info.id_personaggio ) === -1 ) ) { if ( pgids.indexOf( conversazione[0].id_destinatario ) === -1 ) return { id_mittente: conversazione[0].id_mittente, nome_mittente: conversazione[0].nome_mittente, id_destinatario: conversazione[0].id_destinatario, nome_destinatario: conversazione[0].nome_destinatario } else return { id_mittente: conversazione[0].id_destinatario, nome_mittente: conversazione[0].nome_destinatario, id_destinatario: conversazione[0].id_mittente, nome_destinatario: conversazione[0].nome_mittente } } else if ( this.pg_info && attori.indexOf( this.pg_info.id_personaggio ) !== -1 ) { if ( conversazione[0].id_mittente === this.pg_info.id_personaggio ) return { id_mittente: conversazione[0].id_mittente, nome_mittente: conversazione[0].nome_mittente, id_destinatario: conversazione[0].id_destinatario, nome_destinatario: conversazione[0].nome_destinatario } else return { id_mittente: conversazione[0].id_destinatario, nome_mittente: conversazione[0].nome_destinatario, id_destinatario: conversazione[0].id_mittente, nome_destinatario: conversazione[0].nome_mittente } } } }, renderizzaMenuMittenteIG: function () { var pgs = this.info_propri_pg, pgids = [], attori = this.trovaRuoliInConversazione( "ig", this.conversazione_in_lettura ); $( "#mittente" ).html( "" ); $( "#mittente" ).prop( "disabled", false ); for ( var p in pgs ) { $( "#mittente" ).append( $( "<option>" ).val( pgs[p].id_personaggio ).text( "Da: " + pgs[p].nome_personaggio ) ); pgids.push( pgs[p].id_personaggio ) } if ( attori.id_mittente ) $( "#mittente" ).val( attori.id_mittente ); if ( this.pg_info && !this.conversazione_in_lettura ) { $( "#mittente" ).prop( "disabled", true ); } else if ( this.pg_info && this.conversazione_in_lettura ) { if ( Utils.controllaPermessiUtente( this.user_info, ["rispondiPerPNG"] ) ) { $( "#mittente" ).prop( "disabled", false ); $( "#mittente" ).find( "option[value!='" + attori.id_mittente + "'][value!='" + attori.id_destinatario + "']" ).remove() } //mittente = this.trovaDestinatarioInConv( this.pg_info.id_personaggio ); } else if ( !this.pg_info && this.conversazione_in_lettura ) $( "#mittente" ).prop( "disabled", true ); }, renderizzaMenuMittenteFG: function () { var mittente $( "#mittente" ).html( "" ); $( "#mittente" ).append( $( "<option>" ).val( this.user_info.email_giocatore ).text( "Da: " + this.user_info.nome_giocatore ) ); $( "#mittente" ).val( this.user_info.email_giocatore ).prop( "disabled", true ); }, recuperaDatiPropriPG: function () { Utils.requestData( Constants.API_GET_PGS_PROPRI, "GET", {}, function ( data ) { this.info_propri_pg = data.result; this.inserisciMittente(); }.bind( this ) ); }, creaDataTable: function ( id, url, data ) { //TODO: checkbox per mostrare i messaggi dei soli propri PG return $( '#' + id ) .on( "error.dt", this.erroreDataTable.bind( this ) ) .on( "draw.dt", this.tabellaDisegnata.bind( this ) ) .DataTable( { language: Constants.DATA_TABLE_LANGUAGE, ajax: function ( d, callback ) { //$("input[name='filtri']").val() var tosend = $.extend( d, data ); if ( data.tipo === "ig" ) tosend.filtro = $( '#' + id ).parents( ".box-body" ).find( "input[name='filtri']:checked" ).val(); Utils.requestData( url, "GET", tosend, callback ); }, columns: [ { title: "Partecipanti Conversazione", data: "coinvolti", width: "50%", render: this.formattaNonLetti.bind( this ) }, { title: "Oggetto", data: "oggetto_messaggio", render: this.formattaOggettoMessaggio.bind( this ) }, { title: "Data", data: "data_messaggio", width: "15%", render: this.formattaNonLetti.bind( this ) } ], order: [[2, 'desc']] } ); }, impostaControlliDestinatari: function () { $( ".form-destinatario" ).find( ".aggiungi-destinatario" ).unbind( "click" ); $( ".form-destinatario" ).find( ".rimuovi-destinatario" ).unbind( "click" ); $( ".form-destinatario" ).find( ".aggiungi-destinatario" ).click( this.aggiungiDestinatario.bind( this ) ); $( ".form-destinatario" ).find( ".rimuovi-destinatario:not(.disabled)" ).click( this.rimuoviDestinatario.bind( this ) ); this.impostaAutocompleteDestinatario(); if ( $( "#tipo_messaggio" ).val() === "ig" ) $( ".form-destinatario" ).find( ".nome-destinatario" ).popover( { content: "In caso di ID inserire sempre # prima del numero.", trigger: Utils.isDeviceMobile() ? "click" : "hover", placement: "top" } ); }, aggiungiDestinatario: function ( e ) { var nodo = $( ".form-destinatario" ).first().clone(); nodo.find( ".nome-destinatario" ).val( "" ); nodo.find( ".rimuovi-destinatario" ).removeClass( "disabled" ); nodo.insertAfter( $( e.currentTarget ).parents( ".form-destinatario" ) ); this.impostaControlliDestinatari(); }, rimuoviDestinatario: function ( e ) { this.rimuoviDestinatarioInArray( $( e.currentTarget ).parents( ".form-destinatario" ).find( ".nome-destinatario" )[0] ); $( e.currentTarget ).parents( ".form-destinatario" ).remove(); }, messaggioInviatoOk: function ( data ) { Utils.showMessage( data.message, Utils.reloadPage ); }, inviaDatiMessaggio: function ( dati ) { delete dati.mittente_text; Utils.requestData( Constants.API_POST_MESSAGGIO, "POST", dati, this.messaggioInviatoOk.bind( this ), null, null ); }, mostraConfermaInvio: function ( dati ) { Utils.showConfirm( dati.mittente_text + ", confermi di voler inviare il messaggio?", this.inviaDatiMessaggio.bind( this, dati ), false ); }, inviaMessaggio: function () { var destinatari = this.id_destinatari, oggetto = $( "#oggetto" ).val(), testo = $( "#messaggio" ).val(), data = {}; if ( !destinatari || ( destinatari && destinatari.length === 0 ) || !oggetto || !testo ) { Utils.showError( "Per favore compilare tutti i campi." ); return false; } data.tipo = $( "#tipo_messaggio" ).val(); data.mittente = $( "#mittente" ).val(); data.destinatari = destinatari; data.oggetto = encodeURIComponent( oggetto ); data.testo = encodeURIComponent( testo ); if ( destinatari.indexOf( data.mittente ) !== -1 ) { Utils.showError( "Il mittente non pu&ograve; figurare nella lista dei destinatari." ) return false; } if ( this.conversazione_in_lettura ) { data.id_risposta = this.conversazione_in_lettura[0].id_messaggio; data.id_conversazione = this.conversazione_in_lettura[0].id_conversazione; } data.mittente_text = $( "#mittente" ).find( "option:selected" ).text().replace( "Da: ", "" ); if ( data.tipo === "ig" ) this.mostraConfermaInvio( data ); else this.inviaDatiMessaggio( data ); }, recuperaConversazione: function ( idconv, tipo ) { var dati = { mexid: idconv, tipo: tipo }; Utils.requestData( Constants.API_GET_CONVERSAZIONE, "POST", dati, function ( data ) { this.mostraConversazione( data.result ); }.bind( this ) ); }, nuovoBoxAppare: function ( cosa, e ) { this.aggiornaDati(); if ( !cosa.is( $( "#leggi_messaggio" ) ) ) this.liberaSpazioMessaggio(); if ( cosa.is( $( "#scrivi_messaggio" ) ) ) this.impostaInterfacciaScrittura(); if ( e && !$( e.target ).is( $( "#rispondi_messaggio" ) ) && !cosa.is( $( "#leggi_messaggio" ) ) ) this.risettaMessaggio(); }, mostra: function ( cosa, e ) { this.visibile_ora = cosa; this.visibile_ora.removeClass( "inizialmente-nascosto" ).fadeIn( 400 ); this.nuovoBoxAppare( cosa, e ); }, vaiA: function ( dove, force, e ) { if ( this.visibile_ora.is( dove ) && !force ) return false; else if ( this.visibile_ora.is( $( "#scrivi_messaggio" ) ) ) { this.resettaInputDestinatari(); this.impostaControlliDestinatari(); } var target = e ? $( e.target ) : null; $( ".active" ).removeClass( "active" ); if ( target && target.is( "a" ) ) target.parent().addClass( "active" ); else if ( target && !target.is( "a" ) ) target.addClass( "active" ); this.visibile_ora.fadeOut( 400, this.mostra.bind( this, dove, e ) ); }, controllaStorage: function () { var scrivi_a = window.localStorage.getItem( "scrivi_a" ); if ( scrivi_a ) { var dati = JSON.parse( scrivi_a ), sp = dati.id.split( "#" ), tipo = sp[0], id_dest = sp[1], id_mitt = 0; window.localStorage.removeItem( "scrivi_a" ); if ( tipo === "ig" && !this.pg_info ) id_mitt = null; else if ( tipo === "ig" && this.pg_info ) id_mitt = this.pg_info.id_personaggio; else if ( tipo === "fg" ) id_mitt = this.user_info.email_giocatore; if ( ( tipo === "ig" && this.user_info && this.user_info.pg_propri.length > 0 && this.user_info.pg_propri.indexOf( id ) !== -1 ) || ( tipo === "fg" && this.user_info.email_giocatore === id ) ) { Utils.showError( "Non puoi mandare messaggi a te stesso o ai tuoi personaggi.", Utils.redirectTo.bind( this, Constants.MAIN_PAGE ) ); return; } this.conversazione_in_lettura = [{ id_mittente: id_dest, id_destinatario: id_mitt, tipo: tipo, mittente: dati.nome }]; this.vaiA( $( "#scrivi_messaggio" ), false, null ); } }, filtraMessaggiIG: function ( e ) { var table_id = $( e.currentTarget ).parents( ".box-body" ).find( "table" ).attr( "id" ); if ( table_id === "lista_ig_table" ) this.tab_ig.draw(); }, setListeners: function () { $( "#vaia_fg" ).click( this.vaiA.bind( this, $( "#lista_fg" ), false ) ); $( "#vaia_ig" ).click( this.vaiA.bind( this, $( "#lista_ig" ), false ) ); $( "#vaia_scrivi" ).click( this.vaiA.bind( this, $( "#scrivi_messaggio" ), false ) ); $( "#rispondi_messaggio" ).click( this.rispondiAMessaggio.bind( this ) ); $( '.iradio' ).iCheck( { radioClass: 'iradio_square-blue', labelHover: true } ).on( "ifChecked", this.filtraMessaggiIG.bind( this ) ); } } }(); $( function () { MessaggingManager.init(); } ); <file_sep>/server/src/classes/Utils.class.php <?php class Utils { static function errorJSON($msg, $type = "genericError") { $json = array( "status" => "error", "type" => $type, "message" => $msg ); return json_encode($json); } static function mappaPermessiUtente($item) { return $item["permessi"]; } static function mappaPGUtente($item) { return $item["id_personaggio"]; } static function mappaRisultatoJson($item) { return $item["json"]; } static function mappaId($item) { return $item["id"]; } static function mappaIdAbilita($item) { return $item["id_abilita"]; } static function mappaOffsetPFAbilita($item) { return $item["offset_pf_abilita"]; } static function mappaCheckbox($item) { return $item == "on" ? 1 : 0; } static function mappaArrayDiArrayAssoc($arr, $key) { $mappa = function ($item) use ($key) { return $item[$key]; }; return array_map($mappa, $arr); } static function filtraArrayConValori($arr, $valori) { $filtro = function ($item) use ($valori) { return in_array($item, $valori); }; return array_filter($arr, $filtro); } static function filtraArrayDiArrayAssoc($arr, $key, $valori) { $filtro = function ( $item ) use ($key, $valori) { return in_array( $item[$key], $valori ); }; return array_values( array_filter($arr, $filtro) ); } /*static function filtraArrayConChiavi( $arr, $chiavi ) { $filtro = function ( $key ) use ( $chiavi ) { return in_array($key, $chiavi); }; return array_filter($arr, $filtro, ARRAY_FILTER_USE_KEY); }*/ static function filtraArrayConChiavi($arr, $chiavi) { $newarr = []; if (count($arr) > 0) { foreach ($arr as $k => $v) { if (in_array($k, $chiavi)) $newarr[$k] = $v; } } return $newarr; } static function filtraClasseSenzaPrerequisito($item) { return $item["prerequisito_classe"] != NULL; } static function filtraAbilitaSenzaPrerequisito($item) { return $item["prerequisito_abilita"] != NULL; } static function filtraAbilitaSportivo($item) { global $ID_CLASSE_SPORTIVO; return (int)$item["classi_id_classe"] === $ID_CLASSE_SPORTIVO; } static function filtraAbilitaGuardianoBase($item) { global $ID_CLASSE_GUARDIANO_BASE; return (int)$item["classi_id_classe"] === $ID_CLASSE_GUARDIANO_BASE; } static function filtraAbilitaGuardianoAvanzato($item) { global $ID_CLASSE_GUARDIANO_AVANZATO; return (int)$item["classi_id_classe"] === $ID_CLASSE_GUARDIANO_AVANZATO; } static function filtraAbilitaAssaltatoreBase($item) { global $ID_CLASSE_ASSALTATORE_BASE; return (int)$item["classi_id_classe"] === $ID_CLASSE_ASSALTATORE_BASE; } static function filtraAbilitaAssaltatoreAvanzato($item) { global $ID_CLASSE_ASSALTATORE_AVANZATO; return (int)$item["classi_id_classe"] === $ID_CLASSE_ASSALTATORE_AVANZATO; } static function filtraAbilitaSupportoBase($item) { global $ID_CLASSE_SUPPORTO_BASE; return (int)$item["classi_id_classe"] === $ID_CLASSE_SUPPORTO_BASE; } static function filtraAbilitaSupportoAvanzato($item) { global $ID_CLASSE_SUPPORTO_AVANZATO; return (int)$item["classi_id_classe"] === $ID_CLASSE_SUPPORTO_AVANZATO; } static function filtraAbilitaGuastatoreBase($item) { global $ID_CLASSE_GUASTATORE_BASE; return (int)$item["classi_id_classe"] === $ID_CLASSE_GUASTATORE_BASE; } static function filtraAbilitaGuastatoreAvanzato($item) { global $ID_CLASSE_GUASTATORE_AVANZATO; return (int)$item["classi_id_classe"] === $ID_CLASSE_GUASTATORE_AVANZATO; } static function rimuoviElementoArrayMultidimensionale(&$arr, $chiave, $valore) { foreach ($arr as $i => $a) { if ($a[$chiave] === $valore) { array_splice($arr, $i, 1); break; } } } static function rimuoviPiuElementiDaArray(&$arr, $elems) { if( count($elems) > 0 ) { foreach ($elems as $e) { $i = array_search($e, $arr); if ($i !== False) array_splice($arr, $i, 1); } } } static function generatePassword($length = 8) { $alphabet = "<KEY>"; $pass = array(); $alphaLength = strlen($alphabet) - 1; for ($i = 0; $i < $length; $i++) { $n = rand(0, $alphaLength); $pass[] = $alphabet[$n]; } return implode($pass); } static function controllaCF($cf) { $pattern = "/^[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]$/"; return preg_match($pattern, $cf); } static function controllaMail($mail) { $pattern = "/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/"; return preg_match($pattern, $mail); } static function soloSpazi($stringa) { $pattern = "/^\s+$/"; return preg_match($pattern, $stringa); } static function utf8ize($d) { if (is_array($d)) { foreach ($d as $k => $v) { $d[$k] = self::utf8ize($v); } } else if (is_string($d)) { return utf8_encode($d); } return $d; } static function getUserIP() { $client = @$_SERVER['HTTP_CLIENT_IP']; $forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; $remote = $_SERVER['REMOTE_ADDR']; if (filter_var($client, FILTER_VALIDATE_IP)) { $ip = $client; } elseif (filter_var($forward, FILTER_VALIDATE_IP)) { $ip = $forward; } else { $ip = $remote; } return $ip; } /** * Check if a client IP is in our Server subnet * * @return boolean */ static function clientInSameLAN($client_ip = false, $server_ip = false) { // if (!$client_ip) // $client_ip = $_SERVER['REMOTE_ADDR']; // if (!$server_ip) // $server_ip = $_SERVER['SERVER_ADDR']; // if( !preg_match("/^192\.168\./", $client_ip) ) // return False; // if( !preg_match("/^192\.168\./", $server_ip) ) // return False; return True; } static function filterDataTableResults($draw, $columns, $order, $start, $length, $search, $query_res) { $output = [ "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => count($query_res), "recordsFiltered" => 0, "data" => [] ]; if (count($query_res) == 0) { return $output; } $filtered = array(); if (isset($search) && isset($search["value"]) && $search["value"] != "") { $ricerca = $search["value"]; foreach($query_res as $row) { foreach($row as $campo => $valore) { if (stripos($valore, $ricerca) !== False) { $filtered[] = $row; break 1; } } } } else { $filtered = $query_res; } if (count($filtered) > 0) $result = array_slice($filtered, $start, $length); $output["recordsFiltered"] = count($filtered); $output["data"] = $result; return $output; } } <file_sep>/server/src/utils/pxreset.php <?php // ini_set('display_errors', 1); // ini_set('display_startup_errors', 1); // error_reporting(E_ALL); $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/DatabaseBridge.class.php"); function registraAzione($database, $pgid, $azione, $tabella, $campo, $vecchio_valore, $nuovo_valore) { $vecchio = !isset($vecchio_valore) ? "NULL" : ":vecchio"; $nuovo = !isset($nuovo_valore) ? "NULL" : ":nuovo"; $query_azione = "INSERT INTO storico_azioni ( id_personaggio_azione, giocatori_email_giocatore, tipo_azione, tabella_azione, campo_azione, valore_vecchio_azione, valore_nuovo_azione ) VALUES ( :idpg, :email, :azione, :tabella, :campo, $vecchio, $nuovo )"; $params = [ ":idpg" => $pgid, ":email" => "<EMAIL>", ":azione" => $azione, ":tabella" => $tabella, ":campo" => $campo ]; if (isset($vecchio_valore)) $params[":vecchio"] = $vecchio_valore; if (isset($nuovo_valore)) $params[":nuovo"] = $nuovo_valore; $database->doQuery($query_azione, $params, False); } echo "<html><head><meta charset='UTF-8' /></head><body>"; try { $db = new DatabaseBridge(); $MAPPA_COSTO_CLASSI_CIVILI = array(0, 20, 40, 60, 80, 100, 120); $query = "SELECT t.id_personaggio, t.nome_personaggio, CONCAT(t.nome_giocatore,' ',t.cognome_giocatore) as nome_giocatore, t.px_personaggio, t.pc_personaggio, t.num_eventi_tot, t.num_live_online, t.num_giorni_live, t.px_base, t.px_base + ((t.num_eventi_tot - t.num_live_online) * 10) + (t.num_giorni_live * 20) as px_guadagnati, t.tot_costo_abilita_civili, t.num_classi_civili, t.pc_base, t.pc_base + t.num_eventi_tot - t.num_live_online as pc_guadagnati, t.pc_spesi, t.pc_base + t.num_eventi_tot - t.num_live_online - t.pc_spesi as pc_rimasti FROM ( SELECT p.id_personaggio, p.nome_personaggio, g.nome_giocatore, g.cognome_giocatore, p.px_personaggio, p.pc_personaggio, g.ruoli_nome_ruolo, COUNT(ip.eventi_id_evento) as num_eventi_tot, IF(p.data_creazione_personaggio > '2019-01-01 00:00:00', 220, 100) as px_base, IF(p.data_creazione_personaggio > '2019-01-01 00:00:00', 6, 4) as pc_base, SUM((e.data_fine_evento - e.data_inizio_evento) + 1) as num_giorni_live, SUM(IF(e.id_evento IN (10,11), 1, 0)) as num_live_online, ( SELECT SUM(a.costo_abilita) FROM personaggi p2 JOIN personaggi_has_abilita pha ON pha.personaggi_id_personaggio = p2.id_personaggio JOIN abilita a ON a.id_abilita = pha.abilita_id_abilita WHERE a.tipo_abilita = 'civile' AND p2.id_personaggio = p.id_personaggio GROUP BY p2.id_personaggio ) as tot_costo_abilita_civili, ( SELECT COUNT(c.id_classe) FROM personaggi p3 JOIN personaggi_has_classi phc ON phc.personaggi_id_personaggio = p3.id_personaggio JOIN classi c ON c.id_classe = phc.classi_id_classe WHERE c.tipo_classe = 'civile' AND p3.id_personaggio = p.id_personaggio GROUP BY p3.id_personaggio ) as num_classi_civili, ( (SELECT COUNT(a2.id_abilita) FROM personaggi p4 JOIN personaggi_has_abilita pha2 ON pha2.personaggi_id_personaggio = p4.id_personaggio JOIN abilita a2 ON a2.id_abilita = pha2.abilita_id_abilita WHERE a2.tipo_abilita = 'militare' AND p4.id_personaggio = p.id_personaggio GROUP BY p4.id_personaggio) + (SELECT COUNT(c2.id_classe) FROM personaggi p5 JOIN personaggi_has_classi phc2 ON phc2.personaggi_id_personaggio = p5.id_personaggio JOIN classi c2 ON c2.id_classe = phc2.classi_id_classe WHERE c2.tipo_classe = 'militare' AND p5.id_personaggio = p.id_personaggio GROUP BY p5.id_personaggio) ) as pc_spesi FROM personaggi p JOIN iscrizione_personaggi ip ON ip.personaggi_id_personaggio = p.id_personaggio JOIN eventi e ON e.id_evento = ip.eventi_id_evento JOIN giocatori g ON g.email_giocatore = p.giocatori_email_giocatore WHERE g.ruoli_nome_ruolo NOT IN ('staff','admin') AND ip.ha_partecipato_iscrizione = 1 GROUP BY p.id_personaggio ) as t ORDER BY pc_rimasti ASC LIMIT 10000"; $risultati = $db->doQuery($query, [], False); echo "<table><thead><tr> <td>ID PG</td> <td>NOME PG</td> <td>NOME GIOCATORE</td> <td>PX GUADAGNATI</td> <td>PX RIMASTI</td> <td>PC GUADAGNATI</td> <td>PC RIMASTI</td> </tr></thead><tbody>"; foreach ($risultati as $r) { $px_spesi = (int)$r["tot_costo_abilita_civili"]; for ($i = 0; $i < (int)$r["num_classi_civili"]; $i++) $px_spesi += $MAPPA_COSTO_CLASSI_CIVILI[$i]; $px_rimasti = (int)$r[px_guadagnati] - $px_spesi; echo " <td>$r[id_personaggio]</td> <td>$r[nome_personaggio]</td> <td>$r[nome_giocatore]</td> <td>$r[px_guadagnati]</td> <td>$px_rimasti</td> <td>$r[pc_guadagnati]</td> <td>$r[pc_rimasti]</td> </tr>"; // $query_mod = "UPDATE personaggi SET px_personaggio = :px, pc_personaggio = :pc WHERE id_personaggio = :id"; // $db->doQuery($query_mod, [":px" => $r["px_guadagnati"], ":pc" => $r["pc_guadagnati"], ":id" => $r["id_personaggio"]], False); // registraAzione( // $db, // $r["id_personaggio"], // "UPDATE", // "personaggi", // "px_personaggio", // $r["px_personaggio"], // $r["px_guadagnati"] // ); // registraAzione( // $db, // $r["id_personaggio"], // "UPDATE", // "personaggi", // "pc_personaggio", // $r["pc_personaggio"], // $r["pc_guadagnati"] // ); // if ($px_rimasti < 0) { // echo "$r[nome_personaggio] ($r[id_personaggio]) => RESETTO ABILITA CIVILI\n"; // $query_ab = " // SELECT // pha.abilita_id_abilita, // a.nome_abilita // FROM // personaggi_has_abilita pha // JOIN // abilita a on a.id_abilita = pha.abilita_id_abilita // WHERE // pha.personaggi_id_personaggio = :id AND // a.tipo_abilita = 'civile';"; // $ris_ab = $db->doQuery($query_ab, [":id" => $r["id_personaggio"]], False); // $query_del_ab = "DELETE FROM personaggi_has_abilita // WHERE personaggi_id_personaggio = :id AND abilita_id_abilita IN (SELECT id_abilita FROM abilita WHERE tipo_abilita = 'civile')"; // $db->doQuery($query_del_ab, [":id" => $r["id_personaggio"]], False); // foreach ($ris_ab as $ra) { // registraAzione( // $db, // $r["id_personaggio"], // "DELETE", // "personaggi_has_abilita", // "", // $ra["nome_abilita"]." (".$ra["abilita_id_abilita"].")", // null // ); // } // $query_cl = " // SELECT // phc.classi_id_classe, // c.nome_classe // FROM // personaggi_has_classi phc // JOIN // classi c on c.id_classe = phc.classi_id_classe // WHERE // phc.personaggi_id_personaggio = :id AND // c.tipo_classe = 'civile';"; // $ris_cl = $db->doQuery($query_cl, [":id" => $r["id_personaggio"]], False); // $query_del_cl = "DELETE FROM personaggi_has_classi // WHERE personaggi_id_personaggio = :id AND classi_id_classe IN (SELECT id_classe FROM classi WHERE tipo_classe = 'civile')"; // $db->doQuery($query_del_cl, [":id" => $r["id_personaggio"]], False); // foreach ($ris_cl as $rc) { // registraAzione( // $db, // $r["id_personaggio"], // "DELETE", // "personaggi_has_classi", // "", // $rc["nome_classe"]." (".$rc["classi_id_classe"].")", // null // ); // } // $query_op = " // SELECT // pho.abilita_id_abilita, // a.nome_abilita, // o.opzione // FROM // personaggi_has_opzioni_abilita pho // JOIN // abilita a on a.id_abilita = pho.abilita_id_abilita // JOIN // opzioni_abilita o on o.opzione = pho.opzioni_abilita_opzione // WHERE // pho.personaggi_id_personaggio = :id AND // a.tipo_abilita = 'civile';"; // $ris_op = $db->doQuery($query_op, [":id" => $r["id_personaggio"]], False); // $query_del_op = "DELETE FROM personaggi_has_opzioni_abilita // WHERE personaggi_id_personaggio = :id AND abilita_id_abilita IN (SELECT id_abilita FROM abilita WHERE tipo_abilita = 'civile')"; // $db->doQuery($query_del_op, [":id" => $r["id_personaggio"]], False); // foreach ($ris_op as $op) { // registraAzione( // $db, // $r["id_personaggio"], // "DELETE", // "personaggi_has_opzioni_abilita", // "", // $op["nome_abilita"]." > ".$op["opzione"], // null // ); // } // } // } echo "</tbody></table>"; } catch (Exception $e) { echo $e->getMessage(); } echo "</body></html>";<file_sep>/client/app/scripts/controllers/MarketplaceManager.js var MarketplaceManager = function () { return { init: function () { $( "#box_carrello" ).width( $( "#box_carrello" ).parent().width() ); $( "#box_carrello" ).css( "max-height", $( ".content-wrapper" ).height() - 41 - 51 - 20 ); $( "#sconto_msg" ).text( $( "#sconto_msg" ).text().replace( /\{X}/g, Constants.CARTELLINI_PER_PAG ).replace( /\{Y}/g, Constants.SCONTO_MERCATO ) ); this.pg_info = JSON.parse( window.localStorage.getItem( "logged_pg" ) ); this.placeholder_credito = $( "#riga_credito" ).find( "td:nth-child(2)" ).html(); this.carrello_componenti = {}; if ( !this.pg_info ) { $( "#paga" ).wrap( "<div data-toggle='tooltip' data-title='Devi essere loggato con un personaggio.'></div>" ); $( "#paga" ).attr( "disabled", true ); } this.setListeners(); this.impostaTabellaTecnico(); this.impostaTabellaChimico(); }, mostraCreditoResiduo: function ( e ) { if ( this.pg_info ) $( "#riga_credito" ).find( "td:nth-child(2)" ).html( this.pg_info.credito_personaggio + " <i class='fa fa-btc'></i>" ); }, nascondiCreditoResiduo: function ( e ) { $( "#riga_credito" ).find( "td:nth-child(2)" ).html( this.placeholder_credito ); }, toggleCreditoResiduo: function () { console.log( $( "#riga_credito" ).find( "td:nth-child(2)" ).html() ); var visible = $( "#riga_credito" ).find( "td:nth-child(2)" ).html().indexOf( this.placeholder_credito ) === -1; if ( this.pg_info && !visible ) this.mostraCreditoResiduo(); else this.nascondiCreditoResiduo(); }, faiPartireStampa: function ( e ) { $( "#pagina_stampa" )[0].contentWindow.print(); }, prendiDatiPGAggiornati: function ( dati_pg ) { this.pg_info = dati_pg; }, stampa: function ( e ) { AdminLTEManager.aggiornaDatiPG( this.prendiDatiPGAggiornati.bind( this ) ); Utils.resetSubmitBtn(); if ( !Utils.isDeviceMobile() ) { window.localStorage.setItem( "cartellini_da_stampare", JSON.stringify( { componente_crafting: this.carrello_componenti } ) ); $( "#pagina_stampa" ).attr( "src", Constants.STAMPA_CARTELLINI_PAGE ); window.stampa_subito = true; } else Utils.reloadPage(); }, paga: function ( e ) { var messaggio = "Pagamento avvenuto con successo.<br>" + ( !Utils.isDeviceMobile() ? "Premi 'CHIUDI' per far partire la stampa." : "Vai dallo staff per la stampa." ) if ( Object.keys( this.carrello_componenti ).length === 0 ) { Utils.showError( "Non ci sono articoli nel carrello." ); return false; } Utils.requestData( Constants.API_COMPRA_COMPONENTI, "POST", { ids: this.carrello_componenti }, messaggio, null, this.stampa.bind( this ) ); }, controllaQtaPerSconto: function () { var qta_tot = $( "#carrello tr:not(tr[id*='riga']) > td:nth-child(2)" ) .toArray() .map( function ( el ) { return parseInt( el.innerText, 10 ) || 0; } ) .reduce( function ( acc, val ) { return acc + val; } ), sconto = qta_tot % Constants.QTA_PER_SCONTO_MERCATO === 0 ? Constants.SCONTO_MERCATO : 0; $( "#riga_sconto > td:nth-child(2)" ).text( sconto + "%" ); }, calcolaTotaleCarrello: function () { var sconto = parseInt( $( "#riga_sconto > td:nth-child(2)" ).text(), 10 ) / 100 || 0, tot = $( "#carrello tr > td:nth-child(3)" ) .toArray() .map( function ( el ) { return parseInt( el.innerText, 10 ) || 0; } ) .reduce( function ( acc, val ) { return acc + val; } ), tot_scontato = tot - ( tot * sconto ); $( "#riga_totale > td:nth-child(2)" ).text( tot_scontato ); }, aumentaQtaProdotto: function ( e ) { var t = $( e.target ), riga = t.parents( "tr" ), id_prodotto = riga.find( "td:nth-child(1)" ).text(), qta = parseInt( riga.find( "td:nth-child(2)" ).text(), 10 ) || 0, vecchio_tot = parseInt( riga.find( "td:nth-child(3)" ).text(), 10 ) || 0, costo = vecchio_tot / qta, indice = Utils.indexOfArrayOfObjects( this.carrello_componenti, "id", id_prodotto ); riga.hide(); riga.find( "td:nth-child(2)" ).text( qta + 1 ); riga.find( "td:nth-child(3)" ).text( vecchio_tot + costo ); riga.show( 500 ); if ( this.carrello_componenti[id_prodotto] ) this.carrello_componenti[id_prodotto]++; else this.carrello_componenti[id_prodotto] = 1; this.controllaQtaPerSconto(); this.calcolaTotaleCarrello(); }, diminuisciQtaProdotto: function ( e ) { var t = $( e.target ), riga = t.parents( "tr" ), id_prodotto = riga.find( "td:nth-child(1)" ).text(), qta = parseInt( riga.find( "td:nth-child(2)" ).text(), 10 ) || 0, vecchio_tot = parseInt( riga.find( "td:nth-child(3)" ).text(), 10 ) || 0, costo = vecchio_tot / qta; if ( qta - 1 <= 0 ) riga.remove(); else { riga.hide(); riga.find( "td:nth-child(2)" ).text( qta - 1 ); riga.find( "td:nth-child(3)" ).text( vecchio_tot - costo ); riga.show( 500 ); } if ( this.carrello_componenti[id_prodotto] && this.carrello_componenti[id_prodotto] > 1 ) this.carrello_componenti[id_prodotto]--; else if ( this.carrello_componenti[id_prodotto] && this.carrello_componenti[id_prodotto] === 1 ) delete this.carrello_componenti[id_prodotto]; this.controllaQtaPerSconto(); this.calcolaTotaleCarrello(); }, impostaPulsantiCarrello: function () { $( "td > button.add-item" ).unbind( "click" ); $( "td > button.add-item" ).click( this.aumentaQtaProdotto.bind( this ) ); $( "td > button.remove-item" ).unbind( "click" ); $( "td > button.remove-item" ).click( this.diminuisciQtaProdotto.bind( this ) ); }, oggettoInCarrello: function ( e ) { var t = $( e.target ), datatable = this[t.parents( "table" ).attr( "id" )], dati = datatable.row( t.parents( "tr" ) ).data(), id_prodotto = dati.id_componente, costo = parseInt( dati.costo_attuale_componente, 10 ), col_car = $( "#carrello" ).find( "#" + id_prodotto + " td:first-child" ); if ( col_car.length === 0 ) { var riga = $( "<tr></tr>" ); riga.attr( "id", id_prodotto ); riga.append( "<td>" + id_prodotto + "</td>" ); riga.append( "<td>1</td>" ); riga.append( "<td>" + costo + "</td>" ); riga.append( $( "<td></td>" ) .append( "<button type='button' class='btn btn-xs btn-default remove-item'><i class='fa fa-minus'></i></button>" ) .append( "&nbsp;" ) .append( "<button type='button' class='btn btn-xs btn-default add-item'><i class='fa fa-plus'></i></button>" ) ); riga.hide(); $( "#riga_sconto" ).before( riga ); riga.show( 500 ); this.carrello_componenti[id_prodotto] = 1; } else this.aumentaQtaProdotto( { target: col_car } ); this.controllaQtaPerSconto(); this.calcolaTotaleCarrello(); this.impostaPulsantiCarrello(); }, setGridListeners: function () { AdminLTEManager.controllaPermessi(); $( "td [data-toggle='popover']" ).popover( "destroy" ); $( "td [data-toggle='popover']" ).popover(); //$( 'input[type="checkbox"]' ).iCheck("destroy"); //$( 'input[type="checkbox"]' ).iCheck( { checkboxClass : 'icheckbox_square-blue' } ); //$( 'input[type="checkbox"]' ).on( "ifChanged", this.ricettaSelezionata.bind(this) ); $( "[data-toggle='tooltip']" ).tooltip( "destroy" ); $( "[data-toggle='tooltip']" ).tooltip(); $( "td > button.carrello" ).unbind( "click" ); $( "td > button.carrello" ).click( this.oggettoInCarrello.bind( this ) ); }, erroreDataTable: function ( e, settings ) { if ( !settings.jqXHR || !settings.jqXHR.responseText ) { console.log( "DataTable error:", e, settings ); return false; } var real_error = settings.jqXHR.responseText.replace( /^([\S\s]*?)\{"[\S\s]*/i, "$1" ); real_error = real_error.replace( "\n", "<br>" ); Utils.showError( real_error ); }, renderCaratteristiche: function ( data, type, row ) { var text_color_energia = "yellow", text_color_volume = "yellow", caret_energia = "left", caret_volume = "left"; if ( parseInt( row.energia_componente ) > 0 ) { text_color_energia = "green"; caret_energia = "up"; } else if ( parseInt( row.energia_componente ) < 0 ) { text_color_energia = "red"; caret_energia = "down"; } if ( parseInt( row.volume_componente ) > 0 ) { text_color_volume = "green"; caret_volume = "up"; } else if ( parseInt( row.volume_componente ) < 0 ) { text_color_volume = "red"; caret_volume = "down"; } return "<span class='description-percentage text-" + text_color_energia + "'><i class='fa fa-caret-" + caret_energia + "'></i></span> Enerigia (" + row.energia_componente + ")</span><br>" + "<span class='description-percentage text-" + text_color_volume + "'><i class='fa fa-caret-" + caret_volume + "'></i></span> Volume (" + row.volume_componente + ")</span>"; }, renderVariazioni: function ( data, type, row ) { var variazione = 0, caret = "left", text_color = "yellow"; if ( row.costo_vecchio_componente && parseInt( row.costo_vecchio_componente ) !== 0 ) variazione = ( ( parseInt( row.costo_attuale_componente ) - parseInt( row.costo_vecchio_componente ) ) / parseInt( row.costo_vecchio_componente ) ) * 100; else variazione = 100; if ( variazione > 0 ) { caret = "up"; text_color = "red"; } else if ( variazione < 0 ) { caret = "down"; text_color = "green"; } return "<span class='description-percentage text-" + text_color + "'>" + "<i class='fa fa-caret-" + caret + "'></i> " + variazione.toFixed( 2 ) + " %</span>"; }, renderAzioni: function ( data, type, row ) { var pulsanti = ""; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default carrello' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Aggiungi al Carrello'><i class='fa fa-cart-plus'></i></button>"; return pulsanti; }, impostaTabellaTecnico: function () { var columns = []; columns.push( { title: "ID", data: "id_componente" } ); columns.push( { title: "Tipo", data: "tipo_componente" } ); columns.push( { title: "Nome", data: "nome_componente" } ); //columns.push({ // title: "Descrizione", // data : "descrizione_componente" //}); columns.push( { title: "Effetti", data: "effetto_sicuro_componente" } ); columns.push( { title: "Caratteristiche", render: this.renderCaratteristiche.bind( this ), orderable: false } ); columns.push( { title: "Costo", data: "costo_attuale_componente" } ); columns.push( { title: "Variazioni", render: this.renderVariazioni.bind( this ), orderable: false } ); columns.push( { title: "Azioni", render: this.renderAzioni.bind( this ), orderable: false } ); this.tabella_tecnico = $( '#tabella_tecnico' ) .on( "error.dt", this.erroreDataTable.bind( this ) ) .on( "draw.dt", this.setGridListeners.bind( this ) ) .DataTable( { language: Constants.DATA_TABLE_LANGUAGE, ajax: function ( data, callback ) { Utils.requestData( Constants.API_GET_COMPONENTI_BASE, "GET", $.extend( data, { tipo: "tecnico" } ), callback ); }, columns: columns, order: [[0, 'asc']] } ); }, impostaTabellaChimico: function () { var columns = []; columns.push( { title: "ID", data: "id_componente" } ); columns.push( { title: "Tipo", data: "tipo_componente" } ); columns.push( { title: "Nome", data: "nome_componente" } ); columns.push( { title: "Descrizione", data: "descrizione_componente" } ); columns.push( { title: "Val Curativo", data: "curativo_primario_componente" } ); columns.push( { title: "Val Tossico", data: "tossico_primario_componente", type: "num" } ); columns.push( { title: "Val Psicotropo", data: "psicotropo_primario_componente", type: "num" } ); columns.push( { title: "Costo", data: "costo_attuale_componente", type: "num" } ); columns.push( { title: "Azioni", render: this.renderAzioni.bind( this ), orderable: false } ); this.tabella_chimico = $( '#tabella_chimico' ) .on( "error.dt", this.erroreDataTable.bind( this ) ) .on( "draw.dt", this.setGridListeners.bind( this ) ) .DataTable( { language: Constants.DATA_TABLE_LANGUAGE, ajax: function ( data, callback ) { Utils.requestData( Constants.API_GET_COMPONENTI_BASE, "GET", $.extend( data, { tipo: "chimico" } ), callback ); }, columns: columns, order: [[0, 'asc']] } ); }, pageResize: function () { $( "#box_carrello" ).width( $( "#box_carrello" ).parent().width() ); }, setListeners: function () { $( window ).resize( this.pageResize.bind( this ) ); $( "#paga" ).click( this.paga.bind( this ) ); if ( !Utils.isDeviceMobile() ) { $( "#riga_credito" ).find( "td:nth-child(2)" ).mousedown( this.mostraCreditoResiduo.bind( this ) ); $( document ).mouseup( this.nascondiCreditoResiduo.bind( this ) ); } else if ( Utils.isDeviceMobile() ) $( "#riga_credito" ).find( "td:nth-child(2)" ).click( this.toggleCreditoResiduo.bind( this ) ); } }; }(); $( function () { MarketplaceManager.init(); } ); <file_sep>/server/src/classes/CartelliniManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class CartelliniManager { protected $db; protected $session; public function __construct() { $this->session = SessionManager::getInstance(); $this->db = new DatabaseBridge(); } public function __destruct() { } private function controllaErroriCartellino($form_obj) { $errori = []; if (!isset($form_obj["titolo_cartellino"]) || $form_obj["titolo_cartellino"] === "") $errori[] = "Il titolo del cartellino non pu&ograve; essere vuoto."; if (!isset($form_obj["descrizione_cartellino"]) || $form_obj["descrizione_cartellino"] === "") $errori[] = "La descrizione del cartellino non pu&ograve; essere vuota."; if (count($errori) > 0) throw new APIException("Sono stati trovati errori durante l'invio dei dati del cartellino:<br><ul><li>" . implode("</li><li>", $errori) . "</li></ul>"); } public function creaCartellino($params, $etichette = NULL, $trama = NULL) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $this->controllaErroriCartellino($params); if (isset($params["approvato_cartellino"]) && $params["approvato_cartellino"] == 1 && !UsersManager::controllaPermessi($this->session, ["approvaCartellino"])) throw new APIException("Non hai i permessi per approvare i cartellini."); if (isset($params["nome_modello_cartellino"])) { $query_check_modello = "SELECT id_cartellino FROM cartellini WHERE nome_modello_cartellino = ?"; $modello = $this->db->doQuery($query_check_modello, [$params["nome_modello_cartellino"]], False); if (isset($modello) && count($modello) > 0) throw new APIException("Un modello con il nome <strong>" . $params["nome_modello_cartellino"] . "</strong> esiste gi&agrave;. Nel caso si voglia modificarlo, modificare direttamente il cartellino con ID " . $modello[0]["id_cartellino"] . "."); } if (isset($params["costo_attuale_ravshop_cartellino"])) $params["costo_vecchio_ravshop_cartellino"] = floor((int) $params["costo_attuale_ravshop_cartellino"] * rand(0.25, 0.75)); //$params["approvato_cartellino"] = UsersManager::controllaPermessi($this->session, ["approvaCartellino"]) ? 1 : 0; $params["titolo_cartellino"] = nl2br($params["titolo_cartellino"]); $params["descrizione_cartellino"] = nl2br($params["descrizione_cartellino"]); $params["creatore_cartellino"] = $this->session->email_giocatore; $params["icona_cartellino"] = !isset($params["icona_cartellino"]) ? "NULL" : $params["icona_cartellino"]; $campi = implode(", ", array_keys($params)); $marchi = ""; //str_repeat("?,", count(array_keys($params)) - 1) . "?"; $valori = []; //array_values($params); foreach ($params as $k => $v) { $marchi .= strtoupper($v) !== "NULL" ? "?," : "NULL,"; if (strtoupper($v) !== "NULL") $valori[] = $v; } $marchi = substr($marchi, 0, strlen($marchi) - 1); $query_insert = "INSERT INTO cartellini ($campi) VALUES ($marchi)"; $id_cartellino = $this->db->doQuery($query_insert, $valori, False); if (isset($etichette)) $this->associazioneCartellinoEtichette($id_cartellino, explode(",", $etichette)); if (isset($trama)) $this->associazioneCartellinoTrama($trama, $id_cartellino); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function modificaCartellino($id, $params, $etichette = NULL, $old_etichette = NULL) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $this->controllaErroriCartellino($params); if (isset($params["approvato_cartellino"]) && $params["approvato_cartellino"] == 1 && !UsersManager::controllaPermessi($this->session, ["approvaCartellino"])) throw new APIException("Non hai i permessi per approvare i cartellini."); if ( isset($params["old_costo_attuale_ravshop_cartellino"]) && $params["costo_attuale_ravshop_cartellino"] != $params["old_costo_attuale_ravshop_cartellino"] ) { $params["costo_vecchio_ravshop_cartellino"] = $params["old_costo_attuale_ravshop_cartellino"]; } unset($params["old_costo_attuale_ravshop_cartellino"]); if (isset($params["nome_modello_cartellino"])) { $query_check_modello = "SELECT id_cartellino FROM cartellini WHERE nome_modello_cartellino = ?"; $modello = $this->db->doQuery($query_check_modello, [$params["nome_modello_cartellino"]], False); if (isset($modello) && count($modello) > 0 && $modello[0]["id_cartellino"] !== $id) throw new APIException("Un modello con il nome <strong>" . $params["nome_modello_cartellino"] . "</strong> esiste gi&agrave;. Nel caso si voglia modificarlo, modificare direttamente il cartellino con ID " . $modello[0]["id_cartellino"] . "."); } //$params["approvato_cartellino"] = isset($params["approvato_cartellino"]) && UsersManager::controllaPermessi($this->session, ["approvaCartellino"]) ? 1 : 0; $params["titolo_cartellino"] = nl2br($params["titolo_cartellino"]); $params["descrizione_cartellino"] = nl2br($params["descrizione_cartellino"]); $params["icona_cartellino"] = !isset($params["icona_cartellino"]) ? "NULL" : $params["icona_cartellino"]; $to_update = []; foreach ($params as $k => $p) $to_update[] = $k . " = " . (strtoupper($p) !== "NULL" ? "?" : "NULL"); $campi = implode(", ", $to_update); foreach ($params as $k => $p) if (strtoupper($p) === "NULL") unset($params[$k]); $valori = array_values($params); $valori[] = $id; $query_update = "UPDATE cartellini SET $campi WHERE id_cartellino = ?"; $this->db->doQuery($query_update, $valori, False); if (isset($etichette)) { if (isset($old_etichette)) { $et_arr = explode(",", $etichette); $et_old_arr = explode(",", $old_etichette); $rimosse = array_diff($et_old_arr, $et_arr); $aggiunte = array_diff($et_arr, $et_old_arr); if (count($rimosse) > 0) $this->disassociazioneCartellinoEtichette($id, $rimosse); } else $aggiunte = explode(",", $etichette); if (count($aggiunte) > 0) $this->associazioneCartellinoEtichette($id, $aggiunte); } $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function eliminaCartellino($id) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $query_del = "DELETE FROM cartellini WHERE id_cartellino = ?"; $this->db->doQuery($query_del, [$id], False); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function associazioneCartellinoTrama($id_trama, $id_cartellino) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $query_trama = "INSERT INTO trame_has_cartellini (trame_id_trama, cartellini_id_cartellino) VALUES (?,?)"; $this->db->doQuery($query_trama, [$id_trama, $id_cartellino], False); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function associazioneCartellinoEtichette($id_cartellino, $etichette) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $query_etichette = "INSERT INTO cartellino_has_etichette (cartellini_id_cartellino, etichetta) VALUES (?,?)"; $params = array_map(function ($tag) use ($id_cartellino) { return [$id_cartellino, $tag]; }, $etichette); $this->db->doMultipleManipulations($query_etichette, array_values($params), False); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function disassociazioneCartellinoEtichette($id_cartellino, $etichette) { UsersManager::operazionePossibile($this->session, "associazioneCartellinoEtichette"); $query_etichette = "DELETE FROM cartellino_has_etichette WHERE cartellini_id_cartellino = ? AND etichetta = ?"; $params = array_map(function ($tag) use ($id_cartellino) { return [$id_cartellino, $tag]; }, $etichette); $this->db->doMultipleManipulations($query_etichette, array_values($params), False); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function recuperaModelli() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $query_modelli = "SELECT * FROM cartellini WHERE nome_modello_cartellino IS NOT NULL"; $modelli = $this->db->doQuery($query_modelli, [], False); $result = []; if (isset($modelli) && count($modelli) > 0) $result = $modelli; $output = [ "status" => "ok", "result" => $result ]; return json_encode($output); } public function recuperaTagsUnici() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $query_tags = "SELECT DISTINCT etichetta FROM ( SELECT etichetta FROM cartellino_has_etichette AS che UNION ALL SELECT etichetta FROM trame_has_etichette AS the ) AS u"; $tags = $this->db->doQuery($query_tags, [], False); $result = []; if (isset($tags) && count($tags) > 0) $result = $tags; return json_encode(array_column($result, "etichetta")); } public function recuperaCartellini($draw, $columns, $order, $start, $length, $search, $etichette = [], $where = []) { $filter = False; $order_str = ""; $params = []; $campi = array_column($columns, "data"); $campi = array_filter($campi, function ($el) { return preg_match("/^\D+$/", $el); }); if (($index = array_search("nome_creatore_cartellino", $campi)) !== False) $campi[$index] = "CONCAT( gi.nome_giocatore, ' ', gi.cognome_giocatore ) AS nome_creatore_cartellino"; if (isset($search) && isset($search["value"]) && $search["value"] != "") { $filter = True; $params[":search"] = "%$search[value]%"; $campi_search = array_filter($campi, function ($el) { return preg_replace("/^(.*?) AS.*$/i", "${1}", $el); }); $campi_where = implode(" LIKE :search OR ", $campi_search) . " LIKE :search"; $where[] = " ($campi_where)"; } if (isset($order) && !empty($order) && count($order) > 0) { $sorting = array(); foreach ($order as $elem) $sorting[] = $columns[$elem["column"]]["data"] . " " . $elem["dir"]; $order_str = "ORDER BY " . implode(",", $sorting); } $campi[] = "GROUP_CONCAT( che.etichetta SEPARATOR ',' ) AS etichette_cartellino"; //$campi[] = "CONCAT( gi.nome_giocatore, ' ', gi.cognome_giocatore ) AS nome_creatore_cartellino"; $campi_str = implode(", ", $campi); if (count($where) > 0) $where = "WHERE " . implode(" AND ", $where); else $where = ""; $query_ric = "SELECT $campi_str FROM cartellini AS ca LEFT JOIN cartellino_has_etichette AS che ON ca.id_cartellino = che.cartellini_id_cartellino JOIN giocatori AS gi ON gi.email_giocatore = ca.creatore_cartellino $where GROUP BY ca.id_cartellino $order_str"; $risultati_tot = $this->db->doQuery($query_ric, $params, False); $totale = count($risultati_tot); if (count($etichette) > 0) { $risultati_tot = array_filter($risultati_tot, function ($el) use ($etichette) { if (!$el["etichette_cartellino"]) return false; $etichette_cartellino = explode(",", $el["etichette_cartellino"]); $presenti = array_intersect($etichette, $etichette_cartellino); // Se tutti i tag cercati sono stati trovati all'interno dei tag del cartellino // questo può essere lasciato nella tabella return count($presenti) === count($etichette); }); $recordsFiltered = count($risultati_tot); } if (count($risultati_tot) > 0) $pagina = array_splice($risultati_tot, $start, $length); else $pagina = array(); $output = array( "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => $totale, "recordsFiltered" => isset($recordsFiltered) ? $recordsFiltered : $totale, "data" => $pagina ); return json_encode($output); } public function recuperaCartelliniConId($ids) { $colonne = [ ["data" => "id_cartellino"], ["data" => "data_creazione_cartellino"], ["data" => "tipo_cartellino"], ["data" => "titolo_cartellino"], ["data" => "descrizione_cartellino"], ["data" => "icona_cartellino"], ["data" => "testata_cartellino"], ["data" => "piepagina_cartellino"], ["data" => "costo_attuale_ravshop_cartellino"], ["data" => "costo_vecchio_ravshop_cartellino"], ["data" => "approvato_cartellino"], ["data" => "attenzione_cartellino"], ["data" => "nome_modello_cartellino"] ]; $where = ["id_cartellino IN (" . implode(", ", $ids) . ")"]; return $this->recuperaCartellini(NULL, $colonne, NULL, 0, 9999999, NULL, NULL, $where); } } <file_sep>/client/app/scripts/utils/Constants.js var Constants = {}; Constants.API_URL = "http://localhost/api.php"; Constants.SITE_URL = "http://localhost:9000"; Constants.API_POST_REGISTRA = Constants.API_URL + "/usersmanager/registra"; Constants.API_POST_RECUPERO_PWD = Constants.API_URL + "/usersmanager/recuperapassword"; Constants.API_POST_LOGIN = Constants.API_URL + "/usersmanager/login"; Constants.API_POST_MOD_GIOCATORE = Constants.API_URL + "/usersmanager/modificautente"; Constants.API_POST_MOD_PWD = Constants.API_URL + "/usersmanager/modificapassword"; Constants.API_POST_CREAPG = Constants.API_URL + "/charactersmanager/creapg"; Constants.API_POST_ACQUISTA = Constants.API_URL + "/charactersmanager/acquista"; Constants.API_POST_EDIT_PG = Constants.API_URL + "/charactersmanager/modificapg"; Constants.API_POST_EDIT_ETA_PG = Constants.API_URL + "/charactersmanager/modificaetapg"; Constants.API_POST_EDIT_MOLTI_PG = Constants.API_URL + "/charactersmanager/modificamoltipg"; Constants.API_POST_MESSAGGIO = Constants.API_URL + "/messagingmanager/inviamessaggio"; Constants.API_POST_EVENTO = Constants.API_URL + "/eventsmanager/creaevento"; Constants.API_POST_MOD_EVENTO = Constants.API_URL + "/eventsmanager/modificaevento"; Constants.API_POST_ISCRIZIONE = Constants.API_URL + "/eventsmanager/iscrivipg"; Constants.API_POST_DISISCRIZIONE = Constants.API_URL + "/eventsmanager/disiscrivipg"; Constants.API_POST_PUBBLICA_EVENTO = Constants.API_URL + "/eventsmanager/pubblicaevento"; Constants.API_POST_RITIRA_EVENTO = Constants.API_URL + "/eventsmanager/ritiraevento"; Constants.API_POST_DEL_EVENTO = Constants.API_URL + "/eventsmanager/eliminaevento"; Constants.API_POST_EDIT_ISCRIZIONE = Constants.API_URL + "/eventsmanager/modificaiscrizionepg"; Constants.API_POST_PUNTI_EVENTO = Constants.API_URL + "/eventsmanager/impostapuntiassegnatievento"; Constants.API_POST_CREA_RUOLO = Constants.API_URL + "/grantsmanager/crearuolo"; Constants.API_POST_DEL_RUOLO = Constants.API_URL + "/grantsmanager/eliminaruolo"; Constants.API_POST_ASSOCIA_PERMESSI = Constants.API_URL + "/grantsmanager/associapermessi"; Constants.API_POST_CREA_ARTICOLO = Constants.API_URL + "/newsmanager/creanotizia"; Constants.API_POST_EDIT_ARTICOLO = Constants.API_URL + "/newsmanager/modificanotizia"; Constants.API_POST_PUBBLICA_ARTICOLO = Constants.API_URL + "/newsmanager/pubblicanotizia"; Constants.API_POST_RITIRA_ARTICOLO = Constants.API_URL + "/newsmanager/ritiranotizia"; Constants.API_POST_CRAFTING_PROGRAMMA = Constants.API_URL + "/craftingmanager/inserisciricettanetrunner"; Constants.API_POST_CRAFTING_TECNICO = Constants.API_URL + "/craftingmanager/inserisciricettatecnico"; Constants.API_POST_CRAFTING_CHIMICO = Constants.API_URL + "/craftingmanager/inserisciricettamedico"; Constants.API_POST_NUOVO_COMPONENTE = Constants.API_URL + "/craftingmanager/inseriscicomponente"; Constants.API_EDIT_RICETTA = Constants.API_URL + "/craftingmanager/modificaricetta"; Constants.API_POST_EDIT_COMPONENT = Constants.API_URL + "/craftingmanager/modificacomponente"; Constants.API_POST_BULK_EDIT_COMPONENTS = Constants.API_URL + "/craftingmanager/modificagruppocomponenti" Constants.API_POST_REMOVE_COMPONENT = Constants.API_URL + "/craftingmanager/eliminacomponente"; Constants.API_POST_RICETTE_STAMPATE = Constants.API_URL + "/craftingmanager/segnaricettecomestampate"; Constants.API_POST_TRANSAZIONE = Constants.API_URL + "/transactionmanager/inseriscitransazione"; Constants.API_POST_TRANSAZIONE_MOLTI = Constants.API_URL + "/transactionmanager/inseriscitransazionemolti"; Constants.API_COMPRA_COMPONENTI = Constants.API_URL + "/transactionmanager/compracomponenti"; Constants.API_COMPRA_OGGETTI = Constants.API_URL + "/transactionmanager/compraoggetti"; Constants.API_POST_CARTELLINO = Constants.API_URL + "/cartellinimanager/creacartellino"; Constants.API_POST_EDIT_CARTELLINO = Constants.API_URL + "/cartellinimanager/modificacartellino"; Constants.API_POST_DEL_CARTELLINO = Constants.API_URL + "/cartellinimanager/eliminacartellino"; Constants.API_GET_LOGOUT = Constants.API_URL + "/usersmanager/logout"; Constants.API_GET_ACESS = Constants.API_URL + "/usersmanager/controllaaccesso"; Constants.API_CHECK_PWD = Constants.API_URL + "/usersmanager/controllapwd"; Constants.API_GET_PLAYERS = Constants.API_URL + "/usersmanager/recuperalistagiocatori"; Constants.API_GET_NOTE_GIOCATORE = Constants.API_URL + "/usersmanager/recuperanoteutente"; Constants.API_GET_STAFF_USERS = Constants.API_URL + "/usersmanager/recuperautentistaffer"; Constants.API_GET_PGS_PROPRI = Constants.API_URL + "/charactersmanager/recuperapropripg"; Constants.API_GET_PG_LOGIN = Constants.API_URL + "/charactersmanager/loginpg"; Constants.API_GET_INFO = Constants.API_URL + "/charactersmanager/recuperainfoclassi"; Constants.API_GET_OPZIONI_ABILITA = Constants.API_URL + "/charactersmanager/recuperaopzioniabilita"; Constants.API_GET_PGS = Constants.API_URL + "/charactersmanager/mostrapersonaggi"; Constants.API_GET_PGS_CON_ID = Constants.API_URL + "/charactersmanager/mostrapersonaggiconid"; Constants.API_GET_STORICO_PG = Constants.API_URL + "/charactersmanager/recuperastorico"; Constants.API_GET_NOTE_CARTELLINO_PG = Constants.API_URL + "/charactersmanager/recuperaNoteCartellino"; Constants.API_GET_MESSAGGI = Constants.API_URL + "/messagingmanager/recuperamessaggi"; Constants.API_GET_CONVERSAZIONE = Constants.API_URL + "/messagingmanager/recuperaconversazione"; Constants.API_GET_DESTINATARI_FG = Constants.API_URL + "/messagingmanager/recuperadestinatarifg"; Constants.API_GET_DESTINATARI_IG = Constants.API_URL + "/messagingmanager/recuperadestinatariig"; Constants.API_GET_MESSAGGI_NUOVI = Constants.API_URL + "/messagingmanager/recuperanonletti"; Constants.API_GET_EVENTO = Constants.API_URL + "/eventsmanager/recuperaevento"; Constants.API_GET_LISTA_EVENTI = Constants.API_URL + "/eventsmanager/recuperalistaeventi"; Constants.API_GET_INFO_ISCRITTI_AVANZATE = Constants.API_URL + "/eventsmanager/recuperalistaiscrittiavanzato"; Constants.API_GET_INFO_ISCRITTI_BASE = Constants.API_URL + "/eventsmanager/recuperalistaiscrittibase"; Constants.API_GET_PARTECIPANTI_EVENTO = Constants.API_URL + "/eventsmanager/recuperalistapartecipanti"; Constants.API_GET_NOTE_ISCRITTO = Constants.API_URL + "/eventsmanager/recuperanotepgiscritto"; Constants.API_GET_RUOLI = Constants.API_URL + "/grantsmanager/recuperaruoli"; Constants.API_GET_PERMESSI = Constants.API_URL + "/grantsmanager/recuperalistapermessi"; Constants.API_GET_PERMESSI_DEI_RUOLI = Constants.API_URL + "/grantsmanager/recuperapermessideiruoli"; Constants.API_GET_ARTICOLI_PUBBLICATI = Constants.API_URL + "/newsmanager/recuperanotiziepubbliche"; Constants.API_GET_TUTTI_ARTICOLI = Constants.API_URL + "/newsmanager/recuperanotizie"; Constants.API_GET_RICETTE = Constants.API_URL + "/craftingmanager/recuperaricette"; Constants.API_GET_RICETTE_CON_ID = Constants.API_URL + "/craftingmanager/recuperaricetteconid"; Constants.API_GET_RICETTE_PER_RAVSHOP = Constants.API_URL + "/craftingmanager/recuperaricetteperravshop"; Constants.API_GET_COMPONENTI_BASE = Constants.API_URL + "/craftingmanager/recuperacomponentibase"; Constants.API_GET_COMPONENTI_AVANZATO = Constants.API_URL + "/craftingmanager/recuperacomponentiavanzato"; Constants.API_GET_COMPONENTI_CON_ID = Constants.API_URL + "/craftingmanager/recuperacomponenticonid"; Constants.API_GET_INFO_BANCA = Constants.API_URL + "/transactionmanager/recuperainfobanca"; Constants.API_GET_MOVIMENTI = Constants.API_URL + "/transactionmanager/recuperamovimenti"; Constants.API_GET_STATS_CLASSI = Constants.API_URL + "/statistics/recuperastatisticheclassi"; Constants.API_GET_STATS_ABILITA = Constants.API_URL + "/statistics/recuperastatisticheabilita"; Constants.API_GET_STATS_ABILITA_PER_PROFESSIONE = Constants.API_URL + "/statistics/recuperastatisticheabilitaperprofessione"; Constants.API_GET_STATS_CREDITI = Constants.API_URL + "/statistics/recuperastatistichecrediti"; Constants.API_GET_STATS_PG = Constants.API_URL + "/statistics/recuperastatistichepg"; Constants.API_GET_STATS_PUNTEGGI = Constants.API_URL + "/statistics/recuperastatistichepunteggi"; Constants.API_GET_STATS_RAVSHOP = Constants.API_URL + "/statistics/recuperastatisticheqtaravshop"; Constants.API_GET_STATS_ACQUISTI_RAVSHOP = Constants.API_URL + "/statistics/recuperastatisticheacquistiravshop"; Constants.API_GET_STATS_ARMI = Constants.API_URL + "/statistics/recuperastatistichearmistampate"; Constants.API_GET_TAGS = Constants.API_URL + "/cartellinimanager/recuperatagsunici"; Constants.API_GET_CARTELLINI = Constants.API_URL + "/cartellinimanager/recuperacartellini"; Constants.API_GET_CARTELLINI_CON_ID = Constants.API_URL + "/cartellinimanager/recuperacartelliniconid"; Constants.API_GET_MODELLI_CARTELLINI = Constants.API_URL + "/cartellinimanager/recuperamodelli"; Constants.API_GET_ABILITA = Constants.API_URL + "/abilitiesmanager/recuperaabilita" Constants.API_DEL_GIOCATORE = Constants.API_URL + "/usersmanager/eliminagiocatore"; Constants.API_DEL_CLASSE_PG = Constants.API_URL + "/charactersmanager/rimuoviclassepg"; Constants.API_DEL_ABILITA_PG = Constants.API_URL + "/charactersmanager/rimuoviabilitapg"; Constants.API_DEL_PERSONAGGIO = Constants.API_URL + "/charactersmanager/eliminapg"; Constants.API_GET_RUMORS = Constants.API_URL + "/rumorsmanager/recuperalistarumors"; Constants.API_PUT_RUMORS = Constants.API_URL + "/rumorsmanager/inseriscirumor"; Constants.API_POST_RUMORS = Constants.API_URL + "/rumorsmanager/modificarumor"; Constants.API_DEL_RUMORS = Constants.API_URL + "/rumorsmanager/eliminarumor"; Constants.LOGIN_PAGE = Constants.SITE_URL + "/"; Constants.MAIN_PAGE = Constants.SITE_URL + "/main.html"; Constants.PG_PAGE = Constants.SITE_URL + "/scheda_pg.html"; Constants.ABILITY_SHOP_PAGE = Constants.SITE_URL + "/negozio_abilita.html"; Constants.STAMPA_CARTELLINI_PAGE = Constants.SITE_URL + "/stampa_cartellini.html"; Constants.STAMPA_ISCRITTI_PAGE = Constants.SITE_URL + "/stampa_tabella_iscritti.html"; Constants.STAMPA_RICETTE = Constants.SITE_URL + "/stampa_ricetta.html"; Constants.CREAPG_PAGE = Constants.SITE_URL + "/crea_pg.html"; Constants.EVENTI_PAGE = Constants.SITE_URL + "/eventi.html"; Constants.CREA_EVENTO_PAGE = Constants.SITE_URL + "/crea_evento.html"; Constants.MESSAGGI_PAGE = Constants.SITE_URL + "/messaggi.html"; Constants.PROFILO_PAGE = Constants.SITE_URL + "/profilo.html"; Constants.PX_TOT = 220; Constants.PC_TOT = 6; Constants.ANNO_PRIMO_LIVE = 271; Constants.ANNO_INIZIO_OLOCAUSTO = 239; Constants.ANNO_FINE_OLOCAUSTO = 244; Constants.SCONTO_MERCATO = 5; Constants.QTA_PER_SCONTO_MERCATO = 6; Constants.CARTELLINI_PER_PAG = 6; Constants.COSTI_PROFESSIONI = [0, 20, 40, 60, 80, 100, 120]; Constants.PREREQUISITO_TUTTE_ABILITA = -1; Constants.PREREQUISITO_F_TERRA_T_SCELTO = -2; Constants.PREREQUISITO_5_SUPPORTO_BASE = -3; Constants.PREREQUISITO_3_GUASTATOR_BASE = -4; Constants.PREREQUISITO_4_SPORTIVO = -5; Constants.PREREQUISITO_3_ASSALTATA_BASE = -6; Constants.PREREQUISITO_3_GUASTATO_AVAN = -7; Constants.PREREQUISITO_3_ASSALTATA_AVAN = -8; Constants.PREREQUISITO_15_GUARDIAN_BASE = -9; Constants.PREREQUISITO_5_GUARDIANO_BAAV = -10; Constants.PREREQUISITO_4_ASSALTATO_BASE = -11; Constants.PREREQUISITO_7_SUPPORTO_BASE = -12; Constants.PREREQUISITO_SMUOVER_MP_RESET = -13; Constants.PREREQUISITO_15_GUARDIAN_AVAN = -14; Constants.PREREQUISITO_15_ASSALTAT_BASE = -15; Constants.PREREQUISITO_15_ASSALTAT_AVAN = -16; Constants.PREREQUISITO_15_SUPPORTO_BASE = -17; Constants.PREREQUISITO_15_SUPPORTO_AVAN = -18; Constants.PREREQUISITO_15_GUASTATO_BASE = -19; Constants.PREREQUISITO_15_GUASTATO_AVAN = -20; Constants.PREREQUISITO_3_GUASTATORE = -21; Constants.ID_ABILITA_F_TERRA = 135; Constants.ID_ABILITA_T_SCELTO = 130; Constants.ID_ABILITA_IDOLO = 12; Constants.ID_ABILITA_ARMA_SEL = 140; Constants.ID_ABILITA_SMUOVERE = 162; Constants.ID_ABILITA_MEDPACK_RESET = 167; Constants.ID_CLASSE_SPORTIVO = 1; Constants.ID_CLASSE_GUARDIANO_BASE = 8; Constants.ID_CLASSE_GUARDIANO_AVANZATO = 9; Constants.ID_CLASSE_ASSALTATORE_BASE = 10; Constants.ID_CLASSE_ASSALTATORE_AVANZATO = 11; Constants.ID_CLASSE_SUPPORTO_BASE = 12; Constants.ID_CLASSE_SUPPORTO_AVANZATO = 13; Constants.ID_CLASSE_GUASTATORE_BASE = 14; Constants.ID_CLASSE_GUASTATORE_AVANZATO = 15; Constants.TIPO_GRANT_PG_PROPRIO = "_proprio"; Constants.TIPO_GRANT_PG_ALTRI = "_altri"; Constants.RUOLO_ADMIN = "admin"; Constants.INTERVALLO_CONTROLLO_MEX = 60000; Constants.ID_RICETTA_PAG = 4; Constants.DEFAULT_ACCREDITO_BIT = "Accredito a vostro favore da parte di {1}."; Constants.DEFAULT_ADDEBITO_BIT = "Addebito a favore di {1}."; Constants.DEFAULT_ERROR = "Impossibile completare l'operazione, verificare che la tipologia sia conforme alla destinazione."; Constants.DEVE_ERROR = "Impossibile completare l'operazione. Non &egrave; possibile combinare pi&ugrave; applicazioni che DEVONO dichiarare qualcosa."; Constants.MAPPA_TIPI_CARTELLINI = { schede_pg: { icona: "fa-user", acquistabile: false, nome: "Scheda PG", colore: "bianco", colore_eng: "white" }, componente_consumabile: { icona: "fa-cubes", acquistabile: true, nome: "Componente Consumabile", colore: "verde", colore_eng: "green" }, abilita_sp_malattia: { icona: "fa-medkit", acquistabile: false, nome: "Abilit&agrave; Speciale / Malattia", colore: "rosso", colore_eng: "red" }, armatura_protesi_potenziamento: { icona: "fa-shield", acquistabile: true, nome: "Armatura / Protesi / Potenziamento", colore: "azzurro", colore_eng: "light-blue" }, arma_equip: { icona: "fa-rocket", acquistabile: true, nome: "Arma / Equipaggiamento", colore: "bianco", colore_eng: "white" }, interazione_area: { icona: "fa-puzzle-piece", acquistabile: false, nome: "Interazione / Area", colore: "giallo", colore_eng: "yellow" } }; Constants.DATA_TABLE_LANGUAGE = { "decimal": "", "emptyTable": "Nessun dato disponibile", "info": "Da _START_ a _END_ di _TOTAL_ risultati visualizzati", "infoEmpty": "Da 0 a 0 di 0 visualizzati", "infoFiltered": "(filtrati da un massimo di _MAX_ risultati)", "infoPostFix": "", "thousands": ".", "lengthMenu": "_MENU_", "loadingRecords": "Carico...", "processing": "Elaboro...", "search": "Cerca:", "zeroRecords": "Nessuna corrispondenza trovata", "paginate": { "first": "Primo", "last": "Ultimo", "next": ">>", "previous": "<<" }, "aria": { "sortAscending": ": clicca per ordinare la colonna in ordine crescente", "sortDescending": ": clicca per ordinare la colonna in ordine decrescente" } }; Constants.CHART_COLORS = ["#fcb3bc", "#ff61a1", "#e026c9", "#a726e3", "#735e7f", "#a42946", "#df7623", "#f8ae29", "#ffd658", "#cde02f", "#70f03b", "#70e026", "#11c26a", "#3affb5", "#3a80ff", "#114a67", "#b8656f", "#711d96", "#431d96", "#204b99", "#1e9194", "#1b9a17", "#8f9a18", "#c2d517", "#e6ff00", "#ffb403", "#fe7903", "#e0611a", "#dc3717", "#f11310", "#821613", "#8e1f40"]; Constants.SPECIAL_PREREQUISITES = { "-1": "tutte le abilta della classe", "-2": "FUOCO A TERRA e TIRATORE SCELTO", "-3": "almeno 5 abilita di Supporto Base", "-4": "almeno 3 abilita Guastatore Base", "-5": "almeno 4 abilita da Sportivo", "-6": "almeno 3 talenti da Assaltatore Base", "-7": "almeno 3 talenti da Guastatore Avanzato", "-8": "almeno 3 talenti da Assaltatore Avanzato", "-9": "almeno 15 abilita da Guardiano Base", "-10": "almeno 5 abilita da Guardiano Base / Avanzato", "-11": "almeno 4 abilita da Assaltatore Base", "-12": "almeno 7 abilita da Supporto Base", "-13": "SMUOVERE e MEDIPACK - RESETTARE", "-14": "almeno 15 abilita da Guardiano Avanzato", "-15": "almeno 15 abilita da Assaltatore Base", "-16": "almeno 15 abilita da Assaltatore Avanzato", "-17": "almeno 15 abilita da Supporto Base", "-18": "almeno 15 abilita da Supporto Avanzato", "-19": "almeno 15 abilita da Guastatore Base", "-20": "almeno 15 abilita da Guastatore Avanzato", }<file_sep>/server/src/classes/APIException.class.php <?php class APIException extends Exception { static $GENERIC_ERROR = "genericError"; static $GRANTS_ERROR = "grantsError"; static $LOGIN_ERROR = "loginError"; static $PG_LOGIN_ERROR = "pgLoginError"; static $DATABASE_ERROR = "databaseError"; protected $type; public function __construct( $message = "", $type = "error", $code = 0, Exception $previous = null ) { $this->type = $type; parent::__construct($message, $code, $previous); } public function getType() { return $this->type; } }<file_sep>/server/src/classes/EventsManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/CharactersManager.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/Mailer.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class EventsManager { protected $db; protected $grants; protected $session; protected $mailer; public function __construct() { $this->db = new DatabaseBridge(); $this->session = SessionManager::getInstance(); $this->mailer = new Mailer(); $this->charManager = new CharactersManager(); } private function controllaErrori($titolo, $data_inizio, $ora_inizio, $data_fine, $ora_fine, $luogo, $costo, $costo_max) { $error = ""; if (!isset($titolo) || Utils::soloSpazi($titolo)) $error .= "<li>Il campo Titolo non pu&ograve; essere lasciato vuoto.</li>"; if (!isset($data_inizio) || Utils::soloSpazi($data_inizio)) $error .= "<li>Il campo Data Inizio non pu&ograve; essere lasciato vuoto.</li>"; else $d_inizio = DateTime::createFromFormat("d/m/Y", $data_inizio); if (!isset($ora_inizio) || Utils::soloSpazi($ora_inizio)) $error .= "<li>Il campo Ora Inizio non pu&ograve; essere lasciato vuoto.</li>"; if (!isset($data_fine) || Utils::soloSpazi($data_fine)) $error .= "<li>Il campo Data Fine non pu&ograve; essere lasciato vuoto.</li>"; else $d_fine = DateTime::createFromFormat("d/m/Y", $data_fine); if (!isset($ora_fine) || Utils::soloSpazi($ora_fine)) $error .= "<li>Il campo Ora Fine non pu&ograve; essere lasciato vuoto.</li>"; if (isset($costo) && !Utils::soloSpazi($costo) && !preg_match("/^\d+(\.\d+)?$/", $costo)) $error .= "<li>Il campo Costo pu&ograve; contenere solo numeri.</li>"; if (isset($costo_max) && Utils::soloSpazi($costo_max) && !preg_match("/^\d+$/", $costo_max)) $error .= "<li>Il campo Costo Maggiorato pu&ograve; contenere solo numeri.</li>"; if (!isset($luogo) || Utils::soloSpazi($luogo)) $error .= "<li>Il campo Luogo non pu&ograve; essere lasciato vuoto.<br>"; if (isset($d_inizio) && isset($d_fine) && $d_fine < $d_inizio) $error .= "<li>La data di fine non pu&ograve; essere prima di quella d'inizio.</li>"; return $error; } private function possoPubblicare() { $query_pub = "SELECT pubblico_evento FROM eventi WHERE pubblico_evento = 1 AND data_inizio_evento > DATE(NOW())"; $result = $this->db->doQuery($query_pub, [], False); if (count($result) > 0) throw new APIException("&Egrave; stato gi&agrave; aperto un evento alle iscrizioni. Non &egrave; possibile pubblicarne altri a meno di ritirare il precedente."); } private function controllaDataEvento($id) { $query_data = "SELECT id_evento FROM eventi WHERE data_inizio_evento > DATE(NOW()) AND id_evento = :idev"; $evento = $this->db->doQuery($query_data, [":idev" => $id], False); if (!isset($evento) || (isset($evento) && count($evento) === 0)) throw new APIException("Non &egrave; possibile modificare un evento passato."); } public function creaEvento($titolo, $data_inizio, $ora_inizio, $data_fine, $ora_fine, $luogo, $costo, $costo_max, $note) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $errori = $this->controllaErrori($titolo, $data_inizio, $ora_inizio, $data_fine, $ora_fine, $luogo, $costo, $costo_max); if (!empty($errori)) throw new APIException("Sono stati rilevati i seguenti errori:<ul>" . $errori . "</ul>"); $params = [ ":titolo" => $titolo, ":d_inizio" => DateTime::createFromFormat("d/m/Y", $data_inizio)->format("Y-m-d"), ":t_inizio" => $ora_inizio . ":00", ":d_fine" => DateTime::createFromFormat("d/m/Y", $data_fine)->format("Y-m-d"), ":t_fine" => $ora_fine . ":00", ":luogo" => $luogo, ":costo" => $costo, ":costo_max" => $costo_max, ":creatore" => $this->session->email_giocatore, ":note" => nl2br($note) ]; $query_crea = "INSERT INTO eventi (id_evento, titolo_evento, data_inizio_evento, ora_inizio_evento, data_fine_evento, ora_fine_evento, luogo_evento, costo_evento, costo_maggiorato_evento, pubblico_evento, creatore_evento, note_evento) VALUES (NULL, :titolo, :d_inizio, :t_inizio, :d_fine, :t_fine, :luogo, :costo, :costo_max, 0, :creatore, :note)"; $this->db->doQuery($query_crea, $params, False); return json_encode(["status" => "ok", "result" => "true"]); } public function modificaEvento($id, $titolo, $data_inizio, $ora_inizio, $data_fine, $ora_fine, $luogo, $costo, $costo_max, $note) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $this->controllaDataEvento($id); $errori = $this->controllaErrori($titolo, $data_inizio, $ora_inizio, $data_fine, $ora_fine, $luogo, $costo, $costo_max, $note); if (!empty($errori)) throw new APIException("Sono stati rilevati i seguenti errori:<ul>" . $errori . "</ul>"); $params = [ ":id" => $id, ":titolo" => $titolo, ":d_inizio" => DateTime::createFromFormat("d/m/Y", $data_inizio)->format("Y-m-d"), ":t_inizio" => $ora_inizio . ":00", ":d_fine" => DateTime::createFromFormat("d/m/Y", $data_fine)->format("Y-m-d"), ":t_fine" => $ora_fine . ":00", ":luogo" => $luogo, ":costo" => $costo, ":costo_max" => $costo_max, ":note" => nl2br($note) ]; $query_crea = "UPDATE eventi SET titolo_evento = :titolo, data_inizio_evento = :d_inizio, ora_inizio_evento = :t_inizio, data_fine_evento = :d_fine, ora_fine_evento = :t_fine, luogo_evento = :luogo, costo_evento = :costo, costo_maggiorato_evento = :costo_max, note_evento = :note WHERE id_evento = :id"; $this->db->doQuery($query_crea, $params, False); return json_encode(["status" => "ok", "result" => "true"]); } public function impostaPuntiAssegnatiEvento($id) { UsersManager::operazionePossibile($this->session, "modificaEvento"); $query_pt = "UPDATE eventi SET punti_assegnati_evento = :punti WHERE id_evento = :id"; $this->db->doQuery($query_pt, [":punti" => 1, ":id" => $id], False); return json_encode(["status" => "ok", "result" => "true"]); } public function recuperaEvento($id = "last") { UsersManager::operazionePossibile($this->session, "recuperaEventi"); $query_end = $id === "last" ? "WHERE pubblico_evento = 1 AND data_inizio_evento > DATE(NOW()) ORDER BY id_evento DESC LIMIT 1" : "WHERE id_evento = :id"; $params = $id === "last" ? [] : [":id" => $id]; $query_ev = "SELECT ev.*, DATE_FORMAT(ev.data_inizio_evento, '%d/%m/%Y') AS data_inizio_evento_it, DATE_FORMAT(ev.data_fine_evento, '%d/%m/%Y') AS data_fine_evento_it FROM eventi AS ev $query_end"; $evento = $this->db->doQuery($query_ev, $params, False); return json_encode(["status" => "ok", "result" => $evento[0]]); } public function recuperaEventoInCorso() { $query_ev = "SELECT id_evento FROM eventi AS ev WHERE ev.pubblico_evento = 1 AND DATE(NOW()) BETWEEN ev.data_inizio_evento AND ev.data_fine_evento"; $res_ev = $this->db->doQuery($query_ev, [], False); if (!isset($res_ev) || count($res_ev) === 0) return NULL; return $res_ev[0]["id_evento"]; } public function recuperaListaEventi($draw, $columns, $order, $start, $length, $search) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $filter = False; $params = []; if (isset($order)) { $sorting = array(); foreach ($order as $elem) $sorting[] = $columns[$elem["column"]]["data"] . " " . $elem["dir"]; $order_str = "ORDER BY " . implode(",", $sorting); } $query_mex = "SELECT ev.*, CONCAT(gi.nome_giocatore,' ',gi.cognome_giocatore) AS nome_completo FROM eventi AS ev JOIN giocatori AS gi ON gi.email_giocatore = ev.creatore_evento $order_str"; $risultati = $this->db->doQuery($query_mex, $params, False); $output = Utils::filterDataTableResults($draw, $columns, $order, $start, $length, $search, $risultati); return json_encode($output); } public function recuperaListaEventiPublic() { $filtra_evts = [6,9,10,11]; $marker_evts = str_repeat("?,", count($filtra_evts) - 1) . "?"; $query_mex = "SELECT id_evento, titolo_evento, DATE_FORMAT(data_inizio_evento,'%d/%m/%Y') data_inizio_evento, DATE_FORMAT(data_fine_evento,'%d/%m/%Y') data_fine_evento, ora_inizio_evento, ora_fine_evento, luogo_evento FROM eventi WHERE pubblico_evento = 1 AND id_evento NOT IN ($marker_evts) ORDER BY id_evento DESC"; $risultati = $this->db->doQuery($query_mex, $filtra_evts, False); return json_encode(["status" => "ok", "result" => $risultati]); } public function iscriviPg($id_pg, $pagato, $tipo_pagamento, $note = "") { if (!isset($id_pg) || empty($id_pg)) throw new APIException("Devi selezionare un personaggio da iscrivere."); UsersManager::operazionePossibile($this->session, __FUNCTION__, $id_pg); $query_idev = "SELECT id_evento FROM eventi WHERE pubblico_evento = 1 ORDER BY data_inizio_evento DESC LIMIT 1"; $res_idev = $this->db->doQuery($query_idev, [], False); $id_evento = $res_idev[0]["id_evento"]; $query_check = "SELECT count(*) qta_iscritti FROM iscrizione_personaggi ip JOIN eventi ev ON ev.id_evento = ip.eventi_id_evento JOIN personaggi pg ON pg.id_personaggio = ip.personaggi_id_personaggio JOIN giocatori gi ON gi.email_giocatore = pg.giocatori_email_giocatore WHERE ip.eventi_id_evento = :idev AND pg.id_personaggio = :pgid GROUP BY gi.email_giocatore"; $res_check = $this->db->doQuery($query_check, [":idev" => $id_evento, ":pgid" => $id_pg], False); if (isset($res_check) && count($res_check) > 0 && $res_check[0]["qta_iscritti"] > 0) throw new APIException("Lo stesso giocatore non pu&ograve; iscrivere pi&ugrave; di un personaggio allo stesso evento."); $params = [ ":id_ev" => $id_evento, ":id_pg" => $id_pg, ":pagato" => $pagato, ":tipo_pag" => $tipo_pagamento, ":note" => nl2br($note) ]; $query_ev = "INSERT INTO iscrizione_personaggi (eventi_id_evento,personaggi_id_personaggio,pagato_iscrizione,tipo_pagamento_iscrizione,note_iscrizione) VALUES ( :id_ev, :id_pg, :pagato, :tipo_pag, :note)"; $evento = $this->db->doQuery($query_ev, $params, False); $query_gi = "SELECT pg.nome_personaggio, CONCAT(gi.nome_giocatore, ' ', gi.cognome_giocatore) as nome_completo, gi.note_giocatore, ev.titolo_evento FROM personaggi AS pg JOIN giocatori AS gi ON pg.giocatori_email_giocatore = gi.email_giocatore JOIN iscrizione_personaggi AS ip ON ip.personaggi_id_personaggio = pg.id_personaggio JOIN eventi AS ev ON ev.id_evento = ip.eventi_id_evento WHERE pg.id_personaggio = :idpg AND ev.id_evento = :idev"; $info = $this->db->doQuery($query_gi, [":idev" => $id_evento, ":idpg" => $id_pg], False); $this->mailer->inviaAvvisoIscrizione($info[0]["nome_completo"], $info[0]["nome_personaggio"], $info[0]["note_giocatore"], $id_pg, $res_pub[0]["titolo_evento"], $note); $this->charManager->registraAzione( $id_pg, "INSERT", "iscrizione_personaggi", "eventi_id_evento", NULL, $id_evento, "iscrizione evento ".$info[0]["titolo_evento"]); return json_encode(["status" => "ok", "result" => $evento[0]]); } public function modificaIscrizionePG($id_evento, $pgid, $modifiche) { foreach ($modifiche as $campo => $valore) { UsersManager::operazionePossibile($this->session, __FUNCTION__ . "_" . $campo, $pgid); $campi[] = $campo; $valori[] = $valore; } $to_update = implode(" = ?, ", $campi) . " = ?"; $valori[] = $pgid; $valori[] = $id_evento; $query_mod = "UPDATE iscrizione_personaggi SET $to_update WHERE personaggi_id_personaggio = ? AND eventi_id_evento = ?"; $this->db->doQuery($query_mod, $valori, False); return json_encode(["status" => "ok", "result" => true]); } public function disiscriviPG($id_evento, $id_pg) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $id_pg); $params = [ ":id_ev" => $id_evento, ":id_pg" => $id_pg ]; $query_ev = "DELETE FROM iscrizione_personaggi WHERE personaggi_id_personaggio = :id_pg AND eventi_id_evento = :id_ev"; $evento = $this->db->doQuery($query_ev, $params, False); return json_encode(["status" => "ok", "result" => $evento[0]]); } public function pubblicaEvento($id_evento) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $this->possoPubblicare(); $params = [ ":id_ev" => $id_evento, ":pub" => 1 ]; $query_pub = "UPDATE eventi SET pubblico_evento = :pub WHERE id_evento = :id_ev"; $this->db->doQuery($query_pub, $params, False); $this->mailer->inviaAvvisoEvento(); return json_encode(["status" => "ok", "result" => true]); } public function ritiraEvento($id_evento) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $this->controllaDataEvento($id_evento); $params = [ ":id_ev" => $id_evento, ":pub" => 0 ]; $query_pub = "UPDATE eventi SET pubblico_evento = :pub WHERE id_evento = :id_ev"; $this->db->doQuery($query_pub, $params, False); return json_encode(["status" => "ok", "result" => true]); } public function eliminaEvento($id_evento) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $this->controllaDataEvento($id_evento); $params = [ ":id_ev" => $id_evento ]; $query_del = "DELETE FROM eventi WHERE id_evento = :id_ev"; $this->db->doQuery($query_del, $params, False); return json_encode(["status" => "ok", "result" => true]); } private function recuperaListaIscritti($tipo, $draw, $columns, $order, $start, $length, $search, $quando, $where = []) { $params = []; $filter = False; $extra_sel = $tipo === "avanzato" ? "ip.pagato_iscrizione, ip.tipo_pagamento_iscrizione, ip.note_iscrizione, ip.ha_partecipato_iscrizione, gi.note_giocatore, " : ""; $order_str = ""; if ($quando === "prossimo") $where[] = "t1.pubblico_evento = 1 AND t1.data_inizio_evento > DATE(NOW())"; else if ($quando === "precedente") $where[] = "t1.id_evento = (SELECT id_evento FROM eventi WHERE pubblico_evento = 1 AND data_inizio_evento <= DATE(NOW()) ORDER BY data_inizio_evento DESC LIMIT 1)"; if (isset($search) && isset($search["value"]) > 0 && $search["value"] != "") { $filter = True; $params[":search"] = "%$search[value]%"; $where[] = "( t1.nome_completo LIKE :search OR t1.personaggi_id_personaggio LIKE :search OR t1.nome_personaggio LIKE :search OR t1.classi_civili LIKE :search OR t1.classi_militari LIKE :search " . ($tipo === "avanzato" ? "OR t1.tipo_pagamento_iscrizione LIKE :search OR t1.note_iscrizione LIKE :search" : "") . ")"; } if (isset($order) && count($order) > 0 && !empty($order)) { $sorting = array(); foreach ($order as $elem) $sorting[] = $columns[$elem["column"]]["data"] . " " . $elem["dir"]; $order_str = "ORDER BY " . implode(",", $sorting); } if (count($where) > 0) $where = implode(" AND ", $where); else $where = ""; $query_mex = "SELECT * FROM ( SELECT ip.personaggi_id_personaggio, ev.id_evento, ev.titolo_evento, ev.data_inizio_evento, ev.pubblico_evento, ev.punti_assegnati_evento, $extra_sel pg.nome_personaggio, CONCAT(gi.nome_giocatore,' ',gi.cognome_giocatore) AS nome_completo, GROUP_CONCAT(DISTINCT cl_c.nome_classe SEPARATOR ', ') AS classi_civili, GROUP_CONCAT(DISTINCT cl_m.nome_classe SEPARATOR ', ') AS classi_militari, '$quando' AS quando FROM iscrizione_personaggi AS ip JOIN eventi AS ev ON ev.id_evento = ip.eventi_id_evento JOIN personaggi AS pg ON pg.id_personaggio = ip.personaggi_id_personaggio JOIN giocatori AS gi ON gi.email_giocatore = pg.giocatori_email_giocatore LEFT OUTER JOIN personaggi_has_classi AS phc ON phc.personaggi_id_personaggio = pg.id_personaggio LEFT OUTER JOIN classi AS cl_m ON cl_m.id_classe = phc.classi_id_classe AND cl_m.tipo_classe = 'militare' LEFT OUTER JOIN classi AS cl_c ON cl_c.id_classe = phc.classi_id_classe AND cl_c.tipo_classe = 'civile' GROUP BY ev.id_evento, ip.personaggi_id_personaggio ) AS t1 WHERE $where $order_str"; $risultati = $this->db->doQuery($query_mex, $params, False); $totale = count($risultati); if (count($risultati) > 0) $risultati = array_splice($risultati, $start, $length); else $risultati = array(); $output = array( "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => $totale, "recordsFiltered" => $filter ? count($risultati) : $totale, "data" => $risultati ); return json_encode($output); } public function recuperaListaIscrittiAvanzato($draw, $columns, $order, $start, $length, $search, $quando) { UsersManager::operazionePossibile($this->session, __FUNCTION__); return $this->recuperaListaIscritti("avanzato", $draw, $columns, $order, $start, $length, $search, $quando); } public function recuperaListaPartecipanti($id_ev) { UsersManager::operazionePossibile($this->session, "recuperaListaIscrittiAvanzato"); return $this->recuperaListaIscritti("avanzato", 1, [], [], 0, 999, [], "precedente", ["t1.ha_partecipato_iscrizione = 1"]); } public function recuperaListaIscrittiBase($draw, $columns, $order, $start, $length, $search, $quando) { UsersManager::operazionePossibile($this->session, __FUNCTION__); return $this->recuperaListaIscritti("base", $draw, $columns, $order, $start, $length, $search, $quando); } public function recuperaNotePGIscritto($id_evento, $id_pg) { UsersManager::operazionePossibile($this->session, "recuperaListaIscrittiAvanzato"); $query_note = "SELECT note_iscrizione FROM iscrizione_personaggi WHERE eventi_id_evento = :idev AND personaggi_id_personaggio = :idpg"; $note = $this->db->doQuery($query_note, [":idev" => $id_evento, ":idpg" => $id_pg], False); $output = ["status" => "ok", "result" => $note[0]["note_iscrizione"]]; return json_encode($output); } } <file_sep>/server/src/utils/togliabilita.php <?php //ini_set('memory_limit', '1024M'); $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "config/constants.php"); echo "<pre>"; try { $db = new DatabaseBridge(); $query_sel_abilita = "SELECT pg.id_personaggio, ab.id_abilita, ab.costo_abilita FROM personaggi pg JOIN personaggi_has_abilita pha ON pha.personaggi_id_personaggio = pg.id_personaggio JOIN abilita ab ON pha.abilita_id_abilita = ab.id_abilita WHERE ab.id_abilita IN (33, 36, 39, 41, 52, 53)"; $res_sel_abilita = $db->doQuery($query_sel_abilita, [], False); foreach($res_sel_abilita as $i => $elem) { echo "restituisco $elem[costo_abilita] px al pg $elem[id_personaggio]\n"; $query_ridai_px = "UPDATE personaggi SET px_personaggio = px_personaggio + :px WHERE id_personaggio = :idpg"; //$db->doQuery($query_ridai_px, [":px" => $elem['costo_abilita'], ":idpg" => $elem['id_personaggio']], False); echo "elimino l'abilita $elem[id_abilita] dalla lista del pg $elem[id_personaggio]\n"; $query_del_abilita = "DELETE FROM personaggi_has_abilita WHERE personaggi_id_personaggio = :idpg AND abilita_id_abilita = :idab"; //$db->doQuery($query_del_abilita, [":idpg" => $elem['id_personaggio'], ":idab" => $elem['id_abilita']], False); } } catch (Exception $e) { echo $e->getMessage(); } echo "</pre>";<file_sep>/data/useful_queries.sql -- GET CONVERSATIONS SELECT CONCAT( IF( mittente_messaggio > destinatario_messaggio, CONCAT( mittente_messaggio, '_', destinatario_messaggio ), CONCAT( destinatario_messaggio, '_', mittente_messaggio ) ), '_', REPLACE (oggetto_messaggio, 'Re%3A%20', '') ) AS temp_id FROM messaggi_ingioco GROUP BY temp_id ORDER BY temp_id ASC, id_messaggio ASC<file_sep>/client/app/scripts/controllers/RegistrationManager.js var RegistrationManager = function () { return { init: function () { this.setListeners(); }, setListeners: function () { $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); $("#inviaDatiGiocatore").click( this.inviaDati.bind(this) ); $("#message").on( "hidden.bs.modal", this.gotoLogin.bind(this) ); }, gotoLogin: function () { window.location.href = Constants.LOGIN_PAGE; }, controllaCampi: function () { var errors = "", nome = $("input[name='nome']").val(), cognome = $("input[name='cognome']").val(), note = $("textarea[name='note']").val(), mail = $("input[name='mail']").val(), password1 = $("input[name='password1']").val(), password2 = $("input[name='password2']").val(), condizioni = $("input[name='condizioni']").is(":checked"); if ( nome === "" || Utils.soloSpazi(nome) ) errors += "Il campo Nome non pu&ograve; essere vuoto.<br>"; if ( cognome === "" || Utils.soloSpazi(cognome) ) errors += "Il campo Cognome non pu&ograve; essere vuoto.<br>"; if ( mail === "" || Utils.soloSpazi(mail) ) errors += "Il campo Mail non pu&ograve; essere vuoto.<br>"; else if ( !Utils.controllaMail(mail) ) errors += "Il campo Mail contiene un indirizzo non valido.<br>"; if ( password1 === "" || Utils.soloSpazi(password1) ) errors += "Il primo campo Password non pu&ograve; essere vuoto.<br>"; if ( password2 === "" || Utils.soloSpazi(password2) ) errors += "Il secondo campo Password non pu&ograve; essere vuoto.<br>"; if( password1 !== "" && !Utils.soloSpazi(password1) && password2 !== "" && !Utils.soloSpazi(password2) && password1 !== password2 ) errors += "Le password inserite non combaciano.<br>"; //if( !condizioni ) // errors += "Accettare i termini e le condizioni &egrave; obbligatorio."; return errors; }, inviaDati: function () { var errors = this.controllaCampi(); if( errors ) { Utils.showError( errors ); return false; } Utils.requestData( Constants.API_POST_REGISTRA, "POST", $("#formRegistrazione").find("input, textarea, checkbox").serialize(), "La registrazione è avvenuta con successo.<br>Riceverai a breve una mail con i dati di accesso.<br>Per favore controlla anche nella cartella <strong>Anti-Spam</strong>" ); } } }(); $(function () { RegistrationManager.init(); });<file_sep>/client/app/scripts/controllers/InGameObjectManager.js /** * Created by Miroku on 11/03/2018. */ var InGameObjectManager = function () { return { init: function () { this.setListeners(); }, setListeners: function() { } }; }(); $(function () { InGameObjectManager.init(); });<file_sep>/client/app/scripts/controllers/RecipesManager.js var RecipesManager = function() { return { init: function() { this.ricette_selezionate = { ricetta: {} }; this.recuperaDatiLocali(); this.setListeners(); this.creaDataTable(); }, resettaContatori: function(e) { for (var c in this.ricette_selezionate) this.ricette_selezionate[c] = {}; window.localStorage.removeItem("cartellini_da_stampare"); $("#griglia_ricette").find("input[type='number']").val(0); }, stampaCartellini: function(e) { window.localStorage.removeItem("cartellini_da_stampare"); window.localStorage.setItem("cartellini_da_stampare", JSON.stringify(this.ricette_selezionate)); window.open(Constants.STAMPA_CARTELLINI_PAGE, "Stampa Cartellini"); }, inviaModificheRicetta: function(id_ricetta) { var approv = $("#modal_modifica_ricetta").find("#approvata").val(), extra = encodeURIComponent(Utils.stripHMTLTag($("#modal_modifica_ricetta") .find("#extra_cartellino") .val()).replace(/\n/g, "<br>")), note = encodeURIComponent(Utils.stripHMTLTag($("#modal_modifica_ricetta").find("#note_ricetta").val()) .replace(/\n/g, "<br>")), dati = { id: id_ricetta, modifiche: { note_ricetta: note, extra_cartellino_ricetta: extra, approvata_ricetta: approv, in_ravshop_ricetta: $("input[name='pubblico_ricetta']").is(":checked") ? 1 : 0 } }; if (dati.modifiche.in_ravshop_ricetta) { dati.modifiche.costo_attuale_ricetta = $("input[name='costo_attuale_ricetta']").val(); dati.modifiche.old_costo_attuale_ricetta = $("input[name='old_costo_attuale_ricetta']").val(); dati.modifiche.disponibilita_ravshop_ricetta = $("input[name='disponibilita_ricetta']").val(); } Utils.requestData( Constants.API_EDIT_RICETTA, "POST", dati, "Modifiche apportate con successo", null, this.recipes_grid.ajax.reload.bind(this, null, false) ); }, pubblicaSuRavshop: function(e) { if ($("input[name='pubblico_ricetta']").is(":checked")) { $("#modal_modifica_ricetta").find(".costo_attuale_ricetta").show(500).removeClass("inizialmente-nascosto"); $("#modal_modifica_ricetta").find(".disponibilita_ricetta").show(500).removeClass("inizialmente-nascosto"); } else { $("#modal_modifica_ricetta").find("input[name='costo_attuale_ricetta']").val(0); $("#modal_modifica_ricetta").find("input[name='disponibilita_ricetta']").val(1); $("#modal_modifica_ricetta").find(".costo_attuale_ricetta").hide(500); $("#modal_modifica_ricetta").find(".disponibilita_ricetta").hide(500); } }, mostraModalRicetta: function(editMode, e) { var t = $(e.target), dati = this.recipes_grid.row(t.parents('tr')).data(), note_pg = decodeURIComponent(dati.note_pg_ricetta || ""), extra = decodeURIComponent(dati.extra_cartellino_ricetta), extra_nohtml = Utils.unStripHMTLTag(extra).replace(/<br>/g, "\r"), note_staff = decodeURIComponent(dati.note_ricetta || ""), note_staff_nohtml = Utils.unStripHMTLTag(note_staff).replace(/<br>/g, "\r"), note_staff = note_staff === "null" ? "" : note_staff, comps = "<li>" + dati.componenti_ricetta.split(";").join("</li><li>") + "</li>", result = dati.risultato_ricetta ? "<li>" + dati.risultato_ricetta.split(";") .join("</li><li>") + "</li>" : "<li></li>"; $("#modal_modifica_ricetta").find("#nome_ricetta").text(dati.nome_ricetta); $("#modal_modifica_ricetta").find("#lista_componenti").html(comps); $("#modal_modifica_ricetta").find("#risultato").html(result); if (editMode === true) { $("#modal_modifica_ricetta").find("#vedi_note_pg_ricetta").parent().hide(); $("#modal_modifica_ricetta").find("#vedi_extra_cartellino_ricetta").parent().hide(); $("#modal_modifica_ricetta").find("#vedi_note_ricetta").parent().hide(); $("#modal_modifica_ricetta").find("#approvata").val(dati.approvata_ricetta); $("#modal_modifica_ricetta").find("#extra_cartellino").val(extra_nohtml); $("#modal_modifica_ricetta").find("#note_ricetta").val(note_staff_nohtml); $("#modal_modifica_ricetta").find("#btn_invia_modifiche_ricetta").unbind("click"); $("#modal_modifica_ricetta") .find("#btn_invia_modifiche_ricetta") .click(this.inviaModificheRicetta.bind(this, dati.id_ricetta)); $("#modal_modifica_ricetta").find("input[name='pubblico_ricetta']").iCheck(parseInt(dati.in_ravshop_ricetta, 10) === 1 ? "check" : "uncheck").trigger("change"); $("#modal_modifica_ricetta").find("input[name='costo_attuale_ricetta']").val(dati.costo_attuale_ricetta); $("#modal_modifica_ricetta").find("input[name='old_costo_attuale_ricetta']").val(dati.costo_attuale_ricetta); $("#modal_modifica_ricetta").find("input[name='disponibilita_ricetta']").val(dati.disponibilita_ravshop_ricetta); $("#modal_modifica_ricetta").find("form").show(); $("#modal_modifica_ricetta").find("#btn_invia_modifiche_ricetta").show(); } else if (editMode === false) { $("#modal_modifica_ricetta").find("#vedi_note_pg_ricetta").html(note_pg).parent().show(); $("#modal_modifica_ricetta").find("#vedi_extra_cartellino_ricetta").html(extra).parent().show(); $("#modal_modifica_ricetta").find("#vedi_note_ricetta").html(note_staff).parent().show(); $("#modal_modifica_ricetta").find("form").hide(); $("#modal_modifica_ricetta").find("#btn_invia_modifiche_ricetta").hide(); } $("#modal_modifica_ricetta").modal({ drop: "static" }); }, ricettaSelezionata: function(e) { var t = $(e.target), num = parseInt(t.val(), 10), dati = this.recipes_grid.row(t.parents("tr")).data(), tipo = "ricetta"; if (num > 0) this.ricette_selezionate[tipo][dati.id_ricetta] = num; else delete this.ricette_selezionate[tipo][dati.id_ricetta]; }, selezionaRicette: function(e) { $("input[type='text']").val(0); for (var tipo in this.ricette_selezionate) for (var id in this.ricette_selezionate[tipo]) $("#ck_" + id).val(this.ricette_selezionate[tipo][id]); }, rifiutaRicetta: function(dati) { Utils.requestData( Constants.API_EDIT_RICETTA, "POST", { id: dati.id_ricetta, modifiche: { "approvata_ricetta": -1 } }, "Ricetta rifiutata con successo.", null, this.recipes_grid.ajax.reload.bind(this, null, false) ); }, approvaRicetta: function(dati) { Utils.requestData( Constants.API_EDIT_RICETTA, "POST", { id: dati.id_ricetta, modifiche: { "approvata_ricetta": 1 } }, "Ricetta approvata con successo.", null, this.recipes_grid.ajax.reload.bind(this, null, false) ); }, confermaRifiutaRicetta: function(e) { var t = $(e.target), dati = this.recipes_grid.row(t.parents('tr')).data(); Utils.showConfirm("Sicuro di voler rifiutare questa ricetta?", this.rifiutaRicetta.bind(this, dati)); }, confermaApprovaRicetta: function(e) { var t = $(e.target), dati = this.recipes_grid.row(t.parents('tr')).data(); Utils.showConfirm("Sicuro di voler approvare questa ricetta?", this.approvaRicetta.bind(this, dati)); }, setGridListeners: function() { AdminLTEManager.controllaPermessi(); $("td [data-toggle='popover']").popover("destroy"); $("td [data-toggle='popover']").popover(); $('input[type="number"]').unbind("change"); $('input[type="number"]').on("change", this.ricettaSelezionata.bind(this)); $("[data-toggle='tooltip']").tooltip(); $("button.modifica-note").unbind("click", this.mostraModalRicetta.bind(this, true)); $("button.modifica-note").click(this.mostraModalRicetta.bind(this, true)); $("button.dettagli-ricetta").unbind("click", this.mostraModalRicetta.bind(this, false)); $("button.dettagli-ricetta").click(this.mostraModalRicetta.bind(this, false)); $("button.rifiuta-ricetta").unbind("click", this.confermaRifiutaRicetta.bind(this)); $("button.rifiuta-ricetta").click(this.confermaRifiutaRicetta.bind(this)); $("button.approva-ricetta").unbind("click", this.confermaApprovaRicetta.bind(this)); $("button.approva-ricetta").click(this.confermaApprovaRicetta.bind(this)); this.selezionaRicette(); }, erroreDataTable: function(e, settings) { if (!settings.jqXHR || !settings.jqXHR.responseText) { console.log(e, settings); return false; } var real_error = settings.jqXHR.responseText.replace(/^([\S\s]*?)\{"[\S\s]*/i, "$1"); real_error = real_error.replace("\n", "<br>"); Utils.showError(real_error); }, renderRisultati: function(data, type, row) { if (data) { var ret = data.split(";").join("<br>"); if (row.id_unico_risultato_ricetta !== null) ret = row.tipo_ricetta.substr(0, 1) .toUpperCase() + Utils.pad(row.id_unico_risultato_ricetta, Constants.ID_RICETTA_PAG) + "<br>" + ret; return ret; } else return ""; }, renderComps: function(data, type, row) { var ret = data; if (row.tipo_ricetta === "Programmazione") ret = data.replace(/Z\=(\d);\s/g, "Z=$1<br>"); else ret = data.replace(/;/g, "<br>"); return ret; }, renderNote: function(data, type, row) { var denc_data = Utils.unStripHMTLTag(decodeURIComponent(data)); denc_data = denc_data === "null" ? "" : denc_data; return $.fn.dataTable.render.ellipsis(20, false, true, true)(denc_data, type, row); }, renderApprovato: function(data, type, row) { var ret = "In elaborazione...", data = parseInt(data); if (data === -1) ret = "Rifiutato"; else if (data === 1) ret = "Approvato"; return ret; }, renderGiaStampata: function(data, type, row) { var stampata = parseInt(row.gia_stampata, 10) === 1, checked = stampata ? "checked" : ""; return stampata ? "S&Igrave;" : "NO"; }, renderCheckStampa: function(data, type, row) { return "<div class=\"input-group\">" + "<input type='number' min='0' step='1' value='0' class='form-control' id='ck_" + row.id_ricetta + "'>" + "</div>"; }, creaPulsantiAzioni: function(data, type, row) { var pulsanti = ""; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default dettagli-ricetta modificaRicetta ' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Dettagli Ricetta'><i class='fa fa-eye'></i></button>"; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default modifica-note modificaRicetta ' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Modifica Note'><i class='fa fa-pencil'></i></button>"; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto modificaRicetta rifiuta-ricetta' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Rifiuta Ricetta'><i class='fa fa-remove'></i></button>"; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto modificaRicetta approva-ricetta' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Approva Ricetta'><i class='fa fa-check'></i></button>"; return pulsanti; }, creaDataTable: function() { var columns = []; columns.push({ title: "Stampa", render: this.renderCheckStampa.bind(this) }); columns.push({ title: "Gi&agrave; Stampata", render: this.renderGiaStampata.bind(this) }); columns.push({ title: "Giocatore", data: "nome_giocatore" }); columns.push({ title: "Personaggio", data: "nome_personaggio" }); columns.push({ title: "Data Creazione", data: "data_inserimento_it" }); columns.push({ title: "Nome Ricetta", data: "nome_ricetta" }); columns.push({ title: "Tipo", data: "tipo_ricetta" }); columns.push({ title: "Qta In Ravshop", data: "disponibilita_ravshop_ricetta" }); columns.push({ title: "Costo Ravshop", data: "costo_attuale_ricetta" }); columns.push({ title: "Azioni", render: this.creaPulsantiAzioni.bind(this) }); this.recipes_grid = $('#griglia_ricette') .on("error.dt", this.erroreDataTable.bind(this)) .on("draw.dt", this.setGridListeners.bind(this)) .DataTable({ language: Constants.DATA_TABLE_LANGUAGE, ajax: function(data, callback) { data.filtro = $('#griglia_ricette').parents(".box-body").find("input[name='filtri']:checked").val(); Utils.requestData( Constants.API_GET_RICETTE, "GET", data, callback ); }, columns: columns, //lengthMenu: [ 5, 10, 25, 50, 75, 100 ], order: [ [4, 'desc'] ] }); }, recuperaDatiLocali: function() { this.user_info = JSON.parse(window.localStorage.getItem("user")); }, filtraRicette: function(e) { this.recipes_grid.draw(); }, setListeners: function() { $('input[type="checkbox"]').iCheck("destroy"); $('input[type="checkbox"]').iCheck({ checkboxClass: 'icheckbox_square-blue' }); $('.iradio').iCheck({ radioClass: 'iradio_square-blue', labelHover: true }) .on("ifChecked", this.filtraRicette.bind(this)); $("[data-toggle='tooltip']").tooltip(); $("input[name='pubblico_ricetta']").on("ifChanged", this.pubblicaSuRavshop.bind(this)); $("#btn_stampaRicette").click(this.stampaCartellini.bind(this)); $("#btn_resettaContatoriTecnico").click(this.resettaContatori.bind(this)); } }; }(); $(function() { RecipesManager.init(); });<file_sep>/server/README.md # Reboot Live API ## Prerequisiti * [Git](https://git-scm.com/) * [NodeJS 4+](https://nodejs.org/it/download/current/) (solo per fare le build) * NPM (Si installa automaticamente assieme a NodeJS) (solo per fare le build) * [Grunt CLI](https://gruntjs.com/getting-started#installing-the-cli) (solo per fare le build) * [PHP](http://www.php.net/) * [Apache](https://httpd.apache.org/) * [MySQL](https://www.mysql.com/it/) ## Installazione Clonare questa repository nella folder `htdocs` o `www` di apache. Una volta terminato il trasferimento installare tutti i pacchetti di NodeJS: ``` npm install ``` Importare il database tramite il file .sql con la versione più alta trovato nella cartella `data`. Recuperare il file `gruntconfig.json`, con tutte le password, dalla repository privata (il pc di Andre =D). ## Avvio * Avviare il server Apache * Avviare il demone MySQL <file_sep>/server/src/classes/NewsManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class NewsManager { protected $db; protected $session; protected $idev_in_corso; public static $MAPPA_PAGINA_ABILITA = [ 26 => "Informazioni Commerciali", 75 => "Contatti nell'Ago", 81 => "Contatti tra gli Sbirri", 77 => "Contatti nella Malavita", 82 => "Contatti nella Famiglia" ]; public function __construct( $idev_in_corso = NULL ) { $this->idev_in_corso = $idev_in_corso; $this->session = SessionManager::getInstance(); $this->db = new DatabaseBridge(); } public function __destruct() { } private function controllaInputArticolo( $tipo, $titolo, $autore, $pub_manuale, $data_pub, $ora_pub, $testo ) { $error = ""; if( !isset($tipo) || $tipo === "-1" ) $error .= "<li>&Egrave; obbligatorio scegliere il tipo dell'articolo.</li>"; if( !isset($titolo) || Utils::soloSpazi($titolo) ) $error .= "<li>Il campo Titolo non pu&ograve; essere lasciato vuoto.</li>"; if( !isset($autore) || Utils::soloSpazi($autore) ) $error .= "<li>Il campo Autore non pu&ograve; essere lasciato vuoto.</li>"; if( isset($pub_manuale) && $pub_manuale === "0" && ( !isset($data_pub) || empty($data_pub) || Utils::soloSpazi($data_pub) || !isset($ora_pub) || empty($ora_pub) || Utils::soloSpazi($ora_pub) ) ) $error .= "<li>Se la pubblicazione &egrave; automatica &egrave; obbligatorio inserire data e ora di pubblicazione.</li>"; if( !isset($testo) || Utils::soloSpazi($testo) ) $error .= "<li>Il Testo dell'Articolo non pu&ograve; essere lasciato vuoto.</li>"; return $error; } private function azioneNotizia( $tipo, $titolo, $autore, $data_ig, $pub_manuale, $data_pub, $ora_pub, $testo, $id_articolo = NULL ) { $errors = $this->controllaInputArticolo( $tipo, $titolo, $autore, $pub_manuale, $data_pub, $ora_pub, $testo ); if( !empty($errors) ) throw new APIException( "Sono stati riscontrati i seguenti errori: <ul>$errors</ul>" ); $macro_data = "NULL"; $params = [ ":tipo" => $tipo, ":titolo" => $titolo, ":autore" => $autore, ":dataig" => $data_ig, ":testo" => $testo ]; if( $pub_manuale === "0" ) { $datetime = DateTime::createFromFormat("d/m/Y H:i", $data_pub." ".$ora_pub ); $time_str = $datetime->format("Y-m-d H:i:s" ); $params[":data_pub"] = $time_str; $macro_data = ":data_pub"; } if ( !isset($id_articolo) ) { $query = "INSERT INTO notizie (id_notizia, tipo_notizia, titolo_notizia, autore_notizia, data_ig_notizia, data_pubblicazione_notizia, testo_notizia, creatore_notizia) VALUES ( NULL, :tipo, :titolo, :autore, :dataig, $macro_data, :testo, :creatore)"; $params[":creatore"] = $this->session->email_giocatore; } else if ( isset($id_articolo) ) { $query = "UPDATE notizie SET tipo_notizia = :tipo, titolo_notizia = :titolo, autore_notizia = :autore, data_ig_notizia = :dataig, data_pubblicazione_notizia = $macro_data, testo_notizia = :testo WHERE id_notizia = :id"; $params[":id"] = $id_articolo; } $this->db->doQuery( $query, $params, False ); $output = ["status" => "ok"]; return json_encode($output); } public function creaNotizia( $tipo, $titolo, $autore, $data_ig, $pub_manuale, $data_pub, $ora_pub, $testo ) { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); return $this->azioneNotizia( $tipo, $titolo, $autore, $data_ig, $pub_manuale, $data_pub, $ora_pub, $testo ); } public function modificaNotizia( $tipo, $titolo, $autore, $data_ig, $pub_manuale, $data_pub, $ora_pub, $testo, $id_art ) { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); return $this->azioneNotizia( $tipo, $titolo, $autore, $data_ig, $pub_manuale, $data_pub, $ora_pub, $testo, $id_art ); } public function recuperaNotizie( $draw, $columns, $order, $start, $length, $search ) { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $filter = False; $where = ""; $params = []; if( isset( $search ) && isset( $search["value"] ) && $search["value"] != "" ) { $filter = True; $params[":search"] = "%$search[value]%"; $where .= " ( CONCAT(gi.nome_giocatore,' ',gi.cognome_giocatore) LIKE :search OR n.creatore_notizia LIKE :search OR n.data_pubblicazione_notizia LIKE :search OR n.titolo_notizia LIKE :search OR n.tipo_notizia LIKE :search OR n.autore_notizia LIKE :search OR n.data_ig_notizia LIKE :search OR n.testo_notizia LIKE :search )"; } if( isset( $order ) ) { $sorting = array(); foreach ( $order as $elem ) $sorting[] = $columns[$elem["column"]]["data"]." ".$elem["dir"]; $order_str = "ORDER BY ".implode( $sorting, "," ); } if( !empty($where) ) $where = "WHERE".$where; $query = "SELECT n.*, IF( ( n.pubblica_notizia = 1 OR ( n.data_pubblicazione_notizia IS NOT NULL AND n.data_pubblicazione_notizia <= NOW() ) ), 'S&igrave;', 'No') as pubblica_notizia, IF( n.data_pubblicazione_notizia IS NULL, 'Manuale', DATE_FORMAT( n.data_pubblicazione_notizia, '%d/%m/%Y %H:%i:%s' ) ) AS data_pubblicazione_notizia, DATE_FORMAT( n.data_creazione_notizia, '%d/%m/%Y %H:%i:%s' ) AS data_creazione_notizia, CONCAT(gi.nome_giocatore,' ',gi.cognome_giocatore) AS nome_giocatore FROM notizie AS n JOIN giocatori AS gi ON gi.email_giocatore = n.creatore_notizia $where $order_str"; $risultati = $this->db->doQuery( $query, $params, False ); $totale = count($risultati); if( count($risultati) > 0 ) $risultati = array_splice($risultati, $start, $length); else $risultati = array(); $output = array( "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => $totale, "recordsFiltered" => $filter ? count($risultati) : $totale, "data" => $risultati ); return json_encode($output); } public function recuperaNotiziePubbliche( $tipi = NULL ) { global $GRANT_CREA_NOTIZIE; global $GRANT_MODIFICA_NOTIZIE; UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $legge_tutto = UsersManager::controllaPermessi( $this->session, [$GRANT_CREA_NOTIZIE, $GRANT_MODIFICA_NOTIZIE], False ); if( !$legge_tutto && !isset($this->session->pg_loggato) ) throw new APIException("Devi essere loggato con un personaggio per compiere questa operazione.", APIException::$PG_LOGIN_ERROR); if (!$legge_tutto) { if (!isset($tipi)) { $ids_civile = Utils::mappaArrayDiArrayAssoc($this->session->pg_loggato["abilita"]["civile"], "id_abilita"); $ids_militare = Utils::mappaArrayDiArrayAssoc($this->session->pg_loggato["abilita"]["militare"], "id_abilita"); $ids = array_merge($ids_civile, $ids_militare); $id_con_pag = Utils::filtraArrayConValori($ids, array_keys(self::$MAPPA_PAGINA_ABILITA)); $pagine = Utils::filtraArrayConChiavi(self::$MAPPA_PAGINA_ABILITA, $id_con_pag); $tipi = array_values($pagine); } else if (isset($tipi) && !is_array($tipi)) $tipi = [$tipi]; $marcatori = str_repeat("?, ", count( $tipi ) - 1 ) . "?"; $query_sel = "SELECT * FROM notizie WHERE tipo_notizia IN ($marcatori) AND ( pubblica_notizia = 1 OR ( data_pubblicazione_notizia IS NOT NULL AND data_pubblicazione_notizia <= NOW() ) ) ORDER BY tipo_notizia ASC, data_creazione_notizia DESC "; } else { $query_sel = "SELECT * FROM notizie WHERE ( pubblica_notizia = 1 OR ( data_pubblicazione_notizia IS NOT NULL AND data_pubblicazione_notizia <= NOW() ) ) ORDER BY tipo_notizia ASC, data_creazione_notizia DESC "; $tipi = []; } $result = $this->db->doQuery($query_sel, $tipi, False); $result = !isset( $result ) ? [] : $result; $output = [ "status" => "ok", "result" => $result ]; return json_encode($output); } public function pubblicaNotizia( $id ) { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $query = "UPDATE notizie SET pubblica_notizia = :pub WHERE id_notizia = :id"; $params = [":id" => $id, ":pub" => 1]; $this->db->doQuery( $query, $params, False ); $output = ["status" => "ok"]; return json_encode($output); } public function ritiraNotizia( $id ) { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $query = "UPDATE notizie SET pubblica_notizia = :pub, data_pubblicazione_notizia = NULL WHERE id_notizia = :id"; $params = [":id" => $id, ":pub" => 0]; $this->db->doQuery( $query, $params, False ); $output = ["status" => "ok"]; return json_encode($output); } } <file_sep>/client/app/scripts/controllers/CraftingSoftwareManager.js /** * Created by Miroku on 11/03/2018. */ var CraftingSoftwareManager = function () { var QUESTIONS_PROG_BASE = [ { name : "nome_programma", text : "Inserire il nome del nuovo software.", prompt : "Nome: ", sommabile : false }, { name : "x_val", text : "\nInserire il parametro X della {num}^ sequenza in vostro possesso.", prompt : "X: ", sommabile : true, validation: function (cmd) { if( /^\s*\d\s*$/i.test(cmd) ) return true; return false; } }, { name : "y_val", text : "\nInserire il parametro Y della {num}^ sequenza in vostro possesso.", prompt : "Y: ", sommabile : true, validation: function (cmd) { if( /^\s*\d\s*$/i.test(cmd) ) return true; return false; } }, { name : "z_val", text : "\nInserire il parametro Z della {num}^ sequenza in vostro possesso.", prompt : "Z: ", sommabile : true, validation: function (cmd) { if( /^\s*\d\s*$/i.test(cmd) ) return true; return false; } } ], QUESTIONS_PROG_AVAN = [ { name : "nome_programma", text : "Inserire il nome per la nuova combinazione di software.", prompt : "Nome: ", sommabile : false }, { name : "x_val", text : "\nInserire il parametro X del {num}° software da combinare.", prompt : "X: ", sommabile : true, validation: function (cmd) { if( /^\s*\d\s*$/i.test(cmd) ) return true; return false; } }, { name : "y_val", text : "\nInserire il parametro Y del {num}° software da combinare.", prompt : "Y: ", sommabile : true, validation: function (cmd) { if( /^\s*\d\s*$/i.test(cmd) ) return true; return false; } }, { name : "z_val", text : "\nInserire il parametro Z del {num}° software da combinare.", prompt : "Z: ", sommabile : true, validation: function (cmd) { if( /^\s*\d\s*$/i.test(cmd) ) return true; return false; } } ], GREETINGS = " _________ _________________ .__ .__ \n"+ " / _____// _____/\\_ ___ \\ ____ | | |__|\n"+ " \\_____ \\/ \\ ___/ \\ \\/ _/ ___\\| | | |\n"+ " / \\ \\_\\ \\ \\____ \\ \\___| |_| |\n"+ "/_______ /\\______ /\\______ / \\___ >____/__|\n"+ " \\/ \\/ \\/ \\/ \n"+ "Benvenuto nel framework di sviluppo software dell'SGC.\n" + "Prego, inserire i parametri in vostro possesso:\n", SPINNERS = { "line": { "interval": 80, "frames": [ "-", "\\", "|", "/" ] }, "simpleDots": { "interval": 400, "frames": [ ". ", ".. ", "...", " " ] } }; return { init : function () { this.setListeners(); this.recuperaDatiLocali(); this.impostaTerminale(); }, progress : function (term, percent) { var width = ( term.cols() / 1.5 ) - 10; var size = Math.round(width * percent / 100); var left = '', taken = '', i; for (i = size; i >= 0; i--) taken += '='; if (taken.length > 0) taken = taken.replace(/=$/, '>'); for (i = width - size; i >= 0; i--) left += ' '; term.set_prompt( '[' + taken + left + '] ' + percent + '%' ); }, start : function (term, spinner) { var i = 0; function set() { var text = spinner.frames[i++ % spinner.frames.length]; term.set_prompt(text); }; this.terminal_prompt = term.get_prompt(); term.find('.cursor').hide(); set(); this.terminal_timer = setInterval(set, spinner.interval); }, stop : function (term, spinner) { clearInterval(this.terminal_timer); var frame = spinner.frames[0]; term.echo(frame); term.find('.cursor').show(); }, showFinalMessage : function () { this.terminal.echo( this.terminal.get_prompt() ); this.terminal.echo( "" ); this.terminal.set_prompt( this.default_prompt ); this.terminal.focus(true); this.terminal.scroll_to_bottom(); }, showTechnoBabble : function ( i ) { i = typeof i === "undefined" ? 0 : i; var texts = Testi.TECHNO_BUBBLING, delay = parseInt(Math.random() * 1000) / 4; setTimeout(function () { this.terminal.echo(texts[i].text); this.progress(this.terminal, parseInt( ( i / texts.length ) * 100 ) ); this.terminal.scroll_to_bottom(); if( typeof texts[i+1] !== "undefined" ) this.showTechnoBabble(i+1); else { this.progress(this.terminal, 100); this.showFinalMessage(); } }.bind(this), 50 + delay); }, craftinInviato : function ( ) { this.stop(this.terminal,SPINNERS.line); this.progress(this.terminal, 0); this.showTechnoBabble(); }, inviaDatiCrafting : function ( programmi ) { this.start(this.terminal,SPINNERS.line); this.terminal.freeze(true); Utils.requestData( Constants.API_POST_CRAFTING_PROGRAMMA, "POST", { pg: this.pg_info.id_personaggio, programmi: programmi }, this.craftinInviato.bind(this) ); }, mostraOpzioni: function ( domanda, opzioni ) { this.terminal.push(function (command) { var opz = opzioni.filter(function(el){ return el.opzione === command; }); if( opz.length === 0 ) { this.terminal.echo('[[b;#f00;]L\'opzione inserita non &egrave; contemplata.]'); this.terminal.pop(); this.mostraOpzioni(domanda,opzioni); } opz[0].reazione(); }.bind(this), { prompt : domanda + ' ' }); }, rispostaMultipla: function ( domanda, risposte ) { this.terminal.push(function (command) { var trimmed = command.replace(/^\s+|\s+$/g, ""); for (var r in risposte) { if (( new RegExp("^" + risposte[r].command + "$", "i") ).test(trimmed) && typeof risposte[r].callback === "function") risposte[r].callback(); } }, { prompt : domanda + ' ' }); }, sommaStringhe : function ( a, b ) { var somma = ( parseInt( a, 10 ) + parseInt( b, 10 ) ) + ""; return parseInt( somma.substr( somma.length-1, 1 ), 10 ); }, terminaDomande: function ( prog_avanz ) { this.terminal.echo('\nEcco il risultato finale:'); var somma = {}, str = "", perdb = {}; this.answers.pop(); for ( var a in this.answers ) { if( prog_avanz && this.answers[a].nome_programma ) { somma["Nome comnbinazione"] = this.answers[a].nome_programma; var copia = JSON.parse( JSON.stringify( this.answers[a] ) ); delete copia.nome_programma; somma[(parseInt(a, 10) + 1) + "° software"] = $.map(copia, function (el) { return el; }); } else if ( prog_avanz ) somma[(parseInt(a,10)+1)+"° software"] = $.map(this.answers[a],function(el){return el;}); else if ( !prog_avanz ) for( var p in this.answers[a] ) { if( !isNaN( parseInt( this.answers[a][p], 10 ) ) && somma[p] ) somma[p] = this.sommaStringhe( somma[p], this.answers[a][p] ); else somma[p] = this.answers[a][p]; } } for( var s in somma ) str += '[[b;#fff;]' + s + ']: ' + somma[s] + '\n'; this.terminal.echo(str); perdb = prog_avanz ? this.answers : [somma]; this.rispostaMultipla( prog_avanz ? "Confermi la combinazione di software? (s|n)" : "Confermi il software? (s|n)", [ {command: "s", callback: this.inviaDatiCrafting.bind(this, perdb)}, {command: "n", callback: this.impostaTerminale.bind(this)} ] ); }, mostraDomande: function ( cancella_precedenti, prog_avanz ) { cancella_precedenti = typeof cancella_precedenti === "undefined" ? true : cancella_precedenti; if( cancella_precedenti ) this.answers.pop(); if( cancella_precedenti && prog_avanz ) this.num_programmi--; this.answers.push({}); this.terminal.pop(); if( this.answers.length - 1 >= 2 && ( !prog_avanz || ( prog_avanz && this.num_programmi <= this.max_programmi ) ) ) { this.rispostaMultipla( prog_avanz ? "Combinare un nuovo software? (s|n)" : "Sommare una nuova sequenza? (s|n)", [ {command: "s", callback: this.ask_questions.bind( this, 1, prog_avanz )}, {command: "n", callback: this.terminaDomande.bind( this, prog_avanz )} ] ); } else if ( this.answers.length - 1 < 2 ) this.ask_questions( 1, prog_avanz ); }, aggiungiProgrammi: function ( combinare_programmi ) { this.terminal.pop(); }, finish : function ( prog_avanz ) { if( prog_avanz ) this.num_programmi++; this.terminal.echo('\nSono stati inseriti i seguenti valori:'); var ai = this.answers.length - 1, str = ""; for( var a in this.answers[ai] ) { //non chiedo conferma del nome se non alla fine if( a !== "nome_programma" ) str += '[[b;#fff;]' + a + ']: ' + this.answers[ai][a] + '\n'; } this.terminal.echo(str); this.rispostaMultipla( !prog_avanz ? "Confermare sequenza (s|n)" : "Confermare software (s|n)", [ {command: "s", callback: this.mostraDomande.bind(this, false, prog_avanz)}, {command: "n", callback: this.mostraDomande.bind(this, true, prog_avanz)} ] ); }, ask_questions : function ( step, prog_avanz ) { this.terminal.set_command(""); var question = this.domande[step]; if (question) { var ai = this.answers.length - 1; if (question.text) this.terminal.echo('[[b;#fff;]' + question.text.replace(/\{num}/g,(ai+1)+"") + ']'); this.terminal.push(function (command) { if( typeof question.validation === "function" && question.validation(command) === true || typeof question.validation !== "function" ) { this.answers[ai][question.name] = command; this.terminal.pop(); this.ask_questions(step + 1, prog_avanz); } else this.terminal.echo('[[b;#f00;]Valore inserito errato. Riprovare.]'); }.bind(this), { prompt : question.prompt || question.name + ": " } ); } else { this.finish( prog_avanz ); } }, domandeBase: function () { this.domande = QUESTIONS_PROG_BASE.concat(); this.ask_questions(0,false); }, domandeAvan: function () { this.domande = QUESTIONS_PROG_AVAN.concat(); this.terminal.echo('\nIn base al tuo chip potrai combinare fino a un massimo di '+this.max_programmi+' software gi&agrave; compilati.'); this.ask_questions(0,true); }, impostaTerminale: function () { var utente = this.pg_info.nome_personaggio.toLowerCase().replace(/[^A-zÀ-ú]/g,"-"); this.domande = QUESTIONS_PROG_BASE.concat(); this.answers = [{}]; this.default_prompt = utente+'@SGC> '; $('#terminal').height( $(".content-wrapper").height() - 51 ); //$('#terminal').width( $(".content-wrapper").width() ); $('.scanlines').height( $('#terminal').height() ); $('.scanlines').width( $('#terminal').width() ); if( this.terminal ) this.terminal.destroy(); this.terminal = $('#terminal').terminal( { exit: function () { Utils.redirectTo(Constants.PG_PAGE); } }, { prompt : this.default_prompt, greetings : GREETINGS, exit : false, keymap: { "CTRL+R": function() { return false; }, "TAB" : function() { return false; }, "Shift+Enter" : function() { return false; }, "Up Arrow/CTRL+P" : function() { return false; }, "Down Arrow/CTRL+N" : function() { return false; }, "CTRL+R" : function() { return false; }, "CTRL+G" : function() { return false; }, "CTRL+L" : function() { return false; }, "CTRL+Y" : function() { return false; }, "Delete/backspace" : function() { return false; }, "Left Arrow/CTRL+B" : function() { return false; }, "CTRL+TAB" : function() { return false; }, "Right Arrow/CTRL+F" : function() { return false; }, "CTRL+Left Arrow" : function() { return false; }, "CTRL+Right Arrow" : function() { return false; }, "CTRL+A/Home" : function() { return false; }, "CTRL+E/End" : function() { return false; }, "CTRL+K" : function() { return false; }, "CTRL+U" : function() { return false; }, "CTRL+V/SHIFT+Insert" : function() { return false; }, "CTRL+W" : function() { return false; }, "CTRL+H" : function() { return false; }, "ALT+D" : function() { return false; }, "PAGE UP" : function() { return false; }, "PAGE DOWN" : function() { return false; }, "CTRL+D" : function() { return false; } } } ); this.terminal.history().disable(); if( this.max_programmi > 1 ) { this.rispostaMultipla( "Il chip dell'utente permette la combinazione di pi&ugrave; programmi conosciuti. Cosa vuoi fare?"+ "\na) Unire nuove stringhe di codice (Programmazione)"+ "\nb) Unire pi&ugrave; programmi conosciuti (Programmazione Avanzata/Totale)"+ "\n(a|b)", [ {command: "a", callback: this.domandeBase.bind(this)}, {command: "b", callback: this.domandeAvan.bind(this)} ] ); } else this.domandeBase(); }, recuperaDatiLocali : function () { this.user_info = JSON.parse(window.localStorage.getItem("user")); this.pg_info = JSON.parse(window.localStorage.getItem("logged_pg")); if( !this.pg_info ) { Utils.showError("Devi loggarti con un personaggio prima di accedere a questa sezione.", Utils.redirectTo.bind(this,Constants.MAIN_PAGE)); throw new Error("Devi loggarti con un personaggio prima di accedere a questa sezione."); } else if( this.pg_info && !Utils.controllaPermessiPg( this.pg_info, ["visualizza_pagina_crafting_programmazione"] ) ) { Utils.showError("Non puoi accedere a questa sezione.", Utils.redirectTo.bind(this,Constants.MAIN_PAGE)); throw new Error("Non puoi accedere a questa sezione."); } this.num_programmi = 0; this.max_programmi = this.pg_info.max_programmi_netrunner; }, setListeners : function () { } }; }(); $(function () { CraftingSoftwareManager.init(); }); <file_sep>/docker-php-apache/Dockerfile FROM php:5.6.30-apache MAINTAINER <NAME> RUN docker-php-ext-install pdo pdo_mysql mysqli <file_sep>/makefile .PHONY: dev dev: docker-compose rm -f && docker-compose up --build .PHONY: local local: export BUILD_TYPE=local && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build .PHONY: local-client local-client: export BUILD_TYPE=local && export BUILD_WHAT=client && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build .PHONY: local-server local-server: export BUILD_TYPE=local && export BUILD_WHAT=server && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build .PHONY: preprod preprod: export BUILD_TYPE=preprod && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build .PHONY: preprod-client preprod-client: export BUILD_TYPE=preprod && export BUILD_WHAT=client && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build .PHONY: preprod-server preprod-server: export BUILD_TYPE=preprod && export BUILD_WHAT=server && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build .PHONY: prod prod: export BUILD_TYPE=prod && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build .PHONY: prod-client prod-client: export BUILD_TYPE=prod && export BUILD_WHAT=client && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build .PHONY: prod-server prod-server: export BUILD_TYPE=prod && export BUILD_WHAT=server && docker-compose rm -f && docker-compose -f ./docker-compose-build.yml up --build <file_sep>/client/app/scripts/controllers/__ManagerModel.js var Model = function () { return { init: function () { this.setListeners(); }, setListeners: function() { } }; }(); $(function () { Model.init(); });<file_sep>/server/src/api.php <?php $path = $_SERVER['DOCUMENT_ROOT']."/"; include_once( $path."classes/APIException.class.php" ); include_once( $path."classes/UsersManager.class.php" ); include_once( $path."classes/CharactersManager.class.php" ); include_once( $path."classes/MessagingManager.class.php" ); include_once( $path."classes/EventsManager.class.php" ); include_once( $path."classes/GrantsManager.class.php" ); include_once( $path."classes/NewsManager.class.php" ); include_once( $path."classes/CraftingManager.class.php" ); include_once( $path."classes/TransactionManager.class.php" ); include_once( $path."classes/Statistics.class.php" ); include_once( $path."classes/CartelliniManager.class.php" ); include_once( $path."classes/AbilitiesManager.class.php" ); include_once( $path."classes/RumorsManager.class.php" ); include_once( $path."config/constants.php" ); class Main { protected $usersmanager; protected $charactersmanager; protected $messagingmanager; protected $eventsmanager; protected $grantsmanager; protected $newsmanager; protected $craftingmanager; protected $transactionmanager; protected $statistics; protected $cartellinimanager; protected $abilitiesmanager; protected $rumorsmanager; public function __construct() { global $ALLOWED_ORIGINS; ini_set( 'html_errors', false ); date_default_timezone_set( 'Europe/Rome' ); header( 'Content-Type: application/json;charset=UTF-8' ); header( 'Access-Control-Allow-Credentials: true' ); if( in_array( @$_SERVER["HTTP_ORIGIN"], $ALLOWED_ORIGINS ) ) header( 'Access-Control-Allow-Origin: '.$_SERVER["HTTP_ORIGIN"] ); $this->eventsmanager = new EventsManager(); $idev_in_corso = $this->eventsmanager->recuperaEventoInCorso(); $this->usersmanager = new UsersManager( $idev_in_corso ); $this->charactersmanager = new CharactersManager( $idev_in_corso ); $this->messagingmanager = new MessagingManager( $idev_in_corso ); $this->grantsmanager = new GrantsManager(); $this->newsmanager = new NewsManager( $idev_in_corso ); $this->craftingmanager = new CraftingManager( $idev_in_corso ); $this->transactionmanager = new TransactionManager( $this->charactersmanager, $idev_in_corso ); $this->statistics = new Statistics( $this->charactersmanager ); $this->cartellinimanager = new CartelliniManager( ); $this->abilitiesmanager = new AbilitiesManager( ); $this->rumorsmanager = new RumorsManager( ); } public function __destruct() { } public function runAPI() { global $DEBUG; global $MAINTENANCE; global $MESSAGGIO_CHIUSURA; global $IP_MAINTAINER; $method = $_SERVER['REQUEST_METHOD']; $request = explode( '/', trim( $_SERVER['PATH_INFO'], '/' ) ); $classe = $request[0]; $func = $request[1]; $data = []; try { if( $MAINTENANCE && !in_array( Utils::getUserIP(), $IP_MAINTAINER) ) throw new APIException("Ci scusiamo, ma al momento il database &egrave; in manutenzione. Per favore attendi comunicazioni dallo Staff."); if( $method == "GET" ) $data = $_GET; else if ( $method == "POST" ) $data = $_POST; return call_user_func_array( array( $this->$classe, $func ), $data ); } catch( Exception $e ) { $mex = $e->getMessage(); if( $DEBUG ) $mex .= " \n".$e->getTraceAsString(); if( method_exists($e,'getType') ) $err = Utils::errorJSON( $mex, $e->getType() ); else $err = Utils::errorJSON( $mex ); return $err; } } } $main = new Main(); echo $main->runAPI(); <file_sep>/client/app/scripts/models/Contatore.js /** * Created by Miroku on 10/02/2018. */ var Contatore = Contatore || (function () { var DEFAULT_PARAMS = { valore_max : 0, valore_min : 0, valore_ora : 0, testo : "{num}", macro : "{num}", elemento : "contatore" }; function Contatore( params ) { Object.call(this); this._settings = {}; for( var d in DEFAULT_PARAMS ) { if( params[d] ) this._settings[d] = params[d]; else this._settings[d] = DEFAULT_PARAMS[d]; } this._valore_max = this._settings.valore_max; this._valore_min = this._settings.valore_min; this._valore_ora = this._settings.valore_ora; if( this._valore_ora > this._valore_max ) throw new Error( Contatore.ERRORS.VAL_TROPPO_ALTO ); if( this._valore_ora < this._valore_min ) throw new Error( Contatore.ERRORS.VAL_TROPPO_BASSO ); _getDOMElements.call(this); this.impostaConteggio(); return this; } Contatore.ERRORS = { VAL_TROPPO_ALTO : "valTroppoAlto", VAL_TROPPO_BASSO : "valTroppoBasso" }; Contatore.prototype = Object.create( Object.prototype ); Contatore.prototype.constructor = Contatore; function _getDOMElements() { this.elem_testo = Utils.getJQueryObj( this._settings.elemento ) } function _renderizzaConteggio() { this.elem_testo.html( this._settings.testo.replace( this._settings.macro, this._valore_ora ) ); } Contatore.prototype.impostaConteggio = function( valore ) { this._valore_ora = this._settings.valore_ora; if( this._valore_ora > this._valore_max ) throw new Error( Contatore.ERRORS.VAL_TROPPO_ALTO ); if( this._valore_ora < this._valore_min ) throw new Error( Contatore.ERRORS.VAL_TROPPO_BASSO ); _renderizzaConteggio.call( this ); }; Contatore.prototype.aumentaConteggio = function( valore ) { valore = typeof valore === "undefined" ? 1 : parseInt( valore, 10 ); var nuovo_valore = this._valore_ora + valore; if( nuovo_valore > this._valore_max ) throw new Error( Contatore.ERRORS.VAL_TROPPO_ALTO ); this._valore_ora = nuovo_valore; _renderizzaConteggio.call( this ); }; Contatore.prototype.diminuisciConteggio = function( valore ) { valore = typeof valore === "undefined" ? 1 : parseInt( valore, 10 ); var nuovo_valore = this._valore_ora - valore; if( nuovo_valore < this._valore_min ) throw new Error( Contatore.ERRORS.VAL_TROPPO_BASSO ); this._valore_ora = nuovo_valore; _renderizzaConteggio.call( this ); }; Contatore.prototype.valoreConteggio = function( ) { return this._valore_ora; }; return Contatore; })();<file_sep>/server/src/classes/UsersManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/Mailer.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class UsersManager { protected $db; protected $grants; protected $session; protected $idev_in_corso; public function __construct($idev_in_corso = NULL) { $this->idev_in_corso = $idev_in_corso; $this->session = SessionManager::getInstance(); $this->db = new DatabaseBridge(); $this->mailer = new Mailer(); } public function __destruct() { } public function __toString() { return "[UsersManager]"; } static function controllaPermessi($sessione, $permessi, $tutti = True) { foreach ($permessi as $p) { if (in_array($p, $sessione->permessi_giocatore) && !$tutti) return True; else if (!in_array($p, $sessione->permessi_giocatore) && $tutti) return False; } if ($tutti) return True; else return False; } static function controllaLogin($sessione) { if (!isset($sessione->permessi_giocatore)) throw new APIException("Devi essere loggato per compiere questa operazione.", APIException::$LOGIN_ERROR); } static function operazionePossibile($sessione, $funzione, $id = NULL, $throw_exception = True) { global $TIPO_GRANT_PG_PROPRIO; global $TIPO_GRANT_PG_ALTRI; $tipo_grant = ""; self::controllaLogin($sessione); if (isset($id) && in_array($id, $sessione->pg_propri)) $tipo_grant = in_array($id, $sessione->pg_propri) ? $TIPO_GRANT_PG_PROPRIO : $TIPO_GRANT_PG_ALTRI; else if (isset($id) && !in_array($id, $sessione->pg_propri)) $tipo_grant = $id === $sessione->email_giocatore ? $TIPO_GRANT_PG_PROPRIO : $TIPO_GRANT_PG_ALTRI; if ($throw_exception && !in_array($funzione . $tipo_grant, $sessione->permessi_giocatore)) throw new APIException("Non hai i permessi per compiere questa operazione: <code>$funzione $tipo_grant</code>", APIException::$GRANTS_ERROR); else { if (in_array($funzione . $tipo_grant, $sessione->permessi_giocatore)) return TRUE; else return FALSE; } } private function controllaInputPwd($pass1, $pass2) { $errors = ""; if ($pass1 === "" || Utils::soloSpazi($pass1)) $errors .= "Il primo campo Password non pu&ograve; essere vuoto.<br>"; if ($pass2 === "" || Utils::soloSpazi($pass2)) $errors .= "Il secondo campo Password non pu&ograve; essere vuoto.<br>"; if ( $pass1 !== "" && !Utils::soloSpazi($pass1) && $pass2 !== "" && !Utils::soloSpazi($pass2) && $pass1 !== $pass2 ) $errors .= "Le password inserite non combaciano.<br>"; return $errors; } private function controllaDatiRegistrazione($nome, $cognome, $note, $mail, $pass1, $pass2) { $errors = ""; if ($nome === "" || Utils::soloSpazi($nome)) $errors .= "Il campo Nome non pu&ograve; essere vuoto.<br>"; if ($cognome === "" || Utils::soloSpazi($cognome)) $errors .= "Il campo Cognome non pu&ograve; essere vuoto.<br>"; if ($mail === "" || Utils::soloSpazi($mail)) $errors .= "Il campo Mail non pu&ograve; essere vuoto.<br>"; else if (!Utils::controllaMail($mail)) $errors .= "Il campo Mail contiene un indirizzo non valido.<br>"; $errors .= $this->controllaInputPwd($pass1, $pass2); return $errors; } public function login($mail, $pass) { global $GRANT_MOSTRA_ALTRI_PG; global $GRANT_LOGIN_QUANDO_CHIUSO; global $GRANT_VISUALIZZA_MAIN; global $MESSAGGIO_CHIUSURA; if (!Utils::controllaMail($mail)) throw new APIException("La mail inserita non &egrave; valida. Riprova con un'altra."); $query_grants = "SELECT gi.email_giocatore, gi.default_pg_giocatore, CONCAT(gi.nome_giocatore,' ', gi.cognome_giocatore) AS nome_completo, rhg.grants_nome_grant AS permessi FROM giocatori AS gi LEFT OUTER JOIN ruoli_has_grants AS rhg ON gi.ruoli_nome_ruolo = rhg.ruoli_nome_ruolo WHERE gi.email_giocatore = :mail AND gi.password_giocatore = :pass AND gi.eliminato_giocatore = 0"; $params = array(":mail" => $mail, ":pass" => <PASSWORD>($pass)); $result = $this->db->doQuery($query_grants, $params, False); if (count($result) === 0) throw new APIException("Email utente o password sono errati. Per favore riprovare."); $grants = array_map("Utils::mappaPermessiUtente", $result); $query_pg_propri = "SELECT id_personaggio FROM personaggi WHERE giocatori_email_giocatore = :email"; $pg_propri = $this->db->doQuery($query_pg_propri, array(":email" => $mail), False); if (!isset($pg_propri) || count($pg_propri) === 0) $pg_propri = []; if (isset($MESSAGGIO_CHIUSURA) && !empty($MESSAGGIO_CHIUSURA) && !in_array($GRANT_LOGIN_QUANDO_CHIUSO, $grants)) throw new APIException($MESSAGGIO_CHIUSURA, APIException::$GRANTS_ERROR); $this->session->destroy(); $this->session = SessionManager::getInstance(); $this->session->email_giocatore = $result[0]["email_giocatore"]; $this->session->nome_giocatore = $result[0]["nome_completo"]; $this->session->permessi_giocatore = $grants; $this->session->pg_propri = array_map("Utils::mappaPGUtente", $pg_propri); $output = [ "status" => "ok", "email_giocatore" => $this->session->email_giocatore, "nome_giocatore" => $this->session->nome_giocatore, "pg_propri" => $this->session->pg_propri, "permessi" => $this->session->permessi_giocatore ]; if (Utils::clientInSameLAN() && isset($this->idev_in_corso) && !UsersManager::controllaPermessi($this->session, [$GRANT_MOSTRA_ALTRI_PG])) { $query_iscrizione = "SELECT personaggi_id_personaggio FROM iscrizione_personaggi AS ip JOIN personaggi AS pg ON pg.id_personaggio = ip.personaggi_id_personaggio JOIN giocatori AS gi ON gi.email_giocatore = pg.giocatori_email_giocatore WHERE eventi_id_evento = :idev AND gi.email_giocatore = :mail"; $res_iscrizione = $this->db->doQuery($query_iscrizione, [":idev" => $this->idev_in_corso, ":mail" => $this->session->email_giocatore], False); if (!isset($res_iscrizione) || count($res_iscrizione) === 0) throw new APIException("Ci dispiace, solo i giocatori con personaggi iscritti all'evento in corso possono loggare."); $output["pg_da_loggare"] = $res_iscrizione[0]["personaggi_id_personaggio"]; $output["event_id"] = $this->idev_in_corso; } else if ($result[0]["default_pg_giocatore"] != NULL) $output["pg_da_loggare"] = $result[0]["default_pg_giocatore"]; return json_encode($output); } public function controllaaccesso() { $section = func_get_arg(0); if (!isset($this->session) || (isset($this->session) && !in_array("visualizza_pagina_" . $section, $this->session->permessi_giocatore))) throw new APIException("Impossibile accedere a questa sezione.", APIException::$GRANTS_ERROR); return "{\"status\": \"ok\"}"; } public function controllaPwd($pass) { $query_pwd = "SELECT * FROM giocatori WHERE email_giocatore = :mail AND password_giocatore = :pass"; $params = array(":mail" => $this->session->email_giocatore, ":pass" => <PASSWORD>($pass)); $result = $this->db->doQuery($query_pwd, $params, False); if (count($result) > 0) $json = "{\"status\": \"ok\"}"; else $json = "{\"status\": \"error\", \"message\":\"Password errata.\"}"; return $json; } public function logout() { $this->session->destroy(); return "{\"status\": \"ok\"}"; } public function registra($nome, $cognome, $note, $mail, $pass1, $pass2, $condizioni = NULL) { $errors = $this->controllaDatiRegistrazione($nome, $cognome, $note, $mail, $pass1, $pass2, $condizioni); if (isset($errors) && $errors !== "") throw new APIException($errors); $query_controllo = "SELECT email_giocatore FROM giocatori WHERE email_giocatore = :mail"; $controllo = $this->db->doQuery($query_controllo, array(":mail" => $mail), False); if (count($controllo) > 0) throw new APIException("Esiste gi&agrave; un utente con la mail inserita. Inserirne una differente."); $macro_note = "NULL"; $pass = <PASSWORD>($pass1); $params = array( ":pass" => <PASSWORD>, ":nome" => $nome, ":cognome" => $cognome, ":mail" => $mail ); if (!empty($nome) && !Utils::soloSpazi($nome)) { $params[":note"] = $note; $macro_note = ":note"; } $query = "INSERT INTO giocatori (email_giocatore, password_giocatore, nome_giocatore, cognome_giocatore, note_giocatore) VALUES (:mail,:pass,:nome,:cognome,$macro_note)"; $this->db->doQuery($query, $params); $this->mailer->inviaMailRegistrazione($mail, $nome . " " . $cognome, $pass1); return "{\"status\": \"ok\"}"; } public function recuperaPassword($mail) { if (!Utils::controllaMail($mail)) throw new APIException("La mail inserita non &egrave; valida."); $query_check = "SELECT CONCAT(nome_giocatore, ' ', cognome_giocatore) as nome_completo FROM giocatori WHERE email_giocatore = :id"; $giocatore = $this->db->doQuery($query_check, array(":id" => $mail), False); if (count($giocatore) < 1) throw new APIException("La mail inserita non esiste."); $new_pass = Utils::generatePassword(); $pass = <PASSWORD>($new_pass); $query = "UPDATE giocatori SET password_giocatore = :pass WHERE email_giocatore = :id"; $params = array( ":pass" => $pass, ":id" => $mail, ); $this->db->doQuery($query, $params, False); $this->mailer->inviaMailDatiAccesso($mail, $giocatore[0]["nome_completo"], $new_pass); return "{\"status\": \"ok\"}"; } public function recuperaListaGiocatori($draw, $columns, $order, $start, $length, $search) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $filter = False; $where = ""; $params = array(); if (!empty($search) && isset($search) && $search["value"] != "") { $filter = True; $params[":search"] = "%$search[value]%"; $where = "AND ( nome_giocatore LIKE :search OR email_giocatore LIKE :search OR ruoli_nome_ruolo LIKE :search OR note_giocatore LIKE :search OR note_staff_giocatore LIKE :search )"; } if (!empty($order) && isset($order)) { $sorting = array(); foreach ($order as $elem) $sorting[] = $columns[$elem["column"]]["data"] . " " . $elem["dir"]; $order_str = "ORDER BY " . implode(",", $sorting); } $query_players = "SELECT giocatori.*, CONCAT(nome_giocatore, ' ', cognome_giocatore) AS nome_completo FROM giocatori WHERE eliminato_giocatore = 0 $where $order_str"; $risultati = $this->db->doQuery($query_players, $params, False); $totale = count($risultati); if (count($risultati) > 0) $risultati = array_splice($risultati, $start, $length); else $risultati = array(); $output = array( "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => $totale, "recordsFiltered" => $filter ? count($risultati) : $totale, "data" => $risultati ); return json_encode($output); } public function recuperaNoteUtente($id = NULL) { $id = isset($id) ? $id : $this->session->email_giocatore; self::operazionePossibile($this->session, __FUNCTION__, $id); $query_note = "SELECT note_giocatore FROM giocatori WHERE email_giocatore = :id"; $result = $this->db->doQuery($query_note, array(":id" => $id), False); return "{\"status\": \"ok\",\"result\": " . json_encode($result[0]) . " }"; } public function modificaPassword($vecchia, $pass1, $pass2) { $pass_check = json_decode($this->controllaPwd($vecchia)); if ($pass_check->status === "error") throw new APIException("La vecchia password inserita non &egrave; corretta."); $errors = $this->controllaInputPwd($pass1, $pass2); if (isset($errors) && $errors !== "") throw new APIException($errors); $this->modificaUtente(array("password_giocatore" => sha1($pass1))); $this->mailer->inviaMailDatiAccesso($this->session->email_giocatore, $this->session->nome_giocatore, $pass1); return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function modificaUtente($modifiche, $id = NULL) { $id = isset($id) ? $id : $this->session->email_giocatore; $to_update = []; $valori = []; foreach ($modifiche as $campo => $valore) { if (self::operazionePossibile($this->session, __FUNCTION__ . "_" . $campo, $id, False)) { $val = $valore === "NULL" ? "NULL" : "?"; if ($valore !== "NULL") $valori[] = $valore; $to_update[] = "$campo = $val"; } } if (empty($to_update)) throw new APIException("Non &egrave; possibile eseguire l'operazione.", APIException::$GENERIC_ERROR); $to_update_str = implode(",", $to_update); $valori[] = $id; $query_bg = "UPDATE giocatori SET $to_update_str WHERE email_giocatore = ?"; $this->db->doQuery($query_bg, $valori, False); return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function eliminaGiocatore($id) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $query_canc_pg = "UPDATE giocatori SET eliminato_giocatore = 1 WHERE email_giocatore = :id"; $this->db->doQuery($query_canc_pg, array(":id" => $id), False); return "{ \"status\":\"ok\" }"; } public function recuperaUtentiStaffer() { global $RUOLI_STAFFER; UsersManager::operazionePossibile($this->session, __FUNCTION__); $marcatori = str_repeat("?,", count($RUOLI_STAFFER) - 1) . "?"; $query_staffer = "SELECT email_giocatore, CONCAT( nome_giocatore, ' ', cognome_giocatore ) AS nome_giocatore FROM giocatori WHERE ruoli_nome_ruolo IN ($marcatori)"; $staffers = $this->db->doQuery($query_staffer, $RUOLI_STAFFER, False); $output = [ "status" => "ok", "result" => $staffers ]; return json_encode($output); } } <file_sep>/data/aggiunte.sql -- 2 Marzo 2023 INSERT INTO `reboot_live`.`grants` (`nome_grant`, `descrizione_grant`) VALUES ('scaricaSpecchiettoPG', 'L\'utente può scaricare uno specchietto di tutte le informazioni del proprio pg'); INSERT INTO `reboot_live`.`ruoli_has_grants` (`ruoli_nome_ruolo`, `grants_nome_grant`) VALUES ('admin', 'scaricaSpecchiettoPG'); INSERT INTO `reboot_live`.`ruoli_has_grants` (`ruoli_nome_ruolo`, `grants_nome_grant`) VALUES ('staff', 'scaricaSpecchiettoPG'); -- 7 Marzo 2023 UPDATE `abilita` SET `prerequisito_abilita` = NULL WHERE `abilita`.`id_abilita` = 48; UPDATE `abilita` SET `prerequisito_abilita` = NULL WHERE `abilita`.`id_abilita` = 49; UPDATE `abilita` SET `prerequisito_abilita` = NULL WHERE `abilita`.`id_abilita` = 50; UPDATE `abilita` SET `prerequisito_abilita` = NULL WHERE `abilita`.`id_abilita` = 51; -- 28 Marzo 2023 ALTER TABLE `storico_azioni` ADD COLUMN `note_azione` TEXT;<file_sep>/server/src/classes/CharactersManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/Mailer.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class CharactersManager { protected $db; protected $session; protected $mailer; protected $idev_in_corso; public function __construct($idev_in_corso = NULL) { $this->idev_in_corso = $idev_in_corso; $this->session = SessionManager::getInstance(); $this->db = new DatabaseBridge(); $this->mailer = new Mailer(); } public function __destruct() { } public function __toString() { return "[CharactersManager]"; } public function registraAzione($pgid, $azione, $tabella, $campo, $vecchio_valore, $nuovo_valore, $note_azione) { $vecchio = !isset($vecchio_valore) ? "NULL" : ":vecchio"; $nuovo = !isset($nuovo_valore) ? "NULL" : ":nuovo"; $note = !isset($note_azione) || empty($note_azione) ? "NULL" : ":note"; if ($vecchio_valore == $nuovo_valore) return; $query_azione = "INSERT INTO storico_azioni ( id_personaggio_azione, giocatori_email_giocatore, tipo_azione, tabella_azione, campo_azione, valore_vecchio_azione, valore_nuovo_azione, note_azione ) VALUES ( :idpg, :email, :azione, :tabella, :campo, $vecchio, $nuovo, $note )"; $params = array( ":idpg" => $pgid, ":email" => $this->session->email_giocatore, ":azione" => $azione, ":tabella" => $tabella, ":campo" => $campo ); if (isset($vecchio_valore)) $params[":vecchio"] = $vecchio_valore; if (isset($nuovo_valore)) $params[":nuovo"] = $nuovo_valore; if (isset($note_azione) && !empty($note_azione)) $params[":note"] = $note_azione; $this->db->doQuery($query_azione, $params, False); } private function controllaInputCreaPG($nome, $eta, $classi, $abilita) { $error = ""; $permessiPNG = UsersManager::controllaPermessi($this->session, ["creaPNG"]); if (!isset($nome) || empty($nome) || Utils::soloSpazi($nome)) $error .= "<li>Il campo Nome non pu&ograve; essere lasciato vuoto.</li>"; if (!isset($eta) || empty($eta) || Utils::soloSpazi($eta) || $eta === "0" || !preg_match("/^\d+$/", $eta)) $error .= "<li>Il campo Et&agrave; non pu&ograve; essere vuoto, contenere lettere o essere uguale a 0.</li>"; if (count($classi) < 2 && !$permessiPNG) $error .= "<li>&Egrave; obbligatorio scegliere almeno una classe militare e una civile.</li>"; if (count($abilita) < 2 && !$permessiPNG) $error .= "<li>&Egrave; obbligatorio scegliere almeno una abilit&agrave; militare e una civile.</li>"; if (!empty($error)) throw new APIException("Sono stati rilevati i seguenti errori:<ul>" . $error . "</ul>"); } /* 96 Il punteggio di Difesa Mentale del personaggio è aumentato permanentemente di 1. 172 Il personaggio aumenta permanentemente di 1 il suo punteggio di Difesa Mentale. 173 Il personaggio aumenta permanentemente di 2 il suo punteggio di Difesa Mentale (quest'abilità va a<br>sostituire "Protezione Firmware Avanzata - 172"). 202 Il valore di Difesa mentale del personaggio aumenta di 1. 206 Il valore di Difesa Mentale del personaggio aumenta di 2. (Sostituisce il bonus dato da Schermatura Cerebrale - 202) */ public function calcolaDifesaMentale($base, $abilita) { $punti = []; $id_offset_costante = [96, 172, 202]; if (isset($abilita) && count($abilita) > 0) { foreach ($abilita as $a) { if (in_array((int) $a["id_abilita"], $id_offset_costante)) $punti[$a["id_abilita"]] = $a["offset_mente_abilita"]; else if ((int) $a["id_abilita"] === 173) { $punti[$a["id_abilita"]] = $a["offset_mente_abilita"]; if (isset($punti["172"])) unset($punti["172"]); } else if ((int) $a["id_abilita"] === 206) { $punti[$a["id_abilita"]] = $a["offset_mente_abilita"]; if (isset($punti["202"])) unset($punti["202"]); } } } return $base + array_sum($punti); } /* 98 Se il personaggio ha almeno un Punto Shield base, guadagna +2 punti al suo valore globale. 100 Il valore base dei punti Shield garantiti dalle locazioni equipaggiate con una tuta da combattimento<br>corazzata (come indicato a pag. 17) è moltiplicato per 1,5. 101 Il valore base dei punti Shield garantiti dalle locazioni equipaggiate con una tuta da combattimento<br>corazzata (come indicato a pag. 17) è raddoppiato. Questa abilità sostituisce TUTA CORAZZATA MK2 - 100. 102 Se il personaggio ha almeno un Punto Shield base, guadagna +4 punti al suo valore globale. Questa<br>abilità sostituisce SHIELD MK2 - 98 119 Il massimale base del valore di Shield del personaggio non è mai inferiore a 3 punti quando indossa una tuta da combattimento corazzata, neanche a seguito di oggetti equipaggiati. 125 Il punteggio di Shield totale garantito dalla tuta da combattimento equipaggiata aumenta di 1, se la tuta fornisce al personaggio almeno un punto Shield Base. 158 Il valore base dei punti Shield garantiti dalle locazioni equipaggiate con una tuta da combattimento<br>corazzata (come indicato a pag. 17) è moltiplicato per 1,5. 159 Se il personaggio ha almeno un Punto Shield base, guadagna +2 punti al suo valore globale. 174 Il personaggio se equipaggiato con una tuta da combattimento corazzata aumenta di 2 il punteggio di<br>Shield ottenuto dalla suddetta tuta.<br>Una volta per giornata di gioco il personaggio, quando entra in status di Coma, può subire GUARIGIONE<br>5! Subendo quindi BLOCCO! CONTINUO! allo Shield. 190 Il punteggio di Shield garantito da una tuta da combattimento equipaggiata aumenta di 1, se la tuta<br>fornisce al personaggio almeno un punto Shield Base. 191 Se il personaggio ha almeno un Punto Shield base, guadagna +2 punti al suo valore globale. */ public function calcolaShield($base, $abilita) { $punti = [0]; $moltiplicatore_base = 1; $min = 0; $id_offset_costante = [98, 125, 159, 174, 190, 191]; if (isset($abilita) && count($abilita) > 0) { foreach ($abilita as $a) { if (in_array((int) $a["id_abilita"], $id_offset_costante)) $punti[$a["id_abilita"]] = $a["offset_shield_abilita"]; else if ((int) $a["id_abilita"] === 100) $moltiplicatore_base = 1.5; else if ((int) $a["id_abilita"] === 101) $moltiplicatore_base = 2; else if ((int) $a["id_abilita"] === 102) { $punti[$a["id_abilita"]] = $a["offset_shield_abilita"]; if (isset($punti["98"])) unset($punti["98"]); } else if ((int) $a["id_abilita"] === 119) $min = 3; else if ((int) $a["id_abilita"] === 158) $moltiplicatore_base = 1.5; } } return max($min, ($moltiplicatore_base * $base) + array_sum($punti)); } public function calcolaPF($base, $abilita) { $punti = [0]; if (isset($abilita) && count($abilita) > 0) $punti = array_map("Utils::mappaOffsetPFAbilita", $abilita); return $base + max($punti); } private function recuperaPersonaggi($draw, $columns, $order, $start, $length, $search, $extra_where = array(), $extra_param = array()) { global $PF_INIZIALI; global $MAPPA_COSTO_CLASSI_CIVILI; $where = $extra_where; $params = $extra_param; $filter = False; $order_str = ""; if (isset($search) && isset($search["value"]) && $search["value"] != "") { $filter = True; $params[":search"] = "%$search[value]%"; $where[] = "( bj.id_personaggio LIKE :search OR bj.nome_personaggio LIKE :search OR bj.classi_civili LIKE :search OR bj.classi_militari LIKE :search OR bj.abilita_civili LIKE :search OR bj.abilita_militari LIKE :search OR bj.nome_giocatore LIKE :search OR bj.email_giocatore LIKE :search OR bj.ruoli_nome_ruolo LIKE :search OR bj.note_giocatore LIKE :search )"; } if (isset($order) && count($order) > 0) { $order_by_field = $columns[$order[0]["column"]]["data"]; $order_by_dir = $order[0]["dir"]; if (array_search($order_by_field, ["pf_personaggio", "mente_personaggio", "shield_personaggio"]) === False) $order_str = "ORDER BY bj." . $order_by_field . " " . $order_by_dir; } $big_join = "SELECT pg.id_personaggio, pg.nome_personaggio, pg.px_personaggio, pg.pc_personaggio, pg.data_creazione_personaggio, pg.eliminato_personaggio, pg.contattabile_personaggio, pg.anno_nascita_personaggio, pg.note_cartellino_personaggio, pg.motivazioni_olocausto_inserite_personaggio, gi.email_giocatore, gi.note_giocatore, gi.eliminato_giocatore, gi.ruoli_nome_ruolo, ( SELECT COALESCE( SUM( COALESCE( u.importo, 0 ) ), 0 ) as credito_personaggio FROM ( SELECT SUM( COALESCE( importo_transazione, 0 ) ) as importo, creditore_transazione as pg FROM transazioni_bit GROUP BY creditore_transazione UNION ALL SELECT ( SUM( COALESCE( importo_transazione, 0 ) ) * -1 ) as importo, debitore_transazione as pg FROM transazioni_bit GROUP BY debitore_transazione ) as u WHERE pg = pg.id_personaggio ) as credito_personaggio, IF( ISNULL(pg.background_personaggio), 0, 1 ) AS bg_personaggio, CONCAT( gi.nome_giocatore, ' ', gi.cognome_giocatore ) AS nome_giocatore, GROUP_CONCAT(DISTINCT cl_c.nome_classe SEPARATOR ', ') AS classi_civili, GROUP_CONCAT(DISTINCT cl_m.nome_classe SEPARATOR ', ') AS classi_militari, GROUP_CONCAT(DISTINCT CONCAT( ab_c.nome_abilita, COALESCE( CONCAT( ' (',phoa_c.opzioni_abilita_opzione,')' ), '' ) ) SEPARATOR ', ') AS abilita_civili, GROUP_CONCAT(DISTINCT CONCAT( ab_m.nome_abilita, COALESCE( CONCAT( ' (',phoa_m.opzioni_abilita_opzione,')' ), '' ) ) SEPARATOR ', ') AS abilita_militari, COUNT(DISTINCT cl_c.nome_classe) as num_classi_civili, COUNT(DISTINCT cl_m.nome_classe) as num_classi_militari, COUNT(DISTINCT ab_m.nome_abilita) as num_abilita_militari, ( SELECT SUM(costo_abilita) FROM abilita WHERE tipo_abilita = 'civile' AND id_abilita IN ( SELECT abilita_id_abilita FROM personaggi_has_abilita WHERE personaggi_id_personaggio = pg.id_personaggio ) ) as costo_abilita_civili, MAX(cl_m.mente_base_classe) as mente_base_personaggio, MAX(cl_m.shield_max_base_classe) as scudo_base_personaggio FROM personaggi AS pg JOIN giocatori AS gi ON gi.email_giocatore = pg.giocatori_email_giocatore LEFT OUTER JOIN personaggi_has_classi AS phc ON phc.personaggi_id_personaggio = pg.id_personaggio LEFT OUTER JOIN personaggi_has_abilita AS pha ON pha.personaggi_id_personaggio = pg.id_personaggio LEFT OUTER JOIN classi AS cl_m ON cl_m.id_classe = phc.classi_id_classe AND cl_m.tipo_classe = 'militare' LEFT OUTER JOIN classi AS cl_c ON cl_c.id_classe = phc.classi_id_classe AND cl_c.tipo_classe = 'civile' LEFT OUTER JOIN abilita AS ab_m ON ab_m.id_abilita = pha.abilita_id_abilita AND ab_m.tipo_abilita = 'militare' LEFT OUTER JOIN abilita AS ab_c ON ab_c.id_abilita = pha.abilita_id_abilita AND ab_c.tipo_abilita = 'civile' LEFT OUTER JOIN personaggi_has_opzioni_abilita AS phoa_c ON phoa_c.personaggi_id_personaggio = pg.id_personaggio AND phoa_c.abilita_id_abilita = ab_c.id_abilita LEFT OUTER JOIN personaggi_has_opzioni_abilita AS phoa_m ON phoa_m.personaggi_id_personaggio = pg.id_personaggio AND phoa_m.abilita_id_abilita = ab_m.id_abilita GROUP BY pg.id_personaggio"; $where_str = count($where) > 0 ? "AND " . implode(" AND ", $where) : ""; $query = "SELECT * FROM ( $big_join ) AS bj WHERE bj.eliminato_giocatore = 0 AND bj.eliminato_personaggio = 0 $where_str $order_str"; $risultati = $this->db->doQuery($query, $params, False); $totale = count($risultati); if (count($risultati) > 0) { for ($i = 0; $i < count($risultati); $i++) { $query_ab = "SELECT id_abilita, offset_pf_abilita, offset_shield_abilita, offset_mente_abilita FROM abilita WHERE id_abilita IN ( SELECT abilita_id_abilita FROM personaggi_has_abilita WHERE personaggi_id_personaggio = :pgid )"; $abilita = $this->db->doQuery($query_ab, [":pgid" => $risultati[$i]["id_personaggio"]], False); $risultati[$i]["pf_personaggio"] = $this->calcolaPF($PF_INIZIALI, $abilita); $risultati[$i]["shield_personaggio"] = $this->calcolaShield($risultati[$i]["scudo_base_personaggio"], $abilita); $risultati[$i]["mente_personaggio"] = $this->calcolaDifesaMentale($risultati[$i]["mente_base_personaggio"], $abilita); $risultati[$i]["pc_risparmiati"] = (int) $risultati[$i]["pc_personaggio"] - (int) $risultati[$i]["num_classi_militari"] - (int) $risultati[$i]["num_abilita_militari"]; $risultati[$i]["px_risparmiati"] = (int) $risultati[$i]["px_personaggio"] - (int) $risultati[$i]["costo_abilita_civili"]; for ($j = 0; $j < (int) $risultati[$i]["num_classi_civili"]; $j++) $risultati[$i]["px_risparmiati"] -= $MAPPA_COSTO_CLASSI_CIVILI[$j]; } if (isset($order_by_field) && isset($order_by_dir) && array_search($order_by_field, ["pf_personaggio", "mente_personaggio", "shield_personaggio"]) !== False) { $dir_mult = $order_by_dir === "asc" ? 1 : -1; usort($risultati, function ($item1, $item2) use ($order_by_field, $dir_mult) { return ((int) $item1[$order_by_field] - (int) $item2[$order_by_field]) * $dir_mult; }); } $risultati = array_splice($risultati, $start, $length); } else $risultati = array(); $output = array( "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => $totale, "recordsFiltered" => $filter ? count($risultati) : $totale, "data" => $risultati ); return json_encode($output); } private function controllaOpzioniDuplicate($opzioni, $pgid = NULL) { if (isset($pgid)) { $query_opzioni = "SELECT opzioni_abilita_opzione FROM personaggi_has_opzioni_abilita WHERE personaggi_id_personaggio = :pgid"; $opzioni_db = $this->db->doQuery($query_opzioni, array(":pgid" => $pgid), False); if (isset($opzioni_db) && count($opzioni_db) > 0) foreach ($opzioni_db as $o) $opzioni[] = $o["opzioni_abilita_opzione"]; } if (is_array($opzioni) && count($opzioni) > 0 && count($opzioni) !== count(array_unique($opzioni))) throw new APIException("Non &egrave; possibile selezionare due opzioni uguali per abilit&agrave; diverse."); } private function controllaPossibilitaPunti($id_classi, $id_abilita, $pg_id = NULL, $disponibilita_px = NULL, $disponibilita_pc = NULL) { global $MAPPA_COSTO_CLASSI_CIVILI; if ((!isset($disponibilita_px) || !isset($disponibilita_pc)) && isset($pg_id)) { $query_punti = "SELECT px_personaggio, pc_personaggio FROM personaggi WHERE id_personaggio = :pgid"; $res_punti = $this->db->doQuery($query_punti, array(":pgid" => $pg_id), False); if (!isset($disponibilita_px)) $px = $res_punti[0]["px_personaggio"]; if (!isset($disponibilita_pc)) $pc = $res_punti[0]["pc_personaggio"]; } else if (isset($disponibilita_px) && isset($disponibilita_pc)) { $px = $disponibilita_px; $pc = $disponibilita_pc; } if (isset($id_abilita) && !empty($id_abilita) && count($id_abilita) > 0) { $marker_abilita = str_repeat("?,", count($id_abilita) - 1) . "?"; $query_costo_abilita = "SELECT tipo_abilita, SUM(costo_abilita) AS costo FROM abilita WHERE id_abilita IN ($marker_abilita) GROUP BY tipo_abilita"; $res_costo_abilita = $this->db->doQuery($query_costo_abilita, $id_abilita, False); foreach ($res_costo_abilita as $rca) $costo[$rca["tipo_abilita"]] = $rca["costo"]; } if (isset($id_classi) && !empty($id_classi) && count($id_classi) > 0) { $marker_classi = str_repeat("?,", count($id_classi) - 1) . "?"; $query_qta_classi = "SELECT tipo_classe, COUNT(id_classe) AS qta FROM classi WHERE id_classe IN ($marker_classi) GROUP BY tipo_classe"; $res_qta_abilita = $this->db->doQuery($query_qta_classi, $id_classi, False); foreach ($res_qta_abilita as $rca) $qta[$rca["tipo_classe"]] = $rca["qta"]; } if (isset($costo["civile"]) && isset($qta["civile"])) for ($i = 0; $i < $qta["civile"]; $i++) $costo["civile"] += $MAPPA_COSTO_CLASSI_CIVILI[$i]; if (isset($costo["militare"]) && isset($qta["militare"])) $costo["militare"] += $qta["militare"]; if (isset($costo["civile"]) && $px < $costo["civile"]) throw new APIException("Non hai abbastanza Punti Esperienza per effettuare questi acquisti."); if (isset($costo["militare"]) && $pc < $costo["militare"]) throw new APIException("Non hai abbastanza Punti Combattimento per effettuare questi acquisti."); } private function controllaPrerequisitiPerEliminazioneAbilita($pgid, $id_abilita, $lista_ab, $params = array()) { global $PREREQUISITO_TUTTE_ABILITA; global $PREREQUISITO_F_TERRA_T_SCELTO; global $PREREQUISITO_5_SUPPORTO_BASE; global $PREREQUISITO_3_GUASTATOR_BASE; global $PREREQUISITO_4_SPORTIVO; global $PREREQUISITO_3_ASSALTATA_BASE; global $PREREQUISITO_3_GUASTATOR_AVAN; global $PREREQUISITO_15_GUARDIAN_BASE; global $PREREQUISITO_5_GUARDIANO_BAAV; global $PREREQUISITO_4_ASSALTATO_BASE; global $PREREQUISITO_7_SUPPORTO_BASE; global $PREREQUISITO_SMUOVER_MP_RESET; global $PREREQUISITO_15_GUARDIAN_AVAN; global $PREREQUISITO_15_ASSALTAT_BASE; global $PREREQUISITO_15_ASSALTAT_AVAN; global $PREREQUISITO_15_SUPPORTO_BASE; global $PREREQUISITO_15_SUPPORTO_AVAN; global $PREREQUISITO_15_GUASTATO_BASE; global $PREREQUISITO_15_GUASTATO_AVAN; global $PREREQUISITO_3_GUASTATORE; global $ID_ABILITA_F_TERRA; global $ID_ABILITA_T_SCELTO; global $ID_ABILITA_SMUOVERE; global $ID_ABILITA_MEDPACK_RESET; $id_abilita = (int) $id_abilita; $query_ab = "SELECT * FROM abilita WHERE id_abilita = :id"; $abilita = $this->db->doQuery($query_ab, array(":id" => $id_abilita), False); $abilita = $abilita[0]; $ab_prereq = array_filter($lista_ab, "Utils::filtraAbilitaSenzaPrerequisito"); $new_params = array(); if (count($ab_prereq) > 0) { // -1 per non contare anche l'abilita che ha il prerequisito $qta_sportivo = count(array_filter($lista_ab, "Utils::filtraAbilitaSportivo")) - 1; $qta_guar_base = count(array_filter($lista_ab, "Utils::filtraAbilitaGuardianoBase")); $qta_guar_avan = count(array_filter($lista_ab, "Utils::filtraAbilitaGuardianoAvanzato")); $qta_assa_base = count(array_filter($lista_ab, "Utils::filtraAbilitaAssaltatoreBase")); $qta_assa_avan = count(array_filter($lista_ab, "Utils::filtraAbilitaAssaltatoreAvanzato")); $qta_supp_base = count(array_filter($lista_ab, "Utils::filtraAbilitaSupportoBase")) - 1; $qta_supp_avan = count(array_filter($lista_ab, "Utils::filtraAbilitaSupportoAvanzato")); $qta_guas_base = count(array_filter($lista_ab, "Utils::filtraAbilitaGuastatoreBase")); $qta_guas_avan = count(array_filter($lista_ab, "Utils::filtraAbilitaGuastatoreAvanzato")); foreach ($ab_prereq as $i => $ap) { $pre = (int) $ap["prerequisito_abilita"]; $pre_cl = (int) $ap["classi_id_classe"]; $ab_cl = (int) $abilita["classi_id_classe"]; if ( $pre === $id_abilita || ($pre === $PREREQUISITO_TUTTE_ABILITA && $ab_cl === $pre_cl) || ($pre === $PREREQUISITO_F_TERRA_T_SCELTO && ($id_abilita === $ID_ABILITA_F_TERRA || $id_abilita === $ID_ABILITA_T_SCELTO)) || ($pre === $PREREQUISITO_SMUOVER_MP_RESET && ($id_abilita === $ID_ABILITA_SMUOVERE || $id_abilita === $ID_ABILITA_MEDPACK_RESET)) || $pre === $PREREQUISITO_5_SUPPORTO_BASE && $qta_supp_base < 5 || $pre === $PREREQUISITO_4_SPORTIVO && $qta_sportivo < 4 || $pre === $PREREQUISITO_3_ASSALTATA_BASE && $qta_assa_base < 3 || $pre === $PREREQUISITO_3_GUASTATOR_BASE && $qta_guas_base < 3 || $pre === $PREREQUISITO_3_GUASTATOR_AVAN && $qta_guas_avan < 3 || $pre === $PREREQUISITO_5_GUARDIANO_BAAV && $qta_guar_base + $qta_guar_avan < 5 || $pre === $PREREQUISITO_4_ASSALTATO_BASE && $qta_assa_base < 4 || $pre === $PREREQUISITO_7_SUPPORTO_BASE && $qta_supp_base < 7 || $pre === $PREREQUISITO_15_GUARDIAN_BASE && $qta_guar_base < 15 || $pre === $PREREQUISITO_15_GUARDIAN_AVAN && $qta_guar_avan < 15 || $pre === $PREREQUISITO_15_ASSALTAT_BASE && $qta_assa_base < 15 || $pre === $PREREQUISITO_15_ASSALTAT_AVAN && $qta_assa_avan < 15 || $pre === $PREREQUISITO_15_SUPPORTO_BASE && $qta_supp_base < 15 || $pre === $PREREQUISITO_15_SUPPORTO_AVAN && $qta_supp_avan < 15 || $pre === $PREREQUISITO_15_GUASTATO_BASE && $qta_guas_base < 15 || $pre === $PREREQUISITO_15_GUASTATO_AVAN && $qta_guas_avan < 15 || $pre === $PREREQUISITO_3_GUASTATORE && ( $qta_guas_avan + $qta_guas_base ) < 3 ) { $new_params[] = $ap["id_abilita"]; Utils::rimuoviElementoArrayMultidimensionale($lista_ab, "id_abilita", $ap["id_abilita"]); } } } if (count($new_params) > 0) { foreach ($new_params as $p) $params = $this->controllaPrerequisitiPerEliminazioneAbilita($pgid, $p, $lista_ab, $params); } return array_merge($new_params, $params); } public function mostraPersonaggi($draw, $columns, $order, $start, $length, $search) { UsersManager::controllaLogin($this->session); $tutti = in_array(__FUNCTION__ . "_proprio", $this->session->permessi_giocatore) && in_array(__FUNCTION__ . "_altri", $this->session->permessi_giocatore); $solo_propri = in_array(__FUNCTION__ . "_proprio", $this->session->permessi_giocatore) && !in_array(__FUNCTION__ . "_altri", $this->session->permessi_giocatore); if ($solo_propri && !$tutti) { $where = array("bj.email_giocatore = :userid"); $params = array(":userid" => $this->session->email_giocatore); $result = $this->recuperaPersonaggi($draw, $columns, $order, $start, $length, $search, $where, $params); } else if ($tutti && !$solo_propri) $result = $this->recuperaPersonaggi($draw, $columns, $order, $start, $length, $search); else throw new APIException("Non hai i permessi per compiere questa operazione: <code>" . __FUNCTION__ . "</code>", APIException::$GRANTS_ERROR); return $result; } public function mostraPersonaggiConId($ids) { UsersManager::operazionePossibile($this->session, "mostraPersonaggi_altri"); $marcatori = str_repeat("?, ", count($ids) - 1) . "?"; $where = ["bj.id_personaggio IN ($marcatori)"]; return $this->recuperaPersonaggi(0, [], [], 0, count($ids), [], $where, $ids); } public function recuperaInfoClassi() { $params = array(); $query_classi = "SELECT * FROM classi"; $res_classi = $this->db->doQuery($query_classi, $params, False); $lista_classi = array(); foreach ($res_classi as $l) $lista_classi[$l["tipo_classe"]][] = $l; $query_abilita = "SELECT a1.*, a2.nome_abilita nome_prerequisito_abilita FROM abilita a1 LEFT JOIN abilita a2 ON a1.prerequisito_abilita > 0 AND a1.prerequisito_abilita = a2.id_abilita"; $res_abilita = $this->db->doQuery($query_abilita, $params, False); $lista_abilita = array(); if (count($res_abilita) > 0) { foreach ($res_abilita as $l) { $l["id_classe"] = $l["classi_id_classe"]; unset($l["classi_id_classe"]); $lista_abilita[$l["id_classe"]][] = $l; } $lista_output = json_encode($lista_abilita); } else $lista_output = "{}"; $info_obj = "{\"classi\":" . json_encode($lista_classi) . ", \"abilita\":$lista_output}"; return "{\"status\": \"ok\", \"info\": $info_obj }"; } public function creaPG($nome, $eta, $classi, $abilita, $opzioni = [], $proprietario = NULL, $contattabile = 1) { global $PX_INIZIALI; global $PC_INIZIALI; global $DB_ERR_DELIMITATORE; global $ANNO_PRIMO_LIVE; UsersManager::operazionePossibile($this->session, __FUNCTION__); $this->controllaInputCreaPG($nome, $eta, $classi, $abilita); $this->controllaPossibilitaPunti($classi, $abilita, NULL, $PX_INIZIALI, $PC_INIZIALI); if (isset($opzioni) && !empty($opzioni)) $this->controllaOpzioniDuplicate($opzioni); $new_pg_params = array( ":nomepg" => $nome, ":anno" => $ANNO_PRIMO_LIVE - (int) $eta, ":initpx" => $PX_INIZIALI, ":initpc" => $PC_INIZIALI, ":email" => !isset($proprietario) ? $this->session->email_giocatore : $proprietario, ":contat" => $contattabile ); $new_pg_query = "INSERT INTO personaggi (nome_personaggio, anno_nascita_personaggio, px_personaggio, pc_personaggio, giocatori_email_giocatore, contattabile_personaggio) VALUES ( :nomepg, :anno, :initpx, :initpc, :email, :contat )"; $new_pg_id = $this->db->doQuery($new_pg_query, $new_pg_params); if (!isset($this->session->pg_propri)) $this->session->pg_propri = []; $pg_propri = $this->session->pg_propri; $pg_propri[] = $new_pg_id; $this->session->pg_propri = $pg_propri; $this->registraAzione($new_pg_id, "INSERT", "personaggi", "nome", NULL, $nome, "creazione pg"); $this->registraAzione($new_pg_id, "INSERT", "personaggi", "PX", NULL, $PX_INIZIALI, "creazione pg"); $this->registraAzione($new_pg_id, "INSERT", "personaggi", "PC", NULL, $PC_INIZIALI, "creazione pg"); $this->registraAzione($new_pg_id, "INSERT", "personaggi", "email", NULL, $this->session->email_giocatore, "creazione pg"); try { if (isset($classi) && !empty($classi)) $this->aggiungiClassiAlPG($new_pg_id, $classi, "creazione pg"); if (isset($abilita) && !empty($abilita)) $this->aggiungiAbilitaAlPG($new_pg_id, $abilita, "creazione pg"); if (isset($opzioni) && !empty($opzioni)) $this->aggiungiOpzioniAbilita($new_pg_id, $opzioni, "creazione pg"); } catch (Exception $e) { $this->eliminaPG($new_pg_id, False); $pg_propri = $this->session->pg_propri; array_splice($pg_propri, count($pg_propri) - 1, 1); $this->session->pg_propri = $pg_propri; $err_mex = explode($DB_ERR_DELIMITATORE, $e->getMessage()); $err_mex = count($err_mex) > 1 ? $err_mex[1] : $err_mex[0]; throw new APIException($err_mex); } return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function aggiungiClassiAlPG($pgid, $class_ids, $note_azione) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $classi_query = "INSERT INTO personaggi_has_classi VALUES ( :idpg, :idclasse )"; $classi_params = array(); foreach ($class_ids as $ci) $classi_params[] = array(":idpg" => $pgid, ":idclasse" => $ci); $this->db->doMultipleManipulations($classi_query, $classi_params); $marcatori = str_repeat("?, ", count($class_ids) - 1) . " ?"; $query_nomi = "SELECT nome_classe FROM classi WHERE id_classe IN ($marcatori)"; $nomi = $this->db->doQuery($query_nomi, $class_ids, False); foreach ($nomi as $n) $this->registraAzione($pgid, "INSERT", "classi_personaggio", "classe", NULL, $n["nome_classe"], $note_azione); return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function aggiungiAbilitaAlPG($pgid, $ab_ids, $note_azione) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $marcatori = str_repeat("?,", count($ab_ids) - 1) . "?"; $query_prereq = "SELECT * FROM ( SELECT 1 AS rank, id_abilita, nome_abilita, prerequisito_abilita FROM abilita WHERE id_abilita IN ( $marcatori ) AND prerequisito_abilita IS NULL UNION ALL SELECT 2 AS rank, id_abilita, nome_abilita, prerequisito_abilita FROM abilita WHERE id_abilita IN ( $marcatori ) AND prerequisito_abilita > 0 UNION ALL SELECT 3 AS rank, id_abilita, nome_abilita, prerequisito_abilita FROM abilita WHERE id_abilita IN ( $marcatori ) AND prerequisito_abilita < 0 ) AS ab GROUP BY rank, prerequisito_abilita, id_abilita"; $ordine_ab = $this->db->doQuery($query_prereq, array_merge($ab_ids, $ab_ids, $ab_ids), False); $abilita_query = "INSERT INTO personaggi_has_abilita VALUES ( :idpg, :idabilita )"; $abilita_params = array(); foreach ($ordine_ab as $ab) $abilita_params[] = array(":idpg" => $pgid, ":idabilita" => $ab["id_abilita"]); $this->db->doMultipleManipulations($abilita_query, $abilita_params); foreach ($ordine_ab as $ab) $this->registraAzione($pgid, "INSERT", "abilita_personaggio", "abilita", NULL, $ab["nome_abilita"], $note_azione); return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function aggiungiOpzioniAbilita($pgid, $opzioni = [], $note_azione = "") { UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); if (count($opzioni) > 0) { $query_opzioni = "INSERT INTO personaggi_has_opzioni_abilita VALUES ( :idpg, :idabilita, :opzione )"; $params_opzioni = array(); foreach ($opzioni as $id_ab => $opz) $params_opzioni[] = array(":idpg" => $pgid, ":idabilita" => $id_ab, ":opzione" => $opz); $this->db->doMultipleManipulations($query_opzioni, $params_opzioni); $marcatori = str_repeat("?,", count($opzioni) - 1) . "?"; $query_abilita = "SELECT id_abilita, nome_abilita FROM abilita WHERE id_abilita IN ($marcatori)"; $lista_abilita = $this->db->doQuery($query_abilita, array_keys($opzioni), False); foreach ($lista_abilita as $ab) $this->registraAzione($pgid, "INSERT", "opzioni_abilita", "abilita - opzione", NULL, $ab["nome_abilita"] . " - " . $opzioni[$ab["id_abilita"]], $note_azione); } return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function rimuoviClassePG($pgid, $id_classe, $note_azione = "") { UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $query_info = "SELECT cl.id_classe, cl.nome_classe, cl.prerequisito_classe FROM personaggi_has_classi AS phc JOIN classi AS cl ON phc.classi_id_classe = cl.id_classe WHERE phc.personaggi_id_personaggio = :pgid AND phc.classi_id_classe != :id"; $lista_cl = $this->db->doQuery($query_info, array(":pgid" => $pgid, ":id" => $id_classe), False); $classi_del = array($id_classe); $cl_prereq = []; if (count($lista_cl) > 0) { $cl_prereq = array_filter($lista_cl, "Utils::filtraClasseSenzaPrerequisito"); } if (count($cl_prereq) > 0) { foreach ($cl_prereq as $cp) { if ($cp["prerequisito_classe"] === $id_classe) $classi_del[] = $cp["id_classe"]; } } $params = $classi_del; array_unshift($params, $pgid); $marcatori_cl = str_repeat("?,", count($params) - 2) . "?"; $query_del = "DELETE FROM personaggi_has_classi WHERE personaggi_id_personaggio = ? AND classi_id_classe IN ($marcatori_cl)"; $this->db->doQuery($query_del, $params, False); $query_sel_ab = "SELECT id_abilita, nome_abilita FROM personaggi_has_abilita AS pha JOIN abilita AS ab ON pha.abilita_id_abilita = ab.id_abilita WHERE pha.personaggi_id_personaggio = ? AND ab.classi_id_classe IN ($marcatori_cl)"; $lista_ab = $this->db->doQuery($query_sel_ab, $params, False); if (count($lista_ab) == 0) { return "{\"status\": \"ok\",\"result\": \"true\"}"; } $params_ab = array_map("Utils::mappaIdAbilita", $lista_ab); array_unshift($params_ab, $pgid); $marcatori_ab = str_repeat("?, ", count($params_ab) - 2) . "?"; $query_del_ab = "DELETE FROM personaggi_has_abilita WHERE personaggi_id_personaggio = ? AND abilita_id_abilita IN ($marcatori_ab)"; $this->db->doQuery($query_del_ab, $params_ab, False); $query_del_opzioni = "DELETE FROM personaggi_has_opzioni_abilita WHERE personaggi_id_personaggio = ? AND abilita_id_abilita IN ($marcatori_ab)"; $this->db->doQuery($query_del_opzioni, $params_ab, False); $query_nomi_cl = "SELECT nome_classe FROM classi WHERE id_classe IN ($marcatori_cl)"; $nomi_cl = $this->db->doQuery($query_nomi_cl, $classi_del, False); foreach ($nomi_cl as $n) $this->registraAzione($pgid, "DELETE", "classi_personaggio", "classe", $n["nome_classe"], NULL, $note_azione); foreach ($lista_ab as $la) $this->registraAzione($pgid, "DELETE", "abilita_personaggio", "abilita", $la["nome_abilita"], NULL, $note_azione); return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function rimuoviAbilitaPG($pgid, $id_abilita, $note_azione = "") { UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $query_info = "SELECT ab.id_abilita, ab.nome_abilita, ab.classi_id_classe, ab.prerequisito_abilita FROM personaggi_has_abilita AS pha JOIN abilita AS ab ON pha.abilita_id_abilita = ab.id_abilita WHERE pha.personaggi_id_personaggio = :pgid AND pha.abilita_id_abilita != :id"; $lista_ab = $this->db->doQuery($query_info, array(":pgid" => $pgid, ":id" => $id_abilita), False); $lista_completa = $this->controllaPrerequisitiPerEliminazioneAbilita($pgid, $id_abilita, $lista_ab); array_unshift($lista_completa, $id_abilita); $params = $lista_completa; array_unshift($params, $pgid); $marcatori = str_repeat("?,", count($params) - 2) . "?"; $query_del = "DELETE FROM personaggi_has_abilita WHERE personaggi_id_personaggio = ? AND abilita_id_abilita IN ($marcatori)"; $this->db->doQuery($query_del, $params, False); $query_del_opzioni = "DELETE FROM personaggi_has_opzioni_abilita WHERE personaggi_id_personaggio = ? AND abilita_id_abilita IN ($marcatori)"; $this->db->doQuery($query_del_opzioni, $params, False); $query_nomi_ab = "SELECT nome_abilita FROM abilita WHERE id_abilita IN ($marcatori)"; $nomi_ab = $this->db->doQuery($query_nomi_ab, $lista_completa, False); foreach ($nomi_ab as $n) $this->registraAzione($pgid, "DELETE", "abilita_personaggio", "abilita", $n["nome_abilita"], NULL, $note_azione); return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function acquista($pgid, $classi, $abilita, $opzioni = []) { global $DB_ERR_DELIMITATORE; if (is_array($opzioni) && count($opzioni) > 0) $this->controllaOpzioniDuplicate($opzioni, $pgid); try { if (is_array($classi) && count($classi) > 0) $this->aggiungiClassiAlPG($pgid, $classi, "nuovi acquisti"); if (is_array($abilita) && count($abilita) > 0) $this->aggiungiAbilitaAlPG($pgid, $abilita, "nuovi acquisti"); if (is_array($opzioni) && count($opzioni) > 0) $this->aggiungiOpzioniAbilita($pgid, $opzioni, "nuovi acquisti"); } catch (Exception $e) { $err_mex = explode($DB_ERR_DELIMITATORE, $e->getMessage()); if (count($err_mex) > 1) $err_mex = $err_mex[1]; else $err_mex = $err_mex[0]; throw new APIException($err_mex); } return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function modificaPG($pgid, $modifiche, $is_offset = False, $note_azione = "") { $is_offset = $is_offset === "true"; foreach ($modifiche as $campo => $valore) { UsersManager::operazionePossibile($this->session, __FUNCTION__ . "_" . $campo, $pgid); $campi[] = $campo; $valori[] = nl2br($valore); } $campi_virgola = implode(", ", $campi); $query_vecchi_dati = "SELECT $campi_virgola FROM personaggi WHERE id_personaggio = :pgid"; $vecchi_dati = $this->db->doQuery($query_vecchi_dati, array(":pgid" => $pgid), False); $to_update = ""; if ($is_offset) { foreach ($campi as $c) $to_update .= "$c = $c + ?, "; $to_update = substr($to_update, 0, -2); } else $to_update = implode(" = ?, ", $campi) . " = ?"; $valori[] = $pgid; $query_bg = "UPDATE personaggi SET $to_update WHERE id_personaggio = ?"; $this->db->doQuery($query_bg, $valori, False); if (in_array("background_personaggio", $campi)) $this->mailer->inviaAvvisoBackground($pgid); if (in_array("pc_personaggio", $campi) && in_array("px_personaggio", $campi)) $this->mailer->inviaAvvisoPunti($pgid, $vecchi_dati[0]["pc_personaggio"], (int) $vecchi_dati[0]["pc_personaggio"] + (int) $modifiche["pc_personaggio"], $vecchi_dati[0]["px_personaggio"], (int) $vecchi_dati[0]["px_personaggio"] + (int) $modifiche["px_personaggio"]); else if (in_array("pc_personaggio", $campi) && !in_array("px_personaggio", $campi)) $this->mailer->inviaAvvisoPunti($pgid, $vecchi_dati[0]["pc_personaggio"], (int) $vecchi_dati[0]["pc_personaggio"] + (int) $modifiche["pc_personaggio"]); else if (!in_array("pc_personaggio", $campi) && in_array("px_personaggio", $campi)) $this->mailer->inviaAvvisoPunti($pgid, NULL, NULL, $vecchi_dati[0]["px_personaggio"], (int) $vecchi_dati[0]["px_personaggio"] + (int) $modifiche["px_personaggio"]); foreach ($vecchi_dati as $vd) foreach ($vd as $k => $val) { $nuovo_val = !$is_offset ? $modifiche[$k] : $val + $modifiche[$k]; if ($nuovo_val !== $val) $this->registraAzione($pgid, 'UPDATE', 'personaggi', $k, $val, $nuovo_val, $note_azione); } return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function modificaMoltiPG($pgids, $modifiche, $is_offset = False, $note_azione = "") { foreach ($pgids as $id) $this->modificaPG($id, $modifiche, $is_offset, $note_azione); return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function modificaEtaPG($pgid, $eta_pg, $note_azione = "") { global $ANNO_PRIMO_LIVE; return $this->modificaPG($pgid, ["anno_nascita_personaggio" => $ANNO_PRIMO_LIVE - (int) $eta_pg], $note_azione); } public function eliminaPG($pgid, $controlla_permessi = True, $note_azione = "") { if ($controlla_permessi) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $query_canc_pg = "UPDATE personaggi SET eliminato_personaggio = 1 WHERE id_personaggio = :idpg"; $this->db->doQuery($query_canc_pg, array(":idpg" => $pgid), False); $this->registraAzione($pgid, "DELETE", "personaggi", "eliminato_personaggio", 0, 1, $note_azione); } else { $query_canc_pg = "DELETE FROM personaggi WHERE id_personaggio = :idpg"; $this->db->doQuery($query_canc_pg, array(":idpg" => $pgid), False); } return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function loginPG($pgid) { global $MAPPA_COSTO_CLASSI_CIVILI; global $ABILITA_CRAFTING; global $PF_INIZIALI; global $GRANT_VISUALIZZA_CRAFT_CHIMICO; global $GRANT_VISUALIZZA_CRAFT_PROGRAM; global $GRANT_VISUALIZZA_CRAFT_TECNICO; global $GRANT_VISUALIZZA_NOTIZIE; global $GRANT_RECUPERA_NOTIZIE; global $GRANT_VISUALIZZA_MERCATO; global $GRANT_CRAFTA_ARMI; global $GRANT_CRAFTA_PROTESI; global $GRANT_CRAFTA_GADGET_SHIELD; global $GRANT_CRAFTA_SCUDI_ESOSCHELE; global $CRAFTING_ARMI; global $CRAFTING_PROTESI; global $CRAFTING_GADGET_SHIELD; global $CRAFTING_SCUDI_ESOSCHELE; UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $query_pg = "SELECT pg.id_personaggio, CONCAT( gi.nome_giocatore, ' ', gi.cognome_giocatore ) AS nome_giocatore_completo, pg.nome_personaggio, pg.background_personaggio, pg.px_personaggio, pg.pc_personaggio, pg.data_creazione_personaggio, pg.note_master_personaggio, pg.giocatori_email_giocatore, pg.anno_nascita_personaggio, pg.contattabile_personaggio, pg.motivazioni_olocausto_inserite_personaggio AS motivazioni, gi.nome_giocatore, ( SELECT SUM( COALESCE( u.importo, 0 ) ) as credito_personaggio FROM ( SELECT SUM( COALESCE( importo_transazione, 0 ) ) as importo, creditore_transazione as pg FROM transazioni_bit GROUP BY creditore_transazione UNION ALL SELECT ( SUM( COALESCE( importo_transazione, 0 ) ) * -1 ) as importo, debitore_transazione as pg FROM transazioni_bit GROUP BY debitore_transazione ) as u WHERE pg = pg.id_personaggio ) as credito_personaggio, MAX(COALESCE(cl.mente_base_classe,0)) as mente_base_personaggio, MAX(COALESCE(cl.shield_max_base_classe,0)) as scudo_base_personaggio FROM personaggi AS pg JOIN giocatori AS gi ON pg.giocatori_email_giocatore = gi.email_giocatore JOIN personaggi_has_classi AS phc ON phc.personaggi_id_personaggio = pg.id_personaggio JOIN classi AS cl ON phc.classi_id_classe = cl.id_classe LEFT OUTER JOIN transazioni_bit AS trans_d ON trans_d.debitore_transazione = pg.id_personaggio LEFT OUTER JOIN transazioni_bit AS trans_c ON trans_c.creditore_transazione = pg.id_personaggio WHERE id_personaggio = :idpg"; $res_pg = $this->db->doQuery($query_pg, array(":idpg" => $pgid), False); if (isset($res_pg) && count($res_pg) === 0) throw new APIException("Non puoi scaricare i dati di un giocatore non tuo."); $pg_data = $res_pg[0]; $pg_data["permessi"] = []; $query_classi = "SELECT cl.* FROM classi AS cl WHERE id_classe IN ( SELECT classi_id_classe FROM personaggi_has_classi WHERE personaggi_id_personaggio = :idpg )"; $res_classi = $this->db->doQuery($query_classi, array(":idpg" => $pgid), False); $query_abilita = "SELECT ab.id_abilita, ab.costo_abilita, ab.nome_abilita, ab.descrizione_abilita, ab.prerequisito_abilita, ab.tipo_abilita, ab.distanza_abilita, ab.classi_id_classe, ab.effetto_abilita, ab.offset_pf_abilita, COALESCE(ab.offset_mente_abilita,0) AS offset_mente_abilita, COALESCE(ab.offset_shield_abilita,0) AS offset_shield_abilita, cl.nome_classe FROM abilita AS ab JOIN classi AS cl ON ab.classi_id_classe = cl.id_classe WHERE id_abilita IN ( SELECT abilita_id_abilita FROM personaggi_has_abilita WHERE personaggi_id_personaggio = :idpg )"; $res_abilita = $this->db->doQuery($query_abilita, array(":idpg" => $pgid), False); $classi = array("civile" => array(), "militare" => array()); $abilita = array("civile" => array(), "militare" => array()); if (isset($res_classi) && count($res_classi) > 0) foreach ($res_classi as $cl) $classi[$cl["tipo_classe"]][] = $cl; $crafting_chimico = False; $crafting_programmazione = False; $crafting_ingegneria = False; $abilita_notizie = array_keys(NewsManager::$MAPPA_PAGINA_ABILITA); if (isset($res_abilita) && count($res_abilita) > 0) { foreach ($res_abilita as $ab) { $abilita[$ab["tipo_abilita"]][] = $ab; if ($ab["id_abilita"] == $ABILITA_CRAFTING["chimico"]) { $crafting_chimico = True; $pg_data["permessi"][] = $GRANT_VISUALIZZA_CRAFT_CHIMICO; } if ($ab["id_abilita"] == $ABILITA_CRAFTING["programmazione"]) { $crafting_programmazione = True; $pg_data["permessi"][] = $GRANT_VISUALIZZA_CRAFT_PROGRAM; $pg_data["max_programmi_netrunner"] = 1; } if ($ab["id_abilita"] == $ABILITA_CRAFTING["programmazione_avanzata"]) $pg_data["max_programmi_netrunner"] = 2; if ($ab["id_abilita"] == $ABILITA_CRAFTING["programmazione_totale"]) $pg_data["max_programmi_netrunner"] = 4; if (in_array($ab["id_abilita"], $ABILITA_CRAFTING["ingegneria"])) { $crafting_ingegneria = True; if (!array_search($GRANT_VISUALIZZA_CRAFT_TECNICO, $pg_data["permessi"])) $pg_data["permessi"][] = $GRANT_VISUALIZZA_CRAFT_TECNICO; if ($ab["id_abilita"] == $CRAFTING_ARMI) $pg_data["permessi"][] = $GRANT_CRAFTA_ARMI; else if ($ab["id_abilita"] == $CRAFTING_GADGET_SHIELD) $pg_data["permessi"][] = $GRANT_CRAFTA_GADGET_SHIELD; else if ($ab["id_abilita"] == $CRAFTING_PROTESI) $pg_data["permessi"][] = $GRANT_CRAFTA_PROTESI; else if ($ab["id_abilita"] == $CRAFTING_SCUDI_ESOSCHELE) $pg_data["permessi"][] = $GRANT_CRAFTA_SCUDI_ESOSCHELE; } if (isset($this->idev_in_corso) && in_array($ab["id_abilita"], $abilita_notizie) && !array_search($GRANT_VISUALIZZA_NOTIZIE, $pg_data["permessi"])) { $pg_data["permessi"][] = $GRANT_VISUALIZZA_NOTIZIE; $pg_data["permessi"][] = $GRANT_RECUPERA_NOTIZIE; } } } if (isset($this->idev_in_corso)) $pg_data["permessi"][] = $GRANT_VISUALIZZA_MERCATO; $px_spesi = 0; $pc_spesi = count($classi["militare"]) + count($abilita["militare"]); if (isset($abilita["civile"]) && count($abilita["civile"]) > 0) { for ($i = 0; $i < count($classi["civile"]); $i++) $px_spesi += $MAPPA_COSTO_CLASSI_CIVILI[$i]; foreach ($abilita["civile"] as $ac) $px_spesi += $ac["costo_abilita"]; } $px_risparmiati = $pg_data["px_personaggio"] - $px_spesi; $pc_risparmiati = $pg_data["pc_personaggio"] - $pc_spesi; //recupero le opzioni $query_opz = "SELECT phoa.*, ab.nome_abilita FROM personaggi_has_opzioni_abilita AS phoa JOIN abilita AS ab ON ab.id_abilita = phoa.abilita_id_abilita WHERE personaggi_id_personaggio = :pgid"; $result_opz = $this->db->doQuery($query_opz, array(":pgid" => $pgid), False); $opzioni = array(); if (isset($result_opz) && count($result_opz) > 0) foreach ($result_opz as $r) $opzioni[$r["abilita_id_abilita"]] = ["nome_abilita" => $r["nome_abilita"], "opzione" => $r["opzioni_abilita_opzione"]]; $query_ricette = "SELECT COUNT(id_ricetta) as num_ricette FROM ricette WHERE personaggi_id_personaggio = :pgid"; $res_ricette = $this->db->doQuery($query_ricette, [":pgid" => $pgid], False); $pg_data["num_ricette"] = (int) $res_ricette[0]["num_ricette"]; $pg_data["pf_personaggio"] = $this->calcolaPF($PF_INIZIALI, $res_abilita); $pg_data["shield_personaggio"] = $this->calcolaShield($pg_data["scudo_base_personaggio"], $res_abilita); $pg_data["mente_personaggio"] = $this->calcolaDifesaMentale($pg_data["mente_base_personaggio"], $res_abilita); $pg_data["classi"] = $classi; $pg_data["abilita"] = $abilita; $pg_data["px_spesi"] = $px_spesi; $pg_data["px_risparmiati"] = $px_risparmiati; $pg_data["pc_spesi"] = $pc_spesi; $pg_data["pc_risparmiati"] = $pc_risparmiati; $pg_data["crafting_chimico"] = $crafting_chimico; $pg_data["crafting_programmazione"] = $crafting_programmazione; $pg_data["crafting_ingegneria"] = $crafting_ingegneria; $pg_data["opzioni"] = $opzioni; $permessi_giocatore = $this->session->permessi_giocatore; Utils::rimuoviPiuElementiDaArray($permessi_giocatore, $this->session->pg_loggato["permessi"]); $this->session->permessi_giocatore = array_merge($permessi_giocatore, $pg_data["permessi"]); $this->session->pg_loggato = $pg_data; return "{\"status\": \"ok\",\"result\": " . json_encode($pg_data) . "}"; } public function recuperaPropriPg() { UsersManager::controllaLogin($this->session); $where = "WHERE giocatori_email_giocatore = :id AND eliminato_personaggio = 0"; $params = array(":id" => $this->session->email_giocatore); if (UsersManager::controllaPermessi($this->session, ["rispondiPerPNG"])) { $where = "JOIN giocatori AS gi ON gi.email_giocatore = pg.giocatori_email_giocatore WHERE gi.ruoli_nome_ruolo IN ('admin','staff') AND pg.eliminato_personaggio = 0"; $params = []; } $query_pg = "SELECT id_personaggio, nome_personaggio, anno_nascita_personaggio FROM personaggi AS pg $where ORDER BY nome_personaggio ASC"; $result = $this->db->doQuery($query_pg, $params); $result = isset($result) ? $result : "[]"; return "{\"status\": \"ok\",\"result\": $result}"; } public function recuperaStorico($pgid) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $query = "SELECT CONCAT( gi.nome_giocatore, ' ', gi.cognome_giocatore ) AS nome_giocatore, st.data_azione, st.tipo_azione, st.tabella_azione, st.campo_azione, st.valore_nuovo_azione, st.valore_vecchio_azione, st.note_azione FROM storico_azioni AS st JOIN giocatori AS gi ON gi.email_giocatore = st.giocatori_email_giocatore WHERE st.id_personaggio_azione = :idpg ORDER BY st.data_azione DESC, st.valore_nuovo_azione DESC, st.valore_vecchio_azione DESC"; $result = $this->db->doQuery($query, array(":idpg" => $pgid)); $result = isset($result) ? $result : "[]"; return "{\"status\": \"ok\",\"result\": $result}"; } public function recuperaOpzioniAbilita() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $query = "SELECT * FROM opzioni_abilita"; $result = $this->db->doQuery($query, array(), False); $ret = array(); foreach ($result as $r) { if (!isset($ret[$r["abilita_id_abilita"]])) $ret[$r["abilita_id_abilita"]] = []; $ret[$r["abilita_id_abilita"]][] = $r["opzione"]; } return "{\"status\": \"ok\",\"result\": " . json_encode($ret) . "}"; } public function recuperaNoteCartellino($pgid) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $query = "SELECT note_cartellino_personaggio FROM personaggi WHERE id_personaggio = :pgid"; $result = $this->db->doQuery($query, [":pgid" => $pgid], False); $note = $result[0]["note_cartellino_personaggio"]; $output = [ "status" => "ok", "result" => !isset($note) ? "" : $note ]; return json_encode($output); } public function recuperaCredito($pgid) { $sql_check = "SELECT COALESCE( SUM( COALESCE( u.importo, 0 ) ), 0 ) as credito FROM ( SELECT SUM( COALESCE( importo_transazione, 0 ) ) as importo, creditore_transazione as pg FROM transazioni_bit GROUP BY creditore_transazione UNION ALL SELECT ( SUM( COALESCE( importo_transazione, 0 ) ) * -1 ) as importo, debitore_transazione as pg FROM transazioni_bit GROUP BY debitore_transazione ) as u WHERE pg = :idpg"; $ris_check = $this->db->doQuery($sql_check, [":idpg" => $pgid], False); $credito = isset($ris_check) ? (int) $ris_check[0]["credito"] : 0; return $credito; } } <file_sep>/client/app/scripts/controllers/PgViewerManager.js var PgViewerManager = function () { return { init: function () { window.controllo_permessi_autorizzato = false; this.user_info = JSON.parse(window.localStorage.getItem('user')); this.faiLoginPG(); this.recuperaStoricoAzioni(); this.setListeners(); }, mostraTextAreaBG: function () { $("#avviso_bg").hide(); $("#aggiungi_bg").hide(); $("#background").hide(); $("#background_form").show(); $("#invia_bg").unbind("click"); $("#invia_bg").click(this.inviaModifichePG.bind(this, "background_personaggio", $("#testo_background"))); $("#annulla_bg").unbind("click"); $("#annulla_bg").click(this.impostaBoxBackground.bind(this)); Utils.setSubmitBtn(); }, mostraTextAreaNoteMaster: function () { $("#avviso_note_master").hide(); $("#aggiungi_note_master").hide(); $("#note_master").hide(); $("#note_master_form").show(); $("#invia_note_master").unbind("click"); $("#invia_note_master") .click(this.inviaModifichePG.bind(this, "note_master_personaggio", $("#testo_note_master"))); $("#annulla_note_master").unbind("click"); $("#annulla_note_master").click(this.impostaBoxNoteMaster.bind(this)); Utils.setSubmitBtn(); }, mostraTextAreaNoteCartellino: function () { $("#avviso_note_cartellino").hide(); $("#aggiungi_note_cartellino").hide(); $("#note_cartellino").hide(); $("#note_cartellino_form").show(); $("#invia_note_cartellino").unbind("click"); $("#invia_note_cartellino") .click(this.inviaModifichePG.bind(this, "note_cartellino_personaggio", $("#testo_note_cartellino"))); $("#annulla_note_cartellino").unbind("click"); $("#annulla_note_cartellino").click(this.impostaNoteCartellino.bind(this)); Utils.setSubmitBtn(); }, classeIsPrerequisito: function (id_cl, el) { return el.prerequisito_classe !== null && parseInt(el.prerequisito_classe, 10) === id_cl; }, abilitaIsPrerequisito: function (id_ab, lista_ab, ids) { id_ab = parseInt(id_ab, 10); ids = typeof ids === "undefined" ? [] : ids; var new_ab = [], id_cl = parseInt(this.pg_info.abilita.civile.concat(this.pg_info.abilita.militare) .filter(function (el) { return parseInt(el.id_abilita, 10) === id_ab; })[0].classi_id_classe, 10), n_sportivo = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_SPORTIVO; }).length, n_guar_base = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_GUARDIANO_BASE; }).length, n_guar_avan = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_GUARDIANO_AVANZATO; }).length, n_assa_base = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_ASSALTATORE_BASE; }).length, n_assa_avan = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_ASSALTATORE_AVANZATO; }).length, n_supp_base = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_SUPPORTO_BASE; }).length, n_supp_avan = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_SUPPORTO_AVANZATO; }).length, n_guas_base = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_GUASTATORE_BASE; }).length, n_guas_avan = lista_ab.filter(function (el) { return el.classi_id_classe === Constants.ID_CLASSE_GUASTATORE_AVANZATO; }).length, vera_lista = lista_ab.filter(function (el) { return el.prerequisito_abilita !== null; }); for (var v in vera_lista) { if (typeof vera_lista[v].id_abilita === "undefined") continue; var ab = vera_lista[v], pre = parseInt(ab.prerequisito_abilita, 10), ab_cl = parseInt(ab.classi_id_classe, 10); if ( pre === id_ab || pre === Constants.PREREQUISITO_TUTTE_ABILITA && id_cl === ab_cl || ( pre === Constants.PREREQUISITO_F_TERRA_T_SCELTO && ( id_ab === Constants.ID_ABILITA_F_TERRA || id_ab === Constants.ID_ABILITA_T_SCELTO ) ) || ( pre === Constants.PREREQUISITO_SMUOVER_MP_RESET && ( id_ab === Constants.ID_ABILITA_SMUOVERE || id_ab === Constants.ID_ABILITA_MEDPACK_RESET ) ) || pre === Constants.PREREQUISITO_4_SPORTIVO && n_sportivo - 1 < 4 || pre === Constants.PREREQUISITO_5_SUPPORTO_BASE && n_supp_base - 1 < 5 || pre === Constants.PREREQUISITO_3_ASSALTATA_BASE && n_assa_base - 1 < 3 || pre === Constants.PREREQUISITO_3_ASSALTATA_AVAN && n_assa_avan - 1 < 3 || pre === Constants.PREREQUISITO_3_GUASTATOR_BASE && n_guas_base - 1 < 3 || pre === Constants.PREREQUISITO_3_GUASTATO_AVAN && n_guas_avan - 1 < 3 || pre === Constants.PREREQUISITO_15_GUARDIAN_BASE && n_guar_base - 1 < 15 || pre === Constants.PREREQUISITO_5_GUARDIANO_BAAV && n_guar_base + n_guar_avan - 1 < 5 || pre === Constants.PREREQUISITO_4_ASSALTATO_BASE && n_assa_base - 1 < 4 || pre === Constants.PREREQUISITO_7_SUPPORTO_BASE && n_supp_base - 1 < 4 || pre === Constants.PREREQUISITO_15_GUARDIAN_AVAN && n_guar_avan - 1 < 15 || pre === Constants.PREREQUISITO_15_ASSALTAT_BASE && n_assa_base - 1 < 15 || pre === Constants.PREREQUISITO_15_ASSALTAT_AVAN && n_assa_avan - 1 < 15 || pre === Constants.PREREQUISITO_15_SUPPORTO_BASE && n_supp_base - 1 < 15 || pre === Constants.PREREQUISITO_15_SUPPORTO_AVAN && n_supp_avan - 1 < 15 || pre === Constants.PREREQUISITO_15_GUASTATO_BASE && n_guas_base - 1 < 15 || pre === Constants.PREREQUISITO_15_GUASTATO_AVAN && n_guas_avan - 1 < 15 ) { new_ab.push(ab.id_abilita); Utils.rimuoviElemDaArrayMultidimensione(lista_ab, "id_abilita", ab.id_abilita); } } if (new_ab.length > 0) { for (var na in new_ab) if (typeof new_ab[na] !== "function") ids = this.abilitaIsPrerequisito.call(this, new_ab[na], lista_ab, ids); } return new_ab.concat(ids); }, eliminazioneConfermata: function (cosa, id) { var url = "", data = {}; if (cosa === "classe") { url = Constants.API_DEL_CLASSE_PG; data = { pg_id: this.pg_info.id_personaggio, id_classe: id }; } else if (cosa === "abilita") { url = Constants.API_DEL_ABILITA_PG; data = { pg_id: this.pg_info.id_personaggio, id_abilita: id }; } Utils.requestData( url, "POST", data, "Elemento eliminato con successo.", null, Utils.reloadPage ); }, rimuoviClasse: function (e) { var id_classe = $(e.currentTarget).attr("data-id"), t_classi = $("#info_professioni") .find(e.currentTarget).length > 0 ? this.pg_info.classi.civile : this.pg_info.classi.militare, t_abilita = $("#lista_abilita_civili") .find(e.currentTarget).length > 0 ? this.pg_info.abilita.civile : this.pg_info.abilita.militare, classi = t_classi.filter(this.classeIsPrerequisito.bind(this, id_classe)), classi_id = classi.map(function (el) { return el.id_classe; }).concat([id_classe]), classi_nomi = classi.map(function (el) { return el.nome_classe; }), classi_nomi = classi_nomi.length > 0 ? classi_nomi : ["Nessuna"], abilita = t_abilita.filter(function (el) { return classi_id.indexOf(el.classi_id_classe) !== -1; }), abilita = abilita.map(function (el) { return el.nome_abilita; }), abilita = abilita.length > 0 ? abilita : ["Nessuna"], lista_cl = "<ul><li>" + classi_nomi.join("</li><li>") + "</li></ul>", lista_ab = "<ul><li>" + abilita.join("</li><li>") + "</li></ul>", testo = "Cancellando questa classe verranno eliminate anche le seguenti classi:" + lista_cl + "E anche le seguenti abilit&agrave;:" + lista_ab + "Sicuro di voler procedere?"; Utils.showConfirm(testo, this.eliminazioneConfermata.bind(this, "classe", id_classe)); }, rimuoviAbilita: function (e) { var id_abilita = $(e.currentTarget).attr("data-id"), t_abilita = $("#lista_abilita_civili") .find(e.currentTarget).length > 0 ? this.pg_info.abilita.civile : this.pg_info.abilita.militare, ids = this.abilitaIsPrerequisito.call(this, id_abilita, t_abilita.concat()), abilita = t_abilita.filter(function (el) { return ids.indexOf(el.id_abilita) !== -1; }), abilita = abilita.map(function (el) { return el.nome_abilita; }), abilita = abilita.length > 0 ? abilita : ["Nessuna"], lista = "<ul><li>" + abilita.join("</li><li>") + "</li></ul>"; Utils.showConfirm("Cancellando questa abilit&agrave; anche le seguenti verranno eliminate:" + lista + "Sicuro di voler procedere?", this.eliminazioneConfermata.bind(this, "abilita", id_abilita)); }, expandRow: function (e) { var t = $(e.currentTarget); t.closest("tr").next().toggle(); }, impostaBoxBackground: function () { $("#background_form").hide(); $("#background").show(); if (this.pg_info.background_personaggio !== null) { $("#avviso_bg").remove(); $("#background").html(decodeURIComponent(this.pg_info.background_personaggio)); $("#testo_background") .val(Utils.unStripHMTLTag(decodeURIComponent(this.pg_info.background_personaggio)) .replace(/<br>/g, "\r")); if (Utils.controllaPermessiUtente(this.user_info, ["modificaPG_background_personaggio_altri"]) || (this.pg_nato_in_olocausto && !this.pg_info.motivazioni)) { $("#aggiungi_bg").show(); $("#aggiungi_bg").removeClass("inizialmente-nascosto"); } else $("#aggiungi_bg").hide(); } else { $("#aggiungi_bg").show(); $("#aggiungi_bg").removeClass("inizialmente-nascosto"); $("#avviso_bg").show(); $("#background").remove(); } }, impostaBoxNoteMaster: function () { if (Utils.controllaPermessiUtente(this.user_info, ["recuperaNoteMaster_altri", "recuperaNoteMaster_proprio"])) { $("#recuperaNoteMaster").show(); $("#avviso_note_master").show(); $("#aggiungi_note_master").show(); $("#note_master").show(); $("#note_master_form").hide(); if (this.pg_info.note_master_personaggio !== null) { $("#avviso_note_master").remove(); $("#note_master").html(decodeURIComponent(this.pg_info.note_master_personaggio)); $("#testo_note_master") .val(Utils.unStripHMTLTag(decodeURIComponent(this.pg_info.note_master_personaggio)) .replace(/<br>/g, "\r")); $("#aggiungi_note_master").show(); } else { $("#avviso_note_master").show(); $("#note_master").remove(); } } }, impostaNoteCartellino: function (data) { if (typeof data.result !== "undefined") this.note_cartellino = data.result || null; $("#recuperaNoteCartellino").show(); $("#avviso_note_cartellino").show(); $("#aggiungi_note_cartellino").show(); $("#note_cartellino").show(); $("#note_cartellino_form").hide(); if (this.note_cartellino !== null) { $("#avviso_note_cartellino").remove(); $("#note_cartellino").html(decodeURIComponent(this.note_cartellino)); $("#testo_note_cartellino") .val(Utils.unStripHMTLTag(decodeURIComponent(this.note_cartellino)) .replace(/<br>/g, "\r")); $("#aggiungi_note_cartellino").show(); } else { $("#avviso_note_cartellino").show(); $("#note_cartellino").remove(); } }, impostaDefaultPG: function () { var data = { modifiche: { default_pg_giocatore: this.pg_info.id_personaggio }, id: this.user_info.email_giocatore }; this.user_info.pg_da_loggare = this.pg_info.id_personaggio; window.localStorage.setItem("user", JSON.stringify(this.user_info)); Utils.requestData( Constants.API_POST_MOD_GIOCATORE, "POST", data, "Operazione eseguita con successo.", null, Utils.reloadPage ); }, rimuoviDefaultPG: function () { delete this.user_info.pg_da_loggare; window.localStorage.setItem("user", JSON.stringify(this.user_info)); Utils.requestData( Constants.API_POST_MOD_GIOCATORE, "POST", { modifiche: { default_pg_giocatore: "NULL" }, id: this.user_info.email_giocatore }, "Operazione eseguita con successo.", null, Utils.reloadPage ); }, controllaPGDefault: function () { if (typeof this.user_info.event_id !== "undefined") { $("#imposta_default_pg_giocatore").remove(); $("#rimuovi_default_pg_giocatore").remove(); } else if (typeof this.user_info.event_id === "undefined" && this.pg_info.id_personaggio == this.user_info.pg_da_loggare) $("#imposta_default_pg_giocatore").remove(); else $("#rimuovi_default_pg_giocatore").remove(); }, impostaPulsanteModifica: function () { $(".mostraModalEditPG").attr("data-id_personaggio", this.pg_info.id_personaggio); $(".mostraModalEditPG").attr("data-anno_nascita_personaggio", this.pg_info.anno_nascita_personaggio); $(".mostraModalEditPG").attr("data-contattabile_personaggio", this.pg_info.contattabile_personaggio); $(".mostraModalEditPG").attr("data-motivazioni_olocausto_inserite_personaggio", this.pg_info.motivazioni); $(".mostraModalEditPG").attr("data-nome_personaggio", this.pg_info.nome_personaggio); $(".mostraModalEditPG").attr("data-giocatori_email_giocatore", this.pg_info.giocatori_email_giocatore); }, mostraDati: function () { var bin_button = " <button type=\"button\" " + "class=\"btn btn-xs btn-default inizialmente-nascosto rimuoviClassePG\" " + "data-toggle=\"tooltip\" " + "data-placement=\"top\" " + "title=\"Elimina\" " + "data-id=\"{1}\"><span class=\"fa fa-trash-o\"></span></button>", professioni = this.pg_info.classi.civile.reduce(function (pre, curr) { return (pre ? pre + "<br>" : "") + curr.nome_classe + bin_button.replace("{1}", curr.id_classe) }, ""), cl_militari = this.pg_info.classi.militare.reduce(function (pre, curr) { return (pre ? pre + "<br>" : "") + curr.nome_classe + bin_button.replace("{1}", curr.id_classe) }, ""), px_percento = parseInt((parseInt(this.pg_info.px_risparmiati, 10) / this.pg_info.px_personaggio) * 100, 10), pc_percento = parseInt((parseInt(this.pg_info.pc_risparmiati, 10) / this.pg_info.pc_personaggio) * 100, 10); $("#info_giocatore").html(this.pg_info.nome_giocatore_completo); $("#info_id").html(this.pg_info.id_personaggio); $("#info_nome").html(this.pg_info.nome_personaggio); $("#info_data").html(this.pg_info.data_creazione_personaggio); $("#info_nascita").html(this.pg_info.anno_nascita_personaggio); $("#info_professioni").html(professioni); $("#info_militari").html(cl_militari); $("#info_pf").html(this.pg_info.pf_personaggio); $("#info_dm").html(this.pg_info.mente_personaggio); $("#info_ps").html(this.pg_info.shield_personaggio); $("#info_credito").html(this.pg_info.credito_personaggio); $("#px_risparmiati").html(this.pg_info.px_risparmiati); $("#px_tot").html(this.pg_info.px_personaggio); $("#px_bar").css({ "width": px_percento + "%" }); $("#pc_risparmiati").html(this.pg_info.pc_risparmiati); $("#pc_tot").html(this.pg_info.pc_personaggio); $("#pc_bar").css({ "width": pc_percento + "%" }); if (this.user_info.permessi.indexOf("rimuoviAbilitaPG_altri") === -1 && this.user_info.permessi.indexOf("rimuoviAbilitaPG_proprio") === -1) { $("#lista_abilita_civili").find("tr > th:last-child").remove(); $("#lista_abilita_militari").find("tr > th:last-child").remove(); } $.each(this.pg_info.abilita.civile, function (i, val) { var azioni_abilita = $("<button type=\"button\" " + "class=\"btn btn-xs btn-default inizialmente-nascosto rimuoviAbilitaPG\" " + "data-toggle=\"tooltip\" " + "data-placement=\"top\" " + "title=\"Elimina\" " + "data-id=\"" + val.id_abilita + "\"><span class=\"fa fa-trash-o\"></span></button>"), tr = $("<tr></tr>"); tr.append("<td><span class=\"expand-bt\"><li class=\"fa fa-angle-down\"></li> " + val.nome_abilita + "</span></td>"); tr.append("<td>" + val.nome_classe + "</td>"); tr.append("<td>" + val.costo_abilita + "</td>"); $("<td class='inizialmente-nascosto rimuoviAbilitaPG'></td>").appendTo(tr).append(azioni_abilita); $("#lista_abilita_civili").find("tbody").append(tr); tr = $("<tr style=\"display:none;\"><td colspan=\"6\">" + val.descrizione_abilita + "</td></tr>"); $("#lista_abilita_civili").find("tbody").append(tr) azioni_abilita.click(this.rimuoviAbilita.bind(this)); }.bind(this)); $.each(this.pg_info.abilita.militare, function (i, val) { var azioni_abilita = $("<button type=\"button\" " + "class=\"btn btn-xs btn-default inizialmente-nascosto rimuoviAbilitaPG\" " + "data-toggle=\"tooltip\" " + "data-placement=\"top\" " + "title=\"Elimina\" " + "data-id=\"" + val.id_abilita + "\"><span class=\"fa fa-trash-o\"></span></button>"), tr = $("<tr></tr>"); tr.append("<td><span class=\"expand-bt\"><li class=\"fa fa-angle-down\"></li> " + val.nome_abilita + "</span></td>"); tr.append("<td>" + val.nome_classe + "</td>"); tr.append("<td>" + val.costo_abilita + "</td>"); tr.append("<td>" + val.distanza_abilita + "</td>"); tr.append("<td>" + val.effetto_abilita + "</td>"); $("<td class='inizialmente-nascosto rimuoviAbilitaPG'></td>").appendTo(tr).append(azioni_abilita); $("#lista_abilita_militari").find("tbody").append(tr); tr = $("<tr style=\"display:none;\"><td colspan=\"6\">" + val.descrizione_abilita + "</td></tr>"); $("#lista_abilita_militari").find("tbody").append(tr); azioni_abilita.click(this.rimuoviAbilita.bind(this)); }.bind(this)); if (this.pg_info.opzioni && Object.keys(this.pg_info.opzioni).length > 0) { for (var o in this.pg_info.opzioni) { var val = this.pg_info.opzioni[o], tr = $("<tr></tr>"); tr.append("<td>" + val.nome_abilita + "</td>"); tr.append("<td>" + val.opzione + "</td>"); $("#lista_opzioni_abilita").find("tbody").append(tr); } $("#sezione_opzioni_abilita").removeClass("inizialmente-nascosto").show(); } this.impostaBoxBackground(); this.impostaBoxNoteMaster(); $(".rimuoviClassePG").click(this.rimuoviClasse.bind(this)); $(".expand-bt").click(this.expandRow.bind(this)); setTimeout(function () { $("[data-toggle='tooltip']").tooltip(); Utils.setSubmitBtn(); window.controllo_permessi_autorizzato = true; AdminLTEManager.controllaPermessi(); AdminLTEManager.controllaPermessi(".sidebar-menu", true); }.bind(this), 100); }, creaSpecchietto: function () { var iframe = $($("#containerSpecchiettoPG").contents()), professioni = this.pg_info.classi.civile.reduce(function (pre, curr) { return (pre ? pre + "<br>" : "") + curr.nome_classe }, ""), cl_militari = this.pg_info.classi.militare.reduce(function (pre, curr) { return (pre ? pre + "<br>" : "") + curr.nome_classe }, ""); iframe.find("#specchietto_giocatore").html(this.pg_info.nome_giocatore_completo); iframe.find("#specchietto_id").html(this.pg_info.id_personaggio); iframe.find("#specchietto_nome").html(this.pg_info.nome_personaggio); iframe.find("#specchietto_pc").html(this.pg_info.pc_risparmiati + " / " + this.pg_info.pc_personaggio); iframe.find("#specchietto_px").html(this.pg_info.px_risparmiati + " / " + this.pg_info.px_personaggio); iframe.find("#specchietto_data").html(this.pg_info.data_creazione_personaggio); iframe.find("#specchietto_nascita").html(this.pg_info.anno_nascita_personaggio); iframe.find("#specchietto_professioni").html(professioni); iframe.find("#specchietto_militari").html(cl_militari); iframe.find("#specchietto_pf").html(this.pg_info.pf_personaggio); iframe.find("#specchietto_dm").html(this.pg_info.mente_personaggio); iframe.find("#specchietto_ps").html(this.pg_info.shield_personaggio); iframe.find("#specchietto_credito").html(this.pg_info.credito_personaggio); iframe.find("#note_pg").html(this.pg_info.note_cartellino); var classe = ""; $.each(this.pg_info.abilita.civile, function (i, val) { var tr = $("<tr></tr>"); if (classe != val.nome_classe) { tr = $("<tr class='nome_classe'><td colspan=\"2\">" + val.nome_classe + "</td></tr>"); iframe.find("#specchietto_abilita_civili").append(tr); classe = val.nome_classe; } tr = $("<tr></tr>"); tr.append("<td>" + val.nome_abilita + "</td>"); tr.append("<td>" + val.costo_abilita + " PX</td>"); iframe.find("#specchietto_abilita_civili").append(tr); var descrizione = val.descrizione_abilita; if (this.pg_info.opzioni[val.id_abilita]) { descrizione += "<br><br><b>Specializzazione:</b>" + this.pg_info.opzioni[val.id_abilita].opzione; } tr = $("<tr><td colspan=\"2\">" + descrizione + "</td></tr>"); iframe.find("#specchietto_abilita_civili").append(tr); }.bind(this)); classe = ""; $.each(this.pg_info.abilita.militare, function (i, val) { var tr = $("<tr></tr>"); if (classe != val.nome_classe) { tr = $("<tr class='nome_classe'><td colspan=\"4\">" + val.nome_classe + "</td></tr>"); iframe.find("#specchietto_abilita_militari").append(tr); classe = val.nome_classe; } tr = $("<tr></tr>"); tr.append("<td>" + val.nome_abilita + "</td>"); tr.append("<td>" + val.costo_abilita + " PC</td>"); tr.append("<td>" + val.distanza_abilita + "</td>"); tr.append("<td>" + val.effetto_abilita + "</td>"); iframe.find("#specchietto_abilita_militari").append(tr); var descrizione = val.descrizione_abilita; if (this.pg_info.opzioni[val.id_abilita]) { descrizione += "<br><br><b>Specializzazione: </b>" + this.pg_info.opzioni[val.id_abilita].opzione; } tr = $("<tr><td colspan=\"4\">" + descrizione + "</td></tr>"); iframe.find("#specchietto_abilita_militari").append(tr); }.bind(this)); }, mostraStorico: function () { $.each(this.storico, function () { var tr = $("<tr></tr>"), vecchio_val = decodeURIComponent(this.valore_vecchio_azione || "n.d."), nuovo_val = decodeURIComponent(this.valore_nuovo_azione || "n.d."), vecchio_td = $("<td></td>"), nuovo_td = $("<td></td>"); note = this.note_azione === null ? "" : this.note_azione; if (vecchio_val.length > 50) { var plus = $("<i class='fa fa-plus-circle'></i>"); plus.popover({ container: "body", placement: "left", trigger: Utils.isDeviceMobile() ? "click" : "hover", content: vecchio_val }); vecchio_td.text(vecchio_val.substr(0, 50) + "..."); vecchio_td.append(plus); } else vecchio_td.text(vecchio_val); if (nuovo_val.length > 50) { var plus = $("<i class='fa fa-plus-circle'></i>"); plus.popover({ container: "body", placement: "left", trigger: Utils.isDeviceMobile() ? "click" : "hover", content: nuovo_val }); nuovo_td.text(nuovo_val.substr(0, 50) + "..."); nuovo_td.append(plus); } else nuovo_td.text(nuovo_val); tr.append("<td>" + this.nome_giocatore + "</td>"); tr.append("<td>" + this.data_azione + "</td>"); tr.append("<td>" + this.tipo_azione + "</td>"); tr.append("<td>" + this.tabella_azione + "</td>"); tr.append("<td>" + this.campo_azione + "</td>"); tr.append(vecchio_td); tr.append(nuovo_td); tr.append("<td>" + note + "</td>"); $("#recuperaStorico").find("tbody").append(tr); }); $("#recuperaStorico").removeClass("inizialmente-nascosto"); $("#recuperaStorico").show(); }, modificaPuntiPG: function () { PointsManager.impostaModal({ pg_ids: [this.pg_info.id_personaggio], nome_personaggi: [this.pg_info.nome_personaggio], onSuccess: Utils.reloadPage }); }, modificaCreditoPG: function () { CreditManager.impostaModal({ pg_ids: [this.pg_info.id_personaggio], nome_personaggi: [this.pg_info.nome_personaggio], onSuccess: Utils.reloadPage, valore_min: 0 }); }, apriModalSpecchietto: function () { var pg_name = this.pg_info.nome_personaggio.toLowerCase().replaceAll(/\W/ig, "_"); $("#modal_specchietto_pg").modal({ drop: "static" }); var to_save = $("#containerSpecchiettoPG").contents().find("#specchiettoWrapper")[0]; html2canvas(to_save).then(function (canvas) { var img_specchietto = canvas.toDataURL("image/png"); img_specchietto = img_specchietto.replace(/^data:image\/png/, "data:application/octet-stream"); $("#btn_scarica_specchietto") .attr("download", "specchietto_" + pg_name + ".png") .attr("href", img_specchietto) .attr("disabled", false) .on("click", function () { $("#modal_specchietto_pg").modal("hide"); }); }); }, inviaModifichePG: function (campo, elemento, e) { var data = { pgid: this.pg_info.id_personaggio, modifiche: {} }; data.modifiche[campo] = encodeURIComponent(Utils.stripHMTLTag(elemento.val()).replace(/\n/g, "<br>")); if (campo === "background_personaggio" && this.pg_nato_in_olocausto && !this.pg_info.motivazioni) data.modifiche.motivazioni_olocausto_inserite_personaggio = 1; Utils.requestData( Constants.API_POST_EDIT_PG, "POST", data, "Il campo &egrave; stato aggiornato con successo.", null, Utils.reloadPage ); }, inviaModificheRicetta: function (id_ricetta) { var note = encodeURIComponent(Utils.stripHMTLTag($("#modal_modifica_ricetta") .find("#note_pg_ricetta") .val()).replace(/\n/g, "<br>")), dati = { id: id_ricetta, modifiche: { note_pg_ricetta: note } }; if ($("#new_nome_ricetta").is(":visible") && $("#new_nome_ricetta").val() !== "") dati.modifiche.nome_ricetta = $("#new_nome_ricetta").val(); Utils.requestData( Constants.API_EDIT_RICETTA, "POST", dati, "Modifiche apportate con successo", null, this.recipes_grid.ajax.reload.bind(this, null, false) ); }, mostraModalRicetta: function (e) { var t = $(e.target), dati = this.recipes_grid.row(t.parents('tr')).data(), note = Utils.unStripHMTLTag(decodeURIComponent(dati.note_pg_ricetta)).replace(/<br>/g, "\r"), note = note === "null" ? "" : note, comps = "<li>" + dati.componenti_ricetta.split(";").join("</li><li>") + "</li>"; if (dati.tipo_ricetta === "Programmazione") $("#modal_modifica_ricetta") .find("#new_nome_ricetta") .parents(".form-group") .removeClass("inizialmente-nascosto"); $("#modal_modifica_ricetta").find("#nome_ricetta").text(dati.nome_ricetta); $("#modal_modifica_ricetta").find("#new_nome_ricetta").val(dati.nome_ricetta); $("#modal_modifica_ricetta").find("#lista_componenti").html(comps); $("#modal_modifica_ricetta").find("#note_ricetta").val(note); $("#modal_modifica_ricetta").find("#btn_invia_modifiche_ricetta").unbind("click"); $("#modal_modifica_ricetta") .find("#btn_invia_modifiche_ricetta") .click(this.inviaModificheRicetta.bind(this, dati.id_ricetta)); $("#modal_modifica_ricetta").modal({ drop: "static" }); }, setGridListeners: function () { AdminLTEManager.controllaPermessi(); $("td [data-toggle='popover']").popover("destroy"); $("td [data-toggle='popover']").popover(); $("[data-toggle='tooltip']").tooltip(); $("button.modifica-note").unbind("click", this.mostraModalRicetta.bind(this)); $("button.modifica-note").click(this.mostraModalRicetta.bind(this)); }, erroreDataTable: function (e, settings) { if (!settings.jqXHR.responseText) return false; var real_error = settings.jqXHR.responseText.replace(/^([\S\s]*?)\{"[\S\s]*/i, "$1"); real_error = real_error.replace("\n", "<br>"); Utils.showError(real_error); }, renderComps: function (data, type, row) { if (!data) return ""; var ret = data; if (row.tipo_ricetta === "Programmazione") ret = data.replace(/Z\=(\d);\s/g, "Z=$1<br>"); else ret = data.replace(/;/g, "<br>"); return ret; }, renderNote: function (data, type, row) { var denc_data = Utils.unStripHMTLTag(decodeURIComponent(data)); denc_data = denc_data === "null" ? "" : denc_data; return $.fn.dataTable.render.ellipsis(20, false, true, true)(denc_data, type, row); }, renderApprovato: function (data, type, row) { var ret = "In elaborazione...", data = parseInt(data); if (data === -1) ret = "Rifiutato"; else if (data === 1) ret = "Approvato"; return ret; }, creaPulsantiAzioni: function (data, type, row) { var pulsanti = ""; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default modifica-note ' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Modifica Note'><i class='fa fa-pencil'></i></button>"; return pulsanti; }, recuperaRicetteCrafting: function () { if (this.pg_info.num_ricette === 0) return false; var columns = []; columns.push({ title: "Data Creazione", data: "data_inserimento_it" }); columns.push({ title: "Nome Ricetta", data: "nome_ricetta" }); columns.push({ title: "Tipo", data: "tipo_ricetta" }); columns.push({ title: "Componenti", data: "componenti_ricetta", render: this.renderComps.bind(this) }); columns.push({ title: "Approvata", data: "approvata_ricetta", render: this.renderApprovato.bind(this) }); columns.push({ title: "Note", data: "note_pg_ricetta", render: this.renderNote.bind(this) }); columns.push({ title: "Azioni", render: this.creaPulsantiAzioni.bind(this) }); this.recipes_grid = $('#griglia_ricette') .on("error.dt", this.erroreDataTable.bind(this)) .on("draw.dt", this.setGridListeners.bind(this)) .DataTable({ language: Constants.DATA_TABLE_LANGUAGE, ajax: function (data, callback) { Utils.requestData( Constants.API_GET_RICETTE, "GET", $.extend(data, { filtro: null, pgid: window.localStorage.getItem("pg_da_loggare") }), callback ); }, columns: columns, //lengthMenu: [ 5, 10, 25, 50, 75, 100 ], order: [ [0, 'desc'] ] }); $("#griglia_ricette").parents(".row").removeClass("inizialmente-nascosto"); $("#griglia_ricette").parents(".row").show(); }, recuperaNoteCartellino: function () { if (Utils.controllaPermessiUtente(this.user_info, ["recuperaNoteCartellino_altri", "recuperaNoteCartellino_proprio"], false)) { var data = { pgid: this.pg_info.id_personaggio }; Utils.requestData( Constants.API_GET_NOTE_CARTELLINO_PG, "GET", data, this.impostaNoteCartellino.bind(this) ); } }, recuperaStoricoAzioni: function () { if (this.user_info.permessi.filter(function (el) { return el.indexOf("recuperaStorico") !== -1 }).length > 0) { var data = { pgid: window.localStorage.getItem("pg_da_loggare") }; Utils.requestData( Constants.API_GET_STORICO_PG, "GET", data, function (data) { this.storico = data.result; this.mostraStorico(); }.bind(this) ); } }, controllaMotivazioniOlocausto: function () { this.pg_info.anno_nascita_personaggio = parseInt(this.pg_info.anno_nascita_personaggio, 10); this.pg_info.motivazioni = this.pg_info.motivazioni === "1" ? true : false; this.pg_nato_in_olocausto = this.pg_info.anno_nascita_personaggio >= Constants.ANNO_INIZIO_OLOCAUSTO && this.pg_info.anno_nascita_personaggio <= Constants.ANNO_FINE_OLOCAUSTO; if (this.pg_nato_in_olocausto && !this.pg_info.motivazioni) Utils.showMessage("<NAME>,<br>" + "ci siamo accorti che il personaggio che stai visualizzando &egrave; nato durante l'<strong>Olocausto dell'Innocenza</strong>.<br>" + "Ci servirebbe che aggiungessi nel Background come lui/lei ha fatto a sopravvivere alla disgrazia.<br>" + "Vai nell'apposita sezione e clicca il pulsante 'Modifica Background'.<br>" + "Grazie, lo Staff!"); }, faiLoginPG: function () { var dati = { pgid: window.localStorage.getItem("pg_da_loggare") }; Utils.requestData( Constants.API_GET_PG_LOGIN, "GET", dati, function (data) { this.pg_info = data.result; var pg_no_bg = JSON.parse(JSON.stringify(this.pg_info)); delete pg_no_bg.background_personaggio; delete pg_no_bg.note_master_personaggio; window.localStorage.removeItem('logged_pg'); window.localStorage.setItem('logged_pg', JSON.stringify(pg_no_bg)); AdminLTEManager.mostraNomePersonaggio(this.pg_info.nome_personaggio); AdminLTEManager.controllaMessaggi(); this.controllaMotivazioniOlocausto(); this.mostraDati(); this.creaSpecchietto(); this.impostaPulsanteModifica(); this.controllaPGDefault(); this.recuperaRicetteCrafting(); this.recuperaNoteCartellino(); }.bind(this), null, null, window.history.back ); }, setListeners: function () { $("#mostra_form_bg").click(this.mostraTextAreaBG.bind(this)); $("#mostra_note_master").click(this.mostraTextAreaNoteMaster.bind(this)); $("#mostra_note_cartellino").click(this.mostraTextAreaNoteCartellino.bind(this)); $("#btn_aggiungiAbilitaAlPG").click(Utils.redirectTo.bind(this, Constants.ABILITY_SHOP_PAGE)); $("#btn_modificaPG_px_personaggio").click(this.modificaPuntiPG.bind(this)); $("#btn_modificaPG_credito_personaggio").click(this.modificaCreditoPG.bind(this)); $("#btn_scaricaSpecchiettoPG").click(this.apriModalSpecchietto.bind(this)); $("#imposta_default_pg_giocatore").click(this.impostaDefaultPG.bind(this)); $("#rimuovi_default_pg_giocatore").click(this.rimuoviDefaultPG.bind(this)); } } }(); $(function () { PgViewerManager.init(); });<file_sep>/client/app/scripts/models/PointsManager.js var PointsManager = function () { return { init: function () { //TODO: mettere pulsanti per aumentare e diminure il valore a causa di cel che non fanno inserire numeri negativi this.listeners_set = false; }, impostaModal: function (settings) { this.settings = { valore_max: Infinity, valore_min: -Infinity }; this.settings = $.extend(this.settings, settings); this.setListeners(); this.risettaValori(); this.impostaValori(); }, inviaRichiestaAssegna: function () { Utils.requestData( Constants.API_POST_EDIT_MOLTI_PG, "POST", { pg_ids: this.settings.pg_ids, modifiche: { pc_personaggio: $("#modal_assegna_punti").find("#offset_pc").val(), px_personaggio: $("#modal_assegna_punti").find("#offset_px").val() }, is_offset: true, note_azione: $("#modal_assegna_punti").find(".note-azione").val() }, "Punti modificati con successo.", null, this.settings.onSuccess ); }, impostaValori: function () { $("#modal_assegna_punti").find("#nome_personaggi").text(this.settings.nome_personaggi.join(", ")); $("#modal_assegna_punti").find(".note-azione").val(this.settings.note_azione); $("#modal_assegna_punti").modal({ drop: "static" }); }, risettaValori: function () { $("#modal_assegna_punti").find("#btn_assegna").attr("disabled", false).find("i").remove(); $("#modal_assegna_punti").find("#nome_personaggi").html(""); $("#modal_assegna_punti").find("#offset_pc").val(0); $("#modal_assegna_punti").find("#offset_px").val(0); }, setListeners: function () { if (this.listeners_set) return false; this.listeners_set = true; $("#modal_assegna_punti").find("#btn_assegna").unbind("click", this.inviaRichiestaAssegna.bind(this)); $("#modal_assegna_punti").find("#btn_assegna").click(this.inviaRichiestaAssegna.bind(this)); if (Utils.isDeviceMobile()) { $("#modal_assegna_punti").find(".pulsantiera-mobile").removeClass("inizialmente-nascosto"); new PulsantieraNumerica({ target: $("#modal_assegna_punti").find("#offset_pc"), pulsantiera: $("#modal_assegna_punti").find("#pulsanti_pc"), valore_max: this.settings.valore_max, valore_min: this.settings.valore_min }); new PulsantieraNumerica({ target: $("#modal_assegna_punti").find("#offset_px"), pulsantiera: $("#modal_assegna_punti").find("#pulsanti_px"), valore_max: this.settings.valore_max, valore_min: this.settings.valore_min }); } } } }(); $(function () { PointsManager.init(); });<file_sep>/docker-node-grunt/wait_and_install.sh #!/bin/sh while [ ! -f /app/bower.json ] do echo "Waiting for bower.json" sleep 1 done<file_sep>/server/src/utils/password.php <?php echo sha1("Reboot1234");<file_sep>/client/app/scripts/controllers/StatisticsManager.js /** * Created by Miroku on 11/10/2018. */ var StatisticsManager = StatisticsManager || function () { var color_index = 0; return { getColor: function () { var i = color_index++; if ( i < Constants.CHART_COLORS.length ) return Constants.CHART_COLORS[ i ]; else return Utils.dynamicColor(); }, disegnaStatisticheClassi: function disegnaStatisticheClassi( data ) { var data = data.data, military_data = data.filter( function ( el ) { return el.tipo_classe === "militare"; } ), military_labels = military_data.map( function ( el ) { return el.nome_classe; } ), military_colors = military_data.map( function ( el ) { return this.getColor(); }.bind( this ) ), military_data = military_data.map( function ( el ) { return parseInt( el.QTY, 10 ); } ), civilian_data = data.filter( function ( el ) { return el.tipo_classe === "civile"; } ), civilian_labels = civilian_data.map( function ( el ) { return el.nome_classe; } ), civilian_colors = civilian_data.map( function ( el ) { return this.getColor(); }.bind( this ) ), civilian_data = civilian_data.map( function ( el ) { return parseInt( el.QTY, 10 ); } ), military_bg_rgba = military_colors.map( function ( c ) { return Utils.hexToRGBa( c, 0.5 ) } ), military_border_rgba = military_colors.map( function ( c ) { return Utils.hexToRGBa( c, 1 ) } ), civilian_bg_rgba = civilian_colors.map( function ( c ) { return Utils.hexToRGBa( c, 0.5 ) } ), civilian_border_rgba = civilian_colors.map( function ( c ) { return Utils.hexToRGBa( c, 1 ) } ); this.military_classes_pie = new Chart( this.military_classes_pie_ctx, { type : 'pie', data : { datasets: [ { data : military_data, backgroundColor: military_bg_rgba, borderColor : military_border_rgba, borderWidth : 1 } ], labels : military_labels }, options: { responsive: true } } ); this.civilian_classes_pie = new Chart( this.civilian_classes_pie_ctx, { type : 'pie', data : { datasets: [ { data : civilian_data, backgroundColor: civilian_bg_rgba, borderColor : civilian_border_rgba, borderWidth : 1 } ], labels : civilian_labels }, options: { responsive: true } } ); }, recuperaStatisticheClassi: function recuperaStatisticheClassi() { Utils.requestData( Constants.API_GET_STATS_CLASSI, "GET", {}, this.disegnaStatisticheClassi.bind( this ), "recuperaStatisticheClassi fallito" ); }, disegnaStatisticheAbilita: function disegnaStatisticheAbilita( data ) { var data = data.data, military_data = data.filter( function ( el ) { return el.tipo_abilita === "militare"; } ), military_labels = military_data.map( function ( el ) { return el.nome_abilita; } ), military_data = military_data.map( function ( el ) { return { y: parseInt( el.QTY, 10 ), x: el.nome_abilita }; } ), civilian_data = data.filter( function ( el ) { return el.tipo_abilita === "civile"; } ), civilian_labels = civilian_data.map( function ( el ) { return el.nome_abilita; } ), civilian_data = civilian_data.map( function ( el ) { return { y: parseInt( el.QTY, 10 ), x: el.nome_abilita }; } ), military_color = this.getColor(), civilian_color = this.getColor(); this.military_abilities_bars = new Chart( this.military_abilities_bars_ctx, { type : 'bar', data : { datasets: [ { data : military_data, label : "Quantità di PG con l'abilità", backgroundColor: Utils.hexToRGBa( military_color, 0.5 ), borderColor : Utils.hexToRGBa( military_color, 1 ), borderWidth : 1 } ], labels : military_labels }, options: { responsive : true, scaleShowValues: true, scales : { xAxes: [ { ticks: { autoSkip: false } } ] } } } ); this.civilian_abilities_bars = new Chart( this.civilian_abilities_bars_ctx, { type : 'bar', data : { datasets: [ { data : civilian_data, label : "Quantità di PG con l'abilità", backgroundColor: Utils.hexToRGBa( civilian_color, 0.5 ), borderColor : Utils.hexToRGBa( civilian_color, 1 ), borderWidth : 1 } ], labels : civilian_labels }, options: { responsive : true, scaleShowValues: true, scales : { xAxes: [ { ticks: { autoSkip: false } } ] } } } ); }, recuperaStatisticheAbilita: function recuperaStatisticheAbilita() { Utils.requestData( Constants.API_GET_STATS_ABILITA, "GET", {}, this.disegnaStatisticheAbilita.bind( this ), "recuperaStatisticheAbilita fallito" ); }, disegnaStatisticheAbilitaProfessionaliPerPg: function disegnaStatisticheAbilitaProfessionaliPerPg( d ) { var data = d.data, ability_data = data.map( function ( el ) { return { x: el.QTY + " da " + el.nome_classe, y: el.num_pgs }; } ), ability_labels = data.map( function ( el ) { return el.QTY + " da " + el.nome_classe; } ), color = this.getColor(); this.civilian_abilities_qty_bars = new Chart( this.civilian_abilities_qty_pg_bars_ctx, { type : 'bar', data : { datasets: [ { data : ability_data, label : "Quantità di PG con questo num di abilità", backgroundColor: Utils.hexToRGBa( color, 0.5 ), borderColor : Utils.hexToRGBa( color, 1 ), borderWidth : 1 } ], labels : ability_labels }, options: { responsive : true, scaleShowValues: true, scales : { xAxes: [ { ticks : { autoSkip: false }, display : true, scaleLabel: { display : true, labelString: 'Qta di abilità per classe' } } ], yAxes: [ { ticks : { beginAtZero : true, fixedStepSize: 1, autoSkip : false }, display : true, scaleLabel: { display : true, labelString: 'Numero giocatori che possiedono quel numero di abilità' } } ] } } } ); }, recuperaStatisticheAbilitaProfessionaliPerPg: function recuperaStatisticheAbilitaProfessionaliPerPg() { Utils.requestData( Constants.API_GET_STATS_ABILITA_PER_PROFESSIONE, "GET", {}, this.disegnaStatisticheAbilitaProfessionaliPerPg.bind( this ), "recuperaStatisticheAbilitaProfessionaliPerPg fallito" ); }, disegnaStatisticheCrediti: function disegnaStatisticheCrediti( data ) { var data = data.data, labels = data.map( function ( el ) { return el.data_transazione_str; } ), line_data = data.map( function ( el ) { return { x: el.data_transazione_str, y: el.credito_personaggio }; } ), color = this.getColor(); this.credits_line = new Chart( this.credits_line_ctx, { type : 'line', data : { datasets: [ { data : line_data, backgroundColor: Utils.hexToRGBa( color, 0.5 ), borderColor : Utils.hexToRGBa( color, 1 ), borderWidth : 1, label : "Bit in gioco", type : 'line', pointRadius : 5, fill : false, lineTension : 0 } ], labels : labels }, options: { responsive : true, scaleShowValues: true, scales : { xAxes: [ { ticks: { autoSkip: false } } ] } } } ); }, recuperaStatisticheCrediti: function recuperaStatisticheCrediti() { Utils.requestData( Constants.API_GET_STATS_CREDITI, "GET", {}, this.disegnaStatisticheCrediti.bind( this ), "recuperaStatisticheCrediti fallito" ); }, disegnaStatistichePG: function disegnaStatistichePG( data ) { var data = data.data, pies = { pf : [], ps : [], mente: [] }, labels = { pf : [], ps : [], mente: [] }, color_pf = this.getColor(), color_ps = this.getColor(), color_pm = this.getColor(); for ( var d in data ) for ( var e in data[ d ] ) { pies[ d ].push( parseInt( data[ d ][ e ], 10 ) ); labels[ d ].push( parseInt( e, 10 ) ); } this.pf_bars = new Chart( this.pf_pie_ctx, { type : 'bar', data : { datasets: [ { data : pies.pf, backgroundColor: Utils.hexToRGBa( color_pf, 0.5 ), borderColor : Utils.hexToRGBa( color_pf, 1 ), borderWidth : 1, label : "Numero Personaggi" } ], labels : labels.pf }, options: { responsive: true, scales : { yAxes: [ { display : true, scaleLabel: { display : true, labelString: 'Numero Personaggi' } } ], xAxes: [ { display : true, scaleLabel: { display : true, labelString: 'Punti Ferita' } } ] } } } ); this.ps_bars = new Chart( this.ps_pie_ctx, { type : 'bar', data : { datasets: [ { data : pies.ps, backgroundColor: Utils.hexToRGBa( color_ps, 0.5 ), borderColor : Utils.hexToRGBa( color_ps, 1 ), borderWidth : 1, label : "Numero Personaggi" } ], labels : labels.ps }, options: { responsive: true, scales : { yAxes: [ { display : true, scaleLabel: { display : true, labelString: 'Numero Personaggi' } } ], xAxes: [ { display : true, scaleLabel: { display : true, labelString: 'Punti Shield' } } ] } } } ); this.mente_bars = new Chart( this.mente_pie_ctx, { type : 'bar', data : { datasets: [ { data : pies.mente, backgroundColor: Utils.hexToRGBa( color_pm, 0.5 ), borderColor : Utils.hexToRGBa( color_pm, 1 ), label : "Numero Personaggi", borderWidth : 1 } ], labels : labels.mente }, options: { responsive: true, scales : { yAxes: [ { display : true, scaleLabel: { display : true, labelString: 'Numero Personaggi' } } ], xAxes: [ { display : true, scaleLabel: { display : true, labelString: 'Punti Difesa Mentale' } } ] } } } ); }, recuperaStatistichePG: function recuperaStatistichePG() { Utils.requestData( Constants.API_GET_STATS_PG, "GET", {}, this.disegnaStatistichePG.bind( this ), "recuperaStatistichePG fallito" ); }, disegnaStatistichePunteggi: function disegnaStatistichePunteggi( data ) { // this.pc_tot_pie_ctx = $( "#pc_tot_pie" )[ 0 ].getContext( "2d" ); // this.px_tot_pie_ctx = $( "#px_tot_pie" )[ 0 ].getContext( "2d" ); // this.pc_spent_pie_ctx = $( "#pc_spent_pie" )[ 0 ].getContext( "2d" ); // this.px_spent_pie_ctx = $( "#px_spent_pie" )[ 0 ].getContext( "2d" ); // this.pc_free_pie_ctx = $( "#pc_free_pie" )[ 0 ].getContext( "2d" ); // this.px_free_pie_ctx = $( "#px_free_pie" )[ 0 ].getContext( "2d" ); }, recuperaStatistichePunteggi: function recuperaStatistichePunteggi() { Utils.requestData( Constants.API_GET_STATS_PUNTEGGI, "GET", {}, this.disegnaStatistichePunteggi.bind( this ), "recuperaStatistichePunteggi fallito" ); }, disegnaStatisticheQtaRavShop: function disegnaStatisticheQtaRavShop( data ) { var data = data.data, bar_labels = data.map( function ( el ) { return el.data_transazione_str; } ), bar_data = data.map( function ( el ) { return el.num_transazioni; } ), color = this.getColor(); this.ravshop_transaction_bar = new Chart( this.ravshop_qty_bar_ctx, { type : 'bar', data : { datasets: [ { data : bar_data, backgroundColor: Utils.hexToRGBa( color, 0.5 ), borderColor : Utils.hexToRGBa( color, 1 ), borderWidth : 1, label : "Numero Acquisti" } ], labels : bar_labels }, options: { responsive: true } } ); }, recuperaStatisticheQtaRavShop: function recuperaStatisticheQtaRavShop() { Utils.requestData( Constants.API_GET_STATS_RAVSHOP, "GET", {}, this.disegnaStatisticheQtaRavShop.bind( this ), "recuperaStatisticheQtaRavShop fallito" ); }, disegnaStatisticheAcquistiRavShop: function disegnaStatisticheAcquistiRavShop( data ) { var data = data.data, bar_labels = data.map( function ( el ) { return el.nome_componente; } ), bar_data = data.map( function ( el ) { return el.num_acquisti; } ), color = this.getColor(); this.ravshop_transaction_bar = new Chart( this.ravshop_popularity_bar_ctx, { type : 'bar', data : { datasets: [ { data : bar_data, backgroundColor: Utils.hexToRGBa( color, 0.5 ), borderColor : Utils.hexToRGBa( color, 1 ), borderWidth : 1, label : "Numero Acquisti" } ], labels : bar_labels }, options: { responsive : true, scaleShowValues: true, scales : { xAxes: [ { ticks: { autoSkip: false } } ] } } } ); }, recuperaStatisticheAcquistiRavShop: function recuperaStatisticheAcquistiRavShop() { Utils.requestData( Constants.API_GET_STATS_ACQUISTI_RAVSHOP, "GET", {}, this.disegnaStatisticheAcquistiRavShop.bind( this ), "recuperaStatisticheAcquistiRavShop fallito" ); }, disegnaStatisticheArmiStampate: function disegnaStatisticheArmiStampate( data ) { var data = data.data, bar_labels = data.map( function ( el ) { return el.dichiarazione; } ), bar_data = data.map( function ( el ) { return el.QTA; } ), color = this.getColor(); this.crafted_bar = new Chart( this.crafted_bar_ctx, { type : 'bar', data : { datasets: [ { data : bar_data, backgroundColor: Utils.hexToRGBa( color, 0.5 ), borderColor : Utils.hexToRGBa( color, 1 ), borderWidth : 1, label : "Quantità Craftate" } ], labels : bar_labels }, options: { responsive : true, scaleShowValues: true, scales : { xAxes: [ { ticks : { autoSkip: false }, display : true, scaleLabel: { display : true, labelString: 'Tipo di danno' } } ], yAxes: [ { ticks : { beginAtZero : true, fixedStepSize: 1, autoSkip : false }, display : true, scaleLabel: { display : true, labelString: 'Quantità craftate' } } ] } } } ); }, recuperaStatisticheArmiStampate: function recuperaStatisticheArmiStampate() { Utils.requestData( Constants.API_GET_STATS_ARMI, "GET", {}, this.disegnaStatisticheArmiStampate.bind( this ), "recuperaStatisticheArmiStampate fallito" ); }, loadCharts: function loadCharts() { this.recuperaStatisticheClassi(); this.recuperaStatisticheAbilita(); this.recuperaStatisticheAbilitaProfessionaliPerPg(); this.recuperaStatisticheCrediti(); this.recuperaStatistichePG(); this.recuperaStatistichePunteggi(); this.recuperaStatisticheQtaRavShop(); this.recuperaStatisticheAcquistiRavShop(); this.recuperaStatisticheArmiStampate(); }, getDOMElements: function getDOMElements() { this.military_classes_pie_ctx = $( "#military_classes_pie" )[ 0 ].getContext( "2d" ); this.military_abilities_bars_ctx = $( "#military_abilities_bars" )[ 0 ].getContext( "2d" ); this.civilian_classes_pie_ctx = $( "#civilian_classes_pie" )[ 0 ].getContext( "2d" ); this.civilian_abilities_bars_ctx = $( "#civilian_abilities_bars" )[ 0 ].getContext( "2d" ); this.civilian_abilities_qty_pg_bars_ctx = $( "#civilian_abilities_qty_pg_bars" )[ 0 ].getContext( "2d" ); this.credits_line_ctx = $( "#credits_line" )[ 0 ].getContext( "2d" ); this.pf_pie_ctx = $( "#pf_pie" )[ 0 ].getContext( "2d" ); this.ps_pie_ctx = $( "#ps_pie" )[ 0 ].getContext( "2d" ); this.mente_pie_ctx = $( "#mente_pie" )[ 0 ].getContext( "2d" ); this.ravshop_qty_bar_ctx = $( "#ravshop_qty_bar" )[ 0 ].getContext( "2d" ); this.ravshop_popularity_bar_ctx = $( "#ravshop_popularity_bar" )[ 0 ].getContext( "2d" ); this.crafted_bar_ctx = $( "#crafted_bar" )[ 0 ].getContext( "2d" ); }, init: function init() { Chart.defaults.global.defaultFontColor = '#18b3b2'; this.getDOMElements(); this.loadCharts(); } }; }(); $( document ).ready( StatisticsManager.init.bind( StatisticsManager ) ); <file_sep>/server/src/classes/MessagingManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/SessionManager.class.php"); class MessagingManager { protected $db; protected $session; protected $idev_in_corso; public function __construct($idev_in_corso = NULL) { $this->idev_in_corso = $idev_in_corso; $this->session = SessionManager::getInstance(); $this->db = new DatabaseBridge(); } public function __destruct() { } private function nuovoIdConversazione($tabella) { $query = "SELECT id_conversazione FROM $tabella ORDER BY id_conversazione DESC LIMIT 1"; $ris = $this->db->doQuery($query, [], False); return (int) $ris[0]["id_conversazione"] + 1; } public function inviaMessaggio($tipo, $mitt, $dest, $ogg, $mex, $risp_id = NULL, $conv_id = NULL) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $tabella = $tipo === "fg" ? "messaggi_fuorigioco" : "messaggi_ingioco"; $tabella_check = $tipo === "fg" ? "giocatori" : "personaggi"; $id_check = $tipo === "fg" ? "email_giocatore" : "id_personaggio"; $name_check = $tipo === "fg" ? "CONCAT(nome_giocatore,' ',cognome_giocatore) AS nome" : "nome_personaggio AS nome"; $eliminato = $tipo === "fg" ? "eliminato_giocatore" : "eliminato_personaggio"; $dest_names = []; if (count($dest) === 0) throw new APIException("Non sono stati specificati dei destinatari."); $query_check = "SELECT $id_check, $name_check FROM $tabella_check WHERE $id_check = :mitt AND $eliminato = 0"; $ris_check = $this->db->doQuery($query_check, array(":mitt" => $mitt), False); if (count($ris_check) === 0) throw new APIException("Il mittente di questo messaggio non esiste."); foreach ($dest as $i => $d) { if (empty($d) || $d == NULL) continue; $query_check_dest = "SELECT $id_check, $name_check FROM $tabella_check WHERE $id_check = :dest AND $eliminato = 0"; $ris_check_dest = $this->db->doQuery($query_check_dest, array(":dest" => trim($d)), False); if (count($ris_check_dest) === 0) throw new APIException("Il destinatario $d di questo messaggio non esiste."); $dest_names[$i] = $ris_check_dest[0]["nome"]; } foreach ($dest as $i => $d) { if (empty($d) || $d == NULL) continue; if ($conv_id == NULL) $conv_id = $this->nuovoIdConversazione($tabella); $params = array( ":mitt" => $mitt, ":dest" => $d, ":ogg" => $ogg, ":mex" => $mex, ":conv" => $conv_id ); if (isset($risp_id)) { $q_risp = ":risp"; $params[":risp"] = $risp_id; } else $q_risp = "NULL"; $query_mex = "INSERT INTO $tabella (mittente_messaggio, destinatario_messaggio, oggetto_messaggio, testo_messaggio, risposta_a_messaggio, id_conversazione) VALUES ( :mitt, :dest, :ogg, :mex, $q_risp, :conv )"; $this->db->doQuery($query_mex, $params, False); $inviato_a[] = $dest_names[$i]; } return json_encode([ "status" => "ok", "result" => True, "message" => "Messaggio inviato correttamente a " . implode(", ", $inviato_a) ]); } public function recuperaConversazione($id_conv, $tipo) { $params = array(":idconv" => $id_conv); $tabella = $tipo === "ig" ? "messaggi_ingioco" : "messaggi_fuorigioco"; $t_join = $tipo === "ig" ? "personaggi" : "giocatori"; $campo_id = $tipo === "ig" ? "id_personaggio" : "email_giocatore"; $campo_nome_mitt = $tipo === "ig" ? "t_mitt.nome_personaggio" : "CONCAT( t_mitt.nome_giocatore, ' ', t_mitt.cognome_giocatore )"; $campo_nome_dest = $tipo === "ig" ? "t_dest.nome_personaggio" : "CONCAT( t_dest.nome_giocatore, ' ', t_dest.cognome_giocatore )"; $query_check_conv = " SELECT DISTINCT mittente_messaggio AS id_utente FROM $tabella WHERE id_conversazione = :idconv UNION ALL SELECT DISTINCT destinatario_messaggio AS id_utente FROM $tabella WHERE id_conversazione = :idconv"; $ris_check_conv = $this->db->doQuery($query_check_conv, [":idconv" => $id_conv], False); if (!isset($ris_check_conv) || count($ris_check_conv) === 0) throw new APIException("La conversazione richiesta non esiste.", APIException::$GENERIC_ERROR); $utenti = array_column($ris_check_conv, "id_utente"); if ( count(array_intersect($this->session->pg_propri, $utenti)) === 0 && !in_array($this->session->email_giocatore, $utenti) && !UsersManager::controllaPermessi($this->session, [__FUNCTION__ . "_altri"]) ) { throw new APIException("Non puoi leggere messaggi non tuoi.", APIException::$GRANTS_ERROR); } $query_mex = "SELECT mex.*, t_mitt.$campo_id AS id_mittente, $campo_nome_mitt AS nome_mittente, t_dest.$campo_id AS id_destinatario, $campo_nome_dest AS nome_destinatario, '$tipo' AS tipo_messaggio FROM $tabella AS mex JOIN $t_join AS t_mitt ON mex.mittente_messaggio = t_mitt.$campo_id JOIN $t_join AS t_dest ON mex.destinatario_messaggio = t_dest.$campo_id WHERE mex.id_conversazione = :idconv ORDER BY data_messaggio DESC"; $risultati = $this->db->doQuery($query_mex, $params, False); if ((in_array($risultati[0]["id_destinatario"], $this->session->pg_propri)) || $risultati[0]["id_destinatario"] === $this->session->email_giocatore ) { $query_letto = "UPDATE $tabella SET letto_messaggio = :letto WHERE id_conversazione = :id"; $this->db->doQuery($query_letto, array(":id" => $id_conv, ":letto" => 1), False); } return "{\"status\": \"ok\",\"result\": " . json_encode($risultati) . "}"; } public function recuperaMessaggi($draw, $columns, $order, $start, $length, $search, $tipo, $filtro = NULL) { //PORCATA PAZZESCA UsersManager::operazionePossibile($this->session, __FUNCTION__ . "_proprio"); $filter = False; $lettura_altri = UsersManager::operazionePossibile($this->session, __FUNCTION__ . "_altri", NULL, false); $params = [":mail" => $this->session->email_giocatore]; $where = []; $having = []; $tabella = $tipo === "ig" ? "messaggi_ingioco" : "messaggi_fuorigioco"; $join = $tipo === "ig" ? "JOIN personaggi AS pg ON base.coinvolto = pg.id_personaggio JOIN giocatori AS gi ON pg.giocatori_email_giocatore = gi.email_giocatore" : "JOIN giocatori AS gi ON base.coinvolto = gi.email_giocatore"; $campo_id = $tipo === "ig" ? "pg.id_personaggio" : "gi.email_giocatore"; $campo_nome = $tipo === "ig" ? "CONCAT( pg.nome_personaggio, ' (', gi.nome_giocatore, ' ', gi.cognome_giocatore, ')' )" : "CONCAT( gi.nome_giocatore, ' ', gi.cognome_giocatore )"; $ispng = $tipo === "ig" ? ", SUM(IF(gi.ruoli_nome_ruolo = 'admin' OR gi.ruoli_nome_ruolo = 'staff',1,0)) AS png_score, SUM(IF((gi.ruoli_nome_ruolo = 'admin' OR gi.ruoli_nome_ruolo = 'staff') AND gi.email_giocatore = :mail,1,0)) AS my_png_score" : ""; $output = array( "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => $totale, "recordsFiltered" => 0, "data" => [] ); if ($tipo === "ig" && count($this->session->pg_propri) == 0){ return json_encode($output); } if ($tipo === "ig" && !$lettura_altri) { $marcatori_pg = []; foreach ($this->session->pg_propri as $i => $pg) $marcatori_pg[] = "id_coinvolti LIKE :id$i"; foreach ($this->session->pg_propri as $i => $pg) $params[":id$i"] = "%$pg%"; $marcatori_pg = implode(" OR ", $marcatori_pg); $having[] = "($marcatori_pg)"; } else if ($tipo === "ig" && $lettura_altri) { // senza WHERE o HAVING si avranno già tutti i risultati } else if ($tipo === "fg") { $params[":id"] = '%' . $this->session->email_giocatore . '%'; $having[] = "id_coinvolti LIKE :id"; } if (isset($search) && $search["value"] != "") { $filter = True; $params[":search"] = "%$search[value]%"; $having[] = "( coinvolti LIKE :search OR oggetto_messaggio LIKE :search )"; } if (isset($order)) { $sorting = array(); foreach ($order as $elem) $sorting[] = $columns[$elem["column"]]["data"] . " " . $elem["dir"]; $order_str = "ORDER BY " . implode(",", $sorting); } if (count($having) > 0) $having = "HAVING " . implode(" AND ", $having); else $having = ""; if (count($where) > 0) $where = "WHERE " . implode(" AND ", $where); else $where = ""; //TODO: finire! $query_mex = " SELECT base.id_conversazione, '$tipo' AS tipo_messaggio, MAX(base.data_messaggio) AS data_messaggio, MIN(base.oggetto_messaggio) AS oggetto_messaggio, GROUP_CONCAT(DISTINCT $campo_id SEPARATOR ',') AS id_coinvolti, GROUP_CONCAT(DISTINCT $campo_nome SEPARATOR ', ') AS coinvolti, SUM(IF(gi.email_giocatore = :mail, base.letto_messaggio, 0)) AS letto_messaggio, SUM(IF(gi.ruoli_nome_ruolo = 'admin' OR gi.ruoli_nome_ruolo = 'staff',1,0)) AS png_score, SUM(IF((gi.ruoli_nome_ruolo = 'admin' OR gi.ruoli_nome_ruolo = 'staff') AND gi.email_giocatore = :mail,1,0)) AS my_png_score FROM ( SELECT oggetto_messaggio, data_messaggio, letto_messaggio, id_conversazione, mittente_messaggio as coinvolto FROM $tabella UNION ALL SELECT oggetto_messaggio, data_messaggio, letto_messaggio, id_conversazione, destinatario_messaggio as coinvolto FROM $tabella) as base $join $where GROUP BY id_conversazione $having $order_str"; $risultati = $this->db->doQuery($query_mex, $params, False); $totale = count($risultati); $totFiltrati = $totale; if ($lettura_altri && !empty($filtro) && $filtro !== "filtro_tutti" && $tipo === "ig") { $risultati = array_filter($risultati, function ($el) use ($filtro) { if ($filtro === "filtro_png") return (int) $el["png_score"] > 0; else if ($filtro === "filtro_miei_png") return (int) $el["my_png_score"] > 0; return False; }); $totFiltrati = count($risultati); } if (count($risultati) > 0) $risultati = array_splice($risultati, $start, $length); else $risultati = array(); $output["recordsFiltered"] = $totFiltrati; $output["data"] = $risultati; return json_encode($output); } private function recuperaDestinatari($tipo, $term) { if (substr($term, 0, 1) === "#") return json_encode(["status" => "ok", "result" => []]); if ($tipo === "ig") $query_dest = "SELECT id_personaggio AS real_value, CONCAT( nome_personaggio, ' (#', id_personaggio, ')' ) AS label FROM personaggi WHERE nome_personaggio LIKE :term AND contattabile_personaggio = 1 AND eliminato_personaggio = 0"; else if ($tipo === "fg") $query_dest = "SELECT email_giocatore AS real_value, CONCAT( nome_giocatore, ' ', cognome_giocatore ) AS label FROM giocatori WHERE CONCAT( nome_giocatore, ' ', cognome_giocatore ) LIKE :term AND eliminato_giocatore = 0"; $ret["status"] = "ok"; $ret["results"] = $this->db->doQuery($query_dest, array(":term" => "%$term%"), False); return json_encode($ret); } public function recuperaDestinatariIG($term) { return $this->recuperaDestinatari("ig", $term); } public function recuperaDestinatariFG($term) { return $this->recuperaDestinatari("fg", $term); } public function recuperaNonLetti() { UsersManager::controllaLogin($this->session); $output = [ "result" => [ "ig" => [], "fg" => [] ] ]; $query_new_fg = "SELECT COUNT(id_messaggio) AS nuovi_fg FROM messaggi_fuorigioco WHERE letto_messaggio = 0 AND destinatario_messaggio = :mail"; $valore_fg = $this->db->doQuery($query_new_fg, [":mail" => $this->session->email_giocatore], False); $output["result"]["fg"] = $valore_fg[0]["nuovi_fg"]; if(count($this->session->pg_propri) === 0) { $output["status"] = "ok"; return json_encode($output); } $marcatori = count($this->session->pg_propri) === 1 ? "?" : str_repeat("?, ", count($this->session->pg_propri) - 1) . "?"; $query_new_ig = "SELECT COUNT(id_messaggio) AS nuovi_ig FROM messaggi_ingioco WHERE letto_messaggio = 0 AND destinatario_messaggio IN ($marcatori)"; $valore_ig = $this->db->doQuery($query_new_ig, $this->session->pg_propri, False); $output["result"]["ig"] = $valore_ig[0]["nuovi_ig"]; $output["status"] = "ok"; return json_encode($output); } } <file_sep>/client/app/scripts/controllers/PgEditManager.js var PgEditManager = function () { return { init: function () { this.user_info = JSON.parse(window.localStorage.getItem("user")); var permessi = [ "modificaPG_anno_nascita_personaggio_altri", "modificaPG_contattabile_personaggio_altri", "modificaPG_motivazioni_olocausto_inserite_personaggio_altri", "modificaPG_nome_personaggio_altri", "modificaPG_giocatori_email_giocatore_altri" ]; if (!Utils.controllaPermessiUtente(this.user_info, permessi, false)) return false; this.modal = $("#modal_modifica_pg"); this.onSuccess = Utils.reloadPage; this.dati = {}; this.getUsers(); this.setListeners(); }, riempiElencoUsers: function (data) { var users = data.data, menu = this.modal.find("select[name='giocatori_email_giocatore']"); for (var s in users) menu.append("<option value='" + users[s].email_giocatore + "'>" + users[s].nome_completo + "</option>"); }, getUsers: function () { Utils.requestData( Constants.API_GET_PLAYERS, "GET", "draw=1&columns=&order=&start=0&length=999&search=", this.riempiElencoUsers.bind(this) ); }, riempiModal: function (elem) { this.dati = elem.data(); for (var d in this.dati) { var campo = $("[name='" + d + "']"); if (campo.is("input[type='checkbox']")) campo.iCheck(this.dati[d] == 1 ? "check" : "uncheck"); else campo.val(this.dati[d]); } }, resettaModal: function () { this.modal.find("form").trigger("reset"); this.modal.find("select[name='giocatori_email_giocatore']").find("option[value='" + this.dati.giocatori_email_giocatore + "']").prop("selected", true); $("#contattabile").iCheck("check"); $("#motivazioni").iCheck("uncheck"); }, mostraModal: function (e) { this.resettaModal(); this.riempiModal($(e.currentTarget)); this.modal.modal("show"); }, inviaDati: function () { var form = Utils.getFormData(this.modal.find("form")), note = form.note_azione || "", tosend = {}; for (var f in form) { if (typeof this.dati[f] !== "undefined" && form[f] != this.dati[f]) tosend[f] = form[f]; } if (Object.keys(tosend).length > 0) Utils.requestData( Constants.API_POST_EDIT_PG, "POST", { id: this.dati.id_personaggio, modifiche: tosend, is_offset: false, note_azione: note }, "Personaggio modificato con successo", null, this.onSuccess ); else this.modal.modal("hide"); }, setListeners: function () { $(".mostraModalEditPG").click(this.mostraModal.bind(this)); this.modal.find("#btn_modifica").click(this.inviaDati.bind(this)); this.modal.find(".icheck").iCheck({ checkboxClass: 'icheckbox_square-blue' }); }, setOnSuccess: function (f) { this.onSuccess = f; } }; }(); $(function () { PgEditManager.init(); });<file_sep>/server/src/classes/CraftingManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class CraftingManager { protected $idev_in_corso; protected $session; protected $db; public function __construct($idev_in_corso = NULL) { $this->idev_in_corso = $idev_in_corso; $this->db = new DatabaseBridge(); $this->session = SessionManager::getInstance(); } public function __destruct() { } public function inserisciRicettaNetrunner($pgid, $programmi) { global $GRANT_VISUALIZZA_CRAFT_PROGRAM; UsersManager::operazionePossibile($this->session, $GRANT_VISUALIZZA_CRAFT_PROGRAM); $nome_programma = $programmi[0]["nome_programma"]; $risultati = []; unset($programmi[0]["nome_programma"]); foreach ($programmi as $p) { $sql_x = "SELECT effetto_valore_crafting AS effetto, parametro_collegato_crafting AS pcc FROM crafting_programmazione WHERE parametro_crafting = 'X1' AND valore_parametro_crafting = :x_val"; $res_x = $this->db->doQuery($sql_x, [":x_val" => $p["x_val"]], False); $sql_y = "SELECT effetto_valore_crafting AS effetto, parametro_collegato_crafting AS pcc FROM crafting_programmazione WHERE parametro_crafting = :pcc AND valore_parametro_crafting = :y_val"; $res_y = $this->db->doQuery($sql_y, [":pcc" => $res_x[0]["pcc"], ":y_val" => $p["y_val"]], False); $sql_z = "SELECT effetto_valore_crafting AS effetto FROM crafting_programmazione WHERE parametro_crafting = :pcc AND valore_parametro_crafting = :z_val"; $res_z = $this->db->doQuery($sql_z, [":pcc" => $res_y[0]["pcc"], ":z_val" => $p["z_val"]], False); $risultati[] = $res_x[0]["effetto"] . " - " . $res_y[0]["effetto"] . " - " . $res_z[0]["effetto"]; } $risultato_crafting = implode(";", $risultati); $sql_progr = "SELECT id_unico_risultato_ricetta FROM ricette WHERE risultato_ricetta = :risultato"; $progr_id = $this->db->doQuery($sql_progr, [":risultato" => $risultato_crafting], False); if (!isset($progr_id) || count($progr_id) === 0) { $sql_id_res = "SELECT IFNULL( MAX( COALESCE(id_unico_risultato_ricetta, 0) ), 0) AS id_unico_risultato_ricetta FROM ricette WHERE tipo_ricetta = :tipo"; $progr_id = $this->db->doQuery($sql_id_res, [":tipo" => "Programmazione"], False); $progr_id[0]["id_unico_risultato_ricetta"] = (int) $progr_id[0]["id_unico_risultato_ricetta"] + 1; } $params = [ ":idpg" => $pgid, ":tipo" => "Programmazione", ":tipo_ogg" => "Programma", ":nome" => $nome_programma, ":res" => $risultato_crafting, ":id_res" => (int) $progr_id[0]["id_unico_risultato_ricetta"] ]; $sql_ricetta = "INSERT INTO ricette (id_ricetta, personaggi_id_personaggio, data_inserimento_ricetta, tipo_ricetta, tipo_oggetto, nome_ricetta, risultato_ricetta, approvata_ricetta, id_unico_risultato_ricetta) VALUES (NULL, :idpg, NOW(), :tipo, :tipo_ogg, :nome, :res, 0, :id_res )"; $id_nuova = $this->db->doQuery($sql_ricetta, $params, False); foreach ($programmi as $k => $p) { $inserts[] = [":idcomp" => "X=" . $p["x_val"], ":idric" => $id_nuova, ":ord" => $k]; $inserts[] = [":idcomp" => "Y=" . $p["y_val"], ":idric" => $id_nuova, ":ord" => $k]; $inserts[] = [":idcomp" => "Z=" . $p["z_val"], ":idric" => $id_nuova, ":ord" => $k]; } $sql_componenti = "INSERT INTO componenti_ricetta (componenti_crafting_id_componente, ricette_id_ricetta, ordine_crafting) VALUES (:idcomp,:idric,:ord)"; $this->db->doMultipleManipulations($sql_componenti, $inserts, False); $output = ["status" => "ok", "result" => true]; return json_encode($output); } public function inserisciRicettaTecnico($pgid, $nome, $tipo, $batterie, $strutture, $applicativi) { global $GRANT_VISUALIZZA_CRAFT_TECNICO; UsersManager::operazionePossibile($this->session, $GRANT_VISUALIZZA_CRAFT_TECNICO); $tutti_id = array_merge($batterie, $strutture, $applicativi); $sotto_query = []; for ($i = 0; $i < count($tutti_id); $i++) $sotto_query[] = "SELECT effetto_sicuro_componente, IF( POSITION( 'deve dichiarare' IN LOWER( effetto_sicuro_componente ) ) > 0,TRUE,FALSE) AS deve, tipo_applicativo_componente, volume_componente, energia_componente FROM componenti_crafting WHERE id_componente = ?"; $union = implode(" UNION ALL ", $sotto_query); $sql_check = "SELECT effetto_sicuro_componente, tipo_applicativo_componente, volume_componente, energia_componente, deve FROM ( $union ) AS u"; $check_res = $this->db->doQuery($sql_check, $tutti_id, False); if (!isset($check_res) || count($check_res) === 0) throw new APIException("Il crafting non &egrave; andato a buon fine. Riprovare."); $deve = array_sum(array_values(Utils::mappaArrayDiArrayAssoc($check_res, "deve"))); if ($deve > 1) throw new APIException("Impossibile completare l'operazione. Non &egrave; possibile combinare pi&ugrave; applicazioni che DEVONO dichiarare qualcosa."); $volume = array_sum(array_values(Utils::mappaArrayDiArrayAssoc($check_res, "volume_componente"))); $energia = array_sum(array_values(Utils::mappaArrayDiArrayAssoc($check_res, "energia_componente"))); $tipi_applicativi = Utils::mappaArrayDiArrayAssoc($check_res, "tipo_applicativo_componente"); $effetti_componenti = Utils::mappaArrayDiArrayAssoc($check_res, "effetto_sicuro_componente"); $risultato_crafting = implode(";", $effetti_componenti); $risultato_crafting = preg_replace("/^;+/", "$1", $risultato_crafting); if ($volume < 0 || $energia < 0) throw new APIException("Il crafting non &egrave; andato a buon fine. Riprovare."); $params = [ ":idpg" => $pgid, ":tipo" => "Tecnico", ":tipo_ogg" => $tipo, ":nome" => $nome, ":res" => $risultato_crafting ]; $sql_ricetta = "INSERT INTO ricette (id_ricetta, personaggi_id_personaggio, data_inserimento_ricetta, tipo_ricetta, tipo_oggetto, nome_ricetta, risultato_ricetta) VALUES (NULL, :idpg, NOW(), :tipo, :tipo_ogg, :nome, :res )"; $id_nuova = $this->db->doQuery($sql_ricetta, $params, False); foreach ($tutti_id as $id) $inserts[] = [":idcomp" => $id, ":idric" => $id_nuova]; $sql_componenti = "INSERT INTO componenti_ricetta (componenti_crafting_id_componente, ricette_id_ricetta) VALUES (:idcomp,:idric)"; $this->db->doMultipleManipulations($sql_componenti, $inserts, False); $output = ["status" => "ok", "result" => true]; return json_encode($output); } public function inserisciRicettaMedico($pgid, $nome, $supporto, $principio_attivo, $sostanza_1, $sostanza_2, $sostanza_3) { global $GRANT_VISUALIZZA_CRAFT_CHIMICO; UsersManager::operazionePossibile($this->session, $GRANT_VISUALIZZA_CRAFT_CHIMICO); $sql_info = "SELECT id_componente, tipo_componente, curativo_primario_componente, tossico_primario_componente, psicotropo_primario_componente, REPLACE(possibilita_dipendeza_componente,',','.') AS possibilita_dipendeza_componente, effetto_sicuro_componente, descrizione_componente FROM componenti_crafting WHERE id_componente IN (?,?,?,?,?)"; $info = $this->db->doQuery($sql_info, [$supporto, $principio_attivo, $sostanza_1, $sostanza_2, $sostanza_3], False); $info_supporto = array_values(Utils::filtraArrayDiArrayAssoc($info, "id_componente", [$supporto]))[0]; $info_principio = array_values(Utils::filtraArrayDiArrayAssoc($info, "id_componente", [$principio_attivo]))[0]; $info_sostanza1 = array_values(Utils::filtraArrayDiArrayAssoc($info, "id_componente", [$sostanza_1]))[0]; $info_sostanza2 = array_values(Utils::filtraArrayDiArrayAssoc($info, "id_componente", [$sostanza_2]))[0]; $info_sostanza3 = array_values(Utils::filtraArrayDiArrayAssoc($info, "id_componente", [$sostanza_3]))[0]; $curativo = (int) $info_principio["curativo_primario_componente"] + (int) $info_sostanza1["curativo_primario_componente"] + (int) $info_sostanza2["curativo_primario_componente"] + (int) $info_sostanza3["curativo_primario_componente"]; $calcoli = "CURA " . ((int) $info_principio["curativo_primario_componente"]) . " + " . ((int) $info_sostanza1["curativo_primario_componente"]) . " + " . ((int) $info_sostanza2["curativo_primario_componente"]) . " + " . ((int) $info_sostanza3["curativo_primario_componente"]) . " = " . $curativo . "\n"; $tossico = (int) $info_principio["tossico_primario_componente"] + (int) $info_sostanza1["tossico_primario_componente"] + (int) $info_sostanza2["tossico_primario_componente"] + (int) $info_sostanza3["tossico_primario_componente"]; $calcoli .= "TOSSICO " . ((int) $info_principio["tossico_primario_componente"]) . " + " . ((int) $info_sostanza1["tossico_primario_componente"]) . " + " . ((int) $info_sostanza2["tossico_primario_componente"]) . " + " . ((int) $info_sostanza3["tossico_primario_componente"]) . " = " . $tossico . "\n"; $id_psicotropo = (int) $info_principio["psicotropo_primario_componente"] + (int) $info_sostanza1["psicotropo_primario_componente"] + (int) $info_sostanza2["psicotropo_primario_componente"] + (int) $info_sostanza3["psicotropo_primario_componente"]; $calcoli .= "PSICO " . ((int) $info_principio["psicotropo_primario_componente"]) . " + " . ((int) $info_sostanza1["psicotropo_primario_componente"]) . " + " . ((int) $info_sostanza2["psicotropo_primario_componente"]) . " + " . ((int) $info_sostanza3["psicotropo_primario_componente"]) . " = " . $id_psicotropo . "\n"; $dipendenza = (int) $info_principio["possibilita_dipendeza_componente"] + (int) $info_sostanza1["possibilita_dipendeza_componente"] + (int) $info_sostanza2["possibilita_dipendeza_componente"] + (int) $info_sostanza3["possibilita_dipendeza_componente"]; $subquery = ""; $params = [":id_psico" => $id_psicotropo]; if ($curativo > $tossico) { $subquery = "( SELECT curativo_crafting_chimico FROM crafting_chimico WHERE :id_effetto BETWEEN min_chimico AND max_chimico ) AS effetto,"; $params[":id_effetto"] = $curativo; } else if ($curativo < $tossico) { $subquery = "( SELECT tossico_crafting_chimico FROM crafting_chimico WHERE :id_effetto BETWEEN min_chimico AND max_chimico ) AS effetto,"; $params[":id_effetto"] = $tossico; } else if ($curativo == $tossico) { $subquery = ""; $params[":id_psico"] = rand(41,76); } $sql_risultato = "SELECT $subquery ( SELECT psicotropo_crafting_chimico FROM crafting_chimico WHERE :id_psico BETWEEN min_chimico AND max_chimico ) AS psicotropo"; $risultato = $this->db->doQuery($sql_risultato, $params, False); $arr_risult = []; if (isset($risultato[0]["effetto"])) { $effetto = $risultato[0]["effetto"]; $arr_risult[] = $effetto; } if (isset($risultato[0]["psicotropo"])) { $psico = $risultato[0]["psicotropo"]; $arr_risult[] = $psico; } if (isset($info_supporto["effetto_sicuro_componente"])) { $sicuro = $info_supporto["effetto_sicuro_componente"]; $arr_risult[] = $sicuro; } // $arr_risult[] = "Dipendenza: $dipendenza"; $risultato_crafting = preg_replace("/^;+/", "$1", implode(";", $arr_risult)); if (!isset($effetto) && empty($psico)) $risultato_crafting = "Nessun effetto"; $params = [ ":idpg" => $pgid, ":tipo" => "Chimico", ":tipo_ogg" => "Sostanza", ":nome" => $nome, ":risult" => $risultato_crafting, ":note" => "Dipendenza: $dipendenza" ]; $sql_ricetta = "INSERT INTO ricette (id_ricetta, personaggi_id_personaggio, data_inserimento_ricetta, tipo_ricetta, tipo_oggetto, nome_ricetta, risultato_ricetta, note_ricetta) VALUES (NULL, :idpg, NOW(), :tipo, :tipo_ogg, :nome, :risult, :note )"; $id_nuova = $this->db->doQuery($sql_ricetta, $params, False); $inserts[] = [":idcomp" => $supporto, ":idric" => $id_nuova, ":ruolo" => "Base"]; $inserts[] = [":idcomp" => $principio_attivo, ":idric" => $id_nuova, ":ruolo" => "Sostanza Satellite"]; $inserts[] = [":idcomp" => $sostanza_1, ":idric" => $id_nuova, ":ruolo" => "Sostanza Satellite"]; $inserts[] = [":idcomp" => $sostanza_2, ":idric" => $id_nuova, ":ruolo" => "Sostanza Satellite"]; $inserts[] = [":idcomp" => $sostanza_3, ":idric" => $id_nuova, ":ruolo" => "Sostanza Satellite"]; $sql_componenti = "INSERT INTO componenti_ricetta (componenti_crafting_id_componente, ricette_id_ricetta, ruolo_componente_ricetta) VALUES (:idcomp,:idric,:ruolo)"; $this->db->doMultipleManipulations($sql_componenti, $inserts, False); $output = ["status" => "ok", "result" => true, "calcoli" => $calcoli]; return json_encode($output); } public function modificaRicetta($id_r, $modifiche) { UsersManager::operazionePossibile($this->session, __FUNCTION__); if (isset($modifiche["old_costo_attuale_ricetta"]) && $modifiche["old_costo_attuale_ricetta"] !== $modifiche["costo_attuale_ricetta"]) { $modifiche["costo_vecchio_ricetta"] = $modifiche["old_costo_attuale_ricetta"]; unset($modifiche["old_costo_attuale_ricetta"]); } $to_update = implode(" = ?, ", array_keys($modifiche)) . " = ?"; $valori = array_values($modifiche); $valori[] = $id_r; $query = "UPDATE ricette SET $to_update WHERE id_ricetta = ?"; $this->db->doQuery($query, $valori, False); return "{\"status\": \"ok\",\"result\": \"true\"}"; } public function recuperaRicette($draw, $columns, $order, $start, $length, $search, $filtro = NULL, $pgid = -1, $check_grants = True, $where = []) { if ($check_grants) UsersManager::operazionePossibile($this->session, __FUNCTION__, $pgid); $filter = False; $order_str = ""; $params = []; $campi_prvt = ["ri.risultato_ricetta", "ri.id_unico_risultato_ricetta", "ri.note_ricetta", "ri.extra_cartellino_ricetta"]; $campi_str = (int) $pgid === -1 ? ", " . implode(", ", $campi_prvt) : ""; if (isset($search) && isset($search["value"]) && $search["value"] != "") { $filter = True; $params[":search"] = "%$search[value]%"; $where[] = " ( r.nome_giocatore LIKE :search OR r.personaggi_id_personaggio LIKE :search OR r.nome_personaggio LIKE :search OR r.tipo_ricetta LIKE :search OR r.componenti_ricetta LIKE :search OR r.risultato_ricetta LIKE :search OR r.note_ricetta LIKE :search OR r.note_pg_ricetta LIKE :search OR r.extra_cartellino_ricetta LIKE :search OR r.data_inserimento_it LIKE :search )"; } if (isset($order) && !empty($order) && count($order) > 0) { $sorting = array(); foreach ($order as $elem) { $colonna = $columns[$elem["column"]]["data"]; $colonna = $colonna === "data_inserimento_it" ? "data_inserimento_ricetta" : $colonna; $sorting[] = "r." . $colonna . " " . $elem["dir"]; } $order_str = "ORDER BY " . implode(",", $sorting); } if ((int) $pgid > 0) { $where[] = "r.personaggi_id_personaggio = :pgid"; $params[":pgid"] = $pgid; } if (count($where) > 0) $where = "WHERE " . implode(" AND ", $where); else $where = ""; $query_ric = "SELECT * FROM ( SELECT ri.id_ricetta, ri.personaggi_id_personaggio, DATE_FORMAT( ri.data_inserimento_ricetta, '%d/%m/%Y %H:%i:%s' ) as data_inserimento_it, ri.data_inserimento_ricetta, ri.tipo_ricetta, ri.tipo_oggetto, ri.risultato_ricetta, ri.extra_cartellino_ricetta, ri.id_unico_risultato_ricetta, ri.note_ricetta, ri.nome_ricetta, ri.gia_stampata, IF( cr.ruolo_componente_ricetta IS NOT NULL, GROUP_CONCAT( CONCAT(cc.nome_componente,' (',cr.ruolo_componente_ricetta,') [',cc.costo_attuale_componente,' Bit]') ORDER BY cr.ordine_crafting ASC, cc.nome_componente ASC SEPARATOR '; '), GROUP_CONCAT( CONCAT(cc.nome_componente,' [',cc.costo_attuale_componente,' Bit]') ORDER BY cr.ordine_crafting ASC, cc.nome_componente ASC SEPARATOR '; ') ) as componenti_ricetta, IF( ri.in_ravshop_ricetta = 1, ri.disponibilita_ravshop_ricetta, 'Non Venduto' ) as disponibilita_ravshop_ricetta, ri.costo_attuale_ricetta, ri.in_ravshop_ricetta, ri.approvata_ricetta, ri.note_pg_ricetta, CONCAT(gi.nome_giocatore,' ',gi.cognome_giocatore) AS nome_giocatore, pg.nome_personaggio, SUM( cc.fcc_componente ) AS fcc_componente, gi.email_giocatore, IF(gi.ruoli_nome_ruolo = 'admin' OR gi.ruoli_nome_ruolo = 'admin' OR gi.ruoli_nome_ruolo = 'staff' OR gi.ruoli_nome_ruolo = 'staff',1,0) AS is_png FROM ricette AS ri JOIN personaggi AS pg ON pg.id_personaggio = ri.personaggi_id_personaggio JOIN giocatori AS gi ON gi.email_giocatore = pg.giocatori_email_giocatore JOIN componenti_ricetta AS cr ON ri.id_ricetta = cr.ricette_id_ricetta JOIN componenti_crafting AS cc ON cr.componenti_crafting_id_componente = cc.id_componente GROUP BY ri.id_ricetta ) AS r $where $order_str"; $risultati = $this->db->doQuery($query_ric, $params, False); $totale = count($risultati); $totFiltrati = $totale; if (count($risultati) > 0 && !empty($filtro) && $filtro !== "filtro_tutti") { $risultati = array_filter($risultati, function ($el) use ($filtro) { if ($filtro === "filtro_png") return (int) $el["is_png"] === 1; else if ($filtro === "filtro_miei_png") return (int) $el["is_png"] === 1 && in_array($el["personaggi_id_personaggio"], $this->session->pg_propri); return False; }); $totFiltrati = count($risultati); } if (count($risultati) > 0) $risultati = array_splice($risultati, $start, $length); else $risultati = array(); $output = array( "status" => "ok", "draw" => $draw, "columns" => $columns, "order" => $order, "start" => $start, "length" => $length, "search" => $search, "recordsTotal" => $totale, "recordsFiltered" => $totFiltrati, "data" => $risultati ); return json_encode($output); } public function recuperaRicettePerRavshop($draw, $columns, $order, $start, $length, $search, $filtro = NULL, $pgid = -1) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $where = ["in_ravshop_ricetta = 1"]; return $this->recuperaRicette($draw, $columns, $order, $start, $length, $search, $filtro, $pgid = -1, False, $where); } public function recupeRaricetteConId($ids) { UsersManager::operazionePossibile($this->session, "recuperaRicette", -1); $marcatori = str_repeat("?, ", count($ids) - 1) . "?"; $query_ric = "SELECT ri.*, SUM(cc.fcc_componente) AS fcc_componente, cc.tipo_componente AS biostruttura_sostanza FROM ricette AS ri LEFT JOIN componenti_ricetta AS cr ON ri.id_ricetta = cr.ricette_id_ricetta AND cr.ruolo_componente_ricetta = 'Base' LEFT JOIN componenti_crafting AS cc ON cr.componenti_crafting_id_componente = cc.id_componente WHERE id_ricetta IN ($marcatori) GROUP BY ri.id_ricetta"; $risultati = $this->db->doQuery($query_ric, $ids, False); $output = [ "status" => "ok", "result" => $risultati ]; return json_encode($output); } public function segnaRicetteComeStampate($ids) { UsersManager::operazionePossibile($this->session, "recuperaRicette_altri"); $marcatori = str_repeat("?, ", count($ids) - 1) . "?"; $query_ric = "UPDATE ricette SET gia_stampata = 1 WHERE id_ricetta IN ($marcatori)"; $risultati = $this->db->doQuery($query_ric, $ids, False); $output = [ "status" => "ok", "result" => $risultati ]; return json_encode($output); } private function recuperaComponenti($draw, $columns, $order, $start, $length, $search, $where = []) { $filter = False; $order_str = ""; $params = []; $campi = Utils::mappaArrayDiArrayAssoc($columns, "data"); $campi[] = "IF( POSITION( 'deve dichiarare' IN LOWER( effetto_sicuro_componente ) ) > 0, TRUE, FALSE ) AS deve"; $campi_str = implode(",", $campi); if (isset($order) && !empty($order) && count($order) > 0) { $sorting = array(); foreach ($order as $elem) $sorting[] = $columns[$elem["column"]]["data"] . " " . $elem["dir"]; $order_str = "ORDER BY " . implode(",", $sorting); } if (count($where) > 0) $where = "WHERE " . implode(" AND ", $where); else $where = ""; $query_ric = "SELECT $campi_str FROM componenti_crafting $where $order_str"; $risultati = $this->db->doQuery($query_ric, $params, False); $output = Utils::filterDataTableResults($draw, $columns, $order, $start, $length, $search, $risultati); return json_encode($output); } public function recuperaComponentiAvanzato($draw, $columns, $order, $start, $length, $search, $tipo_crafting) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $columns[] = ["data" => "costo_vecchio_componente"]; $columns[] = ["data" => "volume_componente"]; $columns[] = ["data" => "energia_componente"]; $columns[] = ["data" => "tipo_componente"]; $columns[] = ["data" => "id_componente"]; $columns[] = ["data" => "nome_componente"]; $columns[] = ["data" => "descrizione_componente"]; $columns[] = ["data" => "tipo_applicativo_componente"]; $columns[] = ["data" => "visibile_ravshop_componente"]; return $this->recuperaComponenti($draw, $columns, $order, $start, $length, $search, ["tipo_crafting_componente = '$tipo_crafting'"]); } public function recuperaComponentiBase($draw, $columns, $order, $start, $length, $search, $tipo_crafting) { UsersManager::operazionePossibile($this->session, __FUNCTION__); if (is_array($order) && count($order) > 0) $order_field = $columns[$order[0]["column"]]["data"]; $columns[] = ["data" => "costo_vecchio_componente"]; $columns[] = ["data" => "volume_componente"]; $columns[] = ["data" => "energia_componente"]; $columns[] = ["data" => "tipo_componente"]; $columns[] = ["data" => "id_componente"]; $columns[] = ["data" => "nome_componente"]; $columns[] = ["data" => "descrizione_componente"]; $columns[] = ["data" => "tipo_applicativo_componente"]; $columns[] = ["data" => "effetto_sicuro_componente"]; $campi_permessi = [ "id_componente", "tipo_componente", "descrizione_componente", "costo_attuale_componente", "nome_componente", "costo_vecchio_componente", "valore_param_componente", "volume_componente", "energia_componente", "curativo_primario_componente", "tossico_primario_componente", "psicotropo_primario_componente", "curativo_secondario_componente", "psicotropo_secondario_componente", "tossico_secondario_componente", "possibilita_dipendeza_componente", "effetto_sicuro_componente", "tipo_applicativo_componente" ]; $campi = Utils::filtraArrayDiArrayAssoc($columns, "data", $campi_permessi); if (isset($order_field)) $order[0]["column"] = array_search($order_field, array_column($campi, 'data')); return $this->recuperaComponenti($draw, $campi, $order, $start, $length, $search, ["tipo_crafting_componente = '$tipo_crafting'", "visibile_ravshop_componente = '1'"]); } public function recuperaComponentiConId($ids) { UsersManager::operazionePossibile($this->session, "recuperaComponentiBase"); $marcatori = str_repeat("?, ", count($ids) - 1) . "?"; $sql = "SELECT id_componente ,nome_componente ,tipo_crafting_componente ,tipo_componente ,volume_componente ,energia_componente ,curativo_primario_componente ,psicotropo_primario_componente ,tossico_primario_componente ,curativo_secondario_componente ,psicotropo_secondario_componente ,tossico_secondario_componente ,possibilita_dipendeza_componente ,descrizione_componente FROM componenti_crafting WHERE id_componente IN ($marcatori)"; $risultati = $this->db->doQuery($sql, $ids, False); $output = [ "status" => "ok", "result" => $risultati ]; return json_encode($output); } private function controllaErroriCartellino($form_obj) { $errori = []; if (!isset($form_obj["id_componente"]) || $form_obj["id_componente"] === "") $errori[] = "L'ID del componente non pu&ograve; essere vuoto."; if (!isset($form_obj["nome_componente"]) || $form_obj["nome_componente"] === "") $errori[] = "Il nome del componente non pu&ograve; essere vuota."; if (count($errori) > 0) throw new APIException("Sono stati trovati errori durante l'invio dei dati del componente:<br><ul><li>" . implode("</li><li>", $errori) . "</li></ul>"); } public function inserisciComponente($params) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $this->controllaErroriCartellino($params); unset($params["old_costo_attuale_componente"]); $campi = implode(", ", array_keys($params)); $marchi = str_repeat("?,", count(array_keys($params)) - 1) . "?"; $valori = array_values($params); $query_insert = "INSERT INTO componenti_crafting ($campi) VALUES ($marchi)"; $id_cartellino = $this->db->doQuery($query_insert, $valori, False); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function modificaGruppoComponenti($idNames, $modifiche) { $SEPARATOR = "££"; $errors = []; foreach ($idNames as $idName) { $split = explode($SEPARATOR, $idName); $ret = $this->modificaComponente($split[0], $modifiche, TRUE); $status = json_decode($ret, true); if ($status["status"] !== "ok") { $errors[] = $split[1] . " (" . $split[0] . ")"; } } if (count($errors) > 0) { throw new APIException( "Non &egrave; stato possibile modificare i seguenti componenti:<br>" . (implode(", ", $errors)), APIException::$GENERIC_ERROR ); } return json_encode(["status" => "ok"]); } public function modificaComponente($id, $modifiche, $is_bulk = FALSE) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $to_update = []; $valori = []; if (!$is_bulk) $this->controllaErroriCartellino($modifiche); foreach ($modifiche as $campo => $valore) { if ($campo === "old_costo_attuale_componente" && $valore !== $modifiche["costo_attuale_componente"]) { $to_update[] = "costo_vecchio_componente = ?"; $valori[] = $valore; } else if ($campo === "tipo_applicativo_componente" && is_array($valore) && in_array("nessuna", $valore)) { throw new APIException("Non &egrave; possibile selezionare 'nessuna' insieme ad altre compatibilit&agrave;.", APIException::$GENERIC_ERROR); } else if ($campo === "tipo_applicativo_componente" && $valore === "nessuna") { $to_update[] = "$campo = ''"; } else if ($campo !== "old_costo_attuale_componente") { $val = $valore === "NULL" ? "NULL" : "?"; if ($valore !== "NULL") { if (is_array($valore)) $valore = implode(",", $valore); $valori[] = $valore; } $to_update[] = "$campo = $val"; } } if (count($to_update) === 0) throw new APIException("Non &egrave; possibile eseguire l'operazione.", APIException::$GENERIC_ERROR); $to_update = implode(", ", $to_update); $valori[] = $id; $query_bg = "UPDATE componenti_crafting SET $to_update WHERE id_componente = ?"; $this->db->doQuery($query_bg, $valori, False); $output = [ "status" => "ok" ]; return json_encode($output); } public function eliminaComponente($id) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $query_ricette = "SELECT ricette_id_ricetta FROM componenti_ricetta WHERE componenti_crafting_id_componente = ?"; $id_ricette = $this->db->doQuery($query_ricette, [$id], False); if (isset($id_ricette) && count($id_ricette) > 0) { $values = array_column($id_ricette, "ricette_id_ricetta"); $marks = str_repeat("?,", count($values) - 1) . "?"; $query_del_ricette = "DELETE FROM ricette WHERE id_ricetta IN ( $marks )"; $this->db->doQuery($query_del_ricette, $values, False); } $query_comps = "DELETE FROM componenti_crafting WHERE id_componente = ?"; $this->db->doQuery($query_comps, [$id], False); $output = [ "status" => "ok" ]; return json_encode($output); } } <file_sep>/client/app/scripts/controllers/CraftingChimicoManager.js var mobile = false; var type = ""; var id_target = ""; var batteria = 0; var volume = 0; var totaleBatteria = 0; var totaleVolume = 0; var usoBatteria = 0; var usoVolume = 0; function loadComponentsFromDB( callback ) { Utils.requestData( Constants.API_GET_COMPONENTI_BASE, "GET", { draw: 1, columns: null, order: null, start: 0, length: 999999, search: null, tipo: "chimico" }, callback ); } function pageResize() { $( "#liste_componenti" ).width( $( "#liste_componenti" ).parent().width() ); } function impostaRicercaComponenti( search_box ) { search_box.on( 'keyup', function () { var term = search_box.val().trim(); if ( term.length === 0 ) { search_box.parents( ".tab-pane" ).find( "div[draggable='true']" ).each( function () { $( this ).show( 0 ); } ); return; } else term = term.toLowerCase(); search_box.parents( ".tab-pane" ).find( "div[draggable='true']" ).each( function () { var id_comp = $( this ).find( ".id_comp" ).text().toLowerCase(), nome_comp = $( this ).find( ".nome_comp" ).text().toLowerCase(), desc_comp = $( this ).find( ".descrizione_comp" ).text().toLowerCase(), tipo_comp = $( this ).find( ".tipo_comp" ).text().toLowerCase(); if ( id_comp.indexOf( term ) === -1 && nome_comp.indexOf( term ) === -1 && desc_comp.indexOf( term ) === -1 && tipo_comp.indexOf( term ) === -1 ) $( this ).hide( 0 ); else $( this ).show( 0 ); } ); } ); } //popolo componenti $( document ).ready( function () { $( '.delete-el' ).hide(); loadComponentsFromDB( function ( data ) { //divido i componenti a seconda del tipo data = data.data; var sostanza = []; var struttura = []; var cerotto = []; var fiala = []; var solido = []; var scartati = []; for ( var i = 0; i < data.length; i++ ) { data[i].Tipo = data[i].tipo_componente; data[i].Codice = data[i].id_componente; data[i].Nome = data[i].nome_componente; data[i].Descrizione = data[i].descrizione_componente; if ( data[i].Tipo.toLowerCase() == "sostanza" ) { sostanza.push( data[i] ); } else if ( data[i].Tipo.toLowerCase() == "cerotto" ) { struttura.push( data[i] ); } else if ( data[i].Tipo.toLowerCase() == "fiala" ) { struttura.push( data[i] ); } else if ( data[i].Tipo.toLowerCase() == "solido" ) { struttura.push( data[i] ); } else { scartati.push( data[i] ); } } // ////loggo quelli scartati //console.log("elementi scartati", scartati); if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ) ) { mobile = true; } //console.log("mobile", mobile); //popolo i div popoloComponenti( sostanza, "sos", "sostanza" ); popoloComponenti( struttura, "str", "struttura" ); //popoloComponenti(cerotto, "cer", "cerotto"); //popoloComponenti(fiala, "fia", "fiala"); //popoloComponenti(solido, "sod", "solido"); impostaRicercaComponenti( $( "#cerca_sostanza" ) ); impostaRicercaComponenti( $( "#cerca_struttura" ) ); } ); $( "#liste_componenti" ).width( $( "#liste_componenti" ).parent().width() ); $( "#liste_componenti" ).css( "max-height", $( ".content-wrapper" ).height() - 41 - 51 - 20 ); $( window ).resize( pageResize ); } ); function popoloComponenti( array, id, div ) { var html = ""; array.forEach( function ( el ) { if ( mobile == false ) { html += ' <div id="' + id + '-' + el.Codice + '" class="info-box bg-aqua drag-' + el.Tipo + '" draggable="true" ondragstart="drag(event)">'; } else { html += ' <div id="' + id + '-' + el.Codice + '" class="info-box bg-aqua drag-' + el.Tipo + '" onclick="addComponente(\'' + id + '-' + el.Codice + '\',\'' + el.Tipo + '\')" data-selezionabile="1">'; } html += ' <div class="info-box-icon">'; if ( el.Tipo == "sostanza" ) { html += '<img src="images/molecule.png" class="img-responsive">'; } else if ( el.Tipo == "cerotto" ) { html += '<img src="images/plaster.png" class="img-responsive">'; } else if ( el.Tipo == "fiala" ) { html += '<img src="images/vial.png" class="img-responsive">'; } else if ( el.Tipo == "solido" ) { html += '<img src="images/salt.png" class="img-responsive">'; } html += ' </div>'; html += ' <div class="info-box-content">'; html += ' <span class="info-box-text sgc-info2"><span class="tipo_comp">' + el.Tipo + '</span> - <span class="id_comp">' + el.Codice + '</span></span>'; html += ' <span class="info-box-number nome_comp">' + el.Nome + '</span>'; html += ' <p class="descrizione_comp">' + el.Descrizione + '</p>'; html += ' </div>'; html += ' </div> '; } ); $( '#' + div + ' > .container-componenti' ).append( html ); } //drag&copy $( '.close' ).click( function () { $( '.alert-danger' ).hide(); } ); function addComponente( id, tipo ) { //mobile if ( tipo === "sostanza" ) { target = $( ".allow-sostanza" ).first(); target.removeClass( "allow-sostanza" ) if ( target.size() === 0 ) { Utils.showError( "Spazio per sostanze terminato. Eliminane una per continuare." ) return; } } else { target = $( "#biostruttura" ) if ( target.children().not( "button" ).size() > 0 ) { Utils.showError( "Spazio per biostrutture terminato. Eliminane una per continuare." ) return; } } target.find( "h1" ).first().remove(); target.append( $( "#" + id ).clone() ); target.find( ".delete-el" ).show(); } function allowDrop( ev ) { ev.preventDefault(); } function drag( ev ) { type = ""; id_target = ""; id_target = ev.target.id; ev.dataTransfer.setData( "text", id_target ); type = id_target.substring( 0, 3 ); } function drop( ev ) { ev.preventDefault(); var target = ev.target; var id_des = ""; if ( ev.target.id.substring( 0, 2 ) == "h1" ) { id_des = target.parentNode.id; target = ev.target.parentNode; } else { id_des = target.id; } var data = ev.dataTransfer.getData( "text" ); var tipo = ""; var corretto = false; if ( type == "sos" && $( '#' + id_des ).hasClass( 'allow-sostanza' ) ) { corretto = true; tipo = "sostanza"; } else if ( type == "str" && $( '#' + id_des ).hasClass( 'allow-sostanza' ) == false ) { corretto = true; tipo = "struttura"; } else if ( type == "cer" && $( '#' + id_des ).hasClass( 'allow-sostanza' ) == false ) { corretto = true; tipo = "cerotto"; } else if ( type == "fia" && $( '#' + id_des ).hasClass( 'allow-sostanza' ) == false ) { corretto = true; tipo = "fiala"; } else if ( type == "sod" && $( '#' + id_des ).hasClass( 'allow-sostanza' ) == false ) { corretto = true; tipo = "solido"; } if ( corretto ) { $( '.alert-danger' ).hide(); $( '#' + id_des + '> h1' ).remove(); target.appendChild( document.getElementById( data ).cloneNode( true ) ); $( '#' + id_des + ' .delete-el' ).show(); $( '#' + id_des ).removeAttr( 'ondragover' ); $( '#' + id_des ).removeAttr( 'ondrop' ); $( '#' + id_des ).removeAttr( 'draggable' ); } else { $( '.alert-danger' ).show(); type = ""; } } function resetBox( id ) { var html = '', is_sostanza = false; if ( id == 'principio' ) { is_sostanza = true; html += ' <button type="button" class="btn btn-info btn-xs pull-right delete-el" onclick="resetBox(\'principio\')">&times;</button> <h1 id="h1-principio" ondrop="drop(event)" ondragover="allowDrop(event)">Principio Attivo</h1>'; } else if ( id == 'sostanza1' ) { is_sostanza = true; html += ' <button type="button" class="btn btn-info btn-xs pull-right delete-el" onclick="resetBox(\'sostanza1\')">&times;</button> <h1 id="h1-sostanza1" ondrop="drop(event)" ondragover="allowDrop(event)">Sostanza #01</h1>'; } else if ( id == 'sostanza2' ) { is_sostanza = true; html += ' <button type="button" class="btn btn-info btn-xs pull-right delete-el" onclick="resetBox(\'sostanza2\')">&times;</button> <h1 id="h1-sostanza2" ondrop="drop(event)" ondragover="allowDrop(event)">Sostanza #02</h1>'; } else if ( id == 'sostanza3' ) { is_sostanza = true; html += ' <button type="button" class="btn btn-info btn-xs pull-right delete-el" onclick="resetBox(\'sostanza3\')">&times;</button> <h1 id="h1-sostanza3" ondrop="drop(event)" ondragover="allowDrop(event)">Sostanza #03</h1>'; } else if ( id == 'biostruttura' ) { html += '<button type="button" class="btn btn-info btn-xs pull-right delete-el" onclick="resetBox(\'biostruttura\')">&times;</button>'; } $( '#' + id ).html( html ); $( '#' + id ).attr( 'ondragover', 'allowDrop(event)' ); $( '#' + id ).attr( 'ondrop', 'drop(event)' ); $( '#' + id + ' .delete-el' ).hide(); if ( is_sostanza && !$( '#' + id ).hasClass( "allow-sostanza" ) ) $( '#' + id ).addClass( "allow-sostanza" ); } $( '#btn_inviaCraftingChimico' ).click( function () { var data = { pgid: JSON.parse( window.localStorage.getItem( "logged_pg" ) ).id_personaggio, nome: $( "#nome_composto" ).val() || null, struttura: $( "#biostruttura > div" ).first().attr( "id" ), principio_attivo: $( "#principio > div" ).first().attr( "id" ), satellite_1: $( "#sostanza1 > div" ).first().attr( "id" ), satellite_2: $( "#sostanza2 > div" ).first().attr( "id" ), satellite_3: $( "#sostanza3 > div" ).first().attr( "id" ) }; if ( !data.nome || Utils.soloSpazi( data.nome ) ) { Utils.showError( "Inserire un nome per l'oggetto da craftare." ); return false; } if ( !data.struttura || !data.principio_attivo || !data.satellite_1 || !data.satellite_2 || !data.satellite_3 ) { Utils.showError( "&Egrave; necessario miscelare 4 sostanze indicando la Biostruttura." ); return false; } else { data.struttura = data.struttura.replace( /^\S*?-(.*)$/, "$1" ); data.principio_attivo = data.principio_attivo.replace( /^\S*?-(.*)$/, "$1" ); data.satellite_1 = data.satellite_1.replace( /^\S*?-(.*)$/, "$1" ); data.satellite_2 = data.satellite_2.replace( /^\S*?-(.*)$/, "$1" ); data.satellite_3 = data.satellite_3.replace( /^\S*?-(.*)$/, "$1" ); } Utils.requestData( Constants.API_POST_CRAFTING_CHIMICO, "POST", data, "Sostanza registrata con successo.", null, Utils.reloadPage ); } ); <file_sep>/server/src/classes/GrantsManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT']."/"; include_once($path."classes/APIException.class.php"); include_once($path."classes/UsersManager.class.php"); include_once($path."classes/DatabaseBridge.class.php"); include_once($path."classes/Mailer.class.php"); include_once($path."classes/SessionManager.class.php"); include_once($path."classes/Utils.class.php"); include_once($path."config/constants.php"); class GrantsManager { protected $db; protected $session; protected $mailer; public function __construct() { $this->session = SessionManager::getInstance(); $this->db = new DatabaseBridge(); $this->mailer = new Mailer(); } public function __destruct() { } public function creaRuolo( $nome ) { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $query_check = "SELECT nome_ruolo FROM ruoli WHERE LOWER(nome_ruolo) = :ruolo"; $result = $this->db->doQuery($query_check,[":ruolo" => strtolower($nome)],False); if( isset($result) && count($result) > 0 ) throw new APIException("Questo ruolo esiste gi&agrave;. Inserirne uno differente."); $query_ruoli = "INSERT INTO ruoli VALUES (:ruolo)"; $this->db->doQuery($query_ruoli,[":ruolo" => $nome],False); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function eliminaRuolo( $nome, $sostituto ) { global $RUOLO_ADMIN; UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); if( $nome === $RUOLO_ADMIN ) throw new APIException("Non &egrave; possibile eliminare o modificare il ruolo di amministratore."); $query_check = "SELECT nome_ruolo FROM ruoli WHERE nome_ruolo = :ruolo"; $result = $this->db->doQuery($query_check,[":ruolo" => $nome],False); if( !isset($result) || count($result) === 0 ) throw new APIException("Questo ruolo non esiste."); $query_update = "UPDATE giocatori SET ruoli_nome_ruolo = :sostituto WHERE ruoli_nome_ruolo = :ruolo"; $this->db->doQuery($query_update,[":sostituto" => $sostituto, ":ruolo" => $nome],False); $query_ruoli = "DELETE FROM ruoli WHERE nome_ruolo = :ruolo"; $this->db->doQuery($query_ruoli,[":ruolo" => $nome],False); $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function associaPermessi( $ruolo, $grants = [] ) { global $DB_ERR_DELIMITATORE; global $MYSQL_DUPLICATE_ENTRY_ERRCODE; UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $query_perm = "SELECT grants_nome_grant FROM ruoli_has_grants WHERE ruoli_nome_ruolo = :ruolo"; $posseduti = $this->db->doQuery($query_perm, [ ":ruolo" => $ruolo ], False); $posseduti = !isset($posseduti) || count($posseduti) === 0 ? [] : Utils::mappaArrayDiArrayAssoc( $posseduti, "grants_nome_grant" ); $query_tutti = "SELECT nome_grant FROM grants"; $tutti = $this->db->doQuery($query_tutti, [ ], False); $tutti = Utils::mappaArrayDiArrayAssoc( $tutti, "nome_grant" ); $params_insert = []; $params_delete = []; foreach ( $tutti as $p ) { if ( isset($grants[$p]) && $grants[$p] === "on" && !in_array($p,$posseduti) ) $params_insert[] = [":ruolo" => $ruolo, ":grnt" => $p]; else if ( !isset($grants[$p]) && in_array($p,$posseduti) ) $params_delete[] = [":ruolo" => $ruolo, ":grnt" => $p]; } $query_insert = "INSERT INTO ruoli_has_grants VALUES (:ruolo, :grnt)"; $query_delete = "DELETE FROM ruoli_has_grants WHERE ruoli_nome_ruolo = :ruolo AND grants_nome_grant = :grnt"; try { if(count($params_insert) > 0) $this->db->doMultipleManipulations($query_insert, $params_insert, False); if(count($params_delete) > 0) $this->db->doMultipleManipulations($query_delete, $params_delete, False); } catch (Exception $e) { $code = explode($DB_ERR_DELIMITATORE, $e->getMessage())[0]; if( $code === $MYSQL_DUPLICATE_ENTRY_ERRCODE ) throw new APIException("Impossibile inserire due volte la stessa coppia ruolo -> permesso.", APIException::$DATABASE_ERROR); else throw $e; } $output = [ "status" => "ok", "result" => True ]; return json_encode($output); } public function recuperaRuoli() { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $query_ruoli = "SELECT ru.nome_ruolo, COUNT(rhg.grants_nome_grant) AS numero_grants FROM ruoli AS ru LEFT OUTER JOIN ruoli_has_grants AS rhg ON rhg.ruoli_nome_ruolo = ru.nome_ruolo GROUP BY ru.nome_ruolo ORDER BY ru.nome_ruolo ASC"; $ruoli = $this->db->doQuery($query_ruoli,[],False); $output = [ "status" => "ok", "result" => $ruoli ]; return json_encode($output); } public function recuperaListaPermessi() { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $query_grants = "SELECT nome_grant, descrizione_grant FROM grants"; $grants = $this->db->doQuery($query_grants,[],False); $output = [ "status" => "ok", "result" => $grants ]; return json_encode($output); } public function recuperaPermessiDeiRuoli() { UsersManager::operazionePossibile( $this->session, __FUNCTION__ ); $query_ruoli = "SELECT * FROM ruoli_has_grants"; $ruoli = $this->db->doQuery($query_ruoli,[],False); $result = []; if( count($ruoli) > 0 ) { foreach ($ruoli as $r) { if( !isset($result[ $r["ruoli_nome_ruolo"] ]) ) $result[ $r["ruoli_nome_ruolo"] ] = []; $result[ $r["ruoli_nome_ruolo"] ][] = $r["grants_nome_grant"]; } } $output = [ "status" => "ok", "result" => $result ]; return json_encode($output); } } <file_sep>/data/db_componenti_bulk_edit.sql ALTER TABLE `ricette` ADD COLUMN `in_ravshop_ricetta` TINYINT(1) NULL, ADD COLUMN `costo_attuale_ricetta` VARCHAR(45) NULL, ADD COLUMN `disponibilita_ravshop_ricetta` INT(255) NULL AFTER `extra_cartellino_ricetta`; ALTER TABLE `componenti_crafting` ADD COLUMN `visibile_ravshop_componente` VARCHAR(45) NULL AFTER `tipo_applicativo_componente`; UPDATE `grants` SET `nome_grant`='recuperaComponentiAvanzato' WHERE `nome_grant`='recuperaComponentiAvanzata'; INSERT INTO `grants` (`nome_grant`, `descrizione_grant`) VALUES ('recuperaModelli', 'L\'utente può recuperare i modelli di cartellini dal database'); INSERT INTO `ruoli_has_grants` (`ruoli_nome_ruolo`, `grants_nome_grant`) VALUES ('admin', 'recuperaModelli'); INSERT INTO `ruoli_has_grants` (`ruoli_nome_ruolo`, `grants_nome_grant`) VALUES ('staff', 'recuperaModelli'); INSERT INTO `grants` (`nome_grant`, `descrizione_grant`) VALUES ('inserisciComponente', 'L\'utente può inserire un nuovo componente crafting all\'interno del database.'); INSERT INTO `ruoli_has_grants` (`ruoli_nome_ruolo`, `grants_nome_grant`) VALUES ('admin', 'inserisciComponente'); CREATE TABLE `cartellini` ( `id_cartellino` int(11) NOT NULL AUTO_INCREMENT, `data_creazione_cartellino` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `tipo_cartellino` varchar(255) NOT NULL, `titolo_cartellino` varchar(255) NOT NULL, `descrizione_cartellino` text NOT NULL, `icona_cartellino` varchar(255) DEFAULT NULL, `testata_cartellino` varchar(255) DEFAULT NULL, `piepagina_cartellino` varchar(255) DEFAULT NULL, `costo_attuale_ravshop_cartellino` int(255) DEFAULT NULL, `costo_vecchio_ravshop_cartellino` int(255) DEFAULT NULL, `approvato_cartellino` tinyint(4) NOT NULL DEFAULT '0', `nome_modello_cartellino` varchar(255) DEFAULT NULL, `attenzione_cartellino` tinyint(4) NOT NULL DEFAULT '0', `creatore_cartellino` varchar(255) NOT NULL DEFAULT '<EMAIL>', PRIMARY KEY (`id_cartellino`) ) ENGINE=InnoDB AUTO_INCREMENT=212 DEFAULT CHARSET=latin1; CREATE TABLE `cartellino_has_etichette` ( `cartellini_id_cartellino` int(11) NOT NULL, `etichetta` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`cartellini_id_cartellino`,`etichetta`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;<file_sep>/client/app/scripts/controllers/PrintSignedTable.js var PrintSignedTable = function () { return { init: function () { this.setListeners(); this.recuperaInfoIscritti(); }, ordinaDati: function(a, b) { var A = a.nome_completo.toUpperCase(), B = b.nome_completo.toUpperCase(); if (A < B) return -1; if (A > B) return 1; return 0; }, riempiTabella: function ( data ) { var pgs = data.data; pgs = pgs.sort(this.ordinaDati); for( var i in pgs ) { if( pgs[i] ) { var tr = $("<tr></tr>"); tr.append( $("<td></td>").html( "&#9744;" ) ); tr.append( $("<td></td>").text( pgs[i].nome_completo ) ); tr.append( $("<td></td>").text( pgs[i].personaggi_id_personaggio ) ); tr.append( $("<td></td>").text( pgs[i].nome_personaggio ) ); tr.append( $("<td></td>").html( pgs[i].pagato_iscrizione === "1" ? "&#9745;" : "&#9744;" ) ); tr.append( $("<td></td>").text( pgs[i].tipo_pagamento_iscrizione ) ); tr.append( $("<td></td>").html( !pgs[i].note_iscrizione ? "" : pgs[i].note_iscrizione ) ); tr.append( $("<td></td>").html( !pgs[i].note_giocatore ? "" : pgs[i].note_giocatore ) ); $("#info_iscritti").find("tbody").append(tr); } } for( var j = 0; j < 5; j++ ) { var tr = $("<tr></tr>"); tr.append( $("<td></td>").html( "&#9744;" ) ); tr.append( $("<td></td>").html("&nbsp;") ); tr.append( $("<td></td>").html("&nbsp;") ); tr.append( $("<td></td>").html("&nbsp;") ); tr.append( $("<td></td>").html( "&#9744;" ) ); tr.append( $("<td></td>").html("&nbsp;") ); tr.append( $("<td></td>").html("&nbsp;") ); tr.append( $("<td></td>").html("&nbsp;") ); $("#info_iscritti").find("tbody").append(tr); } }, recuperaInfoIscritti: function () { Utils.requestData( Constants.API_GET_INFO_ISCRITTI_AVANZATE, "GET", "draw=1&columns=&order=&start=0&length=999&search=&quando=prossimo", this.riempiTabella.bind(this) ); }, setListeners: function () { } } }(); $(function () { PrintSignedTable.init(); }); <file_sep>/client/app/scripts/controllers/CartelliniManager.js var CartelliniManager = ( function () { return { init: function () { this.cartellini_selezionati = {}; this.tabella_cartellini = {}; this.tag_search = $( "#searchTags" ); for ( var t in Constants.MAPPA_TIPI_CARTELLINI ) this.cartellini_selezionati[t] = {}; this.setListeners(); this.setTableSearch(); this.impostaTabella(); }, resettaContatori: function ( e ) { for ( var c in this.cartellini_selezionati ) this.cartellini_selezionati[c] = {}; window.localStorage.removeItem( "cartellini_da_stampare" ); this.tabella_cartellini.find( "input[type='number']" ).val( 0 ); }, stampaCartellini: function ( e ) { var cartellini = this.cartellini_selezionati; if ( Object.keys( cartellini ).length === 0 ) { Utils.showError( "Non è stato selezionato nessun cartellino da stampare." ); return false; } window.localStorage.removeItem( "cartellini_da_stampare" ); window.localStorage.setItem( "cartellini_da_stampare", JSON.stringify( cartellini ) ); window.open( Constants.STAMPA_CARTELLINI_PAGE, "Stampa Cartellini" ); }, cartellinoSelezionato: function ( e ) { var t = $( e.target ), num = parseInt( t.val(), 10 ), dati = this.tabella_cartellini.row( t.parents( "tr" ) ).data(); if ( parseInt( dati.approvato_cartellino, 10 ) === 0 ) { Utils.showError( "Non &egrave; possibile stampare questo cartellino in quanto non &egrave; stato approvato." ); t.val( 0 ); delete this.cartellini_selezionati[dati.tipo_cartellino][dati.id_cartellino]; return false; } if ( num > 0 ) this.cartellini_selezionati[dati.tipo_cartellino][dati.id_cartellino] = num; else delete this.cartellini_selezionati[dati.tipo_cartellino][dati.id_cartellino]; }, selezionaCartellino: function ( e ) { $( "input[type='number']" ).val( 0 ); for ( var t in this.cartellini_selezionati ) for ( var c in this.cartellini_selezionati[t] ) $( "#ck_" + c ).val( this.cartellini_selezionati[t][c] ); }, renderAzioni: function ( data, type, row ) { var pulsanti = ""; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default modifica' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Modifica Cartellino'><i class='fa fa-pencil'></i></button>"; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default elimina' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Elimina Cartellino'><i class='fa fa-trash-o'></i></button>"; return pulsanti; }, renderCheckStampa: function ( data, type, row ) { return ( '<div class="input-group">' + "<input type='number' min='0' step='1' value='0' class='form-control' style='width:70px' id='ck_" + row.id_cartellino + "'>" + "</div>" ); }, renderCosto: function ( data, type, row ) { var testo = !isNaN( parseInt( data ) ) ? data : "Non acquistabile"; return testo; }, renderSiNo: function ( data, type, row ) { var testo = parseInt( data, 10 ) === 1 ? "S&igrave;" : "No"; return testo; }, renderTipo: function ( data, type, row ) { return Constants.MAPPA_TIPI_CARTELLINI[data].nome + " (" + Constants.MAPPA_TIPI_CARTELLINI[data].colore + ")"; }, renderCartellino: function ( data, type, row ) { var c = $( "#cartellino_template" ).clone(), tag_contianer = $( "<div>" ).addClass( "tag-container" ); c.attr( "id", null ); c.removeClass( "template" ); if ( row.icona_cartellino === null ) { c.find( ".icona_cartellino" ) .parent() .remove(); c.find( ".titolo_cartellino" ).height( "80%" ); } for ( var r in row ) { if ( c.find( "." + r ).length !== 0 && row[r] !== null ) { if ( r === "icona_cartellino" ) c.find( "." + r ).html( "<i class='fa " + row[r] + "'></i>" ); else c.find( "." + r ).html( row[r] ); } } if ( row.etichette_cartellino ) { var tags = row.etichette_cartellino.split( "," ); for ( var t in tags ) tag_contianer.append( $( "<span>" ).addClass( "tag label label-info" ).text( tags[t] ) ).append( "&nbsp;" ); } if ( parseInt( row.attenzione_cartellino, 10 ) === 1 ) c.append( "<div class='attenzione'><i class='fa fa-warning'></i></div>" ); return c[0].outerHTML + tag_contianer[0].outerHTML; }, cartellinoEliminato: function () { this.tabella_cartellini.ajax.reload( null, false ) CartelliniCreator.recuperaModelli(); }, eliminaCartellino: function ( id ) { Utils.requestData( Constants.API_POST_DEL_CARTELLINO, "POST", { id: id }, "Cartellino eliminato con successo.", null, this.cartellinoEliminato.bind( this ) ); }, mostraConfermaElimina: function ( e ) { var t = $( e.currentTarget ), dati = this.tabella_cartellini.row( t.parents( "tr" ) ).data(); Utils.showConfirm( "Sicuro di voler eliminare il cartellino <strong>" + dati.titolo_cartellino + "</strong>?", this.eliminaCartellino.bind( this, dati.id_cartellino ), true ); }, mostraModalModifica: function ( e ) { var t = $( e.currentTarget ), dati = this.tabella_cartellini.row( t.parents( "tr" ) ).data(); CartelliniCreator.mostraModalFormCartellino( dati ); }, cercaEtichetta: function ( e ) { var t = $( e.currentTarget ); console.log( t.text() ); this.tag_search.tagsinput( "add", t.text() ) }, setGridListeners: function () { AdminLTEManager.controllaPermessi(); $( "td [data-toggle='popover']" ).popover( "destroy" ); $( "td [data-toggle='popover']" ).popover(); $( "[data-toggle='tooltip']" ).tooltip( "destroy" ); $( "[data-toggle='tooltip']" ).tooltip(); $( "td > button.modifica" ).unbind( "click" ); $( "td > button.modifica" ).click( this.mostraModalModifica.bind( this ) ); $( "td > button.elimina" ).unbind( "click" ); $( "td > button.elimina" ).click( this.mostraConfermaElimina.bind( this ) ); $( "td > button.stampa-cartellino" ).unbind( "click" ); $( "td > button.stampa-cartellino" ).click( this.stampaCartellini.bind( this ) ); $( "td .tag.label.label-info" ).unbind( "click" ); $( "td .tag.label.label-info" ).click( this.cercaEtichetta.bind( this ) ); $( 'input[type="number"]' ).unbind( "change" ); $( 'input[type="number"]' ).on( "change", this.cartellinoSelezionato.bind( this ) ); this.selezionaCartellino(); }, erroreDataTable: function ( e, settings ) { if ( !settings.jqXHR || !settings.jqXHR.responseText ) { console.log( "DataTable error:", e, settings ); return false; } var real_error = settings.jqXHR.responseText.replace( /^([\S\s]*?)\{"[\S\s]*/i, "$1" ); real_error = real_error.replace( "\n", "<br>" ); Utils.showError( real_error ); }, impostaTabella: function () { var columns = []; columns.push( { title: "Stampa", render: this.renderCheckStampa.bind( this ) } ); columns.push( { title: "ID", data: "id_cartellino" } ); columns.push( { title: "Cartellino", render: this.renderCartellino.bind( this ), orderable: false } ); columns.push( { title: "Data Creazione", data: "data_creazione_cartellino" } ); columns.push( { title: "Creatore", data: "nome_creatore_cartellino" } ); columns.push( { title: "Tipo", data: "tipo_cartellino", render: this.renderTipo.bind( this ) } ); columns.push( { title: "Approvato", data: "approvato_cartellino", render: this.renderSiNo.bind( this ) } ); columns.push( { title: "Azioni", render: this.renderAzioni.bind( this ), orderable: false } ); this.tabella_cartellini = $( "#tabella_cartellini" ) .on( "error.dt", this.erroreDataTable.bind( this ) ) .on( "draw.dt", this.setGridListeners.bind( this ) ) .DataTable( { ajax: function ( data, callback ) { var campi_nascosti = [ "titolo_cartellino", "testata_cartellino", "piepagina_cartellino", "descrizione_cartellino", "icona_cartellino", "nome_modello_cartellino", "attenzione_cartellino" ]; for ( var c in campi_nascosti ) data.columns.push( { data: campi_nascosti[c], name: "", searchable: true, orderable: false, search: { regex: false, value: "" } } ); data.etichette = this.tag_search.val() !== "" ? this.tag_search.val().split( "," ) : []; Utils.requestData( Constants.API_GET_CARTELLINI, "GET", data, callback ); }.bind( this ), columns: columns, order: [[1, "desc"]] } ); }, setTableSearch: function () { }, tagItemAggiunto: function ( ev ) { setTimeout( function () { $( '.bootstrap-tagsinput :input' ).val( '' ); if ( this.tabella_cartellini ) this.tabella_cartellini.draw(); }.bind( this ), 0 ); }, setTagsInput: function () { this.tag_search.tagsinput( { typeahead: { source: function ( query ) { return $.get( { url: Constants.API_GET_TAGS, xhrFields: { withCredentials: true } } ); } }, cancelConfirmKeysOnEmpty: true, freeInput: false } ); this.tag_search.on( 'itemAdded', this.tagItemAggiunto.bind( this ) ); this.tag_search.on( 'itemRemoved', this.tagItemAggiunto.bind( this ) ); }, setListeners: function () { $( "#btn_stampaCartellini" ).click( this.stampaCartellini.bind( this ) ); $( "#btn_resettaContatori" ).click( this.resettaContatori.bind( this ) ); this.setTagsInput(); } }; } )(); $( function () { CartelliniManager.init(); } ); <file_sep>/server/src/classes/RumorsManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class RumorsManager { protected $db; protected $grants; protected $session; public function __construct() { $this->db = new DatabaseBridge(); $this->session = SessionManager::getInstance(); } private function controllaErrori($luogo_ig, $testo, $data_ig, $data_pubblicazione, $ora_pubblicazione, $is_bozza) { $error = ""; if ($is_bozza === True) return ""; if (!isset($luogo_ig) || Utils::soloSpazi($luogo_ig)) $error .= "<li>Il campo Luogo IG non pu&ograve; essere lasciato vuoto.</li>"; if (!isset($testo) || Utils::soloSpazi($testo)) $error .= "<li>Il testo del rumor non pu&ograve; essere lasciato vuoto.</li>"; if (!isset($data_ig) || Utils::soloSpazi($data_ig)) $error .= "<li>Il campo Data IG non pu&ograve; essere lasciato vuoto.</li>"; if (!isset($data_pubblicazione) || Utils::soloSpazi($data_pubblicazione)) $error .= "<li>Il campo Data di Pubblicazione non pu&ograve; essere lasciato vuoto.</li>"; else $d_inizio = DateTime::createFromFormat("d/m/Y", $data_pubblicazione); if (!isset($ora_pubblicazione) || Utils::soloSpazi($ora_pubblicazione)) $error .= "<li>Il campo Ora di Pubblicazione non pu&ograve; essere lasciato vuoto.</li>"; return $error; } public function inserisciRumor($luogo_ig, $testo, $data_ig, $data_pubblicazione, $ora_pubblicazione, $is_bozza, $id_evento = NULL) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $errori = $this->controllaErrori($luogo_ig, $testo, $data_ig, $data_pubblicazione, $ora_pubblicazione, $is_bozza); if (!empty($errori)) throw new APIException("Sono stati rilevati i seguenti errori:<ul>" . $errori . "</ul>"); $params = [ ":luogo_ig" => $luogo_ig, ":testo" => $testo, ":data_ig" => $data_ig, ":is_bozza" => $is_bozza == "true" ? 1 : 0, ":creatore" => $this->session->email_giocatore, ":data_crea" => (new DateTime())->format("Y-m-d H:i:s") ]; $id_evento_pl = "NULL"; $data_pubb = "NULL"; $ora_pubb = "NULL"; if (!empty($data_pubblicazione)) { $dt_pubb = DateTime::createFromFormat("d/m/Y H:i", $data_pubblicazione." ".$ora_pubblicazione); if((new DateTime()) > $dt_pubb) { throw new APIException("La data e l'ora di pubblicazione non possono essere già passate."); } $data_pubb = ":data_pubb"; $params[":data_pubb"] = DateTime::createFromFormat("d/m/Y", $data_pubblicazione)->format("Y-m-d"); $ora_pubb = ":ora_pubb"; $params[":ora_pubb"] = $ora_pubblicazione . ":00"; } if (!is_null($id_evento) && !empty($id_evento)) { $id_evento_pl = ":id_evento"; $params[":id_evento"] = $id_evento; } $query_ins = "INSERT INTO rumors (luogo_ig_rumor,testo_rumor,data_ig_rumor,data_pubblicazione_rumor,ora_pubblicazione_rumor,eventi_id_evento,is_bozza_rumor,creatore_rumor, data_creazione) VALUES (:luogo_ig, :testo, :data_ig, $data_pubb, $ora_pubb, $id_evento_pl, :is_bozza, :creatore, :data_crea)"; $this->db->doQuery($query_ins, $params, False); return json_encode(["status" => "ok", "result" => "true"]); } public function modificaRumor($id, $luogo_ig, $testo, $data_ig, $data_pubblicazione, $ora_pubblicazione, $is_bozza, $id_evento = NULL) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $this->session->email_giocatore); $query_sel = "SELECT data_pubblicazione_rumor, ora_pubblicazione_rumor, is_bozza_rumor FROM rumors WHERE id_rumor = :id"; $rumor = $this->db->doQuery($query_sel, [":id" => $id], False); if (count($rumor) == 0) { throw new APIException("Nessun rumor trovato con l'id inviato"); } $pubblicazione_rumor = DateTime::createFromFormat("Y-m-d H:i:s", $rumor[0]["data_pubblicazione_rumor"]." ".$rumor[0]["ora_pubblicazione_rumor"]); if((new DateTime()) > $pubblicazione_rumor && $rumor[0]["is_bozza_rumor"] !== "1") { throw new APIException("Non &egrave; possibile modificare un rumor gi&agrave; pubblicato."); } $errori = $this->controllaErrori($luogo_ig, $testo, $data_ig, $data_pubblicazione, $ora_pubblicazione, $is_bozza); if (!empty($errori)) throw new APIException("Sono stati rilevati i seguenti errori:<ul>" . $errori . "</ul>"); $params = [ ":id" => $id, ":luogo_ig" => $luogo_ig, ":testo" => $testo, ":data_ig" => $data_ig, ":is_bozza" => $is_bozza == "true" ? 1 : 0, ]; $id_evento_pl = "NULL"; $data_pubb = "NULL"; $ora_pubb = "NULL"; if (!empty($data_pubblicazione)) { $dt_pubb = DateTime::createFromFormat("d/m/Y H:i", $data_pubblicazione." ".$ora_pubblicazione); if((new DateTime()) > $dt_pubb) { throw new APIException("La data e l'ora di pubblicazione non possono essere già passate."); } $data_pubb = ":data_pubb"; $params[":data_pubb"] = $dt_pubb->format("Y-m-d"); $ora_pubb = ":ora_pubb"; $params[":ora_pubb"] = $ora_pubblicazione . ":00"; } if (!is_null($id_evento) && !empty($id_evento)) { $id_evento_pl = ":id_evento"; $params[":id_evento"] = $id_evento; } $query_mod = "UPDATE rumors SET luogo_ig_rumor = :luogo_ig, testo_rumor = :testo, data_ig_rumor = :data_ig, data_pubblicazione_rumor = $data_pubb, ora_pubblicazione_rumor = $ora_pubb, is_bozza_rumor = :is_bozza, eventi_id_evento = $id_evento_pl WHERE id_rumor = :id"; $this->db->doQuery($query_mod, $params, False); return json_encode(["status" => "ok", "result" => "true"]); } public function approvaRumor($id, $approvato) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $this->session->email_giocatore); $query_pt = "UPDATE rumors SET approvato_rumor = :approvato WHERE id_rumor = :id"; $this->db->doQuery($query_pt, [":approvato" => $approvato ? 1 : 0, ":id" => $id], False); return json_encode(["status" => "ok", "result" => "true"]); } public function recuperaListaRumors($draw, $columns, $order, $start, $length, $search) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $filter = False; $params = []; if (isset($order)) { $sorting = array(); foreach ($order as $elem) $sorting[] = $columns[$elem["column"]]["data"] . " " . $elem["dir"]; $order_str = "ORDER BY " . implode(",", $sorting); } $query_sel = "SELECT r.*, DATE_FORMAT(r.data_pubblicazione_rumor,'%d/%m/%Y') data_pubb_formattata, ev.titolo_evento, CONCAT(gi.nome_giocatore,' ',gi.cognome_giocatore) AS nome_completo FROM rumors AS r JOIN giocatori AS gi ON gi.email_giocatore = r.creatore_rumor LEFT JOIN eventi AS ev ON ev.id_evento = r.eventi_id_evento $order_str"; $risultati = $this->db->doQuery($query_sel, $params, False); $output = Utils::filterDataTableResults($draw, $columns, $order, $start, $length, $search, $risultati); return json_encode($output); } public function eliminaRumor($id) { UsersManager::operazionePossibile($this->session, __FUNCTION__, $this->session->email_giocatore); $query_sel = "SELECT data_pubblicazione_rumor, ora_pubblicazione_rumor FROM rumors WHERE id_rumor = :id"; $rumor = $this->db->doQuery($query_sel, [":id" => $id], False); if (count($rumor) == 0) { throw new APIException("Nessun rumor trovato con l'id inviato"); } $pubblicazione_rumor = DateTime::createFromFormat("Y-m-d H:i:s", $rumor[0]["data_pubblicazione_rumor"]." ".$rumor[0]["ora_pubblicazione_rumor"]); if((new DateTime()) > $pubblicazione_rumor) { throw new APIException("Non &egrave; possibile eliminare un rumor gi&agrave; pubblicato."); } $query_del = "DELETE FROM rumors WHERE id_rumor = :id"; $this->db->doQuery($query_del, [":id" => $id], False); return json_encode(["status" => "ok", "result" => true]); } public function recuperaListaRumorsPublic($id_evento, $id_tornata) { $query_sel = "SELECT r.*, DATE_FORMAT(r.data_pubblicazione_rumor,'%d/%m/%Y') data_pubb_formattata, ev.id_evento, ev.titolo_evento FROM rumors AS r JOIN eventi AS ev ON ev.id_evento = r.eventi_id_evento WHERE eventi_id_evento = :id AND r.is_bozza_rumor = 0 AND CAST(CONCAT(r.data_pubblicazione_rumor,' ',r.ora_pubblicazione_rumor) as DATETIME) <= now() ORDER BY r.eventi_id_evento ASC, r.data_pubblicazione_rumor ASC, r.ora_pubblicazione_rumor ASC, r.id_rumor ASC"; $risultati = $this->db->doQuery($query_sel, [":id" => $id_evento], False); $eventi = []; foreach($risultati as $row) { $datastr = $row["data_pubblicazione_rumor"]."T".$row["ora_pubblicazione_rumor"]; $eventi[$row["titolo_evento"]][$datastr][] = $row; } return json_encode(["status" => "ok", "result" => $eventi]); } } <file_sep>/client/app/scripts/models/EventSigning.js var EventSigning = ( function EventSigning() { return { init: function () { this.user_info = JSON.parse( window.localStorage.getItem( "user" ) ); this.modal = $( "#modal_iscrivi_pg" ); this.setListeners(); }, showModal: function ( pgs ) { this.modal.find( "#note" ).val( "" ); this.modal.find( "#pagato" ).prop( "checked", false ); this.modal.find( "#personaggio" ).html( "" ); if ( pgs ) this.creaListaPG( pgs ); else this.recuperaPg(); this.modal.modal( { drop: "static" } ); }, creaListaPG: function ( pgs ) { var elems = pgs.reduce( function ( pre, ora ) { return pre + "<option value=\"" + ora.id_personaggio + "\">" + ora.nome_personaggio + "</option>" }, "" ); this.modal.find( "#personaggio" ).append( elems ); }, mandaIscrizione: function () { Utils.requestData( Constants.API_POST_ISCRIZIONE, "POST", { id_pg: this.modal.find( "#personaggio" ).val(), pagato: this.modal.find( "#pagato" ).is( ":checked" ) ? 1 : 0, tipo_pag: this.modal.find( "#metodo_pagamento" ).val(), note: this.modal.find( "#note" ).val() }, "Personaggio iscritto con successo.", null, Utils.reloadPage ); }, salvaListaPG: function ( d ) { this.creaListaPG( d.result || d.data ); }, recuperaPg: function () { var url = Constants.API_GET_PGS_PROPRI; if ( Utils.controllaPermessiPg( this.user_info, ["iscriviPg_altri"] ) ) url = Constants.API_GET_PGS; Utils.requestData( url, "GET", "draw=1&columns[0][data]=id_personaggio&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=nome_giocatore&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=nome_personaggio&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&columns[2][search][regex]=false&order[0][column]=0&order[0][dir]=desc&start=0&length=10&search[value]=&search[regex]=false", this.salvaListaPG.bind( this ) ); }, setListeners: function () { this.modal.find( 'input[type="checkbox"]' ).iCheck( { checkboxClass: 'icheckbox_square-blue' } ); this.modal.find( "#btn_iscrivi" ).click( this.mandaIscrizione.bind( this ) ); } }; } )(); $( function () { EventSigning.init(); } )<file_sep>/client/app/scripts/eg/all-eg.js /** * ZERG */ var z; var tm; cheet('z e r g',function(){ //start the zegrush //all divs has to be targets $('.content-wrapper div').addClass('target'); $('.content-wrapper section').addClass('target'); if(!z){ tm = setTimeout(function(){ alert('sei stato assimilato!'); window.location.reload(); },20*1000); z = new ZergRush(10); } }); cheet('s t o p',function(){ $('.target').removeClass('target'); if(z){ clearTimeout(tm); z.destroy(); z = null; alert('ci è mancato un soffio!'); //window.location.reload(); } }); /** * MATRIX */ var int; cheet('b l u e p i l l',function(){ if(int){ clearInterval(int); } alert("pillola blu o rossa?"); $('.matrixC').remove(); }); cheet('m a t r i x',function(){ $('<canvas class="matrixC"></canvas>').appendTo(document.body); var c = $(".matrixC")[0]; var ctx = c.getContext("2d"); c.height = window.innerHeight; c.width = window.innerWidth; var chinese = "田由甲申甴电甶男甸甹町画甼甽甾甿畀畁畂畃畄畅畆畇畈畉畊畋界畍畎畏畐畑"; chinese = chinese.split(""); var font_size = 10; var columns = c.width/font_size; //number of columns for the rain var drops = []; for(var x = 0; x < columns; x++) drops[x] = 1; function draw() { ctx.fillStyle = "rgba(0, 0, 0, 0.05)"; ctx.fillRect(0, 0, c.width, c.height); ctx.fillStyle = "#0F0"; //green text ctx.font = font_size + "px arial"; for(var i = 0; i < drops.length; i++) { var text = chinese[Math.floor(Math.random()*chinese.length)]; ctx.fillText(text, i*font_size, drops[i]*font_size); if(drops[i]*font_size > c.height && Math.random() > 0.975) drops[i] = 0; drops[i]++; } } int = setInterval(draw, 33); setTimeout(function() { clearInterval(int); alert("pillola blu o rossa?"); $('.matrixC').remove(); },20*1000); }); /** * <NAME> */ cheet('g o d b l e s s t h e q u e e n',function(){ alert("C'è mancato poco ..."); $('.bsod').remove(); }); cheet('b s o d',function(){ $('<div class="bsod"></div>').appendTo(document.body); var testo = `<h1>RAVnet ERROR</h1><br><br><br><p>S&igrave; &egrave; verificato un errore irreversibile si RAV.NET in 0228:STR000SYNAP7 il mondo verr&agrave; terminato.<br> * Digitare "GODBLESSTHEQUEEN" entro 20 secondi per salvare il mondo<br> * Oppure prendere contemporaneamente SPAZIO + TRINAGOLO + R1 + L1 + FRECCIA SU </p>`; $('.bsod').html(testo); setTimeout(function() { alert("I tuoi riflessi estinguerebbero il genere umano ..."); $('.bsod').remove(); },20*1000); }); <file_sep>/client/app/scripts/controllers/PlayersManager.js var PgListManager = function () { return { init: function () { this.recuperaDatiLocali(); this.creaDataTable(); }, controllaCampi: function () { var errors = "", nome = $("#modal_modifica_giocatore").find("#nome_giocatore").val(), cognome = $("#modal_modifica_giocatore").find("#cognome_giocatore").val(), mail = $("#modal_modifica_giocatore").find("#email_giocatore").val(); if ( nome === "" || Utils.soloSpazi(nome) ) errors += "<li>Il campo Nome non pu&ograve; essere vuoto.</li>"; if ( cognome === "" || Utils.soloSpazi(cognome) ) errors += "<li>Il campo Cognome non pu&ograve; essere vuoto.</li>"; if ( mail === "" || Utils.soloSpazi(mail) ) errors += "<li>Il campo Mail non pu&ograve; essere vuoto.</li>"; else if ( !Utils.controllaMail(mail) ) errors += "<li>Il campo Mail contiene un indirizzo non valido.</li>"; //if( !condizioni ) // errors += "Accettare i termini e le condizioni &egrave; obbligatorio."; return errors; }, onDatiGiocatoreInviati: function ( mail_utente_cambiata ) { if( mail_utente_cambiata ) { Utils.showMessage("Dal momento che la tua mail è cambiata verrai disconnesso.",AdminLTEManager.logout); return; } this.player_grid.ajax.reload(null,false); }, inviaModificheGiocatore: function ( id_gioc ) { var errors = this.controllaCampi(); if( errors !== "" ) { Utils.showError("Sono stati rilevati i seguenti errori:<ul>" + errors + "</ul>"); return; } var nome = $("#modal_modifica_giocatore").find("#nome_giocatore").val(), cognome = $("#modal_modifica_giocatore").find("#cognome_giocatore").val(), mail = $("#modal_modifica_giocatore").find("#email_giocatore").val(), ruolo = $("#modal_modifica_giocatore").find("#ruolo_giocatore").val(), note = encodeURIComponent( Utils.stripHMTLTag( $("#modal_modifica_giocatore").find("#note_master_giocatore").val()).replace(/\n/g,"<br>") ), dati = { modifiche: { email_giocatore: mail, nome_giocatore: nome, cognome_giocatore: cognome, ruoli_nome_ruolo: ruolo, note_staff_giocatore: note }, id : id_gioc }; Utils.requestData( Constants.API_POST_MOD_GIOCATORE, "POST", dati, "Modifiche apportate con successo", null, this.onDatiGiocatoreInviati.bind(this, id_gioc === this.user_info.email_giocatore && mail !== this.user_info.email_giocatore ) ); }, mostraModalDatiGiocatore: function ( e ) { var t = $(e.target), dati = this.player_grid.row( t.parents('tr') ).data(), note = Utils.unStripHMTLTag( decodeURIComponent( dati.note_staff_giocatore )).replace(/<br>/g,"\r"), note = note === "null" ? "" : note; $("#modal_modifica_giocatore").find("#email_giocatore").val(dati.email_giocatore); $("#modal_modifica_giocatore").find("#nome_giocatore").val(dati.nome_giocatore); $("#modal_modifica_giocatore").find("#cognome_giocatore").val(dati.cognome_giocatore); $("#modal_modifica_giocatore").find("#ruolo_giocatore").val(dati.ruoli_nome_ruolo); $("#modal_modifica_giocatore").find("#note_master_giocatore").val( note ); $("#modal_modifica_giocatore").find("#btn_invia_modifiche_giocatore").unbind("click"); $("#modal_modifica_giocatore").find("#btn_invia_modifiche_giocatore").click(this.inviaModificheGiocatore.bind(this,dati.email_giocatore)); $("#modal_modifica_giocatore").modal({drop:"static"}); }, eliminaGiocatore: function ( id ) { Utils.requestData( Constants.API_DEL_GIOCATORE, "GET", { id: id }, "Giocatore eliminato con successo.", null, this.player_grid.ajax.reload.bind(this,null,false) ); }, confermaEliminaGiocatore: function ( e ) { var target = $(e.target); Utils.showConfirm("Sicuro di voler eliminare questo giocatore?", this.eliminaGiocatore.bind(this, target.attr("data-id"))); }, scriviMessaggio: function ( e ) { var target = $(e.target); window.localStorage.setItem("scrivi_a",JSON.stringify( {id: target.attr("data-id"), nome: target.attr("data-nome") } ) ); window.location.href = Constants.MESSAGGI_PAGE; }, setGridListeners: function () { AdminLTEManager.controllaPermessi(); $( "td [data-toggle='popover']" ).popover("destroy"); $( "td [data-toggle='popover']" ).popover(); $( "[data-toggle='tooltip']" ).removeData('tooltip').unbind().next('div.tooltip').remove(); $( "[data-toggle='tooltip']" ).tooltip(); $("button.scrivi-messaggio").unbind( "click", this.scriviMessaggio.bind(this) ); $("button.scrivi-messaggio").click( this.scriviMessaggio.bind(this) ); $("button.modificaGiocatore").unbind( "click", this.mostraModalDatiGiocatore.bind(this) ); $("button.modificaGiocatore").click( this.mostraModalDatiGiocatore.bind(this) ); $("button.eliminaGiocatore").unbind( "click", this.confermaEliminaGiocatore.bind(this) ); $("button.eliminaGiocatore").click( this.confermaEliminaGiocatore.bind(this) ); }, erroreDataTable: function ( e, settings ) { if( !settings.jqXHR.responseText ) return false; var real_error = settings.jqXHR.responseText.replace(/^([\S\s]*?)\{"[\S\s]*/i,"$1"); real_error = real_error.replace("\n","<br>"); Utils.showError(real_error); }, formattaNomePg: function (data, type, row) { return data+" <button type='button' " + "class='btn btn-xs btn-default pull-right pg-login-btn' " + "data-id='"+row.id_personaggio+"' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Logga PG'><i class='fa fa-sign-in'></i></button>"; }, renderizzaNoteStaff: function (data, type, row) { var denc_data = Utils.unStripHMTLTag( decodeURIComponent(data) ); denc_data = denc_data === "null" ? "" : denc_data; return $.fn.dataTable.render.ellipsis( 20, false, true, true )(denc_data, type, row); }, creaPulsantiAzioni: function (data, type, row) { var pulsanti = "", permessi_modifica = ["modificaUtente_note_staff_giocatore_altri", "modificaUtente_note_staff_giocatore_proprio", "modificaUtente_email_giocatore_altri", "modificaUtente_email_giocatore_proprio", "modificaUtente_nome_giocatore_altri", "modificaUtente_nome_giocatore_proprio", "modificaUtente_cognome_giocatore_altri", "modificaUtente_cognome_giocatore_proprio", "modificaUtente_ruoli_nome_ruolo_altri", "modificaUtente_ruoli_nome_ruolo_proprio"]; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default scrivi-messaggio' " + "data-id='fg#"+row.email_giocatore+"' " + "data-nome='"+row.nome_completo+"' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Scrivi Messaggio'><i class='fa fa-envelope-o'></i></button>"; if( Utils.controllaPermessiUtente( this.user_info, permessi_modifica, false ) ) pulsanti += "<button type='button' " + "class='btn btn-xs btn-default modificaGiocatore' " + "data-id='"+row.email_giocatore+"' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Modifica Dati'><i class='fa fa-pencil'></i></button>"; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default inizialmente-nascosto eliminaGiocatore' " + "data-id='"+row.email_giocatore+"' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Elimina'><i class='fa fa-trash-o'></i></button>"; return pulsanti; }, creaDataTable: function ( ) { var columns = []; columns.push({data : "email_giocatore"}); columns.push({data : "nome_completo"}); columns.push({data : "data_registrazione_giocatore"}); columns.push({data : "ruoli_nome_ruolo"}); columns.push({ data : "note_giocatore", render: $.fn.dataTable.render.ellipsis( 20, false, false ) }); columns.push({ data : "note_staff_giocatore", render: this.renderizzaNoteStaff.bind(this) }); columns.push({render: this.creaPulsantiAzioni.bind(this) }); this.player_grid = $( '#groglia_giocatori' ) .on("error.dt", this.erroreDataTable.bind(this) ) .on("draw.dt", this.setGridListeners.bind(this) ) .DataTable( { language : Constants.DATA_TABLE_LANGUAGE, ajax : function (data, callback) { Utils.requestData( Constants.API_GET_PLAYERS, "GET", data, callback ); }, columns : columns, order : [[1, 'desc']] } ); }, recuperaDatiLocali: function() { this.user_info = JSON.parse( window.localStorage.getItem("user") ); } }; }(); $(function () { PgListManager.init(); }); <file_sep>/client/app/scripts/controllers/LoginManager.js var LoginManager = function () { var SERVER = window.location.protocol + "//" + window.location.host + "/", MAIN_PAGE = SERVER + "lista_pg.html", COOKIE_EXPIRES = 15; return { init: function () { this.setListeners(); this.rilevaRedirect(); }, setListeners: function () { $( 'input' ).iCheck( { checkboxClass : 'icheckbox_square-blue', radioClass : 'iradio_square-blue', increaseArea : '20%' // optional } ); $( "#login" ).click( this.doLogin.bind( this ) ); $(document).keypress(function(e) { if( e.which == 13 && ( $("input[name='password']").is(":focus") || $("input[name='usermail']").is(":focus") ) ) { this.doLogin(); $("#login").append("<i class='fa fa-spinner fa-pulse' style='margin-left:5px'></i>"); $("#login").attr("disabled",true); } }.bind(this)); }, inputIsValid: function () { var errors = "", username = $("input[name='usermail']").val(), password = $("input[name='<PASSWORD>']").val(), justBlank = /^\s+$/, isMail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (username == "" || justBlank.test(username)) errors += "Per favore riempire il campo email<br>"; else if (username != "" && !justBlank.test(username) && !isMail.test(username)) errors += "La mail inserita non è valida<br>"; if (password == "" || justBlank.test(password)) errors += "Per favore riempire il campo password<br>"; return errors; }, doLogin: function () { var errors = this.inputIsValid(); if (errors) Utils.showError(errors); else if (!errors) { if($("input[name='userremember']").is(":checked")) Utils.setCookie("usermail",$("input[name='usermail']").val(), COOKIE_EXPIRES); else Utils.deleteCookie("usermail"); Utils.requestData( Constants.API_POST_LOGIN, "POST", $("input").serialize(), function( data ) { this.pg_info = data; delete this.pg_info.status; window.localStorage.clear(); window.localStorage.setItem( 'user', JSON.stringify( this.pg_info ) ); if ( this.redirect_to && this.pgid ) { window.localStorage.setItem("pg_da_loggare",this.pgid); Utils.redirectTo(Constants.SITE_URL + "/" + this.redirect_to + ".html"); } else if( typeof data.pg_da_loggare !== "undefined" ) { window.localStorage.setItem("pg_da_loggare",data.pg_da_loggare); Utils.redirectTo( Constants.PG_PAGE ); } else Utils.redirectTo(Constants.MAIN_PAGE); }.bind(this) ); } }, rilevaRedirect: function () { this.redirect_to = Utils.getParameterByName("r"); this.pgid = Utils.getParameterByName("i"); }, checkCookie: function () { var user = Utils.getCookie("usermail"); if (user != "") { $("input[name='usermail']").val(user) $("input[name='userremember']").attr("checked",true); } } } }(); $(function () { LoginManager.init(); });<file_sep>/server/src/classes/AbilitiesManager.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class AbilitiesManager { protected $db; protected $session; public function __construct() { $this->session = SessionManager::getInstance(); $this->db = new DatabaseBridge(); } public function __destruct() { } public function recuperaAbilita($draw, $columns, $order, $start, $length, $search) { UsersManager::operazionePossibile($this->session, __FUNCTION__); $filter = False; $params = []; if (isset($order) && !empty($order) && count($order) > 0) { $sorting = array(); foreach ($order as $elem) { $colonna = $columns[$elem["column"]]["data"]; $sorting[] = "a1." . $colonna . " " . $elem["dir"]; } $order_str = "ORDER BY " . implode(",", $sorting); } $query_abilita = "SELECT a1.*, a2.nome_abilita nome_prerequisito_abilita, c.nome_classe nome_classe_abilita FROM abilita a1 LEFT JOIN abilita a2 ON a1.prerequisito_abilita > 0 AND a1.prerequisito_abilita = a2.id_abilita JOIN classi c ON a1.classi_id_classe = c.id_classe $order_str"; $abilita = $this->db->doQuery($query_abilita, $params, False); $output = Utils::filterDataTableResults($draw, $columns, $order, $start, $length, $search, $abilita); return json_encode($output); } } <file_sep>/server/src/classes/Statistics.class.php <?php $path = $_SERVER['DOCUMENT_ROOT'] . "/"; include_once($path . "classes/APIException.class.php"); include_once($path . "classes/DatabaseBridge.class.php"); include_once($path . "classes/UsersManager.class.php"); include_once($path . "classes/SessionManager.class.php"); include_once($path . "classes/Utils.class.php"); include_once($path . "config/constants.php"); class Statistics { protected $db; protected $charactersmanager; protected $session; private $event_id; private $event_sql; public function __construct($cm) { $this->db = new DatabaseBridge(); $this->session = SessionManager::getInstance(); $this->charactersmanager = $cm; $this->event_sql = "AND pg.id_personaggio IN (SELECT personaggi_id_personaggio FROM iscrizione_personaggi WHERE eventi_id_evento = :idev)"; $query_idev = "SELECT id_evento FROM eventi WHERE pubblico_evento = 1 ORDER BY data_inizio_evento DESC LIMIT 1"; $res_idev = $this->db->doQuery($query_idev, [], False); $this->event_id = [":idev" => $res_idev[0]["id_evento"] ]; } public function recuperaStatisticheClassi() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT COUNT(cl.nome_classe) AS QTY, cl.tipo_classe, cl.nome_classe FROM personaggi_has_classi JOIN classi AS cl ON cl.id_classe = classi_id_classe JOIN personaggi AS pg ON pg.id_personaggio = personaggi_id_personaggio JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore WHERE g.ruoli_nome_ruolo NOT IN ('staff','admin') $this->event_sql GROUP BY cl.tipo_classe, cl.id_classe ORDER BY QTY DESC, tipo_classe, nome_classe"; $data = $this->db->doQuery($sql, $this->event_id, False); return json_encode(["status" => "ok", "data" => $data]); } public function recuperaStatisticheAbilita() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT COUNT(ab.nome_abilita) AS QTY, ab.tipo_abilita, CONCAT(ab.nome_abilita,' (', cl.nome_classe, ')') AS nome_abilita FROM personaggi_has_abilita JOIN abilita AS ab ON ab.id_abilita = abilita_id_abilita JOIN classi AS cl ON cl.id_classe = classi_id_classe JOIN personaggi AS pg ON pg.id_personaggio = personaggi_id_personaggio JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore WHERE g.ruoli_nome_ruolo NOT IN ('staff','admin') $this->event_sql GROUP BY ab.tipo_abilita, ab.id_abilita ORDER BY QTY DESC, tipo_abilita, nome_abilita"; $data = $this->db->doQuery($sql, $this->event_id, False); return json_encode(["status" => "ok", "data" => $data]); } public function recuperaStatisticheAbilitaPerProfessione() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT COUNT(QTY) AS num_pgs, QTY, nome_classe FROM ( SELECT pg.nome_personaggio, COUNT(ab.nome_abilita) AS QTY, cl.nome_classe FROM personaggi_has_abilita JOIN abilita AS ab ON ab.id_abilita = abilita_id_abilita JOIN classi AS cl ON cl.id_classe = classi_id_classe JOIN personaggi AS pg ON pg.id_personaggio = personaggi_id_personaggio JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore WHERE g.ruoli_nome_ruolo NOT IN ('staff' , 'admin') AND ab.tipo_abilita = 'civile' $this->event_sql GROUP BY ab.classi_id_classe , pg.id_personaggio ORDER BY cl.nome_classe , QTY DESC , nome_abilita ) AS qty_t GROUP BY QTY, nome_classe ORDER BY nome_classe, QTY DESC"; $data = $this->db->doQuery($sql, $this->event_id, False); return json_encode(["status" => "ok", "data" => $data]); } public function recuperaStatisticheCrediti() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT SUM( COALESCE( u.importo, 0 ) ) AS credito_personaggio, data_transazione_str, pg_id FROM ( SELECT SUM( COALESCE( importo_transazione, 0 ) ) AS importo, creditore_transazione AS pg_id, DATE_FORMAT( data_transazione, '%d/%m/%Y' ) AS data_transazione_str FROM transazioni_bit GROUP BY creditore_transazione UNION ALL SELECT SUM( COALESCE( importo_transazione, 0 ) ) * -1 AS importo, debitore_transazione AS pg_id, DATE_FORMAT( data_transazione, '%d/%m/%Y' ) AS data_transazione_str FROM transazioni_bit GROUP BY debitore_transazione ) AS u JOIN personaggi AS pg ON pg.id_personaggio = pg_id JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore WHERE g.ruoli_nome_ruolo NOT IN ('staff','admin') $this->event_sql GROUP BY data_transazione_str"; $data = $this->db->doQuery($sql, $this->event_id, False); return json_encode(["status" => "ok", "data" => $data]); } public function recuperaStatistichePG() { global $PF_INIZIALI; UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT id_personaggio, MAX(cl_m.mente_base_classe) AS mente_base_personaggio, MAX(cl_m.shield_max_base_classe) AS scudo_base_personaggio FROM personaggi AS pg LEFT OUTER JOIN personaggi_has_classi AS phc ON phc.personaggi_id_personaggio = pg.id_personaggio LEFT OUTER JOIN classi AS cl_m ON cl_m.id_classe = phc.classi_id_classe AND cl_m.tipo_classe = 'militare' JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore WHERE g.ruoli_nome_ruolo NOT IN ('staff','admin') $this->event_sql GROUP BY id_personaggio"; $pg = $this->db->doQuery($sql, $this->event_id, False); $data = ["pf" => [], "ps" => [], "mente" => []]; for ($i = 0; $i < count($pg); $i++) { $query_ab = "SELECT id_abilita, offset_pf_abilita, offset_shield_abilita, offset_mente_abilita FROM abilita WHERE id_abilita IN ( SELECT abilita_id_abilita FROM personaggi_has_abilita WHERE personaggi_id_personaggio = :pgid )"; $abilita = $this->db->doQuery($query_ab, [":pgid" => $pg[$i]["id_personaggio"]], False); $pf_personaggio = $this->charactersmanager->calcolaPF($PF_INIZIALI, $abilita); $shield_personaggio = $this->charactersmanager->calcolaShield($pg[$i]["scudo_base_personaggio"], $abilita); $mente_personaggio = $this->charactersmanager->calcolaDifesaMentale($pg[$i]["mente_base_personaggio"], $abilita); if (!isset($data["pf"][$pf_personaggio + ""])) $data["pf"][$pf_personaggio + ""] = 1; else $data["pf"][$pf_personaggio + ""]++; if (!isset($data["ps"][$shield_personaggio + ""])) $data["ps"][$shield_personaggio + ""] = 1; else $data["ps"][$shield_personaggio + ""]++; if (!isset($data["mente"][$mente_personaggio + ""])) $data["mente"][$mente_personaggio + ""] = 1; else $data["mente"][$mente_personaggio + ""]++; } arsort($data["pf"]); arsort($data["ps"]); arsort($data["mente"]); return json_encode(["status" => "ok", "data" => $data]); } public function recuperaStatistichePunteggi() { global $MAPPA_COSTO_CLASSI_CIVILI; UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT id_personaggio, pc_personaggio, px_personaggio, COUNT(DISTINCT cl_c.nome_classe) AS num_classi_civili, COUNT(DISTINCT cl_m.nome_classe) AS num_classi_militari, COUNT(DISTINCT ab_m.nome_abilita) AS num_abilita_militari, ( SELECT SUM(costo_abilita) FROM abilita WHERE tipo_abilita = 'civile' AND id_abilita IN ( SELECT abilita_id_abilita FROM personaggi_has_abilita WHERE personaggi_id_personaggio = pg.id_personaggio ) ) AS costo_abilita_civili FROM personaggi AS pg JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore LEFT OUTER JOIN personaggi_has_classi AS phc ON phc.personaggi_id_personaggio = pg.id_personaggio LEFT OUTER JOIN personaggi_has_abilita AS pha ON pha.personaggi_id_personaggio = pg.id_personaggio LEFT OUTER JOIN classi AS cl_m ON cl_m.id_classe = phc.classi_id_classe AND cl_m.tipo_classe = 'militare' LEFT OUTER JOIN classi AS cl_c ON cl_c.id_classe = phc.classi_id_classe AND cl_c.tipo_classe = 'civile' LEFT OUTER JOIN abilita AS ab_m ON ab_m.id_abilita = pha.abilita_id_abilita AND ab_m.tipo_abilita = 'militare' WHERE g.ruoli_nome_ruolo NOT IN ('staff','admin') $this->event_sql GROUP BY id_personaggio"; $pg = $this->db->doQuery($sql, $this->event_id, False); $data = ["pc_risparmiati" => [], "px_risparmiati" => [], "pc_spesi" => [], "px_spesi" => [], "pc_ora" => [], "px_ora" => []]; for ($i = 0; $i < count($pg); $i++) { $pc_ora = (int) $pg[$i]["pc_personaggio"]; $px_ora = (int) $pg[$i]["px_personaggio"]; $pc_spesi = (int) $pg[$i]["num_classi_militari"] + (int) $pg[$i]["num_abilita_militari"]; $px_spesi = (int) $pg[$i]["costo_abilita_civili"]; for ($j = 0; $j < (int) $pg[$i]["num_classi_civili"]; $j++) $px_spesi += $MAPPA_COSTO_CLASSI_CIVILI[$j]; $pc_risparmiati = $pc_ora - $pc_spesi; $px_risparmiati = $px_ora - $px_spesi; if (!isset($data["pc_ora"][$pc_ora + ""])) $data["pc_ora"][$pc_ora + ""] = 0; if (!isset($data["px_ora"][$px_ora + ""])) $data["px_ora"][$px_ora + ""] = 0; if (!isset($data["pc_spesi"][$pc_spesi + ""])) $data["pc_spesi"][$pc_spesi + ""] = 0; if (!isset($data["px_spesi"][$px_spesi + ""])) $data["px_spesi"][$px_spesi + ""] = 0; if (!isset($data["pc_risparmiati"][$pc_risparmiati + ""])) $data["pc_risparmiati"][$pc_risparmiati + ""] = 0; if (!isset($data["px_risparmiati"][$px_risparmiati + ""])) $data["px_risparmiati"][$px_risparmiati + ""] = 0; $data["pc_ora"][$pc_ora + ""]++; $data["px_ora"][$px_ora + ""]++; $data["pc_spesi"][$pc_spesi + ""]++; $data["px_spesi"][$px_spesi + ""]++; $data["pc_risparmiati"][$pc_risparmiati + ""]++; $data["px_risparmiati"][$px_risparmiati + ""]++; } return json_encode(["status" => "ok", "data" => $data]); } public function recuperaStatisticheQtaRavShop() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT COUNT(id_transazione) AS num_transazioni, DATE_FORMAT(data_transazione,'%d/%m/%Y') AS data_transazione_str FROM transazioni_bit JOIN personaggi AS pg ON pg.id_personaggio = debitore_transazione JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore WHERE id_acquisto_componente IS NOT NULL AND g.ruoli_nome_ruolo NOT IN ('staff','admin') GROUP BY data_transazione_str ORDER BY data_transazione"; $data = $this->db->doQuery($sql, $this->event_id, False); return json_encode(["status" => "ok", "data" => $data]); } public function recuperaStatisticheAcquistiRavShop() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT COUNT(id_acquisto) AS num_acquisti, id_componente_acquisto, comp.nome_componente FROM componenti_acquistati JOIN personaggi AS pg ON pg.id_personaggio = cliente_acquisto JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore JOIN componenti_crafting AS comp ON comp.id_componente = id_componente_acquisto WHERE g.ruoli_nome_ruolo NOT IN ('staff','admin') GROUP BY id_componente_acquisto ORDER BY num_acquisti DESC"; $data = $this->db->doQuery($sql, $this->event_id, False); return json_encode(["status" => "ok", "data" => $data]); } public function recuperaStatisticheArmiStampate() { UsersManager::operazionePossibile($this->session, __FUNCTION__); $sql = "SELECT COUNT(dichiarazione) AS QTA, dichiarazione FROM ( SELECT 'DEVE DOPPIO' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%DEVE dichiarare%' AND risultato_ricetta LIKE '%DOPPIO%' UNION ALL SELECT 'DEVE TRIPLO' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%DEVE dichiarare%' AND risultato_ricetta LIKE '%TRIPO%' UNION ALL SELECT 'DEVE QUADRUPLO' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%DEVE dichiarare%' AND risultato_ricetta LIKE '%QUADRUPLO%' UNION ALL SELECT 'PUO CRASH' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%CRASH%' UNION ALL SELECT 'PUO A ZERO' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%A ZERO%' UNION ALL SELECT 'PUO DOLORE' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%può dichiarare%' AND risultato_ricetta LIKE '%DOLORE%' UNION ALL SELECT 'PUO FUOCO' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%può dichiarare%' AND risultato_ricetta LIKE '%FUOCO%' UNION ALL SELECT 'PUO GELO' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%può dichiarare%' AND risultato_ricetta LIKE '%GELO%' UNION ALL SELECT 'PUO PARALISI' AS dichiarazione, personaggi_id_personaggio FROM ricette WHERE risultato_ricetta LIKE '%può dichiarare%' AND risultato_ricetta LIKE '%PARALISI%' ) AS d JOIN personaggi AS pg ON pg.id_personaggio = d.personaggi_id_personaggio JOIN giocatori AS g ON g.email_giocatore = pg.giocatori_email_giocatore WHERE g.ruoli_nome_ruolo NOT IN ('staff','admin') GROUP BY dichiarazione ORDER BY QTA DESC"; $data = $this->db->doQuery($sql, $this->event_id, False); return json_encode(["status" => "ok", "data" => $data]); } } <file_sep>/client/app/scripts/controllers/BankManager.js var BankManager = function () { return { init: function () { this.pg_info = JSON.parse(window.localStorage.getItem("logged_pg")); this.user_info = JSON.parse(window.localStorage.getItem("user")); this.placeholder_credito = 'XXXX <i class="fa fa-eye"></i>'; this.movimenti_bonifico = 0; this.setListeners(); this.recuperaInfoBanca(); this.impostaColonne(); this.impostaGrigliaMovimenti(); if( Utils.controllaPermessiUtente( this.user_info, ["recuperaMovimenti_altri"]) ) this.impostaGrigliaMovimentiDiTutti(); }, bonificoOk: function () { Utils.resetSubmitBtn(); this.griglia_movimenti.ajax.reload(null,true); if( this.griglia_movimenti_tutti ) this.griglia_movimenti_tutti.ajax.reload(null,true); this.recuperaInfoBanca(); }, inviaBonifico: function ( e ) { if( !this.id_creditore && $("#personaggio").val().substr(0,1) === "#" ) this.id_creditore = $("#personaggio").val().substr(1); if( !this.id_creditore ) { Utils.showError("C'&egrave; un problema con il beneficiario del bonifico.<br>Per favore aggiorna la pagina e riprova."); return; } //$id_debitore, $importo, $id_creditore = NULL, $note = NULL, $id_acq_comp = NULL Utils.requestData( Constants.API_POST_TRANSAZIONE, "POST", { id_debitore : this.pg_info.id_personaggio, importo : Math.abs(parseInt($("#offset_crediti").val(),10)), id_creditore : this.id_creditore, note : $("#causale").val() }, "Bonifico eseguito con successo.", null, this.bonificoOk.bind(this) ); }, confermaInvioBonifico: function ( e ) { var beneficiario = $("#modal_bonifico").find("#personaggio").val(), crediti = $("#modal_bonifico").find("#offset_crediti").val(); Utils.showConfirm( "Conferma il bonifico di <strong>"+crediti+"</strong> Bit a beneficio di <strong>"+beneficiario+"</strong>.", this.inviaBonifico.bind(this), true ); }, mostraModalBonifico: function ( e ) { $("#modal_bonifico").find("#personaggio").val(""); $("#modal_bonifico").find("#causale").val(""); $("#modal_bonifico").find("#offset_crediti").val(0); $("#modal_bonifico").modal({drop:"static"}); }, pgSelezionato: function ( event, ui ) { this.id_creditore = ui.item.real_value; }, scrittoSuPg: function ( e, ui ) { if( $(e.target).val().substr(0,1) === "#" ) this.id_creditore = $(e.target).val().substr(1); }, recuperaPgAutofill: function ( req, res ) { Utils.requestData( Constants.API_GET_DESTINATARI_IG, "GET", { term : req.term }, function( data ) { res( data.results ); } ); }, mostraCredito: function ( e ) { var t = $(e.target); if( this.info ) t.html( this.info[t.parents(".box-saldo").attr("id")] + " <i class='fa fa-btc'></i>" ); }, nascondiCredito: function ( ) { $(".saldo").html(this.placeholder_credito); }, infoBancaRecuperate: function ( data ) { this.info = { totale : data.result.credito_personaggio, entrate_corrente : data.result.entrate_anno_personaggio, uscite_corrente : data.result.uscite_anno_personaggio }; }, recuperaInfoBanca: function () { if( !this.pg_info ) { this.infoBancaRecuperate({ result : { credito_personaggio : "----", entrate_anno_personaggio : "----", uscite_anno_personaggio : "----" }}); return; } Utils.requestData( Constants.API_GET_INFO_BANCA, "GET", { }, this.infoBancaRecuperate.bind(this) ); }, renderTipoMovimento: function ( data, type, row ) { //<span class="label bg-green">Entrata</span> var bg_class = "bg-green", label = $('<span class="label"></span>'); if( data === "uscita" ) bg_class = "bg-red"; label.addClass(bg_class); label.text( Utils.firstletterUpper( data ) ); return label[0].outerHTML; }, impostaGrigliaMovimenti: function () { if( !this.pg_info ) { $('#movimenti').parent().html("Logga con un personaggio per poter vedere i suoi movimenti bancari."); return; } var colonne_pg = this.columns.concat(); colonne_pg.unshift({ title: "Tipo", data: "tipo_transazione", render: this.renderTipoMovimento.bind(this) }); this.griglia_movimenti_tutti = $( '#movimenti' ) //.on("error.dt", this.erroreDataTable.bind(this) ) //.on("draw.dt", this.setGridListeners.bind(this) ) .DataTable( { buttons : ["reload"], language : Constants.DATA_TABLE_LANGUAGE, ajax : function (data, callback) { Utils.requestData( Constants.API_GET_MOVIMENTI, "GET", data, callback ); }, columns : colonne_pg, order : [[1, 'desc']] } ); }, impostaGrigliaMovimentiDiTutti: function () { var colonne_tutti = this.columns.concat(); colonne_tutti.splice(1,0,{ title: "Debitore", data: "nome_debitore", }); this.griglia_movimenti = $( '#mov_tutti' ) //.on("error.dt", this.erroreDataTable.bind(this) ) //.on("draw.dt", this.setGridListeners.bind(this) ) .DataTable( { buttons : ["reload"], language : Constants.DATA_TABLE_LANGUAGE, ajax : function (data, callback) { Utils.requestData( Constants.API_GET_MOVIMENTI, "GET", $.extend(data,{tutti:true}), callback ); }, columns : colonne_tutti, order : [[0, 'desc']] } ); $( '#mov_tutti').parents(".row").removeClass("inizialmente-nascosto").show(); }, impostaColonne: function () { this.columns = []; this.columns.push({ title: "Data", data: "datait_transazione" }); this.columns.push({ title: "Beneficiario", data : "nome_creditore" }); this.columns.push({ title: "Importo", data : "importo_transazione" }); this.columns.push({ title: "Descrizione", data : "note_transazione" }); }, setListeners: function () { $(".saldo").mousedown(this.mostraCredito.bind(this)); $(document).mouseup(this.nascondiCredito.bind(this)); $("#btn_bonifico").mouseup(this.mostraModalBonifico.bind(this)); $("#btn_invia").mouseup(this.confermaInvioBonifico.bind(this)); if ( Utils.isDeviceMobile() ) { $("#modal_bonifico").find(".pulsantiera-mobile").removeClass("inizialmente-nascosto"); new PulsantieraNumerica({ target : $("#modal_bonifico").find("#offset_crediti"), pulsantiera : $("#modal_bonifico").find("#pulsanti_credito") }); } $("#personaggio").autocomplete({ autoFocus : true, select : this.pgSelezionato.bind(this), search : this.scrittoSuPg.bind(this), source : this.recuperaPgAutofill.bind(this), appendTo: ".scelta-pg" }); } } }(); $(function () { BankManager.init(); }); <file_sep>/client/app/scripts/controllers/PgCreationManager.js var RegistrationManager = function () { var CIVILIAN_CLASS_LIST_ID = "listaClassiCivili", CIVILIAN_CLASS_BUCKET_ID = "listaClassiCiviliAcquistate", MILITARY_CLASS_LIST_ID = "listaClassiMilitari", MILITARY_CLASS_BUCKET_ID = "listaClassiMilitariAcquistate", CIVILIAN_ABILITY_LIST_ID = "listaAbilitaCivili", CIVILIAN_ABILITY_BUCKET_ID = "listaAbilitaCiviliAcquistate", MILITARY_ABILITY_LIST_ID = "listaAbilitaMilitari", MILITARY_ABILITY_BUCKET_ID = "listaAbilitaMilitariAcquistate", MILITARY_BASE_CLASS_LABEL = "base", MILITARY_ADVA_CLASS_LABEL = "avanzata"; return { init: function () { this.setListeners(); this.getClassesInfo(); this.getInfo(); this.getOptionsInfo(); this.getStaffUsers(); $("#inviaDati").click(this.inviaDati.bind(this)); }, setListeners: function () { $('.icheck input[type="checkbox"]').iCheck("destroy"); $('.icheck input[type="checkbox"]').iCheck({ checkboxClass: 'icheckbox_square-blue' }); }, onMSError: function (err) { console.log(err); }, classeCivileRenderizzata: function (dato, lista, indice, dom_elem) { //dato.costo_classe = Constants.COSTI_PROFESSIONI[ this.ms_classi_civili.numeroCarrello() ]; //dato.innerHTML = dom_elem[0].innerHTML = dato.nome_classe + " ( " + Constants.COSTI_PROFESSIONI[ // this.ms_classi_civili.numeroCarrello() ] + " PX )"; }, ricalcolaCostiClassiCivili: function () { var indice_costo = this.ms_classi_civili.numeroCarrello(), dati_lista = this.ms_classi_civili.datiListaAttuali(); for (var l in dati_lista) { var d = dati_lista[l]; if (d.id_classe) { d.costo_classe = Constants.COSTI_PROFESSIONI[indice_costo]; d.innerHTML = d.nome_classe + " ( " + d.costo_classe + " PX )"; } } this.ms_classi_civili.ridisegnaListe(); }, classeCivileSelezionata: function (tipo_lista, dato, lista, dom_elem, selezionati, da_utente) { if (tipo_lista !== MultiSelector.TIPI_LISTE.LISTA) return false; var indice_costo = this.ms_classi_civili.numeroCarrello() + selezionati.length, id_selezionati = selezionati.map(function (el) { return el.replace(/\D/g, "") + ""; }); for (var l in lista) { var d = lista[l]; if (d.id_classe && id_selezionati.indexOf(l) === -1) { d.costo_classe = Constants.COSTI_PROFESSIONI[indice_costo]; d.innerHTML = d.nome_classe + " ( " + d.costo_classe + " PX )"; } } this.ms_classi_civili.ridisegnaListe(); try { if (da_utente !== false) this.punti_exp.diminuisciConteggio(dato.costo_classe); this.inserisciDatiAbilitaCivili([dato]); } catch (e) { if (e.message === Contatore.ERRORS.VAL_TROPPO_BASSO) { this.ms_classi_civili.deselezionaUltimo(); Utils.showError("Non hai più punti per comprare altre professioni."); } } }, abilitaCivileSelezionata: function (tipo_lista, dato, lista, dom_elem, selezionati) { if (tipo_lista !== MultiSelector.TIPI_LISTE.LISTA) return false; try { this.punti_exp.diminuisciConteggio(dato.costo_abilita); if (this.opzioni_abilita[dato.id_abilita]) { $("#opzioni_abilita").show(400); $("#opzioni_" + dato.id_abilita).show(400); } } catch (e) { if (e.message === Contatore.ERRORS.VAL_TROPPO_BASSO) { this.ms_abilita_civili.deselezionaUltimo(); //TODO: controllare bene questo!!! Utils.showError("Non hai più punti per comprare altre abilit&agrave;."); } } }, classeCivileDeselezionata: function (tipo_lista, dato, lista, dom_elem, selezionati) { if (tipo_lista !== MultiSelector.TIPI_LISTE.LISTA) return false; var indice_costo = this.ms_classi_civili.numeroCarrello() + selezionati.length, indice_costo_2 = parseInt(indice_costo, 10), id_selezionati = selezionati.map(function (el) { return el.replace(/\D/g, "") + ""; }); for (var l in lista) { var d = lista[l]; if (d.id_classe && id_selezionati.indexOf(l) === -1) { d.costo_classe = Constants.COSTI_PROFESSIONI[indice_costo]; d.innerHTML = d.nome_classe + " ( " + d.costo_classe + " PX )"; } else if (d.id_classe && id_selezionati.indexOf(l) !== -1 && indice_costo_2 >= 0) { d.costo_classe = Constants.COSTI_PROFESSIONI[--indice_costo_2]; d.innerHTML = d.nome_classe + " ( " + d.costo_classe + " PX )"; } } this.ms_classi_civili.ridisegnaListe(); this.punti_exp.aumentaConteggio(dato.costo_classe); this.ms_abilita_civili.rimuoviDatiLista("id_classe", dato.id_classe); }, abilitaCivileDeselezionata: function (tipo_lista, dato, lista, dom_elem, selezionati) { this.punti_exp.aumentaConteggio(dato.costo_abilita); if (this.opzioni_abilita[dato.id_abilita]) $("#opzioni_" + dato.id_abilita).hide(400, function () { if ($("#opzioni_abilita .form-group:visible").length === 0) $("#opzioni_abilita").hide(400); }); }, abilitaMilitareSelezionata: function (tipo_lista, dato, lista, dom_elem, selezionati) { if (tipo_lista !== MultiSelector.TIPI_LISTE.LISTA) return false; try { this.punti_comb.diminuisciConteggio(dato.costo_abilita); if (this.opzioni_abilita[dato.id_abilita]) { $("#opzioni_abilita").show(400); $("#opzioni_" + dato.id_abilita).show(400); } } catch (e) { if (e.message === Contatore.ERRORS.VAL_TROPPO_BASSO) { this.ms_abilita_militari.deselezionaUltimo(); Utils.showError("Non hai più punti per comprare altre abilit&agrave;."); } } }, abilitaMilitareDeselezionata: function (tipo_lista, dato, lista, dom_elem, selezionati) { if (tipo_lista !== MultiSelector.TIPI_LISTE.LISTA) return false; this.punti_comb.aumentaConteggio(dato.costo_abilita); if (this.opzioni_abilita[dato.id_abilita]) $("#opzioni_" + dato.id_abilita).hide(400, function () { if ($("#opzioni_abilita .form-group:visible").length === 0) $("#opzioni_abilita").hide(400); }); }, impostaMSClassiCivili: function () { var dati = [], punti = this.pg_info ? this.pg_info.px_risparmiati : Constants.PX_TOT; for (var d in this.classInfos.classi.civile) { var dato = this.classInfos.classi.civile[d]; if (typeof dato === "object") { dato = JSON.parse(JSON.stringify(dato)); dato.innerHTML = dato.nome_classe + " ( " + Constants.COSTI_PROFESSIONI[0] + " PX )"; dato.costo_classe = Constants.COSTI_PROFESSIONI[0]; dato.prerequisito = null; dato.gia_selezionato = false; if (this.pg_info) dato.gia_selezionato = this.pg_info.classi.civile.filter(function (e) { return e.id_classe === dato.id_classe }).length > 0; dati.push(dato); } } this.ms_classi_civili = new MultiSelector({ id_lista: CIVILIAN_CLASS_LIST_ID, id_carrello: CIVILIAN_CLASS_BUCKET_ID, btn_aggiungi: $(".compra-classe-civile-btn"), btn_rimuovi: $(".butta-classe-civile-btn"), ordina_per_attr: "id_classe", dati_lista: dati, onError: this.onMSError.bind(this), elemSelezionato: this.classeCivileSelezionata.bind(this), elemDeselezionato: this.classeCivileDeselezionata.bind(this), elemRenderizzato: this.classeCivileRenderizzata.bind(this) }); this.ms_classi_civili.crea(); this.punti_exp = new Contatore({ elemento: $("#puntiEsperienza"), valore_max: punti, valore_ora: punti }); }, classeMilitareSelezionata: function (tipo_lista, dato, lista, dom_elem, selezionati, da_utente) { if (tipo_lista !== MultiSelector.TIPI_LISTE.LISTA) return false; try { if (da_utente !== false) this.punti_comb.diminuisciConteggio(dato.costo_classe); this.inserisciDatiAbilitaMilitari([dato]) } catch (e) { if (e.message === Contatore.ERRORS.VAL_TROPPO_BASSO) { this.ms_classi_militari.deselezionaUltimo(); Utils.showError("Non hai più punti per comprare altre classi."); } } }, classeMilitareDeselezionata: function (tipo_lista, dato) { if (tipo_lista !== MultiSelector.TIPI_LISTE.LISTA) return false; this.punti_comb.aumentaConteggio(dato.costo_classe); this.ms_abilita_militari.rimuoviDatiLista("id_classe", dato.id_classe); }, classeMilitareAcquistabile: function (id_prerequisito, dato, dati_lista, dati_carrello, selezionati) { var da_controllare = dati_carrello.concat(selezionati || []), elem_selezionato = selezionati.filter(function (el) { return el.id_classe === dato.id_classe }).length > 0; if (da_controllare.length === 2 && !elem_selezionato) return false; if (!id_prerequisito) return true; return da_controllare.filter(function (el) { return el.id_classe === id_prerequisito; }).length > 0; }, impostaMSClassiMilitari: function () { var dati = [], punti = this.pg_info ? this.pg_info.pc_risparmiati : Constants.PC_TOT; for (var d in this.classInfos.classi.militare) { var dato = this.classInfos.classi.militare[d]; if (typeof dato === "object") { dato = JSON.parse(JSON.stringify(dato)); dato.innerHTML = dato.nome_classe + " ( 1 PC )"; dato.prerequisito = this.classeMilitareAcquistabile.bind(this, dato.prerequisito_classe); dato.gia_selezionato = false; if (this.pg_info) dato.gia_selezionato = this.pg_info.classi.militare.filter(function (e) { return e.id_classe === dato.id_classe }).length > 0 || false; dati.push(dato); } } this.ms_classi_militari = new MultiSelector({ id_lista: MILITARY_CLASS_LIST_ID, id_carrello: MILITARY_CLASS_BUCKET_ID, btn_aggiungi: $(".compra-classe-militare-btn"), btn_rimuovi: $(".butta-classe-militare-btn"), ordina_per_attr: "id_classe", dati_lista: dati, onError: this.onMSError.bind(this), elemSelezionato: this.classeMilitareSelezionata.bind(this), elemDeselezionato: this.classeMilitareDeselezionata.bind(this) }); this.ms_classi_militari.crea(); this.punti_comb = new Contatore({ elemento: $("#puntiCombattimento"), valore_max: punti, valore_ora: punti }); }, controllaPrerequisitoAbilita: function (elem, dati_lista, dati_carrello, selezionati) { var da_controllare = dati_carrello.concat(selezionati || []), pre = parseInt(elem.prerequisito_abilita), id = parseInt(elem.id_abilita); if (pre === Constants.PREREQUISITO_TUTTE_ABILITA) return da_controllare.length >= this.classInfos.abilita[elem.id_classe].length - 1; else if (pre === Constants.PREREQUISITO_4_SPORTIVO) { da_controllare = da_controllare.filter(function (el) { return parseInt(el.id_abilita, 10) !== Constants.ID_ABILITA_IDOLO && (!el.prerequisito || (el.prerequisito && parseInt(el.prerequisito.id_abilita, 10) !== Constants.ID_ABILITA_IDOLO)) }); return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_SPORTIVO && parseInt(e.id_abilita) !== id; }).length >= 4; } else if (pre === Constants.PREREQUISITO_F_TERRA_T_SCELTO) return da_controllare.filter(function (e) { return parseInt(e.id_abilita) === Constants.ID_ABILITA_F_TERRA || parseInt(e.id_abilita) === Constants.ID_ABILITA_T_SCELTO; }).length === 2; else if (pre === Constants.PREREQUISITO_SMUOVER_MP_RESET) return da_controllare.filter(function (e) { return parseInt(e.id_abilita) === Constants.ID_ABILITA_SMUOVERE || parseInt(e.id_abilita) === Constants.ID_ABILITA_MEDPACK_RESET; }).length === 2; else if (pre === Constants.PREREQUISITO_5_SUPPORTO_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_SUPPORTO_BASE && parseInt(e.id_abilita) !== id; }).length >= 5; else if (pre === Constants.PREREQUISITO_3_ASSALTATA_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_ASSALTATORE_BASE && parseInt(e.id_abilita) !== id; }).length >= 3; else if (pre === Constants.PREREQUISITO_3_ASSALTATA_AVAN) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_ASSALTATORE_AVANZATO && parseInt(e.id_abilita) !== id; }).length >= 3; else if (pre === Constants.PREREQUISITO_3_GUASTATOR_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_GUASTATORE_BASE && parseInt(e.id_abilita) !== id; }).length >= 3; else if (pre === Constants.PREREQUISITO_3_GUASTATO_AVAN) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_GUASTATORE_AVANZATO && parseInt(e.id_abilita) !== id; }).length >= 3; else if (pre === Constants.PREREQUISITO_15_GUARDIAN_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_GUARDIANO_BASE && parseInt(e.id_abilita) !== id; }).length >= 15; else if (pre === Constants.PREREQUISITO_5_GUARDIANO_BAAV) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_GUARDIANO_BASE && parseInt(e.id_abilita) !== id; }).length + da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_GUARDIANO_AVANZATO && parseInt(e.id_abilita) !== id; }).length >= 5; else if (pre === Constants.PREREQUISITO_4_ASSALTATO_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_ASSALTATORE_BASE && parseInt(e.id_abilita) !== id; }).length >= 4; else if (pre === Constants.PREREQUISITO_7_SUPPORTO_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_SUPPORTO_BASE && parseInt(e.id_abilita) !== id; }).length >= 7; else if (pre === Constants.PREREQUISITO_15_GUARDIAN_AVAN) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_GUARDIANO_AVANZATO && parseInt(e.id_abilita) !== id; }).length >= 15; else if (pre === Constants.PREREQUISITO_15_ASSALTAT_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_ASSALTATORE_BASE && parseInt(e.id_abilita) !== id; }).length >= 15; else if (pre === Constants.PREREQUISITO_15_ASSALTAT_AVAN) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_ASSALTATORE_AVANZATO && parseInt(e.id_abilita) !== id; }).length >= 15; else if (pre === Constants.PREREQUISITO_15_SUPPORTO_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_SUPPORTO_BASE && parseInt(e.id_abilita) !== id; }).length >= 15; else if (pre === Constants.PREREQUISITO_15_SUPPORTO_AVAN) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_SUPPORTO_AVANZATO && parseInt(e.id_abilita) !== id; }).length >= 15; else if (pre === Constants.PREREQUISITO_15_GUASTATO_BASE) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_GUASTATORE_BASE && parseInt(e.id_abilita) !== id; }).length >= 15; else if (pre === Constants.PREREQUISITO_15_GUASTATO_AVAN) return da_controllare.filter(function (e) { return parseInt(e.id_classe) === Constants.ID_CLASSE_GUASTATORE_AVANZATO && parseInt(e.id_abilita) !== id; }).length >= 15; else if (pre === Constants.PREREQUISITO_3_GUASTATORE) return da_controllare.filter(function (e) { return (parseInt(e.id_classe) === Constants.ID_CLASSE_GUASTATORE_AVANZATO || parseInt(e.id_classe) === Constants.ID_CLASSE_GUASTATORE_BASE) && parseInt(e.id_abilita) !== id; }).length >= 3; return false; }, impostaMSAbilitaCivili: function () { this.ms_abilita_civili = new MultiSelector({ id_lista: CIVILIAN_ABILITY_LIST_ID, id_carrello: CIVILIAN_ABILITY_BUCKET_ID, btn_aggiungi: $(".compra-abilita-civile-btn"), btn_rimuovi: $(".butta-abilita-civile-btn"), ordina_per_attr: "id_abilita", onError: this.onMSError.bind(this), elemSelezionato: this.abilitaCivileSelezionata.bind(this), elemDeselezionato: this.abilitaCivileDeselezionata.bind(this) }); this.ms_abilita_civili.crea(); }, impostaMSAbilitaMilitari: function () { this.ms_abilita_militari = new MultiSelector({ id_lista: MILITARY_ABILITY_LIST_ID, id_carrello: MILITARY_ABILITY_BUCKET_ID, btn_aggiungi: $(".compra-abilita-militare-btn"), btn_rimuovi: $(".butta-abilita-militare-btn"), ordina_per_attr: "id_abilita", onError: this.onMSError.bind(this), elemSelezionato: this.abilitaMilitareSelezionata.bind(this), elemDeselezionato: this.abilitaMilitareDeselezionata.bind(this) }); this.ms_abilita_militari.crea(); }, inserisciDatiAbilita: function (selezionati, ms) { var dati = []; for (var s in selezionati) { var id_classe = selezionati[s].id_classe, px_testo = selezionati[s].tipo_classe === "civile" ? "PX" : "PC"; for (var d in this.classInfos.abilita[id_classe]) { var dato = this.classInfos.abilita[id_classe][d]; if (typeof dato === "object") { dato = JSON.parse(JSON.stringify(dato)); var prerequisito = ""; if (parseInt(dato.prerequisito_abilita) > 0) prerequisito = "<br><br>Prerequisiti:<br>" + dato.nome_prerequisito_abilita; else if (parseInt(dato.prerequisito_abilita) < 0) prerequisito = "<br><br>Prerequisiti:<br>" + Constants.SPECIAL_PREREQUISITES[dato.prerequisito_abilita]; dato.innerHTML = dato.nome_abilita + " ( " + dato.costo_abilita + " " + px_testo + " )"; dato.prerequisito = null; dato.title = dato.nome_abilita ? dato.nome_abilita : dato.nome_classe; dato.gia_selezionato = false; if (this.pg_info) dato.gia_selezionato = this.pg_info.abilita[dato.tipo_abilita].filter(function (e) { return e.id_abilita === dato.id_abilita }).length > 0; if (dato.descrizione_abilita) { dato.content = dato.descrizione_abilita + prerequisito; dato.title = dato.nome_abilita; delete dato.descrizione_abilita; delete dato.nome_prerequisito_abilita; } if (dato.prerequisito_abilita && dato.prerequisito_abilita > 0) dato.prerequisito = { id_abilita: dato.prerequisito_abilita }; else if (dato.prerequisito_abilita && dato.prerequisito_abilita < 0) dato.prerequisito = this.controllaPrerequisitoAbilita.bind(this); dati.push(dato); } } } ms.aggiungiDatiLista(dati); ms.deselezionaTutti(); }, inserisciDatiAbilitaCivili: function (selezionati) { this.inserisciDatiAbilita.call(this, selezionati, this.ms_abilita_civili); }, inserisciDatiAbilitaMilitari: function (selezionati) { this.inserisciDatiAbilita.call(this, selezionati, this.ms_abilita_militari); }, impostaOpzioniAbilita: function () { for (var oa in this.opzioni_abilita) { var op = this.opzioni_abilita[oa]; if (typeof oa === "string") { var elems = op.reduce(function (pre, ora) { return pre + "<option value=\"" + ora + "\">" + ora + "</option>" }, ""); $("#opzioni_" + oa + " select").append(elems); if (this.pg_info && this.pg_info.opzioni && this.pg_info.opzioni[oa]) { $("#opzioni_abilita").show(400); console.log(this.pg_info.opzioni[oa].opzione); $("#opzioni_" + oa + " select").val(this.pg_info.opzioni[oa].opzione).attr("disabled", true); $("#opzioni_" + oa).show(400); } } } }, getInfo: function () { this.pg_info = JSON.parse(window.localStorage.getItem('logged_pg')); this.user_info = JSON.parse(window.localStorage.getItem('user')); this.permessoPNG = Utils.controllaPermessiUtente(this.user_info, ["creaPNG"]); }, getClassesInfo: function () { Utils.requestData( Constants.API_GET_INFO, "GET", "", function (data) { this.classInfos = data.info; this.impostaMSClassiCivili(); this.impostaMSClassiMilitari(); this.impostaMSAbilitaCivili(); this.impostaMSAbilitaMilitari(); }.bind(this) ); }, getOptionsInfo: function () { Utils.requestData( Constants.API_GET_OPZIONI_ABILITA, "GET", "", function (data) { this.opzioni_abilita = data.result; this.impostaOpzioniAbilita(); }.bind(this) ); }, getStaffUsers: function () { if (this.permessoPNG) { Utils.requestData( Constants.API_GET_STAFF_USERS, "GET", {}, this.riempiElencoStaffer.bind(this) ); } }, riempiElencoStaffer: function (data) { var staffers = data.result, menu = $("select[name='giocatori_email_giocatore']"); for (var s in staffers) { var selected = this.user_info.email_giocatore === staffers[s].email_giocatore ? "selected" : ""; menu.append("<option value='" + staffers[s].email_giocatore + "' " + selected + ">" + staffers[s].nome_giocatore + "</option>"); } }, submitRedirect: function () { if (this.pg_info) { window.localStorage.setItem("pg_da_loggare", this.pg_info.id_personaggio); Utils.redirectTo(Constants.PG_PAGE); } else Utils.redirectTo(Constants.MAIN_PAGE); ì }, inviaDati: function () { var vuoto = /^\s+$/, errori = "", opzioni_vals = $("#opzioni_abilita").find(".form-group:visible select:not([disabled])").toArray().map(function (e) { return $(e).val(); }), cc_selezionate = this.ms_classi_civili.datiSelezionati(), cm_selezionate = this.ms_classi_militari.datiSelezionati(), ac_selezionate = this.ms_abilita_civili.datiSelezionati(), am_selezionate = this.ms_abilita_militari.datiSelezionati(); if (!this.pg_info) { if (!$("#nomePG").val() || ($("#nomePG").val() && vuoto.test($("#nomePG").val()))) errori += "<li>Il campo nome utente non pu&ograve; essere vuoto.</li>"; if (!$("#etaPG").val() || ($("#etaPG").val() && (vuoto.test($("#etaPG").val()) || !/^\d+$/.test($("#etaPG").val()) || $("#etaPG").val() === "0"))) errori += "<li>Il campo et&agrave; non pu&ograve; essere vuoto o 0.</li>"; if (cc_selezionate.length === 0 && !this.permessoPNG) errori += "<li>Devi acquistare almeno una professione.</li>"; if (cm_selezionate.length === 0 && !this.permessoPNG) errori += "<li>Devi acquistare almeno un'abilit&agrave; civile.</li>"; if (ac_selezionate.length === 0 && !this.permessoPNG) errori += "<li>Devi acquistare almeno una classe militare.</li>"; if (am_selezionate.length === 0 && !this.permessoPNG) errori += "<li>Devi acquistare almeno un'abilit&agrave; militare.</li>"; } else if (this.pg_info && cc_selezionate.length === 0 && cm_selezionate.length === 0 && ac_selezionate.length === 0 && am_selezionate.length === 0 && !this.permessoPNG ) { errori += "<li>Devi acquistare almeno una classe o un'abilit&agrave;.</li>"; } if (opzioni_vals.filter(function (e, i, ar) { return ar.lastIndexOf(e) !== i; }).length > 0) errori += "<li>Non &egrave; possibile selezionare due opzioni uguali per abilit&agrave; diverse.</li>"; if (errori) { Utils.showError("Sono stati rilevati degli errori:<ul>" + errori + "</ul>"); return false; } var classi = cc_selezionate.concat(cm_selezionate) .reduce(function (pre, curr) { return pre + "classi[]=" + curr.id_classe + "&"; }, "") || "classi=&", abilita = ac_selezionate.concat(am_selezionate) .reduce(function (pre, curr) { return pre + "abilita[]=" + curr.id_abilita + "&"; }, "") || "abilita=&", opzioni = $("#opzioni_abilita").find(".form-group:visible select:not([disabled])").serialize() || "opzioni=", nome = !this.pg_info ? "nome=" + encodeURIComponent($("#nomePG").val()) : "id_utente=" + this.pg_info.id_personaggio, eta = !this.pg_info ? "eta=" + $("#etaPG").val() + "&" : "", property = "giocatori_email_giocatore=" + $("[name='giocatori_email_giocatore']").val(), contatta = "contattabile_giocatore=" + ($("[name='contattabile_personaggio']").is(":checked") ? 1 : 0), data = nome + "&" + eta + classi + abilita + opzioni, url = this.pg_info ? Constants.API_POST_ACQUISTA : Constants.API_POST_CREAPG; if (this.permessoPNG) data += "&" + property + "&" + contatta; Utils.requestData( url, "POST", data, function () { var message = ""; if (this.pg_info) message = "Acquisti effettuati con successo."; else message = "La creazione è avvenuta con successo.<br>Potrai vedere il tuo nuovo personaggio nella sezione apposita.<br>È consigliato aggiungere un Background."; $("#message").unbind("hidden.bs.modal"); $("#message").on("hidden.bs.modal", this.submitRedirect.bind(this)); Utils.showMessage(message); }.bind(this) ); } }; }(); // eslint-disable-line no-console $(function () { RegistrationManager.init(); });<file_sep>/client/app/scripts/models/CreditManager.js var CreditManager = function () { return { init: function () { //TODO: mettere pulsanti per aumentare e diminure il valore a causa di cel che non fanno inserire numeri negativi this.modal_selector = "#modal_modifica_credito"; this.listeners_set = false; }, impostaModal: function ( settings ) { this.settings = { valore_max: Infinity, valore_min: -Infinity }; this.settings = $.extend( this.settings, settings ); if ( this.settings.pg_ids.length < 1 ) { Utils.showError( "Impossibile assegnare Bit a 0 personaggi." ); return false; } this.setListeners(); this.risettaValori(); this.impostaValori(); }, inviaRichiestaAssegna: function () { if ( $( this.modal_selector ).find( "#motivo_credito" ).val() === "" ) { Utils.showError( "&Egrave; obbligatorio inserire una motivazione per il bonifico." ); return false; } Utils.requestData( Constants.API_POST_TRANSAZIONE_MOLTI, "POST", { importo: $( this.modal_selector ).find( "#offset_crediti" ).val(), note: $( this.modal_selector ).find( "#motivo_credito" ).val(), creditori: this.settings.pg_ids }, "Bonifico eseguito con successo.", null, this.settings.onSuccess ); }, impostaValori: function () { $( this.modal_selector ).find( "#nome_personaggi" ).text( this.settings.nome_personaggi.join( ", " ) ); $( this.modal_selector ).modal( { drop: "static" } ); }, risettaValori: function () { $( this.modal_selector ).find( "#btn_modifica" ).attr( "disabled", false ).find( "i" ).remove(); $( this.modal_selector ).find( "#nome_personaggi" ).html( "" ); $( this.modal_selector ).find( "#offset_crediti" ).val( 0 ); }, setListeners: function () { if ( this.listeners_set ) return false; this.listeners_set = true; $( this.modal_selector ).find( "#btn_modifica" ).unbind( "click", this.inviaRichiestaAssegna.bind( this ) ); $( this.modal_selector ).find( "#btn_modifica" ).click( this.inviaRichiestaAssegna.bind( this ) ); if ( Utils.isDeviceMobile() ) { $( "#modal_modifica_credito" ).find( ".pulsantiera-mobile" ).removeClass( "inizialmente-nascosto" ); new PulsantieraNumerica( { target: $( "#modal_modifica_credito" ).find( "#offset_crediti" ), pulsantiera: $( "#modal_modifica_credito" ).find( "#pulsanti_credito" ), valore_max: this.settings.valore_max, valore_min: this.settings.valore_min } ); } } } }(); $( function () { CreditManager.init(); } );<file_sep>/client/app/scripts/controllers/AdminLTEManager.js var AdminLTEManager = function () { var SECTION_NAME = window.location.href.replace( Constants.SITE_URL + "/", "" ).replace( window.location.search, "" ).replace( /\.\w+#?$/, "" ).replace( /live_/, "" ), NO_CONTROLLO = ["index", "recupera_password", "registrazione"]; return { init: function () { if ( SECTION_NAME !== "" && NO_CONTROLLO.indexOf( SECTION_NAME ) === -1 ) { this.user_info = this.user_info || JSON.parse( window.localStorage.getItem( 'user' ) ); this.pg_info = JSON.parse( window.localStorage.getItem( 'logged_pg' ) ); this.controllaModalitaEvento(); } this.setListeners(); this.controllaPermessi( ".sidebar-menu", true ); }, controllaAccesso: function () { if ( SECTION_NAME !== "" && NO_CONTROLLO.indexOf( SECTION_NAME ) === -1 && SECTION_NAME.indexOf( "test" ) === -1 ) Utils.controllaAccessoPagina( SECTION_NAME ); }, controllaModalitaEvento: function () { if ( this.pg_info && this.user_info && typeof this.user_info.pg_da_loggare !== "undefined" && typeof this.user_info.event_id !== "undefined" ) { $( "body" ).addClass( "event_ongoing" ); $( ".visualizza_pagina_main" ).remove(); $( "#btn_visualizza_pagina_gestione_eventi" ).remove(); $( "#logo_link" ).attr( "href", Constants.PG_PAGE ); if ( $( "#background_video" )[0] ) { $( "#background_video" ).attr( "autoplay", null ); $( "#background_video" )[0].pause(); } } else { $( ".visualizza_pagina_main" ).removeClass( "inizialmente-nascosto" ).show(); $( "#btn_visualizza_pagina_gestione_eventi" ).removeClass( "inizialmente-nascosto" ).show(); } }, mostraNomePersonaggio: function ( nome ) { var id_personaggio = ""; if ( typeof nome === "undefined" && typeof this.pg_info !== "undefined" && this.pg_info ) { nome = this.pg_info.nome_personaggio; id_personaggio = this.pg_info.id_personaggio; } if ( nome ) { $( "#nome_personaggio" ).find( "p" ).text( nome ); $( "#nome_personaggio" ).find( ".fa" ).removeClass( "text-danger" ).addClass( "text-success" ); $( "#pg_status" ).text( " Online" ); $( ".nome_personaggio" ).text( nome ); if ( typeof this.pg_info !== "undefined" && this.pg_info ) $( "#live_matricola" ).text( "# SGC0215AT54RD" + this.pg_info.id_personaggio ); } }, mostraElementiNascosti: function ( in_selector, animate, permesso ) { var permesso_generico = permesso.replace( Constants.TIPO_GRANT_PG_ALTRI, "" ).replace( Constants.TIPO_GRANT_PG_PROPRIO, "" ), animation = animate ? "fadeIn" : null; if ( typeof permesso === "string" && $( "#btn_" + permesso ).length > 0 ) { $( in_selector ).find( "#btn_" + permesso ).show( animation ); $( "#btn_" + permesso ).removeClass( "inizialmente-nascosto" ); } if ( typeof permesso === "string" && $( "." + permesso ).length > 0 ) { $( in_selector ).find( "." + permesso ).show( animation ); $( "." + permesso ).removeClass( "inizialmente-nascosto" ); } if ( typeof permesso === "string" && $( "#btn_" + permesso_generico ).length > 0 ) { $( in_selector ).find( "#btn_" + permesso_generico ).show( animation ); $( "#btn_" + permesso_generico ).removeClass( "inizialmente-nascosto" ); } if ( typeof permesso === "string" && $( "." + permesso_generico ).length > 0 ) { $( in_selector ).find( "." + permesso_generico ).show( animation ); $( "." + permesso_generico ).removeClass( "inizialmente-nascosto" ); } }, controllaPermessi: function ( in_selector, animate ) { if ( window.controllo_permessi_autorizzato === false ) return false; in_selector = typeof in_selector === "undefined" ? ".content-wrapper > .content" : in_selector; animate = typeof animate === "undefined" ? false : animate; // this.user_info = this.user_info || JSON.parse( window.localStorage.getItem( 'user' ) ); this.pg_info = JSON.parse( window.localStorage.getItem( 'logged_pg' ) ); $( in_selector ).find( ".inizialmente-nascosto:not(.no-hide)" ).hide(); if ( this.user_info ) { for ( var p in this.user_info.permessi ) { var permesso = this.user_info.permessi[p]; this.mostraElementiNascosti( in_selector, animate, permesso ); } $( ".nome_giocatore" ).each( function ( i, el ) { $( el ).text( this.user_info.nome_giocatore ); }.bind( this ) ); } if ( this.pg_info ) { for ( var p in this.pg_info.permessi ) { var permesso = this.pg_info.permessi[p]; this.mostraElementiNascosti( in_selector, animate, permesso ); } } this.mostraNomePersonaggio(); this.controllaModalitaEvento(); this.setupMenuSearch(); }, logout: function () { Utils.requestData( Constants.API_GET_LOGOUT, "GET", "", function ( data ) { Utils.clearLocalStorage(); this.user_info = null; this.pg_info = null; window.location.href = Constants.SITE_URL; }.bind( this ) ); }, setupMenuSearch: function () { $( '#search-input' ).unbind( 'keyup' ); $( '#search-input' ).on( 'keyup', function () { var term = $( '#search-input' ).val().trim(); if ( term.length === 0 ) { $( '.sidebar-menu li' ).each( function () { var elem = $( this ); if ( !elem.hasClass( "inizialmente-nascosto" ) ) elem.show( 0 ); elem.removeClass( 'active' ); if ( elem.data( 'lte.pushmenu.active' ) ) elem.addClass( 'active' ); } ); return; } $( '.sidebar-menu li' ).each( function () { var elem = $( this ); if ( !elem.hasClass( "inizialmente-nascosto" ) ) { if ( elem.text().toLowerCase().indexOf( term.toLowerCase() ) === -1 ) { elem.hide( 0 ); elem.removeClass( 'pushmenu-search-found', false ); if ( elem.is( '.treeview' ) ) { elem.removeClass( 'active' ); } } else { elem.show( 0 ); elem.addClass( 'pushmenu-search-found' ); if ( elem.is( '.treeview' ) ) { elem.addClass( 'active' ); } var parent = elem.parents( 'li' ).first(); if ( parent.is( '.treeview' ) ) { parent.show( 0 ); } } if ( elem.is( '.header' ) ) { elem.show(); } } } ); $( '.sidebar-menu li.pushmenu-search-found.treeview' ).each( function () { $( this ).find( '.pushmenu-search-found' ).show( 0 ); } ); } ); }, aggiornaBadgeMessaggi: function ( data ) { if ( this.pg_info && typeof this.user_info.pg_da_loggare !== "undefined" && typeof this.user_info.event_id !== "undefined" ) $( "#num_mex_fg" ).remove(); else $( "#num_mex_fg" ).text( data.result.fg ); if ( typeof data.result.ig !== "undefined" ) $( "#num_mex_ig" ).text( data.result.ig ); }, controllaMessaggi: function () { Utils.requestData( Constants.API_GET_MESSAGGI_NUOVI, "GET", {}, this.aggiornaBadgeMessaggi.bind( this ) ); }, aggiornaDatiPG: function ( datiAggiornati ) { var dati = { pgid: JSON.parse( window.localStorage.getItem( "logged_pg" ) ).id_personaggio }; Utils.requestData( Constants.API_GET_PG_LOGIN, "GET", dati, function ( data ) { this.pg_info = data.result; var pg_no_bg = JSON.parse( JSON.stringify( this.pg_info ) ); delete pg_no_bg.background_personaggio; delete pg_no_bg.note_master_personaggio; window.localStorage.removeItem( 'logged_pg' ); window.localStorage.setItem( 'logged_pg', JSON.stringify( pg_no_bg ) ); if ( typeof datiAggiornati === "function" ) datiAggiornati( pg_no_bg ); }.bind( this ) ); }, aggiornaDatiUtente: function ( password, datiAggiornati ) { var dati = { usermail: JSON.parse( window.localStorage.getItem( "user" ) ).email_giocatore, password: <PASSWORD> }; Utils.requestData( Constants.API_POST_LOGIN, "POST", dati, function ( data ) { this.pg_info = data; delete this.pg_info.status; window.localStorage.removeItem( "user" ); window.localStorage.setItem( 'user', JSON.stringify( this.pg_info ) ); if ( typeof datiAggiornati === "function" ) datiAggiornati( this.pg_info ); }.bind( this ) ); }, setListeners: function () { this.setupMenuSearch(); if ( jQuery().tree ) $( 'ul.tree' ).tree(); if ( jQuery().tooltip ) $( '[data-toggle="tooltip"]' ).tooltip(); $( '#sidebar-form' ).on( 'submit', function ( e ) { e.preventDefault(); } ); $( '.sidebar-menu li.active' ).data( 'lte.pushmenu.active', true ); $( '#logoutBtn' ).click( this.logout.bind( this ) ); $( '#btn_visualizza_pagina_profilo' ).click( Utils.redirectTo.bind( this, Constants.PROFILO_PAGE ) ); $( '#logo_link' ).attr( "href", Constants.MAIN_PAGE ); Utils.setSubmitBtn(); if ( this.pg_info ) $( "#nome_personaggio" ).parents( ".user-panel" ).click( Utils.redirectTo.bind( this, Constants.PG_PAGE ) ); if ( this.user_info ) { this.controllaMessaggi(); setInterval( this.controllaMessaggi.bind( this ), Constants.INTERVALLO_CONTROLLO_MEX ); } } } }(); AdminLTEManager.controllaAccesso(); $( document ).ready( function ( e ) { AdminLTEManager.init(); } ); <file_sep>/docker-node-grunt/Dockerfile FROM node:9.11.2 MAINTAINER <NAME> COPY ./data/bower_components /tmp/bower_components COPY ./wait_and_install.sh /tmp/wait_and_install.sh WORKDIR /app RUN npm install -g bower RUN npm install -g grunt-cli CMD /tmp/wait_and_install.sh CMD bower install --allow-root && npm install --no-bin-links && cp -r /tmp/bower_components/* /app/bower_components/ && grunt serve #CMD tail -f /dev/null<file_sep>/client/README.md # Reboot Live PG Manager ## Prerequisiti * [Git](https://git-scm.com/) * [NodeJS 4+](https://nodejs.org/it/download/current/) * NPM (Si installa automaticamente assieme a NodeJS) * [Bower](https://bower.io/#install-bower) * [Grunt CLI](https://gruntjs.com/getting-started#installing-the-cli) * [Reboot API](https://github.com/Miroku87/reboot-live-api.git) ## Installazione Clonare questa repository in una folder di vostra preferenza. Una volta terminato il trasferimento installare tutti i pacchetti di NodeJS: ``` npm install ``` Dopo che il processo precedente è terminato, installare i pacchetti Bower. Durante questa fase verranno chieste delle informazioni. Rispondere nel modo seguente * Versione AdminLTE: 2 * Font per le icone: Font Awesome * Versione JQuery: 1.9.x ``` bower install ``` ## Sviluppo La directory di lavoro è `app`, ma prima di iniziare a modificare i file al suo interno avviare il watcher con questo comando: ``` grunt ``` Questo task compilerà tutti i file HTML e i JavaScript, li inserirà nella cartella `.tmp` e poi avvierà un webserver che permetterà di eseguire il codice compilato. Dopo che il server sarà avviato verrà aperto automaticamente il browser predefinito con la pagina iniziale del sito. ### Template Le pagine HTML di questo sito sono tutte generate tramite l'utilizzo del "linguaggio di templating" [Nunjucks](https://mozilla.github.io/nunjucks/). Questo per evitare di dover copiare e incollare mille righe di HTML che, in caso di modifica, devono essere riviste in tutti i file generati. Nunjucks permette di impostare dei template e li renderizza tramite Grunt prima di renderli disponibili al server. In questo modo le pagine HTML che verranno renderizzate dal browser saranno complete con tutto l'HTML necessario. Per creare nuove pagine di contenuti creare un file HTML all'interno della cartella `app` e inserire la struttura base seguente: ``` {% extends "./templates/main_template.html" %} {% set body_classes = body_classes + " <nome-classe-pagina>" %} {% set section = "<nome-sezione-obbligatorio>" %} {% set titolo_sezione = "<titolo-sezione>" %} {% set descrizione_sezione = "<descrizione-sezione-opzionale>" %} {% block styles %} <link href="..." rel="stylesheet" > {% endblock %} {% block mainContent %} {{ super() }} <!-------------------------- | Your Page Content Here | --------------------------> {% endblock %} {% block managers %} {{ super() }} <!-- Creare uno script apposito per la gestione di questa pagina --> <script src="scripts/controllers/PageManager.js"></script> {% endblock %} ``` I due template principali che contengono i codici comuni a tutte le pagine (CSS, JS e HTML dei menù, header e footer) sono: * `app/templates/layout_template.html` il padre di tutto * `app/templates/main_template.html` il template con i menù ### Stili Per sovrascrivere gli stili creare dei file SCSS separati da quelli già presenti e poi importarli ( **con estensione CSS** ) nelle corrette pagine HTML all'interno del blocco `styles` mostrato qui sopra. Per sovrascrivere gli stili di tutte le pagine contemporaneamente modificare il file `app/templates/layout_template.html` e inserire il nuovo tag `<link href...>` **prima** dell'import del file `main.css`. Questo perché in `main.css` vengono fatti altri override degli stili generici di AdminLTE e non possono essere modificati o si rischia di rompere il sito. ### Scripting Ogni HTML ha un suo codice JavaScript chiamato genericamente Manager. Questi codici vengono inseriti per convenzione dentro `app/scripts/controllers`. ## Compilare Per poter testare in ambiente di preproduzione e per mettere in produzione il formato bisogna compilarlo tramite i seguenti comandi Grunt: ``` # Per ambiente di preproduzione grunt preprod # Per ambiente di produzione grunt prod ``` <file_sep>/server/src/config/constants.php <?php $DEBUG = False; $MAINTENANCE = False; $MESSAGGIO_CHIUSURA = NULL; //"Il database rimarr&agrave; chiuso fino al caricamento dei dati aggiornati con le modifiche fatte durante l'evento."; $RETE_LOCALE = False; $IP_MAINTAINER = ["172.16.58.3"]; $MAIL_ACCOUNT = "<EMAIL>"; $MAIL_MITTENTE_INDIRIZZO = "<EMAIL>"; $MAIL_MITTENTE_NOME = "Reboot GRV"; $MAIL_PASSWORD = "<PASSWORD>"; $MAIL_HOST = "smtp.gmail.com"; $MAIL_PORT = 587; $SITE_URL = "http://localhost:9000"; $ALLOWED_ORIGINS = [$SITE_URL,"https://www.rebootgrv.com"]; $MYSQL_DUPLICATE_ENTRY_ERRCODE = "1062"; $DB_ERR_DELIMITATORE = "@@@"; $TIPO_GRANT_PG_PROPRIO = "_proprio"; $TIPO_GRANT_PG_ALTRI = "_altri"; $RUOLO_ADMIN = "admin"; $GRANT_MOSTRA_ALTRI_PG = "mostraPersonaggi_altri"; $GRANT_VISUALIZZA_MAIN = "visualizza_pagina_main"; $GRANT_VISUALIZZA_CRAFT_CHIMICO = "visualizza_pagina_crafting_chimico"; $GRANT_VISUALIZZA_CRAFT_PROGRAM = "visualizza_pagina_crafting_programmazione"; $GRANT_VISUALIZZA_CRAFT_TECNICO = "visualizza_pagina_crafting_ingegneria"; $GRANT_VISUALIZZA_NOTIZIE = "visualizza_pagina_notizie"; $GRANT_VISUALIZZA_MERCATO = "visualizza_pagina_mercato"; $GRANT_CRAFTA_ARMI = "crafta_armi"; $GRANT_CRAFTA_PROTESI = "crafta_protesi"; $GRANT_CRAFTA_GADGET_SHIELD = "crafta_gadget_shield"; $GRANT_CRAFTA_SCUDI_ESOSCHELE = "crafta_scudi_esoscheletri"; $GRANT_CREA_NOTIZIE = "creaNotizia"; $GRANT_MODIFICA_NOTIZIE = "modificaNotizia"; $GRANT_RECUPERA_NOTIZIE = "recuperaNotizie"; $GRANT_LOGIN_QUANDO_CHIUSO = "login_durante_chiusura"; $PX_INIZIALI = 220; $PC_INIZIALI = 6; $PF_INIZIALI = 2; $ANNO_PRIMO_LIVE = 271; $SCONTO_MERCATO = 5; $QTA_PER_SCONTO_MERCATO = 6; $ID_RICETTA_PAG = 4; $CRAFTING_ARMI = 48; $CRAFTING_PROTESI = 49; $CRAFTING_GADGET_SHIELD = 50; $CRAFTING_SCUDI_ESOSCHELE = 51; $ABILITA_CRAFTING = array( "chimico" => 64, "programmazione" => 29, "programmazione_avanzata" => 30, "programmazione_totale" => 31, "ingegneria" => array( $CRAFTING_ARMI, $CRAFTING_PROTESI, $CRAFTING_GADGET_SHIELD, $CRAFTING_SCUDI_ESOSCHELE ) ); $MAPPA_COSTO_CLASSI_CIVILI = array(0, 20, 40, 60, 80, 100, 120); $PREREQUISITO_TUTTE_ABILITA = -1; $PREREQUISITO_F_TERRA_T_SCELTO = -2; $PREREQUISITO_5_SUPPORTO_BASE = -3; $PREREQUISITO_3_GUASTATOR_BASE = -4; $PREREQUISITO_4_SPORTIVO = -5; $PREREQUISITO_3_ASSALTATA_BASE = -6; $PREREQUISITO_3_GUASTATOR_AVAN = -7; $PREREQUISITO_3_ASSALTATA_AVAN = -8; $PREREQUISITO_15_GUARDIAN_BASE = -9; $PREREQUISITO_5_GUARDIANO_BAAV = -10; $PREREQUISITO_4_ASSALTATO_BASE = -11; $PREREQUISITO_7_SUPPORTO_BASE = -12; $PREREQUISITO_SMUOVER_MP_RESET = -13; $PREREQUISITO_15_GUARDIAN_AVAN = -14; $PREREQUISITO_15_ASSALTAT_BASE = -15; $PREREQUISITO_15_ASSALTAT_AVAN = -16; $PREREQUISITO_15_SUPPORTO_BASE = -17; $PREREQUISITO_15_SUPPORTO_AVAN = -18; $PREREQUISITO_15_GUASTATO_BASE = -19; $PREREQUISITO_15_GUASTATO_AVAN = -20; $PREREQUISITO_3_GUASTATORE = -21; $INFINITE_MONEY_PGS = [1]; $ID_ABILITA_F_TERRA = 135; $ID_ABILITA_T_SCELTO = 130; $ID_ABILITA_IDOLO = 12; $ID_ABILITA_SMUOVERE = 162; $ID_ABILITA_MEDPACK_RESET = 167; $ID_CLASSE_SPORTIVO = 1; $ID_CLASSE_GUARDIANO_BASE = 8; $ID_CLASSE_GUARDIANO_AVANZATO = 9; $ID_CLASSE_ASSALTATORE_BASE = 10; $ID_CLASSE_ASSALTATORE_AVANZATO = 11; $ID_CLASSE_SUPPORTO_BASE = 12; $ID_CLASSE_SUPPORTO_AVANZATO = 13; $ID_CLASSE_GUASTATORE_BASE = 14; $ID_CLASSE_GUASTATORE_AVANZATO = 15; $RUOLI_STAFFER = ["admin", "staff"]; <file_sep>/client/app/scripts/controllers/ComponentsManager.js /** * Created by Miroku on 11/03/2018. */ var ComponentsManager = function() { var SEPARATORE = "££"; return { init: function() { this.componenti_selezionati = {}; this.componenti_da_modificare = {} this.setListeners(); this.impostaTabellaTecnico(); this.impostaTabellaChimico(); }, resettaContatori: function(e) { var t = $(e.currentTarget), table_id = t.parents(".box-body").find("table").attr("id"); this.componenti_selezionati[table_id] = {}; window.localStorage.removeItem("componenti_da_stampare"); $("#" + table_id).find("input[type='number']").val(0); }, resettaBulkEdit: function(e) { var t = $(e.currentTarget), table_id = t.parents(".box-body").find("table").attr("id"); this.componenti_da_modificare[table_id] = {}; $("#" + table_id).find(".icheck").iCheck("uncheck"); }, apriBulkEdit: function(e) { var t = $(e.currentTarget), table_id = t.parents(".box-body").find("table").attr("id"), numDaMod = 0, stessoTipo = true, primoID = Object.keys(this.componenti_da_modificare[table_id])[0], primoComp = this.componenti_da_modificare[table_id][primoID]; for (var compID in this.componenti_da_modificare[table_id]) { numDaMod++ if (primoComp.tipo_componente !== this.componenti_da_modificare[table_id][compID].tipo_componente) stessoTipo = false } if (numDaMod > 1 && stessoTipo) this.mostraModalModifica(e, true); else if (numDaMod < 2) Utils.showMessage("Bisogna spuntare almeno 2 componenti."); else if (!stessoTipo) Utils.showMessage("Non puoi spuntare componenti di tipo diverso."); }, stampaCartellini: function(e) { var t = $(e.currentTarget), table_id = t.parents(".box-body").find("table").attr("id"), componenti = this.componenti_selezionati[table_id]; console.log(this.componenti_selezionati, table_id); if (Object.keys(componenti).length === 0) { var tipo_comp = table_id.replace("tabella_", ""); Utils.showError("Non è stato selezionato nessun componente " + tipo_comp + " da stampare."); return false; } window.localStorage.removeItem("cartellini_da_stampare"); window.localStorage.setItem("cartellini_da_stampare", JSON.stringify({ componente_crafting: componenti })); window.open(Constants.STAMPA_CARTELLINI_PAGE, "Stampa Oggetti"); }, creaComponente: function(tipo, e) { var t = $(e.currentTarget), table_id = t.parents(".box-body").find("table").attr("id"), datatable = this[table_id], dati = datatable.row(t.parents("tr")).data(), modal = $("#modal_modifica_componente_" + table_id); modal.find("form").addClass("new-component"); modal.modal("show"); }, componenteSelezionato: function(e) { var t = $(e.target), num = parseInt(t.val(), 10), table_id = t.parents("table").attr("id"), datatable = this[table_id], dati = datatable.row(t.parents("tr")).data(); if (num > 0) this.componenti_selezionati[table_id][dati.id_componente] = num; else delete this.componenti_selezionati[table_id][dati.id_componente]; }, selezionaComponente: function(e) { $("input[type='number']").val(0); for (var t in this.componenti_selezionati) for (var c in this.componenti_selezionati[t]) $("#ck_" + c).val(this.componenti_selezionati[t][c]); }, renderTipoApp: function(data) { if (data !== null) return data.replaceAll(",", ", ") else return data }, renderAzioni: function() { var pulsanti = ""; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default modifica' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Modifica Componente'><i class='fa fa-pencil'></i></button>"; pulsanti += "<button type='button' " + "class='btn btn-xs btn-default elimina' " + "data-toggle='tooltip' " + "data-placement='top' " + "title='Elimina Componente'><i class='fa fa-trash-o'></i></button>"; return pulsanti; }, renderCheckStampa: function(data, type, row) { return "<div class=\"input-group\">" + "<input type='number' min='0' step='1' value='0' class='form-control' style='width:70px' id='ck_" + row.id_componente + "'>" + "</div>"; }, controllaErroriForm: function(form_obj) { var errori = [], is_bulk_edit = form_obj.bulk_edit === "true"; if (form_obj.id_componente === "" && !is_bulk_edit) errori.push("L'ID del componente non pu&ograve; essere vuoto."); if (form_obj.nome_componente === "" && !is_bulk_edit) errori.push("Il nome del componente non pu&ograve; essere vuoto."); if (errori.length > 0) Utils.showError("Sono stati trovati errori durante l'invio dei dati del componente:<br><ol><li>" + errori.join("</li><li>") + "</li></ol>", null, false); return errori.length > 0; }, componenteModificato: function(modal, tabella) { modal.modal("hide"); tabella.ajax.reload(null, false); Utils.resetSubmitBtn(); }, inviaNuovoComponente: function(data, modal, table_id) { var tosend = data; tosend.tipo_crafting_componente = table_id.replace("tabella_", ""); if (tosend.tipo_applicativo_componente instanceof Array) tosend.tipo_applicativo_componente = tosend.tipo_applicativo_componente.join(","); delete tosend.old_id delete tosend.bulk_edit Utils.requestData( Constants.API_POST_NUOVO_COMPONENTE, "POST", { params: tosend }, "Componente inserito con successo.", null, this.componenteModificato.bind(this, modal, this[table_id]) ); }, inviaModificheComponente: function(data, modal, table_id) { var id = data.old_id, url = Constants.API_POST_EDIT_COMPONENT, msg = "Componente modificato con successo.", dati = this.componenti_da_modificare[table_id]; if (data.bulk_edit === "true" && Object.keys(dati).length > 0) { id = Object.keys(dati).map(function(id) { return id + SEPARATORE + dati[id].nome_componente }); url = Constants.API_POST_BULK_EDIT_COMPONENTS; comps = Object.keys(dati).map( function(id) { return dati[id].nome_componente + " (" + id + ")"; } ); msg = "I seguenti componenti sono stati modificati con successo:<br>" + comps.join(", ") delete data.bulk_edit delete data.id_componente delete data.nome_componente delete data.descrizione_componente } delete data.old_id delete data.bulk_edit Utils.requestData( url, "POST", { id: id, modifiche: data }, msg, null, this.componenteModificato.bind(this, modal, this[table_id]) ); }, inviaDati: function(e) { var t = $(e.currentTarget), modal = t.parents(".modal"), table_id = modal.attr("id").replace("modal_modifica_componente_", ""), form = t.parents(".modal").find("form"), data = Utils.getFormData(form, true), isNew = form.hasClass("new-component"); if (this.controllaErroriForm(data)) return false; if (isNew) this.inviaNuovoComponente(data, modal, table_id) else this.inviaModificheComponente(data, modal, table_id) }, mostraSceltaApplicativo: function(e) { var t = $(e.target); $("#modal_modifica_componente_tabella_tecnico") .find(".tipo_applicativo_componente") .show(500) .removeClass("inizialmente-nascosto"); }, recuperaListaCompSpuntati: function(table_id) { return Object.keys(this.componenti_da_modificare[table_id]).map( function(id) { return this.componenti_da_modificare[table_id][id].nome_componente + " (" + id + "), "; }.bind(this)).join(", "); }, recuperaIDCompSpuntati: function(table_id, prefix) { return Object.keys(this.componenti_da_modificare[table_id]).map( function(id) { return prefix + id }); }, onModalHide: function(e) { var modal = $(e.target); modal.find("form").trigger("reset"); modal.find("form").removeClass("new-component", "edit-component"); modal.find("input[type='checkbox']").iCheck("uncheck"); modal.find(".compat_attuali").html(""); modal.find(".form-group").show() modal.find(".bulk-edit-msg").hide(); modal.find(".bulk-edit-msg .lista-componenti").text("") modal.find("input[name='bulk_edit']").val("false") modal.find("input[name='old_id']").val("") modal.find('.icheck input[type="checkbox"]').iCheck("destroy"); modal.find('.icheck input[type="checkbox"]').iCheck({ checkboxClass: 'icheckbox_square-blue' }); modal.find("[name='tipo_componente']").trigger("change"); }, riempiCampiModifica: function(modal, dati) { modal.find("input[name='old_id']").val(dati.id_componente) for (var d in dati) { if (d === "tipo_applicativo_componente" && dati[d] !== null) { $.each(dati[d].split(","), function(i, e) { var v = e.replace("'", "\\'") modal.find("[name='" + d + "'] option[value='" + v + "']").prop("selected", true); modal.find(".compat_attuali").append("<span>" + v + "<br></span>"); }); } else if (d === "visibile_ravshop_componente") { var checkState = parseInt(dati[d], 10) === 1 ? "check" : "uncheck"; modal.find("[name='" + d + "']").iCheck(checkState); } else { if (dati[d] == "") { modal.find("[name='" + d + "']").val("") modal.find("[name='" + d + "']").attr("placeholder", "[valori differenti]") } else { var val = /\d+,\d+/.test(dati[d]) ? parseFloat(dati[d].replace(",", ".")) : dati[d]; modal.find("[name='" + d + "']").val(val); } } } modal.find("[name='costo_attuale_componente_old']").val(dati.costo_attuale_componente); }, riempiCampiModificaDiGruppo: function(modal, dati) { var primoID = Object.keys(dati)[0], valUguali = JSON.parse(JSON.stringify(dati[primoID])); for (var campo in valUguali) { var primo = dati[primoID][campo], tuttiUguali = true; for (var d in dati) { if (dati[d][campo] !== primo) { tuttiUguali = false; break; } } if (tuttiUguali) valUguali[campo] = primo; else valUguali[campo] = ""; } this.riempiCampiModifica(modal, valUguali); }, mostraModalModifica: function(e, bulk_edit) { var t = $(e.target), table_id = t.parents(".box-body").find("table").attr("id"), datatable = this[table_id], modal = $("#modal_modifica_componente_" + table_id), bulk_edit = typeof bulk_edit !== "undefined" ? bulk_edit === true : false; modal.find("form").addClass("edit-component"); if (bulk_edit) { modal.find("[name='id_componente']").parents(".form-group").hide(); modal.find("[name='nome_componente']").parents(".form-group").hide(); modal.find("[name='descrizione_componente']").parents(".form-group").hide(); modal.find(".bulk-edit-msg .lista-componenti").text(this.recuperaListaCompSpuntati(table_id)) modal.find(".bulk-edit-msg").show(); modal.find("input[name='bulk_edit']").val("true") this.riempiCampiModificaDiGruppo(modal, this.componenti_da_modificare[table_id]) } else { var dati = datatable.row(t.parents("tr")).data(); this.riempiCampiModifica(modal, dati) } $("#modal_modifica_componente_tabella_tecnico").find("[name='tipo_componente']").trigger("change"); modal.modal("show"); }, eliminaComponente: function(id_comp, modal, table_id) { Utils.requestData( Constants.API_POST_REMOVE_COMPONENT, "POST", { id: id_comp }, "Componente eliminato con successo.", null, this.componenteModificato.bind(this, modal, this[table_id]) ); }, mostraConfermaElimina: function(e) { var t = $(e.currentTarget), modal = t.parents(".modal"), table_id = t.parents("table").attr("id"), datatable = this[table_id], dati = datatable.row(t.parents("tr")).data(); Utils.showConfirm("Sicuro di voler eliminare il componente <strong>" + dati.id_componente + "</strong>?<br>" + "ATTENZIONE:<br>Ogni ricetta che contiene questo componente verr&agrave; eliminata a sua volta.", this.eliminaComponente.bind(this, dati.id_componente, modal, table_id), true); }, salvaComponenteDaModificare: function(e) { var t = $(e.currentTarget), table_id = t.parents("table").attr("id"), datatable = this[table_id], dati = datatable.row(t.parents("tr")).data(), key = dati.id_componente; // + SEPARATORE + dati.nome_componente; if (t.is(":checked")) this.componenti_da_modificare[table_id][key] = dati else { if (typeof this.componenti_da_modificare[table_id][key] !== "undefined") delete this.componenti_da_modificare[table_id][key] } }, creaCheckBoxBulkEdit: function(data, type, row, meta) { var table_id = meta.settings.sTableId, checked = typeof this.componenti_da_modificare[table_id][row.id_componente] !== "undefined" ? "checked" : ""; return "<div class='checkbox icheck'>" + "<input type='checkbox' " + "class='modificaComponente' " + checked + ">" + "</div>"; }, setGridListeners: function() { AdminLTEManager.controllaPermessi(); $('input[type="checkbox"]').iCheck("destroy"); $('input[type="checkbox"]').iCheck({ checkboxClass: 'icheckbox_square-blue' }); $("td input.modificaComponente").unbind("ifChanged", this.salvaComponenteDaModificare.bind(this)); $("td input.modificaComponente").on("ifChanged", this.salvaComponenteDaModificare.bind(this)); $("td [data-toggle='popover']").popover("destroy"); $("td [data-toggle='popover']").popover(); $("[data-toggle='tooltip']").tooltip("destroy"); $("[data-toggle='tooltip']").tooltip(); $("td > button.modifica").unbind("click"); $("td > button.modifica").click(this.mostraModalModifica.bind(this)); $("td > button.elimina").unbind("click"); $("td > button.elimina").click(this.mostraConfermaElimina.bind(this)); $("td > button.stampa-cartellino").unbind("click", this.stampaCartellini.bind(this)); $("td > button.stampa-cartellino").click(this.stampaCartellini.bind(this)); $('td input[type="number"]').unbind("change"); $('td input[type="number"]').on("change", this.componenteSelezionato.bind(this)); this.selezionaComponente(); }, erroreDataTable: function(e, settings) { if (!settings.jqXHR || !settings.jqXHR.responseText) { console.log("DataTable error:", e, settings); return false; } var real_error = settings.jqXHR.responseText.replace(/^([\S\s]*?)\{"[\S\s]*/i, "$1"); real_error = real_error.replace("\n", "<br>"); Utils.showError(real_error); }, impostaTabellaTecnico: function() { var columns = [], id = "tabella_tecnico"; this.componenti_da_modificare[id] = {}; this.componenti_selezionati[id] = {}; columns.push({ title: "Stampa", render: this.renderCheckStampa.bind(this) }); columns.push({ title: "Modifica", render: this.creaCheckBoxBulkEdit.bind(this), className: 'text-center modificaComponente', orderable: false }); columns.push({ title: "ID", data: "id_componente" }); columns.push({ title: "Nome", data: "nome_componente" }); columns.push({ title: "Descrizione", data: "descrizione_componente" }); columns.push({ title: "Tipo", data: "tipo_componente" }); columns.push({ title: "Energia", data: "energia_componente" }); columns.push({ title: "Volume", data: "volume_componente" }); columns.push({ title: "Tipo App", data: "tipo_applicativo_componente", render: this.renderTipoApp.bind(this), }); columns.push({ title: "Costo", data: "costo_attuale_componente" }); columns.push({ title: "Effetti", data: "effetto_sicuro_componente" }); columns.push({ title: "Azioni", render: this.renderAzioni.bind(this), orderable: false }); this.tabella_tecnico = $('#' + id) .on("error.dt", this.erroreDataTable.bind(this)) .on("draw.dt", this.setGridListeners.bind(this)) .DataTable({ ajax: function(data, callback) { Utils.requestData( Constants.API_GET_COMPONENTI_AVANZATO, "GET", $.extend(data, { tipo: "tecnico" }), callback ); }, columns: columns, rowId: function(data) { return 'comp_' + data.id_componente; }, order: [ [2, 'asc'] ] }); }, impostaTabellaChimico: function() { var columns = [], id = "tabella_chimico"; this.componenti_da_modificare[id] = {}; this.componenti_selezionati[id] = {}; columns.push({ title: "Stampa", render: this.renderCheckStampa.bind(this) }); columns.push({ title: "Modifica", render: this.creaCheckBoxBulkEdit.bind(this), className: 'text-center modificaComponente', orderable: false }); columns.push({ title: "ID", data: "id_componente" }); columns.push({ title: "Tipo", data: "tipo_componente" }); columns.push({ title: "Nome", data: "nome_componente" }); columns.push({ title: "Descrizione", data: "descrizione_componente" }); columns.push({ title: "Val Curativo", data: "curativo_primario_componente" }); columns.push({ title: "Val Tossico", data: "tossico_primario_componente", type: "num" }); columns.push({ title: "Val Psicotropo", data: "psicotropo_primario_componente", type: "num" }); columns.push({ title: "<NAME>", data: "possibilita_dipendeza_componente", type: "num" }); columns.push({ title: "Costo", data: "costo_attuale_componente", type: "num" }); columns.push({ title: "Azioni", render: this.renderAzioni.bind(this), orderable: false }); this.tabella_chimico = $('#' + id) .on("error.dt", this.erroreDataTable.bind(this)) .on("draw.dt", this.setGridListeners.bind(this)) .DataTable({ ajax: function(data, callback) { Utils.requestData( Constants.API_GET_COMPONENTI_AVANZATO, "GET", $.extend(data, { tipo: "chimico" }), callback ); }, columns: columns, rowId: function(data) { return 'comp_' + data.id_componente; }, order: [ [2, 'asc'] ] }); }, setListeners: function() { $("#btn_creaComponentiTecnico").click(this.creaComponente.bind(this, "tecnico")); $("#btn_creaComponentiChimico").click(this.creaComponente.bind(this, "chimico")); $("#btn_stampaRicetteTecnico").click(this.stampaCartellini.bind(this)); $("#btn_stampaRicetteChimico").click(this.stampaCartellini.bind(this)); $("#btn_resettaContatoriTecnico").click(this.resettaContatori.bind(this)); $("#btn_resettaContatoriChimico").click(this.resettaContatori.bind(this)); $("#btn_invia_modifiche_tabella_tecnico").click(this.inviaDati.bind(this)); $("#btn_invia_modifiche_tabella_chimico").click(this.inviaDati.bind(this)); $("#btn_apriBulkEditChimico").click(this.apriBulkEdit.bind(this)); $("#btn_apriBulkEditTecnico").click(this.apriBulkEdit.bind(this)); $("#btn_resettaBulkEditChimico").click(this.resettaBulkEdit.bind(this)); $("#btn_resettaBulkEditTecnico").click(this.resettaBulkEdit.bind(this)); $("#modal_modifica_componente_tabella_tecnico").find("[name='tipo_componente']").on("change", this.mostraSceltaApplicativo.bind(this)); $("#modal_modifica_componente_tabella_tecnico").on("hidden.bs.modal", this.onModalHide.bind(this)); $("#modal_modifica_componente_tabella_chimico").on("hidden.bs.modal", this.onModalHide.bind(this)); $('.icheck input[type="checkbox"]').iCheck("destroy"); $('.icheck input[type="checkbox"]').iCheck({ checkboxClass: 'icheckbox_square-blue' }); } }; }(); $(function() { ComponentsManager.init(); });<file_sep>/client/app/scripts/models/PulsantieraNumerica.js /** * Created by Miroku on 29/03/2018. */ var PulsantieraNumerica = PulsantieraNumerica || function () { function PulsantieraNumerica( settings ) { this.settings = { valore_max: Infinity, valore_min: -Infinity }; this.settings = $.extend( this.settings, settings ); this.target = $( this.settings.target ); this.pulsantiera = $( this.settings.pulsantiera ); if ( !this.target.is( "input[type='number']" ) ) throw new Error( "Il target deve essere un input di tipo number." ); _setListeners.call( this ); } PulsantieraNumerica.prototype = Object.create( Object.prototype ); PulsantieraNumerica.prototype.constructor = PulsantieraNumerica; function _aggiungiValore( val ) { var new_val = parseFloat( this.target.val() ) + val; if ( new_val > this.settings.valore_max ) new_val = this.settings.valore_max; if ( new_val < this.settings.valore_min ) new_val = this.settings.valore_min; this.target.val( new_val ); } function _setListeners() { this.pulsantiera.find( ".meno10" ).click( _aggiungiValore.bind( this, -10 ) ); this.pulsantiera.find( ".meno1" ).click( _aggiungiValore.bind( this, -1 ) ); this.pulsantiera.find( ".piu1" ).click( _aggiungiValore.bind( this, 1 ) ); this.pulsantiera.find( ".piu10" ).click( _aggiungiValore.bind( this, 10 ) ); } return PulsantieraNumerica; }(); /* $(function () { PulsantieraNumerica.init(); });*/
975b8e0f0011ef50c6fdfaac0e432b4674617e63
[ "SQL", "JavaScript", "Markdown", "Makefile", "PHP", "Dockerfile", "Shell" ]
58
JavaScript
Miroku87/reboot-docker
66c37ace47178ba3c5e21920339c99a6ad89e2fb
65c8ebe09495ebaa9e650812add07851fc716aff
refs/heads/master
<repo_name>jamoji100/bannerPrototype<file_sep>/js/app.js "use strict"; let overlay = document.getElementById('overlay'); let loadbg = document.getElementById('loadbg'); let open = document.getElementById('open'); let close = document.getElementById('close') // close the lightbox and prevent mouseover function closelightBox() { overlay.style.display = "none"; open.removeEventListener("mouseover", load); } // open lightbox and remove loading animation after 3s function load() { loadbg.style.display = "grid"; setTimeout(function () { overlay.style.display = "grid"; loadbg.style.display = "none"; }, 3000); } open.addEventListener("mouseover", load); open.addEventListener("click", load); close.addEventListener("click", closelightBox); <file_sep>/README.md # bannerPrototype Banner of the famous video game! vanilla Js/ Css animations ![Alt text](assets/screen.jpeg)
ab3342a2b4ce0772357f97ed182bcda10b6191fa
[ "JavaScript", "Markdown" ]
2
JavaScript
jamoji100/bannerPrototype
5a77f9934352718590c89c7c2da88ed957d785f5
393ebea2207ee7c78b6b2fbbc36342af5601888c
refs/heads/main
<file_sep>from random import * import turtle as t t.shape('turtle') t.speed(2) vy=20 x=0 y=0 k=0.75 while (1): x += 1 y += vy vy -= 1 if (y<=0): vy = k*abs(vy) t.goto(x, y) t.exitonclick()<file_sep>import turtle as t n=int(input()) l=40 a=15 k=1.2 t.shape('turtle') t.speed(1) for i in range(2**(n-1)): d=0 for j in range(n): if(j==n-1): t.color('green') t.width(3) t.forward(l/k**j) if (j == n - 1): t.color('black') t.width(1) b=(i//2**j)%2 d+=(-1)**b t.left((-1)**b*a) t.penup() t.goto(0, 0) t.pendown() t.right(d*a) t.exitonclick()<file_sep>import turtle turtle.shape('turtle') turtle.right (90) for i in range(10): turtle.forward(i*10+10) turtle.right(90) turtle.forward(i * 10 + 10) turtle.right(90) turtle.forward(i * 10 + 10) turtle.right(90) turtle.forward(i * 10 + 10) turtle.penup() turtle.forward(5) turtle.left(90) turtle.forward(5) turtle.right(180) turtle.pendown() <file_sep>def st(n): for i in range(n): t.forward(200) t.right(180 - 180 / n) import turtle as t t.shape('turtle') st(5) t.penup() t.goto(-200, 0) t.pendown() st(11) t.exitonclick()<file_sep>def cirr (k, n): for i in range(360*12): t.forward(k) t.left (i) t.forward(n) t.right (i) t.right(1) return 0 import turtle as t t.shape('turtle') t.speed(0) n=0.5 cirr(1, n) t.exitonclick()<file_sep>c = [0] * 10 c[0] = (1, 1, 1, 1, 1, 0, 1, 0, 0) c[1] = (0, 1, 0, 1, 0, 0, 0, 1, 0) c[2] = (0, 1, 0, 0, 1, 0, 1, 0, 1) c[3] = (0, 0, 0, 0, 1, 1, 0, 1, 1) c[4] = (1, 1, 0, 1, 0, 1, 0, 0, 0) c[5] = (1, 0, 0, 1, 1, 1, 1, 0, 0) c[6] = (0, 0, 1, 1, 0, 1, 1, 1, 0) c[7] = (0, 0, 1, 0, 1, 0, 0, 1, 0) c[8] = (1, 1, 1, 1, 1, 1, 1, 0, 0) c[9] = (1, 1, 0, 0, 1, 1, 0, 0, 1) def draw1(n): d = c[n] for i in range(9): if d[i]==1: draw2(i+1) t.forward(70) def draw2(n): t.penup() if (n==1): t.pendown() t.right(90) t.forward (40) t.backward (40) t.left(90) t.penup() if (n==2): t.forward(40) draw2(1) t.backward(40) if (n==3): t.right(90) t.forward (40) t.left(90) draw2(1) t.left(90) t.forward(40) t.right(90) if (n==4): t.forward(40) t.right(90) t.forward(40) t.left(90) draw2(1) t.left(90) t.forward(40) t.left(90) t.forward(40) t.right(180) if (n==5): t.left(90) draw2(1) t.right(90) if (n==6): t.right(90) t.forward(40) t.left(180) draw2(1) t.forward(40) t.right(90) if (n==7): t.right(90) t.forward(80) t.left(180) draw2(1) t.forward(80) t.right(90) if (n==8): t.forward(40) t.right(135) t.pendown() t.forward(40*2**0.5) t.penup() t.right(135) t.forward(40) t.right(90) if (n==9): t.right(90) t.forward(80) t.left(135) t.pendown() t.forward(40*2**0.5) t.penup() t.left(90) t.forward(40*2**0.5) t.right(135) A = input().split() for i in range(len(A)): A[i] = int(A[i]) import turtle as t t.shape('turtle') t.penup() t.goto(-360, 0) t.speed(0) for i in range(len(A)): draw1(A[i]) t.exitonclick()<file_sep>import turtle as t t.shape('turtle') t.speed(0) k=0.001 for i in range(360*12): t.forward(k*i) t.left(1) t.exitonclick()<file_sep>def cirl (k): for i in range(360): t.forward(k) t.left(1) return 0 def cirr (k): for i in range(360): t.forward(k) t.right(1) return 0 import turtle as t t.shape('turtle') t.speed(0) t.left(90) k=0.1 for i in range (12): cirl(1+i*k) cirr(1+i*k) t.exitonclick()<file_sep>import turtle as t t.shape('turtle') for i in range (30): t.forward(5*i) t.right(90) t.forward(5*i) t.right(90)<file_sep>def pol(n, l): pi=3.1415926 t.penup() t.left(90) t.forward(l / (2 * np.sin(pi / n))) t.right(90) t.pendown() t.right(360/(2*n)) for i in range(n): t.forward(l) t.right(360/n) t.left(360 / (2 * n)) t.penup() t.right(90) t.forward(l / (2 * np.sin(pi / n))) t.left(90) t.pendown() return 0 import turtle as t import numpy as np t.shape('turtle') t.left(90) for i in range(10): pol(i+3, 100) t.exitonclick()<file_sep>from random import randint import turtle def collide(n, m): turtle.color('red') turtle.penup() turtle.goto(0, 0) s='Вы убили черепашек под номерами '+str(n)+' и '+str(m) turtle.write(s, align='center', font=('Red', 20)) number_of_turtles = 20 t=[0]*20 for i in range(20): t[0][i]=randint(-200, 200) # x t[1][i]=randint(-200, 200) # y t[2][i]=randint(-10, 10) #vx t[3][i]=randint(-10, 10) #vy steps_of_time_number = 100 turtle.penup() turtle.goto(-300, -300) turtle.pendown() turtle.forward(600) turtle.left(90) turtle.forward(600) turtle.left(90) turtle.forward(600) turtle.left(90) turtle.forward(600) turtle.hideturtle() pool = [turtle.Turtle(shape='circle') for i in range(number_of_turtles)] for unit in pool: unit.penup() unit.goto(randint(-200, 200), randint(-200, 200)) for i in range(steps_of_time_number): for unit in pool: unit.forward(2) n=randint(1, number_of_turtles-1) m=randint(1, number_of_turtles) if (m==n): m=n+1 collide(m, n) turtle.exitonclick() <file_sep>#copied from <NAME> import pygame from pygame.draw import * def draw_house(x, y, w, h): ''' x, y - the base points are the upper left corner of the house w - width of the house h - height of the house ''' # house polygon(screen, (22, 20, 0), ([x, y + h], [x + w, y + h], [x + w, y], [x, y])) # windows polygon(screen, (139, 0, 0), ( [x + (w // 8), y + 4 * (h // 6)], [x + 2 * (w // 8), y + 4 * (h // 6)], [x + 2 * (w // 8), y + 5 * (h // 6)], [x + (w // 8), y + 5 * (h // 6)])) polygon(screen, (139, 0, 0), ( [x + 3 * (w // 8), y + 4 * (h // 6)], [x + 4 * (w // 8), y + 4 * (h // 6)], [x + 4 * (w // 8), y + 5 * (h // 6)], [x + 3 * (w // 8), y + 5 * (h // 6)])) polygon(screen, (255, 255, 0), ( [x + 5 * (w // 8), y + 4 * (h // 6)], [x + 6 * (w // 8), y + 4 * (h // 6)], [x + 6 * (w // 8), y + 5 * (h // 6)], [x + 5 * (w // 8), y + 5 * (h // 6)])) # polygon(screen, (128, 128, 128), ([x + (w // 5), y], [x + 2 * (w // 5), y], [x + 2 * (w // 5), y + (h // 2)], [x + (w // 5), y + (h // 2)])) polygon(screen, (128, 128, 128), ( [x + 3 * (w // 5), y], [x + 4 * (w // 5), y], [x + 4 * (w // 5), y + (h // 2)], [x + 3 * (w // 5), y + (h // 2)])) # chimney polygon(screen, (36, 34, 14), ([x + (w // 6), y], [x + 2 * (w // 6), y], [x + 2 * (w // 6), y - h // 4], [x + (w // 6), y - h // 4])) polygon(screen, (36, 34, 14), ( [x + 3 * (w // 6), y], [x + 4 * (w // 6), y], [x + 4 * (w // 6), y - h // 6], [x + 3 * (w // 6), y - h // 6])) # roof polygon(screen, (0, 30, 0), ([x - (w // 8), y], [x + w + (w // 8), y], [x + w, y - (h // 8)], [x, y - (h // 8)])) # balcony polygon(screen, (0, 31, 27), ( [x - (w // 8), y + (h // 2)], [x + w + (w // 8), y + (h // 2)], [x + w + (w // 8), y + (h // 2) + (h // 10)], [x - (w // 8), y + (h // 2) + (h // 10)])) # fence polygon(screen, (0, 31, 27), ( [x - (w // 8), y + (h // 2)], [x + (w // 25), y + (h // 2)], [x + (w // 25), y + (h // 2) - (h // 10)], [x - (w // 8), y + (h // 2) - (h // 10)])) polygon(screen, (0, 31, 27), ([x + w + (w // 8) - (h // 10), y + (h // 2)], [x + w + (w // 8), y + (h // 2)], [x + w + (w // 8), y + (h // 2) - (h // 10)], [x + w + (w // 8) - (h // 10), y + (h // 2) - (h // 10)])) i = 1 while i < 11: polygon(screen, (0, 31, 27), ([x + i * (w // 10), y + (h // 2)], [x + (i + 1) * (w // 10), y + (h // 2)], [x + (i + 1) * (w // 10), y + (h // 2) - (h // 10)], [x + i * (w // 10), y + (h // 2) - (h // 10)])) i += 2 polygon(screen, (0, 31, 27), ( [x - (w // 8), y + (h // 2) - (h // 10)], [x + w + (w // 8), y + (h // 2) - (h // 10)], [x + w + (w // 8), y + (h // 2) - (h // 9)], [x - (w // 8), y + (h // 2) - (h // 9)])) def draw_clouds_1(x, y, h, w): ellipse(screen, (40, 40, 40), (x, y, h, w)) def draw_clouds_2(x, y, h, w): # transparent ellipse(cloud_screen, (30, 30, 30), (x, y, h, w)) def draw_clouds_3(x, y, h, w): ellipse(screen, (60, 60, 60), (x, y, h, w)) def ghost_1(x, y, r, h): circle(screen, (255, 255, 255), (x, y), r) polygon(screen, (255, 255, 255), ([x + r, y], [x + r * 1.2, y + h], [x - r * 1.2, y + h], [x - r, y])) for i in range(6): R = int(r // (2.5)) circle(screen, (255, 255, 255), ((x - r) + R * i, y + h), R) for i in range(6): R = int(r // (2.5)) circle(screen, (0, 0, 0), ((x - r) + R * i, y + h + R), R) # eyes ellipse(screen, (0, 191, 255), (x - 0.5 * r, y - 0.5 * r, r * 0.25, r * 0.5)) ellipse(screen, (0, 191, 255), (x + 0.25 * r, y - 0.5 * r, r * 0.25, r * 0.5)) ellipse(screen, (0, 0, 0), (x - 0.50 * r, y - 0.3 * r, r * 0.25, r * 0.25)) ellipse(screen, (0, 0, 0), (x + 0.25 * r, y - 0.3 * r, r * 0.25, r * 0.25)) def ghost_2(x, y, r, h): # transparent circle(ghost_screen, (255, 255, 255), (x, y), r) polygon(ghost_screen, (255, 255, 255), ([x + r, y], [x + r * 1.2, y + h], [x - r * 1.2, y + h], [x - r, y])) for i in range(6): R = int(r // (2.5)) circle(ghost_screen, (255, 255, 255), ((x - r) + R * i, y + h), R) for i in range(6): R = int(r // (2.5)) circle(ghost_screen, (0, 0, 0), ((x - r) + R * i, y + h + R), R) # eyes ellipse(ghost_screen, (0, 191, 255), (x - 0.5 * r, y - 0.5 * r, r * 0.25, r * 0.5)) ellipse(ghost_screen, (0, 191, 255), (x + 0.25 * r, y - 0.5 * r, r * 0.25, r * 0.5)) ellipse(ghost_screen, (0, 0, 0), (x - 0.50 * r, y - 0.3 * r, r * 0.25, r * 0.25)) ellipse(ghost_screen, (0, 0, 0), (x + 0.25 * r, y - 0.3 * r, r * 0.25, r * 0.25)) pygame.init() FPS = 30 # create screens screen = pygame.display.set_mode((400, 400)) screen.fill((255, 255, 255)) ghost_screen = pygame.Surface((200, 200)) ghost_screen.set_alpha(180) ghost_screen.fill((0, 0, 0)) ghost_screen.set_colorkey((0, 0, 0)) cloud_screen = pygame.Surface((400, 400)) cloud_screen.set_alpha(200) cloud_screen.fill((105, 105, 105)) cloud_screen.set_colorkey((105, 105, 105)) # background polygon(screen, (0, 0, 0), ([0, 150], [400, 150], [400, 400], [0, 400])) polygon(screen, (105, 105, 105), ([0, 0], [0, 150], [400, 150], [400, 0])) # moon circle(screen, (255, 255, 255), (350, 50), 20) draw_house(30, 100, 50, 100) draw_house(30, 300, 50, 100) draw_house(100, 200, 100, 150) draw_clouds_1(200, 20, 250, 30) draw_clouds_3(150, 50, 140, 40) draw_house(150, 60, 50, 100) draw_clouds_3(80, 100, 100, 20) ghost_1(300, 150, 30, 20) ghost_1(300, 350, 30, 20) draw_clouds_2(150, 200, 200, 30) draw_clouds_2(50, 150, 100, 30) screen.blit(cloud_screen, (0, 0)) ghost_2(40, 40, 30, 30) screen.blit(ghost_screen, (130, 300)) pygame.display.update() clock = pygame.time.Clock() finished = False while not finished: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: finished = True pygame.quit() <file_sep>import turtle as t n = int(input()) t.shape('turtle') for i in range(n): t.forward(50) t.stamp() t.backward(50) t.right(360/n) t.left(360/n) t.forward(50) t.exitonclick()<file_sep>from random import * import turtle as t while (1): a=random() b=randint(10, 50) t.right(a*360) t.forward(b) t.exitonclick()<file_sep>def cir(k): pi=3.1415926 t.penup() t.left(90) t.forward(360*k/(2*pi)) t.right(90) t.pendown() for i in range(360): t.forward(k) t.right (1) return 0 def cir2(k): pi=3.1415926 t.penup() t.left(90) t.forward(360*k/(2*pi)) t.right(90) t.pendown() for i in range(180): t.forward(k) t.right (1) return 0 import turtle as t pi=3.1415926 t.shape('turtle') t.speed(0) t.color('yellow') t.begin_fill() cir(1.5) t.end_fill() t.penup() t.color('black') t.goto(0, 0) t.left(90) t.forward(40) t.left(90) t.forward(30) t.color('blue') t.begin_fill() cir(0.2) t.end_fill() t.penup() t.goto(0, 0) t.right(90) t.forward(40) t.right(90) t.forward(30) t.begin_fill() cir(0.2) t.end_fill() t.penup() t.color('black') t.width(6) t.goto(0, 10) t.pendown() t.right(90) t.forward(30) t.penup() t.color('red') cir2(pi/4.5) t.exitonclick()<file_sep>def cir(k): pi=3.1415926 t.penup() t.left(90) t.forward(360/(2*pi)) t.right(90) t.pendown() for i in range(360): t.forward(1) t.right (1) return 0 import turtle as t n = 6 t.shape('turtle') t.speed(0) for i in range(n): t.penup() t.forward(50) t.backward(50) t.right(360/n) t.pendown() cir(1) t.exitonclick()
92494526e2841d187337325c5c0c2d6cf40e5b27
[ "Python" ]
16
Python
firsovviktor/14.09
e7cec2ca69f9dec831f5259750af135a840ea0a6
9df0165f977ecccf94619321569eaf2a6622721b
refs/heads/master
<repo_name>DanielBrozoski/TrabalhoPdP<file_sep>/Knight.java import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Knight extends Personagem{ static String imagens[] = { "a_front0.png", "a_front1.png", "a_front2.png", "a_left0.png" , "a_left1.png" , "a_left2.png", "a_right0.png", "a_right1.png", "a_right2.png", "a_back0.png" , "a_back1.png" , "a_back2.png"}; public Knight(){ super(imagens); } } <file_sep>/Rat.java import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Rat here. * * @author (your name) * @version (a version number or a date) */ public class Rat extends Personagem{ int x, y; static String imagens[] = { "a_front0.png", "a_front1.png", "a_front2.png", "a_left0.png" , "a_left1.png" , "a_left2.png", "a_right0.png", "a_right1.png", "a_right2.png", "a_back0.png" , "a_back1.png" , "a_back2.png"}; boolean init = false; public Rat(){ super(imagens); } @Override public void movimentacao(){ Personagem p = Personagem.getInstance("current"); if(p.gety() <= this.y){ this.animacao(1); y -= 2; } if(p.gety() >= this.y){ this.animacao(2); y += 2; } if(p.getx() <= this.x){ this.animacao(3); x -= 2; } if(p.getx() >= this.x){ this.animacao(4); x += 2; } setLocation(x,y); } } <file_sep>/Mob.java public interface Mob { public void movimentacao(); public void ataque(); public void animacao(int animacao); } <file_sep>/Spawner.java import greenfoot.*; public class Spawner extends Actor{ private Personagem prototipo; private GreenfootImage frame01; private GreenfootImage frame02; private GreenfootImage frame03; private int tempoAni; public Spawner(Personagem prototipo){ this.prototipo = prototipo; frame01 = new GreenfootImage("a06.png"); frame02 = new GreenfootImage("a07.png"); frame03 = new GreenfootImage("a08.png"); setImage(frame01); } public void act(){ tempoAni++; if(tempoAni == 18) tempoAni = 0; animacao(); } public Personagem spawnMonster(){ return (Personagem)prototipo.clone(); } public void animacao(){ if(tempoAni == 0) setImage(frame01); if(tempoAni == 9) setImage(frame02); if(tempoAni == 18) setImage(frame03); } }
e8576436330185684601873e1e4e6346b52b7515
[ "Java" ]
4
Java
DanielBrozoski/TrabalhoPdP
bebf2c11f50d163764768b91fad8309053aba149
dc0bd251c2401b082d6cc60892b955480bbc42d8
refs/heads/master
<repo_name>peta727/dotfiles<file_sep>/dotfilesLink.sh #!/bin/sh ln -sf ~/dotfiles/.vimrc ~/.vimrc ln -sf ~/dotfiles/.gvimrc ~/.gvimrc ln -sf ~/dotfiles/_vimrc ~/_vimrc ln -sf ~/dotfiles/_gvimrc ~/_gvimrc
d46dd4a55f98378d57b790560bc01a69d87492a6
[ "Shell" ]
1
Shell
peta727/dotfiles
50d9f3e54e968ecb79d70cd8fb673744f427aae6
47d86d0bbd5f47b3115e4fbcdc4046d923be4fa5
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.User { public class UserChangeMoney { /// <summary> /// 总列数 /// </summary> public int rows { get; set; } /// <summary> /// 用户金钱改变量集合 /// </summary> public List<UserMoney> ListUserMoney { get; set; } public class UserMoney { public int UserID { get; set; } public string UserName { get; set; } public decimal StartMoney { get; set; } public decimal ChangeMoney { get; set; } public int ChangeType { get; set; } public DateTime DateTime { get; set; } public string Remark { get; set; } public int RoomID { get; set; } public int QunNum { get; set; } public int RoomCardNum { get; set; } public int Riqi { get; set; } } } } <file_sep>using Common; using Dal.User; using Model.User; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bll.User { public class UserInfoBll { /// <summary> /// 分页查数据 /// </summary> /// <param name="page">当前页</param> /// <param name="row">每页数</param> /// <param name="where">查询条件</param> /// <returns></returns> public static List<UserInfoModel.userModel> GetProductByStr(int page, int row, string where, out int allrow) { DataSet ds = UserInfDal.GetProductByStr(page, row, where.ToString()); allrow = 0; if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0) { allrow = int.Parse(ds.Tables[0].Rows[0][0].ToString()); } List<UserInfoModel.userModel> list = new List<UserInfoModel.userModel>(); if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0) { foreach (DataRow dr in ds.Tables[1].Rows) { UserInfoModel.userModel userModel = new UserInfoModel.userModel(); userModel.UserID = dr["UserID"].ToString().ToInt(); userModel.NickName = dr["NickName"].ToString(); userModel.userName = dr["userName"].ToString(); userModel.VipeTime = dr["VipeTime"].ToString().ToDateTime(); userModel.VipLevel = dr["VipLevel"].ToString().ToInt(); userModel.WalletMoney = dr["WalletMoney"].ToString().ToInt(); list.Add(userModel); } } return list; } /// <summary> /// 分页查询数据 /// </summary> /// <param name="page">当前页数</param> /// <param name="row">每页数目</param> /// <param name="where">查询条件</param> /// <param name="allrow">第一张表一共有多少列</param> /// <returns></returns> public static List<UserChangeMoney.UserMoney> GetUserMoney(int page, int row,string where ,out int allrow) { DataSet ds = UserInfDal.GetUserMoneyChange(page,row,where.ToString()); allrow = 0; if(ds.Tables[0]!=null && ds.Tables[0].Rows.Count>0) { allrow = int.Parse(ds.Tables[0].Rows[0][0].ToString()); } List<UserChangeMoney.UserMoney> list = new List<UserChangeMoney.UserMoney>(); if(ds.Tables[1]!=null && ds.Tables[1].Rows.Count>0) { foreach(DataRow dr in ds.Tables[1].Rows) { UserChangeMoney.UserMoney usermoney_new = new UserChangeMoney.UserMoney(); usermoney_new.UserID = Int32.Parse(dr["UserID"].ToString()); usermoney_new.UserName = dr["UserName"].ToString(); usermoney_new.StartMoney = decimal.Parse(dr["StartMoney"].ToString()); usermoney_new.ChangeMoney = decimal.Parse(dr["ChangeMoney"].ToString()) ; usermoney_new.ChangeType = Int32.Parse(dr["ChangeType"].ToString()); usermoney_new.DateTime= DateTime.Parse(dr["DateTime"].ToString()) ; usermoney_new.Remark= dr["Remark"].ToString(); usermoney_new.RoomID= Int32.Parse(dr["RoomID"].ToString()) ; usermoney_new.QunNum= Int32.Parse(dr["QunNum"].ToString()); usermoney_new.RoomCardNum= Int32.Parse(dr["RoomCardNum"].ToString()) ; usermoney_new.Riqi= Int32.Parse(dr["Riqi"].ToString()); list.Add(usermoney_new); } } return list; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace DBHelper { /// <summary> /// SQL 通用类 /// Author:Mr_ls /// Date:2012-3-10 /// </summary> public class SQLHelper { /// <summary> /// 获取连接对象 /// </summary> /// <returns></returns> public static SqlConnection GetConnection() { return new SqlConnection(DBConString.GetSqlStr); } /// <summary> /// 关闭连接对象 /// </summary> /// <param name="con"></param> public static void CloseConn(SqlConnection con) { if (con != null) { if (con.State == ConnectionState.Open) { con.Close(); } con.Dispose(); } } /// <summary> /// 执行事物处理 /// </summary> /// <param name="cmdStr"></param> /// <param name="cmdParams"></param> /// <returns></returns> public static bool ExecuteTransaction(List<string> cmdStr, List<SqlParameter[]> cmdParams) { using (SqlConnection con = GetConnection()) { using (SqlCommand cmd = new SqlCommand()) { try { con.Open(); SqlTransaction tran = con.BeginTransaction(); if (cmdStr.Count != cmdParams.Count) { return false; } for (int i = 0; i < cmdStr.Count; i++) { try { ExecuteNonQuery(con, tran, CommandType.Text, cmdStr[i], cmdParams[i]); } catch (Exception) { tran.Rollback(); return false; } } tran.Commit(); tran.Dispose(); return true; } catch (Exception e) { throw e; } finally { CloseConn(con); } } } } /// <summary> /// 执行事物处理 /// </summary> /// <param name="cmdStr"></param> /// <param name="cmdParams"></param> /// <returns></returns> public static bool ExecuteTransaction(List<string> cmdStr, List<SqlParameter[]> cmdParams, out int exsCount) { using (SqlConnection con = GetConnection()) { using (SqlCommand cmd = new SqlCommand()) { try { con.Open(); SqlTransaction tran = con.BeginTransaction(); exsCount = 0; if (cmdStr.Count != cmdParams.Count) { return false; } for (int i = 0; i < cmdStr.Count; i++) { try { exsCount += ExecuteNonQuery(con, tran, CommandType.Text, cmdStr[i], cmdParams[i]); } catch (Exception) { tran.Rollback(); return false; } } tran.Commit(); tran.Dispose(); return true; } catch (Exception e) { throw e; } finally { CloseConn(con); } } } } /// <summary> /// 执行通用增、删、改方法 /// </summary> /// <param name="cmdType"></param> /// <param name="cmdStr"></param> /// <param name="cmdParams"></param> /// <returns></returns> private static int ExecuteNonQuery(SqlTransaction sqlTran, CommandType cmdType, string cmdStr, SqlParameter[] cmdParams) { return ExecuteNonQuery(GetConnection(), sqlTran, cmdType, cmdStr, cmdParams); } public static int ExecuteNonQuery(SqlConnection con, SqlTransaction sqlTran, CommandType cmdType, string cmdStr, SqlParameter[] cmdParams) { using (SqlCommand cmd = new SqlCommand()) { try { ParamCommand(con, cmd, cmdType, sqlTran, cmdStr, cmdParams); int result = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return result; } catch (Exception e) { throw e; } finally { if (sqlTran == null) { CloseConn(con); } } } } public static int ExecuteNonQuery(CommandType cmdType, string cmdStr, SqlParameter[] cmdParams) { return ExecuteNonQuery(null, cmdType, cmdStr, cmdParams); } public static int ExecuteNonQuery(CommandType cmdType, string cmdStr) { return ExecuteNonQuery(cmdType, cmdStr, null); } /// <summary> /// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。 /// </summary> /// <param name="cmdType"></param> /// <param name="cmdStr"></param> /// <param name="cmdParams"></param> /// <returns></returns> public static object ExecuteScalar(CommandType cmdType, string cmdStr, SqlParameter[] cmdParams) { using (SqlConnection con = GetConnection()) { using (SqlCommand cmd = new SqlCommand()) { try { ParamCommand(con, cmd, cmdType, null, cmdStr, cmdParams); object result = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return result; } catch (Exception e) { throw e; } finally { CloseConn(con); } } } } public static object ExecuteScalar(CommandType cmdType, string cmdStr) { return ExecuteScalar(CommandType.Text, cmdStr, null); } /// <summary> /// 查询返回结果 /// </summary> /// <param name="cmdType"></param> /// <param name="cmdStr"></param> /// <param name="cmdParams"></param> /// <returns></returns> public static DataTable ExecuteTable(CommandType cmdType, string cmdStr, SqlParameter[] cmdParams) { using (SqlConnection con = GetConnection()) { using (SqlCommand cmd = new SqlCommand()) { try { ParamCommand(con, cmd, cmdType, null, cmdStr, cmdParams); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable("Table"); da.Fill(dt); cmd.Parameters.Clear(); return dt; } catch (Exception e) { throw e; } finally { CloseConn(con); } } } } /// <summary> /// 查询返回结果集 /// </summary> /// <param name="cmdType"></param> /// <param name="cmdStr"></param> /// <param name="cmdParams"></param> /// <returns></returns> public static DataSet ExecuteDataSet(CommandType cmdType, string cmdStr, SqlParameter[] cmdParams) { using (SqlConnection con = GetConnection()) { using (SqlCommand cmd = new SqlCommand()) { try { ParamCommand(con, cmd, cmdType, null, cmdStr, cmdParams); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); cmd.Parameters.Clear(); return ds; } catch (Exception e) { throw e; } finally { CloseConn(con); } } } } /// <summary> /// 查询返回结果集 /// </summary> /// <param name="cmdType"></param> /// <param name="cmdStr"></param> /// <param name="cmdParams"></param> /// <returns></returns> public static DataSet ExecuteDataSet(CommandType cmdType, string cmdStr) { return ExecuteDataSet(cmdType, cmdStr, null); } public static DataTable ExecuteTable(CommandType cmdType, string cmdStr) { return ExecuteTable(cmdType, cmdStr, null); } /// <summary> /// 执行SqlCommand对象赋值 /// </summary> /// <param name="con"></param> /// <param name="cmd"></param> /// <param name="cmdType"></param> /// <param name="cmdStr"></param> /// <param name="cmdParams"></param> public static void ParamCommand(SqlConnection con, SqlCommand cmd, CommandType cmdType, SqlTransaction sqlTran, string cmdStr, SqlParameter[] cmdParams) { if (con.State != ConnectionState.Open) { con.Open(); } cmd.Connection = con; cmd.CommandType = cmdType; cmd.CommandText = cmdStr; if (sqlTran != null) { cmd.Transaction = sqlTran; } if (cmdParams != null) { foreach (SqlParameter parm in cmdParams) { if (parm != null) { //2012-03-26 Update 升级 Author:Mr_Ls 解决数据库可以为空字段而参数必须非null值现象 if (parm.Value == null) { parm.Value = DBNull.Value; } cmd.Parameters.Add(parm); } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web.UI.WebControls; namespace Common { public static class ExtentionMethods { #region+++++++++++++++++++++字符串操作与判断++++++++++++++++++++++++++++++ /// <summary> /// 是否为Null或者空字符串(包括string.Empty和"",多个空格也算做"") /// </summary> /// <param name="str">用于判断的目标字符串</param> /// <returns></returns> public static bool IsNullOrEmpty(this String str) { if (!string.IsNullOrWhiteSpace(str)) { return false; } else { return true; } } /// <summary> /// 是否为整型数据 /// </summary> /// <param name="str">用于判断的目标字符串</param> /// <returns></returns> public static bool IsInt(this String str) { if (!string.IsNullOrEmpty(str)) { int temp; return int.TryParse(str, out temp); } else { return false; } } /// <summary> /// 是否为布尔值 /// </summary> /// <param name="str">用于判断的目标字符串</param> /// <returns></returns> public static bool IsBool(this String str) { if (!string.IsNullOrEmpty(str)) { bool temp; return bool.TryParse(str, out temp); } else { return false; } } /// <summary> /// 是否为时间类型的数据 /// </summary> /// <param name="str">用于判断的目标字符串</param> /// <returns></returns> public static bool IsDateTime(this String str) { if (!string.IsNullOrEmpty(str)) { DateTime temp; return DateTime.TryParse(str, out temp); } else { return false; } } /// <summary> /// 是否为单精度浮点型数据 /// </summary> /// <param name="str">用于判断的目标字符串</param> /// <returns></returns> public static bool IsFloat(this String str) { if (!string.IsNullOrEmpty(str)) { float temp; return float.TryParse(str, out temp); } else { return false; } } /// <summary> /// 是否为双精度浮点型数据 /// </summary> /// <param name="str">用于判断的目标字符串</param> /// <returns></returns> public static bool IsDouble(this String str) { if (!string.IsNullOrEmpty(str)) { double temp; return double.TryParse(str, out temp); } else { return false; } } /// <summary> /// 转换成整型数据,转换失败将返回0 /// </summary> /// <param name="str">将要被转换的字符串</param> /// <returns></returns> public static int ToInt(this String str) { if (!string.IsNullOrEmpty(str)) { int temp; if (int.TryParse(str, out temp)) { return temp; } else { return 0; } } else { return 0; } } /// <summary> /// 转换成布尔型数据,转换失败将返回false /// </summary> /// <param name="str">将要被转换的字符串</param> /// <returns></returns> public static bool ToBool(this String str) { if (!string.IsNullOrEmpty(str)) { bool temp; if (bool.TryParse(str, out temp)) { return temp; } else { return false; } } else { return false; } } /// <summary> /// 转换成时间类型数据,转换失败将返回最小时间(DateTime.MinValue) /// </summary> /// <param name="str">将要被转换的字符串</param> /// <returns></returns> public static DateTime ToDateTime(this String str) { if (!string.IsNullOrEmpty(str)) { DateTime temp; if (DateTime.TryParse(str, out temp)) { return temp; } else { return DateTime.MinValue; } } else { return DateTime.MinValue; } } /// <summary> /// 转换成单精度浮点型数据,转换失败将返回0.0f /// </summary> /// <param name="str">将要被转换的字符串</param> /// <returns></returns> public static float ToFloat(this String str) { if (!string.IsNullOrEmpty(str)) { float temp; if (float.TryParse(str, out temp)) { return temp; } else { return 0.0f; } } else { return 0.0f; } } /// <summary> /// 转换成decimal,转换失败将返回0 /// </summary> /// <param name="str">将要被转换的字符串</param> /// <returns></returns> public static decimal ToDecimal(this String str) { if (!string.IsNullOrEmpty(str)) { decimal temp; if (decimal.TryParse(str, out temp)) { return temp; } else { return 0; } } else { return 0; } } /// <summary> /// 将字符串进行Base64编码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string EncodeBase64(this String str) { if (!str.IsNullOrEmpty()) { try { return Convert.ToBase64String(Encoding.Default.GetBytes(str)); } catch { return string.Empty; } } else { return str; } } /// <summary> /// 将字符串进行Base64解码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string DecodeBase64(this String str) { if (!str.IsNullOrEmpty()) { try { return Encoding.Default.GetString(Convert.FromBase64String(str)); } catch { return string.Empty; } } else { return str; } } /// <summary> /// 将字符串进行Url编码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string UrlEncode(this String str) { if (!str.IsNullOrEmpty()) { try { return System.Web.HttpServerUtility.UrlTokenEncode(Encoding.Default.GetBytes(str)); } catch { return string.Empty; } } else { return str; } } /// <summary> /// 将字符串进行Url解码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string UrlDecode(this String str) { if (!str.IsNullOrEmpty()) { try { return Encoding.Default.GetString(System.Web.HttpServerUtility.UrlTokenDecode(str)); } catch { return string.Empty; } } else { return str; } } /// <summary> /// 转换成双精度浮点型数据,转换失败将返回0.0d /// </summary> /// <param name="str">将要被转换的字符串</param> /// <returns></returns> public static double ToDouble(this String str) { if (!string.IsNullOrEmpty(str)) { double temp; if (double.TryParse(str, out temp)) { return temp; } else { return 0.0d; } } else { return 0.0d; } } /// <summary> /// 是否是手机号码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsMobile(this String str) { if (!string.IsNullOrEmpty(str)) { Regex mobileRegx = new Regex("^(\\+[0-9]{1,4}\\-){0,1}1(3|4|6|2|7|9|5|8)[0-9]{9}$"); return mobileRegx.IsMatch(str); } else { return false; } } /// <summary> /// 是否是固定电话 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsPhone(this String str) { if (!string.IsNullOrEmpty(str)) { Regex mobileRegx = new Regex("^(\\+[0-9]{1,4}\\-){0,1}[0-9]{1,5}\\-[0-9]{1,9}$"); return mobileRegx.IsMatch(str); } else { return false; } } /// <summary> /// 是否是电子邮箱地址 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsEmail(this String str) { if (!string.IsNullOrEmpty(str)) { Regex mobileRegx = new Regex("^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})$"); return mobileRegx.IsMatch(str); } else { return false; } } /// <summary> /// 是否是邮政编码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsPostal(this String str) { if (!string.IsNullOrEmpty(str)) { Regex mobileRegx = new Regex("^[0-9]{6}$"); return mobileRegx.IsMatch(str); } else { return false; } } /// <summary> /// 是否是正整数 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsNumber(this String str) { if (!string.IsNullOrEmpty(str)) { Regex mobileRegx = new Regex("^[0-9]{1,}$"); return mobileRegx.IsMatch(str); } else { return false; } } /// <summary> /// 向字符串中指定文本后面添加文本 /// </summary> /// <param name="str"></param> /// <param name="beginStr"></param> /// <param name="value"></param> /// <returns></returns> public static string Insert(this String str, string beginStr, string value) { if (!str.IsNullOrEmpty()) { int start = str.IndexOf(beginStr); if (start < 0) { return str; } else { return str.Insert(start + beginStr.Length, value); } } else { return str; } } /// <summary> /// 是否为英文域名(域名前缀判断,并非整个域名) /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsEnDomainName(this String str) { if (str.IsNullOrEmpty()) { return false; } Regex reg = new Regex("^[0-9a-zA-Z\\-]{2,42}$", RegexOptions.IgnoreCase); return reg.IsMatch(str) && str.IndexOf('-') != 0 && str.LastIndexOf('-') != str.Length - 1; } #endregion #region+++++++++++++++++++++其他++++++++++++++++++++++++++++ /// <summary> /// 当前文本框的值与默认提示值是否相同 /// </summary> /// <param name="textBox"></param> /// <returns></returns> public static bool IsDefaultText(this TextBox textBox) { bool flag = false; if (textBox != null) { if (!string.IsNullOrEmpty(textBox.Attributes["DefaultText"])) { if (textBox.Text.Trim() == textBox.Attributes["DefaultText"].Trim()) { flag = true; } } } return flag; } /// <summary> /// 当前文本框是否输入了值 /// </summary> /// <param name="textBox"></param> /// <returns></returns> public static bool IsNoInput(this TextBox textBox) { bool flag = false; if (textBox != null) { if (textBox.IsDefaultText() || textBox.Text.IsNullOrEmpty()) { flag = true; } } return flag; } /// <summary> /// 获取当前月份中最小的一天的日期时间值 /// </summary> /// <param name="date"></param> /// <returns></returns> public static DateTime GetMinDay(this System.DateTime date) { return date.AddDays(-(date.Day - 1)); } /// <summary> /// 获取当前月份中最大的一天的日期时间值 /// </summary> /// <param name="date"></param> /// <returns></returns> public static DateTime GetMaxDay(this System.DateTime date) { int days = DateTime.DaysInMonth(date.Year, date.Month); if (days == date.Day) { return date; } else { return date.AddDays((days - date.Day)); } } /// <summary> /// 获取当前年份中最小的一个月的日期时间值 /// </summary> /// <param name="date"></param> /// <returns></returns> public static DateTime GetMinMonth(this System.DateTime date) { return date.AddMonths(-(date.Month - 1)); } /// <summary> /// 获取当前年份中最大的一个月的日期时间值 /// </summary> /// <param name="date"></param> /// <returns></returns> public static DateTime GetMaxMonth(this System.DateTime date) { if (date.Month == 12) { return date; } else { return date.AddMonths((12 - date.Month)); } } /// <summary> /// 将时间转换成文本描述形态 /// </summary> /// <returns></returns> public static string ToLocalCnDate(this System.DateTime date) { string str = ""; if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month) { if (date.Day == DateTime.Now.Day) { str = "今天 " + date.ToString("HH:mm"); } else if ((date - DateTime.Now).Days == -1) { str = "昨天 " + date.ToString("HH:mm"); } else if ((date - DateTime.Now).Days == -2) { str = "前天 " + date.ToString("HH:mm"); } else { str = date.ToString("yyyy.MM.dd HH:mm"); } } else { str = date.ToString("yyyy.MM.dd HH:mm"); } return str; } /// <summary> /// 将字符串截取到指定位数 /// </summary> /// <param name="str">当前操作的字符串变量</param> /// <param name="cutLength">截取长度</param> /// <param name="cutEndStr">截取后附加的字符串</param> /// <returns></returns> public static string CutString(this string str, int cutLength, string cutEndStr) { if (str.IsNullOrEmpty() || str.Length <= cutLength || cutLength <= 0) { return str; } else { return str.Substring(0, cutLength) + (cutEndStr.IsNullOrEmpty() ? "" : cutEndStr); } } /// <summary> /// 将指定数量的特定字符串拼凑成一个字符串 /// </summary> /// <param name="num"></param> /// <param name="replaceStr"></param> /// <returns></returns> public static string GetReplaceString(this int num, string replaceStr) { string resultStr = ""; if (!replaceStr.IsNullOrEmpty()) { if (num > 0) { for (int i = 0; i < num; i++) { resultStr += replaceStr; } } } return resultStr; } /// <summary> /// 将Email的@符号前的帐号部分替换成*号 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetSecurityEmail(this string str) { if (str.IsEmail()) { if (str.IndexOf("@") > 1) { string prifx = str.Substring(0, str.IndexOf("@")); int secCount = (int)Math.Floor(prifx.Length / 2.0); if (secCount > 0) { prifx = prifx.Substring(0, secCount) + secCount.GetReplaceString("*"); str = prifx + str.Substring(str.IndexOf("@")); } } } return str; } /// <summary> /// 将手机号码的部分替换成*号 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetSecurityMobile(this string str) { if (str.IsMobile() && str.Length >= 7) { int secCount = 4; if (secCount > 0) { str = str.Substring(0, 3) + secCount.GetReplaceString("*") + str.Substring(6); } } return str; } /// <summary> /// 获取远程访问用户的Ip地址 /// </summary> /// <param name="request">当前请求对象</param> /// <returns>Ip地址</returns> public static string GetCustomerIP(this System.Web.HttpRequest request) { string ip = ""; //Request.ServerVariables[""]--获取服务变量集合 if (request.ServerVariables["REMOTE_ADDR"] != null) //判断发出请求的远程主机的ip地址是否为空 { //获取发出请求的远程主机的Ip地址 ip = request.ServerVariables["REMOTE_ADDR"].ToString(); } else if (request.ServerVariables["HTTP_VIA"] != null)//判断登记用户是否使用设置代理 { if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) { //获取代理的服务器Ip地址 ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); } else { //获取客户端IP ip = request.UserHostAddress; } } else { //获取客户端IP ip = request.UserHostAddress; } return ip; } /// <summary> /// 获取当前站点的域名 包含http://或https:// /// </summary> /// <param name="request"></param> /// <returns></returns> public static string GetCurrWebSite(this System.Web.HttpRequest request) { string currDomain = request.Url.Scheme + "://" + request.Url.Host + (request.Url.Port == 80 || request.Url.Port == 443 ? "" : (":" + request.Url.Port.ToString())); return currDomain; } /// <summary> /// 将DataSet 转换成带架构的xml /// </summary> /// <param name="ds"></param> /// <returns></returns> public static string GetXmlAndSchema(this DataSet ds) { try { StringBuilder xmlDataStr = new StringBuilder(); System.Xml.XmlWriter witer = System.Xml.XmlWriter.Create(xmlDataStr); ds.WriteXml(witer, XmlWriteMode.WriteSchema); witer.Flush(); witer.Close(); return xmlDataStr.ToString(); } catch (Exception ex) { throw ex; } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.User { public class UserInfoModel { /// <summary> /// 总的数据量 /// </summary> public int rows { get; set; } public List<userModel> userList { get; set; } public class userModel { /// <summary> /// 用户ID /// </summary> public int UserID { get; set; } /// <summary> /// 用户名 /// </summary> public string userName { get; set; } /// <summary> /// 昵称 /// </summary> public string NickName { get; set;} /// <summary> /// 摩尔豆 /// </summary> public int WalletMoney { get; set; } /// <summary> /// VIP等级 /// </summary> public int VipLevel { get; set; } /// <summary> /// VIP到期时间 /// </summary> public DateTime VipeTime { get; set; } } } } <file_sep>using System.Web.Mvc; namespace Web.Areas.test3 { public class test3AreaRegistration : AreaRegistration { public override string AreaName { get { return "test3"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "test3_default", "test3/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } }<file_sep>using Dal.UserInfo; using Model.UserInfo; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bll.UserInfo { public class UserInfoBll { /// <summary> /// 获取员工信息 /// </summary> /// <param name="name">员工账号</param> /// <param name="pwd"><PASSWORD></param> /// <returns>返回员工信息</returns> public static UserInfoBackGroundModel GetUserinfo(string name , string pwd) { return UserInfoDal.GetUser(name, pwd); } /// <summary> /// 判断员工的登录时间是否修改成功 /// </summary> /// <param name="name"></param> /// <returns>返回值位ture成功否知失败</returns> public static bool UpdateUser(string name) { int a = UserInfoDal.UpdateUser(name); if(a==0) { return false; } else if(a>0) { return true; } else { return false; } } /// <summary> /// 判断是否注册成功 /// </summary> /// <param name="name">注册账号</param> /// <param name="pwd">注册密码</param> /// <returns>返回ture成功返回false失败</returns> public static bool AddUser(string name, string pwd) { int a = UserInfoDal.AddUser(name,pwd); if(a==0) { return false; } else if(a>0) { return true; } else { return false; } } } } <file_sep>using DBHelper; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dal.User { public class UserInfDal { /// <summary> /// 分页查数据 /// </summary> /// <param name="page">当前页</param> /// <param name="row">每页数</param> /// <param name="where">查询条件</param> /// <returns></returns> public static DataSet GetProductByStr(int page, int row, string where) { StringBuilder str = new StringBuilder(); str.AppendFormat("select count(1) from TUsers inner join TUserInfo on TUsers.UserID = TUserInfo.UserID where 1=1 {0};", where); str.AppendFormat(@"select T.* from(select TUsers.UserID,TUsers.userName,TUsers.NickName,TUserInfo.WalletMoney,TUserInfo.VipLevel,TUserInfo.VipeTime,ROW_NUMBER()over(order by TUsers.UserID)rw from TUsers inner join TUserInfo on TUsers.UserID = TUserInfo.UserID where 1=1 {2})T where T.rw between {0} and {1}", (page - 1) * row + 1, page * row, where); DataSet ds = SQLHelper.ExecuteDataSet(CommandType.Text, str.ToString()); return ds; } /// <summary> /// /// </summary> /// <param name="page">当前页数</param> /// <param name="row">每页数</param> /// <param name="where">查询条件</param> /// <returns></returns> public static DataSet GetUserMoneyChange(int page, int row, string where) { StringBuilder str = new StringBuilder(); str.AppendFormat("select count(1) from Web_MoneyChangeLog inner join TUsers on Web_MoneyChangeLog.UserID = TUsers.UserID where 1=1 {0};", where); str.AppendFormat("select T.* from (select Web_MoneyChangeLog.UserID,Web_MoneyChangeLog.UserName,Web_MoneyChangeLog.StartMoney,Web_MoneyChangeLog.ChangeMoney,Web_MoneyChangeLog.ChangeType,Web_MoneyChangeLog.DateTime ,Web_MoneyChangeLog.Remark,Web_MoneyChangeLog.RoomID,Web_MoneyChangeLog.QunNum,Web_MoneyChangeLog.RoomCardNum,Web_MoneyChangeLog.Riqi,ROW_NUMBER() over(order by Web_MoneyChangeLog.UserID)rw from Web_MoneyChangeLog inner join TUsers on Web_MoneyChangeLog.UserID = TUsers.UserID where 1=1 {2})T where T.rw between {0} and {1}", (page - 1) * row + 1, page * row, where); DataSet dt = SQLHelper.ExecuteDataSet(CommandType.Text,str.ToString()); return dt; } } } <file_sep>using Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bll { public class SendSMSBll { /// <summary> /// 发送短信, 使用示例: /// string result = EMPTY; // 用来接收返回内容,失败时保存原因描述 /// eg: if (sendSMS("18888888888", "2151202", "%23code%23=" +smscode, out result)) /*发送成功后的处理*/; /// </summary> /// <param name="phoneNumber">符合规范的接收号码</param> /// <param name="tpl_id">短信模板id</param> /// <param name="tpl_value">短信模板值,eg: %23code%23=92138, %23 表示 # 号</param> /// <param name="result">发送成功则返回 true,否则返回 false</param> /// <returns></returns> public static string sendSMS(string phoneNumber, string tpl_id, string tpl_value, out string result) { string providerUrl = "https://sms.yunpian.com/v2/sms/tpl_single_send.json"; // 指定模板发送方式 string apikey = "87f637e44e5d70d2f9a0a259db2e66cf"; //请用自己的apikey代替 string dat = "apikey=" + apikey + "&mobile=" + phoneNumber + "&tpl_id=" + tpl_id + "&tpl_value=" + tpl_value; if (!HttpHelper.PostWebRequest(out result, providerUrl, dat, System.Text.Encoding.UTF8)) return ""; // 请求失败, result 值是网络错误描述 // 错误时返回值示例:{"code":2,"msg":"请求参数格式错误","detail":"验证码类模板#code#值长度必须1-16个字,且只能是字母和数字"} // 成功时返回值示例:{"code":0,"msg":"发送成功","count":1,"fee":0.042,"unit":"RMB","mobile":"18974485282","sid":21830992082} return result; } //public HttpResponseMessage getVoid() { // string smscode = new System.Random(unchecked((int)DateTime.Now.Ticks)).Next(100000, 999999).ToString(); // string tpl_id = "2151204"; // string tpl_value = "%23code%23=" + smscode; // string result = ""; // Bll.SendSMS.sendSMS("15323718917", tpl_id, tpl_value, out result); // Models.CodeResult codeResult = JsonConvert.DeserializeObject<Models.CodeResult>(result); // if (result.StartsWith("{\"code\":0,")) // 发送成功 // { // } // return new HttpResponseMessage() // { // Content = new StringContent(result, Encoding.UTF8, "application/json"), // }; //} } } <file_sep>using Model.User; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; using System.Web.Http.Cors; namespace Web.Areas.User.Controllers { public class UserInfoController : ApiController { /// <summary> /// 分页查找用户信息 /// </summary> /// <param name="page">当前页数</param> /// <param name="row">每页条数</param> /// <returns>返回json,userId:用户ID,userName:用户名,NickName:昵称, /// WalletMoney:摩尔豆,VipLevel:VIP等级,VipeTime:VIP到期时间 /// </returns> [HttpGet] public HttpResponseMessage GetUserInfo(int page,int row) { int allrow = 0; StringBuilder where = new StringBuilder(); List<UserInfoModel.userModel> list = Bll.User.UserInfoBll.GetProductByStr(page, row, where.ToString(), out allrow); UserInfoModel userInfoModel = new UserInfoModel(); userInfoModel.rows = allrow; userInfoModel.userList = list; string json = JsonConvert.SerializeObject(userInfoModel); return new HttpResponseMessage() { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"), }; } /// <summary> /// 增加摩尔豆 /// </summary> /// <param name="userId">用户ID(userId)</param> /// <param name="num">新增数量</param> /// <returns>返回消息(字符串类型直接显示即可)</returns> [HttpGet] public string UpdateUserWalletMoney(int userId,int num) { Model.moerDataEntities moerDataEntities = new Model.moerDataEntities(); Model.TUserInfo userInfo = moerDataEntities.TUserInfo.FirstOrDefault(item => item.UserID == userId); if (userInfo != null) { userInfo.WalletMoney = userInfo.WalletMoney + num; if (moerDataEntities.SaveChanges() > 0) { return "修改成功"; } else { return "修改失败"; } } else { return "查无此数据"; } } /// <summary> /// 玩家游戏金币变化表 /// </summary> /// <param name="page">当前页数</param> /// <param name="row">每页条数</param> /// <returns></returns> [HttpGet] public HttpResponseMessage GetUserMoneyChange(int page, int row) { int allrow = 0; StringBuilder where = new StringBuilder();//条件待定 List<UserChangeMoney.UserMoney> list = Bll.User.UserInfoBll.GetUserMoney(page,row,where.ToString(),out allrow); UserChangeMoney userchangemoney = new UserChangeMoney(); userchangemoney.rows = allrow; userchangemoney.ListUserMoney = list;//把数据放入集合中 string json = JsonConvert.SerializeObject(userchangemoney); return new HttpResponseMessage() { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"), }; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Web.Areas.SendSMS.Models { public class CodeResult { public int code { get; set; } //0代表发送成功,其他code代表出错,详细见"返回值说明"页面 public string msg { get; set; } //例如""发送成功"",或者相应错误信息 public int count { get; set; } //发送成功短信的计费条数(计费条数:70个字一条,超出70个字时按每67字一条计费) public double fee { get; set; } //扣费金额,单位:元,类型:双精度浮点型/double public string unit { get; set; } //计费单位;例如:“RMB” public string mobile { get; set; } //发送手机号 public long sid { get; set; } //短信id,64位整型, 对应Java和C#的long,不可用int解析 } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common { public class HttpHelper { /// <summary> /// 向服务器 POST 数据 /// </summary> /// <param name="result">接收返回内容</param> /// <param name="postUrl">服务器地址</param> /// <param name="paramData">数据(eg: "键=值&name=Kity",注意值部份需用 string System.Web.HttpUtility.UrlPathEncode(string) 进行编码)</param> /// <param name="dataEncode">参数编码(eg: System.Text.Encoding.UTF8)</param> /// <returns>请求成功则用服务器返回内容填充result, 否则用异常消息填充</returns> public static bool PostWebRequest(out string result, string postUrl, string paramData, System.Text.Encoding dataEncode) { try { byte[] byteArray = dataEncode.GetBytes(paramData); //转化 System.Net.HttpWebRequest webReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(postUrl)); //webReq.ProtocolVersion = new Version("1.0"); //webReq.UserAgent = ""; //webReq.CookieContainer = new System.Net.CookieContainer(); webReq.Method = "POST"; webReq.ContentType = "application/x-www-form-urlencoded"; webReq.ContentLength = byteArray.Length; System.IO.Stream newStream = webReq.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length); newStream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webReq.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), dataEncode); result = sr.ReadToEnd(); sr.Close(); response.Close(); newStream.Close(); } catch (Exception ex) { result = ex.Message; return false; } return true; } } } <file_sep>using DBHelper; using Model.UserInfo; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dal.UserInfo { public class UserInfoDal { /// <summary> /// 获取后台员工信息 /// </summary> /// <param name="id">后台员工账号</param> /// <param name="pwd">后台员工密码</param> /// <returns>返回员工账号和密码</returns> public static UserInfoBackGroundModel GetUser(string name, string pwd) { string user_sql = "select * from Tab_UserLogin where UserName = @name and UserPwd = <PASSWORD>"; SqlParameter[] pars = { new SqlParameter("@name",name), new SqlParameter("@pwd",pwd) }; DataTable user_table = SQLHelper.ExecuteTable(CommandType.Text, user_sql, pars); UserInfoBackGroundModel userone = null; if (user_table.Rows.Count > 0) { userone = new UserInfoBackGroundModel(); userone.UserName = user_table.Rows[0]["UserName"].ToString(); userone.UserPwd = user_table.Rows[0]["UserPwd"].ToString(); } return userone; } /// <summary> /// 修改员工的登录时间 /// </summary> /// <param name="name">员工账号</param> /// <returns>返回受影响的行数</returns> public static int UpdateUser(string name) { SqlConnection con = SQLHelper.GetConnection(); string sqlone = "update Tab_UserLogin set User_Time = @time where UserName = @name"; SqlParameter[] pars = { new SqlParameter("@name",name), new SqlParameter("@time",DateTime.Now) }; return SQLHelper.ExecuteNonQuery(CommandType.Text,sqlone,pars); } /// <summary> /// 添加新用户 /// </summary> /// <param name="name">注册账号</param> /// <param name="pwd">注册密码</param> /// <returns>返回受影响的行数</returns> public static int AddUser(string name, string pwd) { int a = 0; string sqltwo = "select * from Tab_UserLogin where UserName = @name"; SqlParameter[] parstwo = { new SqlParameter("@name", name) }; if (SQLHelper.ExecuteScalar(CommandType.Text, sqltwo, parstwo)!=null) { return a;//测试代表用户已存在 } else { string sqlone = "insert into Tab_UserLogin (UserName,User_Time,UserPwd)values(@name,@time,@pwd)"; SqlParameter[] pars = { new SqlParameter("@name",name), new SqlParameter("@time",DateTime.Now), new SqlParameter("@pwd",pwd) }; return SQLHelper.ExecuteNonQuery(CommandType.Text, sqlone, pars); } } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace Web.Areas.Upload.Controllers { public class UploadController : ApiController { //// <summary> /// 上传文件 使用上传后的默认文件名称 /// 默认名称是BodyPart_XXXXXX,BodyPart_加Guid码 /// </summary> /// <returns></returns> [HttpPost]//Route("Upload") public string Upload() { string result = ""; //获取客户端上传文件 HttpFileCollection filelist = HttpContext.Current.Request.Files; if (filelist != null && filelist.Count > 0) { for (int i = 0; i < filelist.Count; i++) { HttpPostedFile file = filelist[i]; string filename = file.FileName;//上传文件夹名称 string FilePath = HttpContext.Current.Server.MapPath(@"/Upload/APK");//目标文件夹 DirectoryInfo di = new DirectoryInfo(FilePath); if (!di.Exists) { di.Create(); } try { file.SaveAs(FilePath+"\\"+filename); return "上传成功"; } catch(Exception ex) { result = "上传文件写入失败:" + ex.Message; } } } else { result = "上传的文件信息不存在!"; } return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Cors; namespace Web.Areas.SendSMS.Controllers { public class SendValidCodeController : ApiController { // GET api/<controller> /// <summary> /// 发送短信验证码 /// </summary> /// <param name="phone">电话号码</param> /// <returns>返回json,其中code=0表示发送成功,否则失败,msg为失败内容</returns> [HttpGet] public HttpResponseMessage sendCode(string phone) { string smscode = new System.Random(unchecked((int)DateTime.Now.Ticks)).Next(100000, 999999).ToString(); string tpl_id = "2776178"; string tpl_value = "%23code%23=" + smscode; string result = ""; Bll.SendSMSBll.sendSMS(phone, tpl_id, tpl_value, out result); Models.CodeResult codeResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.CodeResult>(result); if (result.StartsWith("{\"code\":0,")) // 发送成功 { Model.tab_SendSMS tab_SendSMS = new Model.tab_SendSMS(); tab_SendSMS.code = smscode; tab_SendSMS.isUse = false; tab_SendSMS.phone = phone; tab_SendSMS.workDate = DateTime.Now; Model.moerDataEntities moerDataEntities = new Model.moerDataEntities(); moerDataEntities.tab_SendSMS.Add(tab_SendSMS); if (moerDataEntities.SaveChanges() > 0) { return new HttpResponseMessage() { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json"), }; } else { return new HttpResponseMessage() { Content = new StringContent("{\"code\":0,\"msg\":\"error\"}", System.Text.Encoding.UTF8, "application/json"), }; } } else { return new HttpResponseMessage() { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json"), }; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Common { public class MD5JM { // <summary> /// MD5加密 --16位 /// </summary> /// <param name="strSource">需要加密的明文</param> /// <returns>返回16位加密结果</returns> public static string Get_MD5(string strSource) { var md5 = MD5.Create(); var data = md5.ComputeHash(Encoding.UTF8.GetBytes(strSource)); StringBuilder builder = new StringBuilder(); // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串 for (int i = 0; i < data.Length; i++) { builder.Append(data[i].ToString("X2")); } string result4 = builder.ToString().Substring(8, 16); return result4; } } } <file_sep>using Bll.UserInfo; using Common; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Web.Areas.UserInfo.Controllers { public class UserLoginController : ApiController { /// <summary> /// 员工登录 /// </summary> /// <param name="name">后台员工账号</param> /// <param name="pwd">后台员工密码</param> /// <returns>code=0成功返回员工姓名,code!=0失败返回错误信息</returns> [HttpGet] public HttpResponseMessage GetUser(string name,string pwd) { string newpwd = <PASSWORD>(pwd); Model.UserInfo.UserInfoBackGroundModel new_user = UserInfoBll.GetUserinfo(name, newpwd); //string result = ""; if (new_user!=null) { //插入一条登录信息 登录成功 UserInfoBll.UpdateUser(new_user.UserName); return new HttpResponseMessage()//成功 { Content = new StringContent("{\"code\":0,\"msg\":\""+ new_user.UserName + "\"}", System.Text.Encoding.UTF8, "application/json") }; } else { return new HttpResponseMessage() { Content = new StringContent("{\"code\":1,\"msg\":\"账号密码有误请重新登录\"}", System.Text.Encoding.UTF8, "application/json") }; } } /// <summary> /// 注册新用户 /// </summary> /// <param name="name">注册账号</param> /// <param name="pwd">注册密码</param> /// <returns>code=0成功返回注册账号,code!=0失败返回错误信息</returns> [HttpGet] public HttpResponseMessage AddUser(string name, string pwd) { string new_pwd = <PASSWORD>(pwd); if (UserInfoBll.AddUser(name, new_pwd)) { return new HttpResponseMessage()//成功 { Content = new StringContent("{\"code\":0,\"msg\":\"" + name + "\"}", System.Text.Encoding.UTF8, "application/json") }; } else { return new HttpResponseMessage() { Content = new StringContent("{\"code\":1,\"msg\":\"用户名重复,请重新注册\"}", System.Text.Encoding.UTF8, "application/json") }; } } /// <summary> /// 接口调用 /// </summary> /// <returns>返回4位随机数</returns> //[HttpGet] //public HttpResponseMessage GatCaptcha() //{ // string captcha = RandomNum(4); // return new HttpResponseMessage()//成功 // { // Content = new StringContent(captcha, System.Text.Encoding.UTF8, "application/json") // }; //} /// <summary> /// 生成验证码 /// </summary> /// <param name="n">验证码位数</param> /// <returns>返回4位随机数</returns> //private string RandomNum(int n) //{ // //定义一个包含数字 大写 小写英文字母 // string strchar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"; // //将strchar 字符串转化为数组 // //String.Split 方法放回包含此实例中的子字符串(由指定Char数组的元素分割)的String数组 // string[] VcArray = strchar.Split(','); // string VNum = ""; // //记录上次随机数组,避免产生几个一样的 // int temp = -1; // //采用一个简单的算法以保证 生产随机数的不同 // Random rand = new Random(); // for (int i = 1; i < n + 1; i++) // { // if (temp != -1) // { // //unchecked 关键字用于取消整型算术运算和转换的溢出检查。 // //DataTime.Ticks 属性获取表示此实例的日期和时间的刻度数。 // rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks)); // } // //Random.Next 方法返回一个小于所指定最大值的非负数随机数。 // int t = rand.Next(61); // if (temp != -1 && temp == t) // { // return RandomNum(n); // } // temp = t; // VNum += VcArray[t]; // } // return VNum;//返回生成的随机数 //} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace DBHelper { /// <summary> /// 数据库连接字符串类 /// Author:Mr_Ls /// Date:2012-3-10 /// </summary> public class DBConString { /// <summary> /// 获取SQL连接字符串 /// </summary> public static string GetSqlStr { get { return ConfigurationManager.ConnectionStrings["SqlStr"].ConnectionString; } } } }
ee9d3a787235b547917c5882ee58a59a02cdf34c
[ "C#" ]
18
C#
WuJunYin/Game
f1654f4a6e540d206c3723be7dbf2e3e1c2207b3
c602e0cf0da20beebcd525aea2a39cb0710327c6
refs/heads/master
<repo_name>snowdrop/istio-java-api<file_sep>/scripts/generate_metadata.sh #!/usr/bin/env bash set -e DECL_DIR=${PWD}/istio-common/src/main/resources CRD_FILE=${DECL_DIR}/istio-crd.properties APIS_TMP=${DECL_DIR}/apis_dir.tmp ADAPTERS_TMP=${DECL_DIR}/adapters_dir.tmp TEMPLATES_TMP=${DECL_DIR}/templates_dir.tmp PACKAGES_CSV=${DECL_DIR}/packages.csv function istioVersion() { istioVersion=$(curl -L -s https://api.github.com/repos/istio/istio/releases | grep tag_name | sed "s/ *\"tag_name\": *\"\\(.*\\)\",*/\\1/" | grep -v -E "(alpha|beta|rc)\.[0-9]$" | sort -t"." -k 1,1 -k 2,2 -k 3,3 -k 4,4 | tail -n 1) echo "${istioVersion}" } # Retrieve Istio version if not already done if [ "$1" == "version" ]; then istioVersion exit elif [ -n "$1" ]; then ISTIO_VERSION="${1}" else ISTIO_VERSION=$(istioVersion) fi # Remove previously generated lines sed -e '/##/q' ${PACKAGES_CSV} >${PACKAGES_CSV}.new rm ${PACKAGES_CSV} mv ${PACKAGES_CSV}.new ${PACKAGES_CSV} echo "Using Istio version ${ISTIO_VERSION}" ISTIO_DIR="istio-$ISTIO_VERSION" if [ ! -d "$ISTIO_DIR" ]; then mkdir "${ISTIO_DIR}" else echo "Istio version $ISTIO_VERSION is already present locally, using it" fi go get istio.io/istio@"${ISTIO_VERSION}" go get istio.io/api@"${ISTIO_VERSION}" if [ ! -d "$ISTIO_DIR/api" ]; then pushd "${ISTIO_DIR}" >/dev/null || exit git clone --depth 1 https://github.com/istio/api.git --branch "${ISTIO_VERSION}" --single-branch 2>/dev/null popd >/dev/null || exit fi if [ ! -d "$ISTIO_DIR/istio" ]; then pushd "${ISTIO_DIR}" >/dev/null || exit git clone --depth 1 https://github.com/istio/istio.git --branch "${ISTIO_VERSION}" --single-branch 2>/dev/null popd >/dev/null || exit fi # Generate CRD information cat "$ISTIO_DIR"/api/kubernetes/customresourcedefinitions.gen.yaml | yq -r '(.spec // empty) as $s | (.metadata // empty) as $m | $s.versions[] | "\(.name).\($s.names.kind)=\($m.name) | istio=\($m.labels.istio // "")"' | grep istio.io | sort -f >"${CRD_FILE}" ls -d "${ISTIO_DIR}"/api/*/v* | sed "s/${ISTIO_DIR}/istio.io/" >"${APIS_TMP}" ls -d "${ISTIO_DIR}"/istio/mixer/adapter/*/config | sed "s/${ISTIO_DIR}/istio.io/" >"${ADAPTERS_TMP}" ls -d "${ISTIO_DIR}"/istio/mixer/template/*/ | sed "s/${ISTIO_DIR}/istio.io/" >"${TEMPLATES_TMP}" { go run cmd/packageGen/packageGen.go api <"${APIS_TMP}" go run cmd/packageGen/packageGen.go adapter <"${ADAPTERS_TMP}" go run cmd/packageGen/packageGen.go template <"${TEMPLATES_TMP}" } >>"${PACKAGES_CSV}" rm -f ${DECL_DIR}/*.tmp rm -f ${PACKAGES_CSV}.bak <file_sep>/istio-common/src/main/java/me/snowdrop/istio/api/internal/ClassWithInterfaceFieldsDeserializer.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api.internal; import java.io.IOException; import java.lang.reflect.Field; import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.ContextualDeserializer; import com.fasterxml.jackson.databind.node.ObjectNode; import static me.snowdrop.istio.api.internal.ClassWithInterfaceFieldsRegistry.getFieldInfo; /** * @author <a href="<EMAIL>"><NAME></a> */ public class ClassWithInterfaceFieldsDeserializer extends JsonDeserializer implements ContextualDeserializer { private String targetClassName; /* * Needed by Jackson */ public ClassWithInterfaceFieldsDeserializer() { } private ClassWithInterfaceFieldsDeserializer(String targetClassName) { this.targetClassName = targetClassName; } @Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectNode node = p.readValueAsTree(); Class targetClass; try { targetClass = Thread.currentThread().getContextClassLoader().loadClass(targetClassName); } catch (ClassNotFoundException e) { throw new RuntimeException(targetClassName + " doesn't appear to be a known Istio class", e); } final Object result; try { result = targetClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Couldn't create an instance of " + targetClassName, e); } final Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { final Map.Entry<String, JsonNode> field = fields.next(); final String fieldName = field.getKey(); final ClassWithInterfaceFieldsRegistry.FieldInfo info = getFieldInfo(targetClassName, fieldName); Object deserialized = info.deserialize(node, fieldName, targetClass, ctxt); try { final Field targetClassField = targetClass.getDeclaredField(info.target()); targetClassField.setAccessible(true); targetClassField.set(result, deserialized); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException("Couldn't assign '" + deserialized + "' to '" + info.target() + "' target field on '" + targetClassName + "' class", e); } } return result; } @Override public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { final Class<?> classToDeserialize; if (property != null) { final JavaType type = property.getType(); classToDeserialize = type.isContainerType() ? type.getContentType().getRawClass() : type.getRawClass(); } else { classToDeserialize = ctxt.getContextualType().getRawClass(); } return new ClassWithInterfaceFieldsDeserializer(classToDeserialize.getName()); } } <file_sep>/istio-common/src/test/java/me/snowdrop/istio/api/test/Enum.java package me.snowdrop.istio.api.test; /** * @author <a href="<EMAIL>"><NAME></a> */ public enum Enum { A(0); private final int intValue; Enum(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/istio-client-uberjar/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>istio-java-api</artifactId> <groupId>me.snowdrop</groupId> <version>1.7.8-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>istio-client-uberjar</artifactId> <name>Snowdrop :: Istio Java API :: Client uberjar</name> <dependencies> <dependency> <groupId>me.snowdrop</groupId> <artifactId>istio-client</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.fabric8</groupId> <artifactId>kubernetes-model</artifactId> <scope>provided</scope> <optional>true</optional> </dependency> <dependency> <groupId>io.fabric8</groupId> <artifactId>kubernetes-client</artifactId> <scope>provided</scope> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.4</version> <executions> <execution> <id>relocation</id> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <shadedArtifactAttached>true</shadedArtifactAttached> <shadedClassifierName>versioned</shadedClassifierName> <artifactSet> <includes> <include>io.fabric8:kubernetes-model</include> <include>io.fabric8:kubernetes-client</include> <include>me.snowdrop:istio-client</include> <include>me.snowdrop:istio-common</include> <include>me.snowdrop:istio-model</include> </includes> </artifactSet> <relocations> <!-- Let's relocate all user facing packages under: - io.fabric8.kubernetes.api.model.vMAJOR_MINOR - io.fabric8.kubernetes.client/vMAJOR_MINOR --> <relocation> <pattern>io.fabric8.kubernetes.api.model</pattern> <shadedPattern>io.fabric8.kubernetes.api.model.v${k8s-client.majorVersion}_${k8s-client.minorVersion} </shadedPattern> </relocation> <relocation> <pattern>io.fabric8.kubernetes.api.builder</pattern> <shadedPattern> io.fabric8.kubernetes.api.builder.v${k8s-client.majorVersion}_${k8s-client.minorVersion} </shadedPattern> </relocation> <relocation> <pattern>io.fabric8.openshift.api.model</pattern> <shadedPattern>io.fabric8.openshift.api.model.v${k8s-client.majorVersion}_${k8s-client.minorVersion} </shadedPattern> </relocation> <relocation> <pattern>io.fabric8.kubernetes.client</pattern> <!-- workaround for the duplicate relocation --> <shadedPattern>io.fabric8.kubernetes.clnt.v${k8s-client.majorVersion}_${k8s-client.minorVersion} </shadedPattern> </relocation> <relocation> <pattern>io.fabric8.openshift.client</pattern> <!-- workaround for the duplicate relocation --> <shadedPattern>io.fabric8.openshift.clnt.v${k8s-client.majorVersion}_${k8s-client.minorVersion} </shadedPattern> </relocation> <relocation> <pattern>io.fabric8.kubernetes.internal</pattern> <shadedPattern> io.fabric8.kubernetes.clnt.v${k8s-client.majorVersion}_${k8s-client.minorVersion}.internal </shadedPattern> </relocation> </relocations> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" /> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/istio-model/src/test/java/me/snowdrop/istio/api/DurationTest.java package me.snowdrop.istio.api; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author shalk * @create 2020-11-30 */ public class DurationTest { @Test public void testDeserializer() throws JsonProcessingException { ObjectMapper om = new ObjectMapper(); Duration du = new Duration(100_000_000, 1L); final String s1 = om.writeValueAsString(du); assertThat(s1).isEqualTo("\"1s100ms\""); } @Test public void testSerializer() throws JsonProcessingException { ObjectMapper om = new ObjectMapper(); String s = "\"2s100ms\""; final Duration o = om.readerFor(Duration.class).readValue(s); assertThat(o.getNanos()).isEqualTo(100_000_000); assertThat(o.getSeconds()).isEqualTo(2L); } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/mixer/config/descriptor/ValueType.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.api.mixer.config.descriptor; import java.net.InetAddress; import java.net.URI; import java.util.Date; import java.util.Map; import me.snowdrop.istio.api.Duration; /** * ValueType describes the types that values in the Istio system can take. These * are used to describe the type of Attributes at run time, describe the type of * the result of evaluating an expression, and to describe the runtime type of * fields of other descriptors. * * @author <a href="<EMAIL>"><NAME></a> */ public enum ValueType { /** * Invalid, default value. */ VALUE_TYPE_UNSPECIFIED(null), /** * An undiscriminated variable-length string. */ STRING(String.class), /** * An undiscriminated 64-bit signed integer. */ INT64(Integer.class), /** * An undiscriminated 64-bit floating-point value. */ DOUBLE(Double.class), /** * An undiscriminated boolean value. */ BOOL(Boolean.class), /** * A point in time. */ TIMESTAMP(Date.class), /** * An IP address. */ IP_ADDRESS(InetAddress.class), /** * An email address. */ EMAIL_ADDRESS(String.class), // todo: create Email class /** * A URI. */ URI(URI.class), /** * A DNS name. */ DNS_NAME(String.class), // todo: not sure what this represents exactly or how to validate /** * A span between two points in time. */ DURATION(Duration.class), /** * A map string - string, typically used by headers. */ STRING_MAP(Map.class); ValueType(Class associatedType) { this.associatedType = associatedType; } private final Class associatedType; } <file_sep>/istio-client/src/test/java/me/snowdrop/istio/client/it/VirtualServiceIT.java package me.snowdrop.istio.client.it; import io.fabric8.kubernetes.api.model.HasMetadata; import me.snowdrop.istio.api.IstioResource; import me.snowdrop.istio.api.networking.v1beta1.ExactMatchType; import me.snowdrop.istio.api.networking.v1beta1.HTTPMatchRequest; import me.snowdrop.istio.api.networking.v1beta1.HTTPMatchRequestBuilder; import me.snowdrop.istio.api.networking.v1beta1.HTTPRoute; import me.snowdrop.istio.api.networking.v1beta1.HttpStatusErrorType; import me.snowdrop.istio.api.networking.v1beta1.PrefixMatchType; import me.snowdrop.istio.api.networking.v1beta1.StringMatch; import me.snowdrop.istio.api.networking.v1beta1.VirtualService; import me.snowdrop.istio.api.networking.v1beta1.VirtualServiceBuilder; import me.snowdrop.istio.api.networking.v1beta1.VirtualServiceSpec; import me.snowdrop.istio.client.DefaultIstioClient; import me.snowdrop.istio.client.IstioClient; import org.junit.Test; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class VirtualServiceIT { private final IstioClient istioClient = new DefaultIstioClient(); /* apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: reviews-route spec: hosts: - reviews.prod.svc.cluster.local http: - match: - uri: prefix: "/wpcatalog" - uri: prefix: "/consumercatalog" rewrite: uri: "/newcatalog" route: - destination: host: reviews.prod.svc.cluster.local subset: v2 - route: - destination: host: reviews.prod.svc.cluster.local subset: v1 */ @Test public void checkVirtualServiceWithMatch() { //given final String reviewsHost = "reviews.prod.svc.cluster.local"; final VirtualService virtualService = new VirtualServiceBuilder() .withApiVersion("networking.istio.io/v1beta1") .withNewMetadata().withName("reviews-route").endMetadata() .withNewSpec() .addToHosts(reviewsHost) .addNewHttp() .addNewMatch().withNewUri().withNewPrefixMatchType("/wpcatalog").endUri().endMatch() .addNewMatch().withNewUri().withNewPrefixMatchType("/consumercatalog").endUri().endMatch() .withNewRewrite().withUri("/newcatalog").endRewrite() .addNewRoute() .withNewDestination().withHost(reviewsHost).withSubset("v2").endDestination() .endRoute() .endHttp() .addNewHttp() .addNewRoute() .withNewDestination().withHost(reviewsHost).withSubset("v1").endDestination() .endRoute() .endHttp() .endSpec() .build(); //when final VirtualService resultResource = istioClient.v1beta1VirtualService().create(virtualService); //then assertThat(resultResource).isNotNull().satisfies(istioResource -> { assertThat(istioResource.getKind()).isEqualTo("VirtualService"); assertThat(istioResource) .extracting("metadata") .extracting("name") .containsOnly("reviews-route"); }); //and final VirtualServiceSpec resultVirtualServiceSpec = resultResource.getSpec(); assertThat(resultVirtualServiceSpec).satisfies(vs -> { assertThat(vs.getHosts()).containsExactly(reviewsHost); assertThat(vs.getGateways()).isEmpty(); final List<HTTPRoute> httpList = vs.getHttp(); assertThat(httpList).hasSize(2); assertThat(httpList.get(0)).satisfies(http -> { assertThat(http) .extracting("rewrite") .extracting("uri") .containsOnly("/newcatalog"); assertThat(http.getMatch()) .extracting("uri") .extracting("matchType") .extracting("class", "prefix") .containsOnly( tuple(PrefixMatchType.class, "/wpcatalog"), tuple(PrefixMatchType.class, "/consumercatalog") ); assertThat(http.getRoute()) .hasSize(1) .extracting("destination") .extracting("host", "subset") .containsOnly(tuple("reviews.prod.svc.cluster.local", "v2")); }); assertThat(httpList.get(1)).satisfies(http -> { assertThat(http.getRoute()) .hasSize(1) .extracting("destination") .extracting("host", "subset") .containsOnly(tuple("reviews.prod.svc.cluster.local", "v1")); }); //when final Boolean deleteResult = istioClient.v1beta1VirtualService().delete(resultResource); //then assertThat(deleteResult).isTrue(); }); } /* apiVersion: "networking.istio.io/v1beta1" kind: "VirtualService" metadata: name: "reviews-route" spec: hosts: - "reviews.prod.svc.cluster.local" http: - route: - destination: host: "reviews.prod.svc.cluster.local" port: number: 9090 subset: "v2" - route: - destination: host: "reviews.prod.svc.cluster.local" port: number: 9090 subset: "v1" */ @Test public void checkVirtualServiceWithPortSelector() { final String reviewsHost = "reviews.prod.svc.cluster.local"; final VirtualService virtualService = new VirtualServiceBuilder() .withApiVersion("networking.istio.io/v1beta1") .withNewMetadata().withName("reviews-route2").endMetadata() .withNewSpec() .addToHosts(reviewsHost) .addNewHttp() .addNewRoute() .withNewDestination().withHost(reviewsHost).withSubset("v2").withNewPort() .withNumber(9090).endPort().endDestination() .endRoute() .endHttp() .addNewHttp() .addNewRoute() .withNewDestination().withHost(reviewsHost).withSubset("v1").withNewPort() .withNumber(9090).endPort().endDestination() .endRoute() .endHttp() .endSpec() .build(); //when final VirtualService resultResource = istioClient.v1beta1VirtualService().create(virtualService); //then assertThat(resultResource).isNotNull().satisfies(istioResource -> { assertThat(istioResource.getKind()).isEqualTo("VirtualService"); assertThat(istioResource) .extracting("metadata") .extracting("name") .containsOnly("reviews-route2"); }); //and final VirtualServiceSpec resultSpec = resultResource.getSpec(); //and assertThat(resultSpec).satisfies(vs -> { assertThat(vs.getHosts()).containsExactly(reviewsHost); assertThat(vs.getGateways()).isEmpty(); final List<HTTPRoute> httpList = vs.getHttp(); assertThat(httpList).hasSize(2); //assert the host and subset were set correctly assertThat(httpList) .flatExtracting("route") .extracting("destination") .extracting("host", "subset") .containsOnly( tuple("reviews.prod.svc.cluster.local", "v1"), tuple("reviews.prod.svc.cluster.local", "v2") ); //assert the port was correctly assertThat(httpList) .flatExtracting("route") .extracting("destination") .extracting("port") .extracting("number") .containsOnly( 9090, 9090 ); //when final Boolean deleteResult = istioClient.v1beta1VirtualService().delete(resultResource); //then assertThat(deleteResult).isTrue(); }); } /* apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: ratings-route spec: hosts: - ratings.prod.svc.cluster.local http: - route: - destination: host: ratings.prod.svc.cluster.local subset: v1 fault: abort: percent: 10 httpStatus: 400 */ @Test public void checkVirtualServiceAbort() { final String ratingsHost = "ratings.prod.svc.cluster.local"; final VirtualService resultResource = istioClient.v1beta1VirtualService() .create(new VirtualServiceBuilder() .withNewMetadata().withName("ratings-route").endMetadata() .withNewSpec() .addNewHost(ratingsHost) .addNewHttp() .withNewFault() .withNewAbort() .withNewPercentage(10.).withNewHttpStatusErrorType(400) .endAbort() .endFault() .addNewRoute() .withNewDestination().withHost(ratingsHost).withSubset("v1").endDestination() .endRoute() .endHttp() .endSpec() .build() ); //then assertThat(resultResource).isNotNull().satisfies(istioResource -> { assertThat(istioResource.getKind()).isEqualTo("VirtualService"); assertThat(istioResource) .extracting("metadata") .extracting("name") .containsOnly("ratings-route"); }); //and final VirtualServiceSpec resultSpec = resultResource.getSpec(); //and assertThat(resultSpec).satisfies(vs -> { assertThat(vs.getHosts()).containsExactly(ratingsHost); final List<HTTPRoute> httpList = vs.getHttp(); assertThat(httpList).hasSize(1); //assert the host and subset were set correctly assertThat(httpList) .flatExtracting("route") .extracting("destination") .extracting("host", "subset") .containsOnly( tuple(ratingsHost, "v1") ); //assert the fault was correctly set assertThat(httpList.get(0).getFault().getAbort()).satisfies(a -> { assertThat(a.getPercentage().getValue()).isEqualTo(10.); assertThat(a.getErrorType()) .isInstanceOfSatisfying( HttpStatusErrorType.class, e -> assertThat(e.getHttpStatus()).isEqualTo(400) ); }); //when final Boolean deleteResult = istioClient.v1beta1VirtualService().delete(resultResource); //then assertThat(deleteResult).isTrue(); }); } @Test public void checkThatRegisterResourceWorksProperly() { IstioResource resource = null; try { final String ratingsHost = "ratings.prod.svc.cluster.local"; final VirtualService virtualService = new VirtualServiceBuilder() .withApiVersion("networking.istio.io/v1beta1") .withNewMetadata().withName("ratings-route").endMetadata() .withNewSpec() .addToHosts(ratingsHost) .addNewHttp() .addNewRoute() .withNewDestination().withHost(ratingsHost).withSubset("v1") .endDestination() .endRoute() .withNewFault() .withNewAbort() .withNewPercentage() .withValue(10.0) .endPercentage() .withNewHttpStatusErrorType(400) .endAbort() .endFault() .endHttp() .endSpec() .build(); resource = istioClient.registerCustomResource(virtualService); assertThat(resource).isNotNull().satisfies(r -> assertThat(r.getSpec()).isInstanceOf(VirtualServiceSpec.class)); } finally { if (resource != null) { istioClient.v1beta1VirtualService().delete((VirtualService) resource); } } List<IstioResource> resources = null; try { final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("virtual-service.yaml"); resources = istioClient.registerCustomResources(inputStream); assertThat(resources).isNotNull().satisfies(list -> { assertThat(list.size()).isEqualTo(1); final IstioResource r = list.get(0); assertThat(r.getSpec()).isInstanceOf(VirtualServiceSpec.class); }); } finally { if (resources != null) { istioClient.v1beta1VirtualService().delete((VirtualService) resources.get(0)); } } } @Test public void checkThatEditingMatchWorksProperly() { final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("virtual-service-with-matches.yaml"); IstioClient client = new DefaultIstioClient(); List<HasMetadata> result = client.load(inputStream).createOrReplace(); VirtualService done = null; try { assertThat(result).isNotEmpty(); assertThat(result.size()).isEqualTo(1); final HasMetadata hasMetadata = result.get(0); assertThat(hasMetadata).isInstanceOf(VirtualService.class); Map<String, StringMatch> matchMap = new HashMap<>(); matchMap.put("tenantid", new StringMatch(new ExactMatchType("coke"))); HTTPMatchRequest req = new HTTPMatchRequestBuilder().withHeaders(matchMap) .build(); done = istioClient.v1beta1VirtualService().withName("reviews-route") .edit( editedVS -> new VirtualServiceBuilder(editedVS) .editSpec() .removeMatchingFromHttp(h -> h.hasMatchingMatch(m -> m.hasHeaders() && m.getHeaders().equals(matchMap)) && h.hasMatchingRoute(r -> r.buildDestination().getHost().equals("service-coke"))) .endSpec() .build() ); assertThat(done.getSpec().getHttp()) .flatExtracting(HTTPRoute::getMatch) .doesNotContain(req); } finally { if (done != null) { istioClient.v1beta1VirtualService().delete(done); } } } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/policy/v1beta1/HandlerSpecDeserializer.java /** * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package me.snowdrop.istio.api.policy.v1beta1; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import me.snowdrop.istio.api.internal.MixerResourceDeserializer; import me.snowdrop.istio.api.internal.MixerSupportRegistry; import java.io.IOException; /** * @author <a href="<EMAIL>"><NAME></a> */ public class HandlerSpecDeserializer extends JsonDeserializer<HandlerSpec> implements MixerResourceDeserializer<HandlerSpec, HandlerParams> { private static final MixerSupportRegistry registry = new MixerSupportRegistry(); static { registry.loadFromProperties("adapters"); } public HandlerSpecDeserializer() { } @Override public HandlerSpec deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { return (HandlerSpec) deserialize(jsonParser, "compiledAdapter"); } @Override public HandlerSpec newInstance() { return new HandlerSpec(); } public Class<? extends HandlerParams> getImplementationClass(String compiledTemplate) { return registry.getImplementationClass(compiledTemplate).asSubclass(HandlerParams.class); } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/security/v1beta1/Action.java package me.snowdrop.istio.api.security.v1beta1; public enum Action { /** * Allow a request only if it matches the rules. This is the default type. */ ALLOW(0), /** * Deny a request if it matches any of the rules. */ DENY(1); private final int intValue; Action(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/mesh/v1alpha1/AuthenticationPolicy.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api.mesh.v1alpha1; /** * AuthenticationPolicy defines authentication policy. It can be set for * different scopes (mesh, service ...), and the most narrow scope with * non-{@link #INHERIT} value will be used. * Mesh policy cannot be {@link #INHERIT}. * * @author <a href="<EMAIL>"><NAME></a> */ public enum AuthenticationPolicy { /** * Do not encrypt Envoy to Envoy traffic. */ NONE(0), /** * Envoy to Envoy traffic is wrapped into mutual TLS connections. */ MUTUAL_TLS(1), /** * Use the policy defined by the parent scope. Should not be used for mesh * policy. */ INHERIT(1000); private final int intValue; AuthenticationPolicy(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/istio-common/src/main/java/me/snowdrop/istio/api/internal/IstioApiVersion.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.api.internal; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface IstioApiVersion { String value(); } <file_sep>/go.mod module github.com/snowdrop/istio-java-api go 1.13 require ( github.com/ghodss/yaml v1.0.0 github.com/gogo/protobuf v1.3.1 github.com/openshift/api v3.9.1-0.20191008181517-e4fd21196097+incompatible // indirect gonum.org/v1/netlib v0.0.0-20190331212654-76723241ea4e // indirect istio.io/api v0.0.0-20210128181506-0c4b8e54850f istio.io/istio v0.0.0-20210129021145-dcbb9a567ff4 sigs.k8s.io/structured-merge-diff v0.0.0-20190817042607-6149e4549fca // indirect sigs.k8s.io/testing_frameworks v0.1.2 // indirect ) <file_sep>/istio-common/src/main/resources/istio-crd.properties v1alpha2.attributemanifest=attributemanifests.config.istio.io | istio=core v1alpha2.handler=handlers.config.istio.io | istio=mixer-handler v1alpha2.HTTPAPISpec=httpapispecs.config.istio.io | istio= v1alpha2.HTTPAPISpecBinding=httpapispecbindings.config.istio.io | istio= v1alpha2.instance=instances.config.istio.io | istio=mixer-instance v1alpha2.QuotaSpec=quotaspecs.config.istio.io | istio= v1alpha2.QuotaSpecBinding=quotaspecbindings.config.istio.io | istio= v1alpha2.rule=rules.config.istio.io | istio=core v1alpha3.DestinationRule=destinationrules.networking.istio.io | istio= v1alpha3.EnvoyFilter=envoyfilters.networking.istio.io | istio= v1alpha3.Gateway=gateways.networking.istio.io | istio= v1alpha3.ServiceEntry=serviceentries.networking.istio.io | istio= v1alpha3.Sidecar=sidecars.networking.istio.io | istio= v1alpha3.VirtualService=virtualservices.networking.istio.io | istio= v1alpha3.WorkloadEntry=workloadentries.networking.istio.io | istio= v1beta1.AuthorizationPolicy=authorizationpolicies.security.istio.io | istio=security v1beta1.DestinationRule=destinationrules.networking.istio.io | istio= v1beta1.Gateway=gateways.networking.istio.io | istio= v1beta1.PeerAuthentication=peerauthentications.security.istio.io | istio=security v1beta1.RequestAuthentication=requestauthentications.security.istio.io | istio=security v1beta1.ServiceEntry=serviceentries.networking.istio.io | istio= v1beta1.Sidecar=sidecars.networking.istio.io | istio= v1beta1.VirtualService=virtualservices.networking.istio.io | istio= v1beta1.WorkloadEntry=workloadentries.networking.istio.io | istio= <file_sep>/istio-client/src/test/java/me/snowdrop/istio/client/it/GatewayIT.java package me.snowdrop.istio.client.it; import java.util.AbstractMap.SimpleEntry; import me.snowdrop.istio.api.networking.v1beta1.Gateway; import me.snowdrop.istio.api.networking.v1beta1.GatewayBuilder; import me.snowdrop.istio.api.networking.v1beta1.GatewaySpec; import me.snowdrop.istio.client.DefaultIstioClient; import me.snowdrop.istio.client.IstioClient; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class GatewayIT { private final IstioClient istioClient = new DefaultIstioClient(); /* apiVersion: networking.istio.io/v1beta1 kind: Gateway metadata: name: httpbin-gateway spec: selector: istio: ingressgateway # use Istio default gateway implementation servers: - port: number: 80 name: http protocol: HTTP hosts: - "httpbin.example.com" */ @Test public void checkBasicGateway() { //given final Gateway gateway = new GatewayBuilder() .withApiVersion("networking.istio.io/v1beta1") .withNewMetadata() .withName("httpbin-gateway") .endMetadata() .withNewSpec() .addToSelector("istio", "ingressgateway") .addNewServer().withNewPort("http", 80, "HTTP", 80).withHosts("httpbin.example.com").endServer() .endSpec() .build(); //when final Gateway resultResource = istioClient.v1beta1Gateway().create(gateway); //then assertThat(resultResource).isNotNull().satisfies(istioResource -> { assertThat(istioResource.getKind()).isEqualTo("Gateway"); assertThat(istioResource) .extracting("metadata") .extracting("name") .containsOnly("httpbin-gateway"); }); //and final GatewaySpec resultSpec = resultResource.getSpec(); //and assertThat(resultSpec).satisfies(gs -> { assertThat(gs.getSelector()) .containsOnly(new SimpleEntry<>("istio", "ingressgateway")); assertThat(gs.getServers()).hasSize(1); assertThat(gs.getServers().get(0)).satisfies(server -> { assertThat(server.getHosts()).containsExactly("httpbin.example.com"); assertThat(server.getPort()).isNotNull().satisfies(port -> { assertThat(port.getName()).isEqualTo("http"); assertThat(port.getProtocol()).isEqualTo("HTTP"); assertThat(port.getNumber()).isEqualTo(80); }); }); }); //when final Boolean deleteResult = istioClient.v1beta1Gateway().delete(resultResource); //then assertThat(deleteResult).isTrue(); } } <file_sep>/istio-common/src/test/java/me/snowdrop/istio/api/internal/ClassWithInterfaceFieldsRegistryTest.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api.internal; import java.util.Set; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; /** * @author <a href="<EMAIL>"><NAME></a> */ public class ClassWithInterfaceFieldsRegistryTest { @Test public void loadingResourceShouldWork() { final Set<String> knownClasses = ClassWithInterfaceFieldsRegistry.getKnownClasses(); assertThat(knownClasses).isNotEmpty(); assertThat(knownClasses).size().isEqualTo(4); assertThat(knownClasses).contains( "me.snowdrop.istio.api.test.Simple", "me.snowdrop.istio.api.test.Interface", "me.snowdrop.istio.api.test.Class", "me.snowdrop.istio.api.test.Map"); } @Test public void simpleClassShouldDefineSimpleFields() { final String targetClassName = "me.snowdrop.istio.api.test.Simple"; checkFieldFor(targetClassName, "aInt", "aInt", "integer"); checkFieldFor(targetClassName, "aNumber", "aNumber", "number"); checkFieldFor(targetClassName, "aString", "aString", "string"); checkFieldFor(targetClassName, "aBoolean", "aBoolean", "boolean"); Throwable thrown = catchThrowable(() -> ClassWithInterfaceFieldsRegistry.getFieldInfo(targetClassName, "foo")); assertThat(thrown).isInstanceOf(IllegalArgumentException.class) .hasNoCause().hasMessageContaining("foo"); } private void checkFieldFor(String targetClassName, String field, String expectedTarget, String expectedType) { ClassWithInterfaceFieldsRegistry.FieldInfo info = ClassWithInterfaceFieldsRegistry.getFieldInfo(targetClassName, field); assertThat(info).isNotNull(); assertThat(info.target()).isEqualTo(expectedTarget); assertThat(info.type()).isEqualTo(expectedType); } } <file_sep>/istio-client/src/main/java/me/snowdrop/istio/client/IstioDsl.java package me.snowdrop.istio.client; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import me.snowdrop.istio.api.networking.v1alpha3.EnvoyFilter; import me.snowdrop.istio.api.networking.v1alpha3.EnvoyFilterList; import me.snowdrop.istio.api.networking.v1beta1.DestinationRule; import me.snowdrop.istio.api.networking.v1beta1.DestinationRuleList; import me.snowdrop.istio.api.networking.v1beta1.Gateway; import me.snowdrop.istio.api.networking.v1beta1.GatewayList; import me.snowdrop.istio.api.networking.v1beta1.ServiceEntry; import me.snowdrop.istio.api.networking.v1beta1.ServiceEntryList; import me.snowdrop.istio.api.networking.v1beta1.VirtualService; import me.snowdrop.istio.api.networking.v1beta1.VirtualServiceList; import me.snowdrop.istio.api.policy.v1beta1.Handler; import me.snowdrop.istio.api.policy.v1beta1.HandlerList; import me.snowdrop.istio.api.policy.v1beta1.Instance; import me.snowdrop.istio.api.policy.v1beta1.InstanceList; import me.snowdrop.istio.api.security.v1beta1.AuthorizationPolicy; import me.snowdrop.istio.api.security.v1beta1.AuthorizationPolicyList; import me.snowdrop.istio.api.security.v1beta1.PeerAuthentication; import me.snowdrop.istio.api.security.v1beta1.PeerAuthenticationList; import me.snowdrop.istio.api.security.v1beta1.RequestAuthentication; import me.snowdrop.istio.api.security.v1beta1.RequestAuthenticationList; public interface IstioDsl { MixedOperation<me.snowdrop.istio.api.networking.v1alpha3.DestinationRule, me.snowdrop.istio.api.networking.v1alpha3.DestinationRuleList, Resource<me.snowdrop.istio.api.networking.v1alpha3.DestinationRule>> v1alpha3DestinationRule(); MixedOperation<DestinationRule, DestinationRuleList, Resource<DestinationRule>> v1beta1DestinationRule(); MixedOperation<EnvoyFilter, EnvoyFilterList, Resource<EnvoyFilter>> v1alpha3EnvoyFilter(); MixedOperation<Gateway, GatewayList, Resource<Gateway>> v1beta1Gateway(); MixedOperation<me.snowdrop.istio.api.networking.v1alpha3.Gateway, me.snowdrop.istio.api.networking.v1alpha3.GatewayList, Resource<me.snowdrop.istio.api.networking.v1alpha3.Gateway>> v1alpha3Gateway(); MixedOperation<ServiceEntry, ServiceEntryList, Resource<ServiceEntry>> v1beta1ServiceEntry(); MixedOperation<me.snowdrop.istio.api.networking.v1alpha3.ServiceEntry, me.snowdrop.istio.api.networking.v1alpha3.ServiceEntryList, Resource<me.snowdrop.istio.api.networking.v1alpha3.ServiceEntry>> v1alpha3ServiceEntry(); MixedOperation<VirtualService, VirtualServiceList, Resource<VirtualService>> v1beta1VirtualService(); MixedOperation<me.snowdrop.istio.api.networking.v1alpha3.VirtualService, me.snowdrop.istio.api.networking.v1alpha3.VirtualServiceList, Resource<me.snowdrop.istio.api.networking.v1alpha3.VirtualService>> v1alpha3VirtualService(); MixedOperation<Handler, HandlerList, Resource<Handler>> v1beta1Handler(); MixedOperation<Instance, InstanceList, Resource<Instance>> v1beta1Instance(); MixedOperation<AuthorizationPolicy, AuthorizationPolicyList, Resource<AuthorizationPolicy>> v1beta1AuthorizationPolicy(); MixedOperation<RequestAuthentication, RequestAuthenticationList, Resource<RequestAuthentication>> v1beta1RequestAuthentication(); MixedOperation<PeerAuthentication, PeerAuthenticationList, Resource<PeerAuthentication>> v1beta1PeerAuthentication(); } <file_sep>/istio-model/src/test/java/me/snowdrop/istio/api/networking/v1alpha3/EnvoyFilterTest.java /** * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package me.snowdrop.istio.api.networking.v1alpha3; import me.snowdrop.istio.tests.BaseIstioTest; import me.snowdrop.istio.util.StructHelper; import org.junit.Test; import java.io.InputStream; import java.util.Map; import static me.snowdrop.istio.api.networking.v1alpha3.PatchContext.SIDECAR_OUTBOUND; import static org.junit.Assert.assertEquals; /** * @author <a href="<EMAIL>"><NAME></a> */ public class EnvoyFilterTest extends BaseIstioTest { @Test public void loadingFromYAMLIssue99ShouldWork() throws Exception { final InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("envoy-filter-issue99.yaml"); final EnvoyFilter filter = mapper.readValue(inputStream, EnvoyFilter.class); final EnvoyConfigObjectPatch configObjectPatch = filter.getSpec().getConfigPatches().get(0); final EnvoyConfigObjectMatch match = configObjectPatch.getMatch(); assertEquals(SIDECAR_OUTBOUND, match.getContext()); /* value: name: istio.stats typed_config: '@type': type.googleapis.com/udpa.type.v1.TypedStruct type_url: type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm value: config: configuration: | { "debug": "false", "stat_prefix": "istio" } root_id: stats_outbound vm_config: code: local: inline_string: envoy.wasm.stats runtime: envoy.wasm.runtime.null vm_id: stats_outbound */ final Map<String, Object> value = configObjectPatch.getPatch().getValue(); final String actual = StructHelper.get(value, "typed_config.value.config.root_id", String.class); assertEquals("stats_outbound", actual); } } <file_sep>/istio-model-annotator/src/main/java/me/snowdrop/istio/annotator/IstioTypeAnnotator.java /** * Copyright 2017 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.annotator; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.sun.codemodel.JAnnotationArrayMember; import com.sun.codemodel.JAnnotationUse; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JPackage; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Plural; import io.fabric8.kubernetes.model.annotation.Version; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.BuildableReference; import io.sundr.transform.annotations.VelocityTransformation; import io.sundr.transform.annotations.VelocityTransformations; import java.io.Serializable; import java.nio.file.Paths; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.Set; import lombok.EqualsAndHashCode; import lombok.ToString; import me.snowdrop.istio.api.IstioSpec; import me.snowdrop.istio.api.internal.ClassWithInterfaceFieldsDeserializer; import me.snowdrop.istio.api.internal.IstioApiVersion; import me.snowdrop.istio.api.internal.IstioKind; import me.snowdrop.istio.api.internal.IstioSpecRegistry; import me.snowdrop.istio.api.internal.MixerAdapter; import me.snowdrop.istio.api.internal.MixerResourceDeserializer; import me.snowdrop.istio.api.internal.MixerTemplate; import org.jsonschema2pojo.GenerationConfig; import org.jsonschema2pojo.Jackson2Annotator; /** * @author <a href="<EMAIL>"><NAME></a> */ public class IstioTypeAnnotator extends Jackson2Annotator { private static final String BUILDER_PACKAGE = "io.fabric8.kubernetes.api.builder"; private static final String OBJECT_META_CLASS_NAME = "io.fabric8.kubernetes.api.model.ObjectMeta"; private static final String IS_INTERFACE_FIELD = "isInterface"; private static final String EXISTING_JAVA_TYPE_FIELD = "existingJavaType"; public static final String INSTANCE_PARAMS_FQN = "me.snowdrop.istio.api.policy.v1beta1.InstanceParams"; public static final String HANDLER_PARAMS_FQN = "me.snowdrop.istio.api.policy.v1beta1.HandlerParams"; public static final String INSTANCE_SPEC_DESERIALIZER_FQN = "me.snowdrop.istio.api.policy.v1beta1.InstanceSpecDeserializer"; public static final String HANDLER_SPEC_DESERIALIZER_FQN = "me.snowdrop.istio.api.policy.v1beta1.HandlerSpecDeserializer"; public static final String SUPPORTED_TEMPLATES_FQN = "me.snowdrop.istio.api.policy.v1beta1.SupportedTemplates"; public static final String SUPPORTED_ADAPTERS_FQN = "me.snowdrop.istio.api.policy.v1beta1.SupportedAdapters"; private final JDefinedClass objectMetaClass; static { final String strict = System.getenv("ISTIO_STRICT"); if ("true".equals(strict)) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { final String unvisitedCRDs = IstioSpecRegistry.unvisitedCRDNames(); if (!unvisitedCRDs.isEmpty()) { throw new IllegalStateException("The following CRDs were not visited:\n" + unvisitedCRDs); } })); } } public IstioTypeAnnotator(GenerationConfig generationConfig) { super(generationConfig); try { objectMetaClass = new JCodeModel()._class(OBJECT_META_CLASS_NAME); } catch (JClassAlreadyExistsException e) { throw new IllegalStateException("Couldn't load " + OBJECT_META_CLASS_NAME); } } @Override public void typeInfo(JDefinedClass clazz, JsonNode node) { super.typeInfo(clazz, node); final JsonNode template = node.get("template"); if (template != null) { clazz.annotate(MixerTemplate.class).param(MixerResourceDeserializer.INSTANCE_TYPE_FIELD, template.textValue()); } final JsonNode adapter = node.get("adapter"); if (adapter != null) { clazz.annotate(MixerAdapter.class).param(MixerResourceDeserializer.HANDLER_TYPE_FIELD, adapter.textValue()); } } @Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { JAnnotationArrayMember annotationValue = clazz.annotate(JsonPropertyOrder.class).paramArray("value"); annotationValue.param("apiVersion"); annotationValue.param("kind"); annotationValue.param("metadata"); final Iterator<Map.Entry<String, JsonNode>> fields = propertiesNode.fields(); while (fields.hasNext()) { final Map.Entry<String, JsonNode> entry = fields.next(); String key = entry.getKey(); switch (key) { case "kind": case "metadata": case "apiVersion": break; case "deprecatedAllowOrigin": key = "allowOrigin"; default: annotationValue.param(key); } } final JPackage pkg = clazz.getPackage(); final String pkgName = pkg.name(); final int i = pkgName.lastIndexOf('.'); final String version = pkgName.substring(i + 1); if (version.startsWith("v")) { final Optional<IstioSpecRegistry.CRDInfo> kind = IstioSpecRegistry.getCRDInfo(clazz.name(), version); kind.ifPresent(k -> { clazz._implements(IstioSpec.class); final String plural = k.getPlural(); clazz.annotate(IstioKind.class).param("name", k.getKind()).param("plural", plural); final String apiVersion = k.getAPIVersion(); clazz.annotate(IstioApiVersion.class).param("value", apiVersion); clazz.annotate(Version.class).param("value", k.getVersion()); clazz.annotate(Group.class) .param("value", apiVersion.substring(0, apiVersion.indexOf('/'))); clazz.annotate(Plural.class).param("value", plural); }); } clazz.annotate(ToString.class); clazz.annotate(EqualsAndHashCode.class); JAnnotationUse buildable = clazz.annotate(Buildable.class) .param("editableEnabled", false) .param("generateBuilderPackage", true) .param("builderPackage", BUILDER_PACKAGE); buildable.paramArray("refs").annotate(BuildableReference.class) .param("value", objectMetaClass); final JClass instanceParamsClass = clazz.owner().directClass(INSTANCE_PARAMS_FQN); final JClass instanceParamsDeserializer = clazz.owner().directClass(INSTANCE_SPEC_DESERIALIZER_FQN); handleMixerResourceSpec(clazz, instanceParamsClass, instanceParamsDeserializer, "InstanceSpec", SUPPORTED_TEMPLATES_FQN, MixerResourceDeserializer.INSTANCE_TYPE_FIELD); final JClass handlerParamsClass = clazz.owner().directClass(HANDLER_PARAMS_FQN); final JClass handlerParamsDeserializer = clazz.owner().directClass(HANDLER_SPEC_DESERIALIZER_FQN); handleMixerResourceSpec(clazz, handlerParamsClass, handlerParamsDeserializer, "HandlerSpec", SUPPORTED_ADAPTERS_FQN, MixerResourceDeserializer.HANDLER_TYPE_FIELD); final boolean isAdapter = isMixerRelated(clazz, pkgName, "mixer.adapter", "MixerAdapter"); final boolean isTemplate = isMixerRelated(clazz, pkgName, "mixer.template", "MixerTemplate"); if (isAdapter || isTemplate) { if (isTemplate) { // if we're dealing with a template class, we need it to implement the 'InstanceParams' interface clazz._implements(instanceParamsClass); } if (isAdapter) { clazz._implements(handlerParamsClass); } } else if (clazz.name().endsWith("Spec")) { JAnnotationArrayMember arrayMember = clazz.annotate(VelocityTransformations.class).paramArray("value"); arrayMember.annotate(VelocityTransformation.class).param("value", "/istio-resource.vm"); arrayMember.annotate(VelocityTransformation.class).param("value", "/istio-resource-list.vm"); arrayMember.annotate(VelocityTransformation.class).param("value", "/istio-manifest.vm") .param("outputPath", "crd.properties").param("gather", true); arrayMember.annotate(VelocityTransformation.class).param("value", "/istio-mappings-provider.vm") .param("outputPath", Paths.get("me", "snowdrop", "istio", "api", "model", "IstioResourceMappingsProvider.java").toString()) .param("gather", true); } } public void handleMixerResourceSpec(JDefinedClass clazz, JClass paramsClass, JClass specDeserializerClass, String specClassName, String supportedResourcesEnumClass, String polymorphicTypeField) { if (clazz.name().contains(specClassName)) { // change the 'params' field to be of type 'InstanceParams' instead of Struct to be able to have // polymorphic params changeFieldType(clazz, MixerResourceDeserializer.POLYMORPHIC_PARAMS_FIELD, paramsClass); // annotate class with custom deserializer clazz.annotate(JsonDeserialize.class).param("using", specDeserializerClass); // use enum for compiledTemplate field final JClass supported = clazz.owner().directClass(supportedResourcesEnumClass); changeFieldType(clazz, polymorphicTypeField, supported); } } private void changeFieldType(JDefinedClass clazz, String field, JClass newType) { // change params to be of type InstanceParams for polymorphic support final JFieldVar params = clazz.fields().get(field); clazz.removeField(params); final JFieldVar newField = clazz.field(params.mods().getValue(), newType, params.name()); // also change accessors final String capitalizedField = field.substring(0, 1).toUpperCase() + field.substring(1); final String getter = "get" + capitalizedField; final String setter = "set" + capitalizedField; clazz.methods().removeIf(m -> m.name().equals(getter) || m.name().equals(setter)); clazz.method(JMod.PUBLIC, newType, getter).body()._return(JExpr.refthis(field)); final JMethod setParams = clazz.method(JMod.PUBLIC, clazz.owner().VOID, setter); setParams.param(newType, field); setParams.body().assign(JExpr.refthis(field), JExpr.direct(field)); } private boolean isMixerRelated(JDefinedClass clazz, String pkgName, String relevantPkgSubPath, String markerAnnotationName) { return pkgName.contains(relevantPkgSubPath) && clazz.annotations().stream().anyMatch(a -> a.getAnnotationClass().name().contains(markerAnnotationName)); } @Override public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) { propertyName = propertyName.equals("deprecatedAllowOrigin") ? "allowOrigin" : propertyName; super.propertyField(field, clazz, propertyName, propertyNode); if (propertyNode.hasNonNull(IS_INTERFACE_FIELD)) { field.annotate(JsonUnwrapped.class); // todo: fix me, this won't work if a type has several fields using interfaces String interfaceFQN = propertyNode.get(EXISTING_JAVA_TYPE_FIELD).asText(); // create interface if we haven't done it yet try { final JDefinedClass fieldInterface = clazz._interface(interfaceFQN.substring(interfaceFQN.lastIndexOf('.') + 1)); fieldInterface._extends(Serializable.class); } catch (JClassAlreadyExistsException e) { throw new RuntimeException(e); } annotateIfNotDone(clazz); } } public void propertyGetter(JMethod getter, JDefinedClass clazz, String propertyName) { // overridden to avoid annotating the getter } public void propertySetter(JMethod setter, JDefinedClass clazz, String propertyName) { // overridden to avoid annotating the setter } private final Set<JDefinedClass> annotated = new HashSet<>(); private void annotateIfNotDone(JDefinedClass clazz) { if (!annotated.contains(clazz)) { clazz.annotate(JsonDeserialize.class).param("using", ClassWithInterfaceFieldsDeserializer.class); annotated.add(clazz); } } } <file_sep>/istio-model/src/test/java/me/snowdrop/istio/api/cexl/TypedValueTest.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.api.cexl; import me.snowdrop.istio.api.mixer.config.descriptor.ValueType; import me.snowdrop.istio.tests.BaseIstioTest; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author <a href="<EMAIL>"><NAME></a> */ public class TypedValueTest extends BaseIstioTest { @Test public void definedAttributesShouldHaveValidTypes() { // loading AttributeVocabulary validates that specified ValueTypes for attributes do exist assertThat(AttributeVocabulary.getKnownAttributes()).isNotEmpty(); } @Test public void expressionsShouldReturnProperType() { assertThat(TypedValue.from("request.size| 200").getType()).isEqualTo(ValueType.INT64); assertThat(TypedValue.from("request.size | 0").getType()).isEqualTo(ValueType.INT64); assertThat(TypedValue.from("request.headers[\"X-FORWARDED-HOST\"]==\"myhost\"").getType()).isEqualTo(ValueType.BOOL); assertThat(TypedValue.from("request.headers[\"X-FORWARDED-HOST\"] == \"myhost\"").getType()).isEqualTo(ValueType.BOOL); assertThat(TypedValue.from("(request.headers[\"x-user-group\"] == \"admin\") || (request.auth.principal == \"admin\")").getType()).isEqualTo(ValueType.BOOL); assertThat(TypedValue.from("(request.auth.principal | \"nobody\" ) == \"user1\" ").getType()).isEqualTo(ValueType.BOOL); assertThat(TypedValue.from("(source.labels[\"app\"]==\"reviews\") && (source.labels[\"version\"]==\"v3\")").getType()).isEqualTo(ValueType.BOOL); } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/mixer/adapter/cloudwatch/Unit.java /* * * * Copyright (C) 2019 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.mixer.adapter.cloudwatch; /** * @author <a href="<EMAIL>"><NAME></a> */ public enum Unit { None(0), Seconds(1), Microseconds(2), Milliseconds(3), Count(4), Bytes(5), Kilobytes(6), Megabytes(7), Gigabytes(8), Terabytes(9), Bits(10), Kilobits(11), Megabits(12), Gigabits(13), Terabits(14), Percent(15), Bytes_Second(16), Kilobytes_Second(17), Megabytes_Second(18), Gigabytes_Second(19), Terabytes_Second(20), Bits_Second(21), Kilobits_Second(22), Megabits_Second(23), Gigabits_Second(24), Terabits_Second(25), Count_Second(26); private final int intValue; Unit(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/mesh/v1alpha1/H2UpgradePolicy.java package me.snowdrop.istio.api.mesh.v1alpha1; public enum H2UpgradePolicy { /** * Do not upgrade connections to http2. */ DO_NOT_UPGRADE(0), /** * Upgrade the connections to http2. */ UPGRADE(1); private final int intValue; H2UpgradePolicy(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/istio-common/src/main/java/me/snowdrop/istio/api/internal/IstioSpecRegistry.java package me.snowdrop.istio.api.internal; /* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ import me.snowdrop.istio.api.IstioSpec; import java.io.InputStream; import java.util.*; import java.util.stream.Collectors; /** * @author <a href="<EMAIL>"><NAME></a> */ public class IstioSpecRegistry { private static final String ISTIO_PACKAGE_PREFIX = "me.snowdrop.istio."; private static final String ISTIO_API_PACKAGE_PREFIX = ISTIO_PACKAGE_PREFIX + "api."; private static final String ISTIO_MIXER_TEMPLATE_PACKAGE_PREFIX = ISTIO_PACKAGE_PREFIX + "mixer.template."; private static final String ISTIO_ADAPTER_PACKAGE_PREFIX = ISTIO_PACKAGE_PREFIX + "adapter."; private static final Map<String, CRDInfo> crdInfos = new HashMap<>(); static { Properties crdFile = new Properties(); try (final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("istio-crd.properties")) { crdFile.load(inputStream); } catch (Exception e) { throw new RuntimeException("Couldn't load Istio CRD information from classpath", e); } crdInfos.putAll(crdFile.entrySet().stream().collect(Collectors.toMap(IstioSpecRegistry::getCRDKeyFrom, IstioSpecRegistry::getCRDInfoFrom))); } private static CRDInfo getCRDInfoFrom(Map.Entry<Object, Object> entry) { final String[] versionAndClass = String.valueOf(entry.getKey()).split("\\."); final String kind = versionAndClass[1]; // compute class name based on CRD kind String className; if (kind.contains("entry")) { className = kind.replace("entry", "Entry"); } else if (kind.contains("Msg")) { className = kind.replace("Msg", ""); } else if (kind.contains("nothing")) { className = kind.replace("nothing", "Nothing"); } else if (kind.contains("key")) { className = kind.replace("key", "Key"); } else if (kind.contains("span")) { className = kind.replace("span", "Span"); } else { className = kind; } final char c = className.charAt(0); className = className.replaceFirst("" + c, "" + Character.toTitleCase(c)); // compute package name based on CRD FQN and labels final String[] crdDetail = String.valueOf(entry.getValue()).split("\\|"); final String name = crdDetail[0].trim(); final String istioLabel = crdDetail[1].trim().substring(crdDetail[1].lastIndexOf('=')); final String version = versionAndClass[0]; String packageName; switch (istioLabel) { case "mixer-adapter": packageName = ISTIO_ADAPTER_PACKAGE_PREFIX + kind.toLowerCase() + "."; break; case "mixer-instance": packageName = ISTIO_MIXER_TEMPLATE_PACKAGE_PREFIX + kind.toLowerCase() + "."; break; case "core": // override group and version since crd info and package don't match (priority given to package) packageName = ISTIO_API_PACKAGE_PREFIX + "policy.v1beta1."; break; default: final String group = CRDInfo.getGroup(name); packageName = ISTIO_API_PACKAGE_PREFIX + group + "." + version + "."; /*if(!istioLabel.isEmpty() && !group.equals(istioLabel)) { System.out.println(kind + " => " + istioLabel + " / proposed pkg: " + packageName); }*/ } return new CRDInfo(kind, version, name, packageName + className); } public static class CRDInfo { private final String kind; private final String version; private final String crdName; private final String className; private Optional<Class<? extends IstioSpec>> clazz = Optional.empty(); private boolean visited; public CRDInfo(String kind, String version, String crdName, String className) { this.kind = kind; this.version = version; this.crdName = crdName; this.className = className; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CRDInfo crdInfo = (CRDInfo) o; return kind.equals(crdInfo.kind); } @Override public int hashCode() { return kind.hashCode(); } @Override public String toString() { return kind + ":\t" + crdName + "\t=>\t" + className; } public String getGroup() { return getGroup(crdName); } static String getGroup(String crdName) { final int beginIndex = crdName.indexOf('.'); return crdName.substring(beginIndex + 1, crdName.indexOf('.', beginIndex + 1)); } public String getAPIVersion() { return crdName.substring(crdName.indexOf(".") + 1) + "/" + version; } public String getPlural() { return getPlural(crdName); } public String getKind() { return kind; } public String getCrdName() { return crdName; } public String getVersion() { return version; } static String getPlural(String crdName) { final int endIndex = crdName.indexOf('.'); return crdName.substring(0, endIndex); } boolean isUnvisited() { return !visited; } } public static String unvisitedCRDNames() { return crdInfos.values().stream().filter(CRDInfo::isUnvisited).map(CRDInfo::toString).collect(Collectors.joining("\n")); } public static Class<? extends IstioSpec> resolveIstioSpecForKind(String name) { final CRDInfo crdInfo = crdInfos.get(name); if (crdInfo != null) { crdInfo.visited = true; Optional<Class<? extends IstioSpec>> result = crdInfo.clazz; if (!result.isPresent()) { final Class<? extends IstioSpec> clazz = loadClassIfExists(crdInfo.className); crdInfo.clazz = Optional.of(clazz); return clazz; } else { return result.get(); } } else { return null; } } public static String getKindFor(Class<? extends IstioSpec> spec) { try { return spec.newInstance().getKind(); } catch (Exception e) { return null; } } public static Optional<CRDInfo> getCRDInfo(String simpleClassName, String version) { final String key = getCRDKeyFrom(simpleClassName, version); CRDInfo crd = crdInfos.get(key); if (crd != null) { crd.visited = true; return Optional.of(crd); } else { return Optional.empty(); } } private static String getCRDKeyFrom(String simpleClassName, String version) { String key = simpleClassName; if (simpleClassName.endsWith("Spec")) { key = simpleClassName.substring(0, simpleClassName.indexOf("Spec")); } // for some reason, instance and handler don't have the same version as their package if (key.equals("Instance") || key.equals("Handler")) { version = "v1alpha2"; } key = version + key; return key.toLowerCase(); } private static String getCRDKeyFrom(Map.Entry<Object, Object> propEntry) { final String[] versionAndClass = String.valueOf(propEntry.getKey()).split("\\."); return getCRDKeyFrom(versionAndClass[1], versionAndClass[0]); } public static Set<String> getKnownKinds() { return crdInfos.keySet(); } private static Class<? extends IstioSpec> loadClassIfExists(String className) { try { final Class<?> loaded = IstioSpecRegistry.class.getClassLoader().loadClass(className); if (IstioSpec.class.isAssignableFrom(loaded)) { return loaded.asSubclass(IstioSpec.class); } else { throw new IllegalArgumentException(String.format("%s is not an implementation of %s", className, IstioSpec.class.getSimpleName())); } } catch (Throwable t) { throw new IllegalArgumentException(String.format("Cannot load class: %s", className), t); } } public static void main(String[] args) { System.out.println(crdInfos.values().stream() .collect(Collectors.groupingBy(CRDInfo::getGroup)) .entrySet().stream() .map(entry -> entry.getKey() + ":\n\t" + entry.getValue().stream() .map(Object::toString) .sorted(String::compareToIgnoreCase) .collect(Collectors.joining("\n\t"))) .collect(Collectors.joining("\n")) ); } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/mixer/adapter/list/ListEntryType.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.mixer.adapter.list; /** * Determines the type of list that the adapter is consulting. * * @author <a href="<EMAIL>"><NAME></a> */ public enum ListEntryType { /** * List entries are treated as plain strings. */ STRINGS(0), /** * List entries are treated as case-insensitive strings. */ CASE_INSENSITIVE_STRINGS(1), /** * List entries are treated as IP addresses and ranges. */ IP_ADDRESSES(2), /** * List entries are treated as re2 regexp. See [here](https://github.com/google/re2/wiki/Syntax) for the supported syntax. */ REGEX(3); private final int intValue; ListEntryType(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/cmd/generate/generate.go /** * Copyright (C) 2011 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package main import ( "bytes" "encoding/json" "flag" "fmt" "github.com/ghodss/yaml" "github.com/gogo/protobuf/types" "io/ioutil" mesh "istio.io/api/mesh/v1alpha1" mixer "istio.io/api/mixer/v1" networkingv1alpha3 "istio.io/api/networking/v1alpha3" networking "istio.io/api/networking/v1beta1" policy "istio.io/api/policy/v1beta1" security "istio.io/api/security/v1beta1" bypass "istio.io/istio/mixer/adapter/bypass/config" circonus "istio.io/istio/mixer/adapter/circonus/config" cloudwatch "istio.io/istio/mixer/adapter/cloudwatch/config" denier "istio.io/istio/mixer/adapter/denier/config" dogstatsd "istio.io/istio/mixer/adapter/dogstatsd/config" fluentd "istio.io/istio/mixer/adapter/fluentd/config" kubernetesenv "istio.io/istio/mixer/adapter/kubernetesenv/config" list "istio.io/istio/mixer/adapter/list/config" memquota "istio.io/istio/mixer/adapter/memquota/config" opa "istio.io/istio/mixer/adapter/opa/config" prometheus "istio.io/istio/mixer/adapter/prometheus/config" redisquota "istio.io/istio/mixer/adapter/redisquota/config" solarwinds "istio.io/istio/mixer/adapter/solarwinds/config" stackdriver "istio.io/istio/mixer/adapter/stackdriver/config" statsd "istio.io/istio/mixer/adapter/statsd/config" stdio "istio.io/istio/mixer/adapter/stdio/config" zipkin "istio.io/istio/mixer/adapter/zipkin/config" "istio.io/istio/mixer/template/apikey" "istio.io/istio/mixer/template/authorization" "istio.io/istio/mixer/template/checknothing" "istio.io/istio/mixer/template/edge" "istio.io/istio/mixer/template/listentry" "istio.io/istio/mixer/template/logentry" "istio.io/istio/mixer/template/metric" "istio.io/istio/mixer/template/quota" "istio.io/istio/mixer/template/reportnothing" "istio.io/istio/mixer/template/tracespan" "log" "os" "reflect" "strings" "bufio" "github.com/snowdrop/istio-java-api/pkg/schemagen" ) type Schema struct { Struct types.Struct Value types.Value BoolValue types.Value_BoolValue ListValue types.Value_ListValue NumberValue types.Value_NumberValue NullValue types.Value_NullValue StringValue types.Value_StringValue StructValue types.Value_StructValue MeshConfig mesh.MeshConfig ProxyConfig mesh.ProxyConfig CustomTag mesh.Tracing_CustomTag EnvironmentCustomTag mesh.Tracing_CustomTag_Environment HeaderCustomTag mesh.Tracing_CustomTag_Header LiteralCustomTag mesh.Tracing_CustomTag_Literal Attributes mixer.Attributes AttributeValue mixer.Attributes_AttributeValue CheckRequest mixer.CheckRequest QuotaParams mixer.CheckRequest_QuotaParams CheckResponse mixer.CheckResponse QuotaResult mixer.CheckResponse_QuotaResult CompressedAttributes mixer.CompressedAttributes ReferencedAttributes mixer.ReferencedAttributes ReportRequest mixer.ReportRequest ReportResponse mixer.ReportResponse StringMap mixer.StringMap EnvoyFilter networkingv1alpha3.EnvoyFilter ClusterObjectTypes networkingv1alpha3.EnvoyFilter_EnvoyConfigObjectMatch_Cluster ListenerObjectTypes networkingv1alpha3.EnvoyFilter_EnvoyConfigObjectMatch_Listener RouteConfigurationObjectTypes networkingv1alpha3.EnvoyFilter_EnvoyConfigObjectMatch_RouteConfiguration V1Alpha3Gateway networkingv1alpha3.Gateway V1Alpha3DestinationRule networkingv1alpha3.DestinationRule V1Alpha3SimpleLoadBalancerSettings networkingv1alpha3.LoadBalancerSettings_Simple V1Alpha3ConsistentHashLoadBalancerSettings networkingv1alpha3.LoadBalancerSettings_ConsistentHash V1Alpha3HttpCookieHashKey networkingv1alpha3.LoadBalancerSettings_ConsistentHashLB_HttpCookie V1Alpha3HttpHeaderNameHashKey networkingv1alpha3.LoadBalancerSettings_ConsistentHashLB_HttpHeaderName V1Alpha3UseSourceIpHashKey networkingv1alpha3.LoadBalancerSettings_ConsistentHashLB_UseSourceIp V1Alpha3ExactStringMatch networkingv1alpha3.StringMatch_Exact V1Alpha3PrefixStringMatch networkingv1alpha3.StringMatch_Prefix V1Alpha3RegexStringMatch networkingv1alpha3.StringMatch_Regex V1Alpha3VPortSelector networkingv1alpha3.PortSelector V1Alpha3ExponentialDelay networkingv1alpha3.HTTPFaultInjection_Delay_ExponentialDelay V1Alpha3FixedDelay networkingv1alpha3.HTTPFaultInjection_Delay_FixedDelay V1Alpha3GrpcStatusAbort networkingv1alpha3.HTTPFaultInjection_Abort_GrpcStatus V1Alpha3Http2ErrorAbort networkingv1alpha3.HTTPFaultInjection_Abort_Http2Error V1Alpha3HttpStatusAbort networkingv1alpha3.HTTPFaultInjection_Abort_HttpStatus V1Alpha3ServiceEntry networkingv1alpha3.ServiceEntry V1Alpha3VirtualService networkingv1alpha3.VirtualService V1Alpha3Sidecar networkingv1alpha3.Sidecar V1Alpha3WorkloadEntry networkingv1alpha3.WorkloadEntry PeerAuthentication security.PeerAuthentication RequestAuthentication security.RequestAuthentication Gateway networking.Gateway DestinationRule networking.DestinationRule SimpleLoadBalancerSettings networking.LoadBalancerSettings_Simple ConsistentHashLoadBalancerSettings networking.LoadBalancerSettings_ConsistentHash HttpCookieHashKey networking.LoadBalancerSettings_ConsistentHashLB_HttpCookie HttpHeaderNameHashKey networking.LoadBalancerSettings_ConsistentHashLB_HttpHeaderName UseSourceIpHashKey networking.LoadBalancerSettings_ConsistentHashLB_UseSourceIp ExactStringMatch networking.StringMatch_Exact PrefixStringMatch networking.StringMatch_Prefix RegexStringMatch networking.StringMatch_Regex VPortSelector networking.PortSelector ExponentialDelay networking.HTTPFaultInjection_Delay_ExponentialDelay FixedDelay networking.HTTPFaultInjection_Delay_FixedDelay GrpcStatusAbort networking.HTTPFaultInjection_Abort_GrpcStatus Http2ErrorAbort networking.HTTPFaultInjection_Abort_Http2Error HttpStatusAbort networking.HTTPFaultInjection_Abort_HttpStatus ServiceEntry networking.ServiceEntry VirtualService networking.VirtualService Sidecar networking.Sidecar WorkloadEntry networking.WorkloadEntry Bypass bypass.Params Circonus circonus.Params CloudWatch cloudwatch.Params CWMetricDatum cloudwatch.Params_MetricDatum CWLogInfo cloudwatch.Params_LogInfo Denier denier.Params Dogstatsd dogstatsd.Params DSMetricInfo dogstatsd.Params_MetricInfo Fluentd fluentd.Params KubernetesEnv kubernetesenv.Params ListChecker list.Params MemQuota memquota.Params OPA opa.Params Prometheus prometheus.Params ExplicitBucketsDefinition prometheus.Params_MetricInfo_BucketsDefinition_ExplicitBuckets LinearBucketsDefinition prometheus.Params_MetricInfo_BucketsDefinition_LinearBuckets ExponentialBucketsDefinition prometheus.Params_MetricInfo_BucketsDefinition_ExponentialBuckets RedisQuota redisquota.Params SolarWinds solarwinds.Params SWLogInfo solarwinds.Params_LogInfo SWMetricInfo solarwinds.Params_MetricInfo StackDriver stackdriver.Params SDLogInfo stackdriver.Params_LogInfo SDMetricInfo stackdriver.Params_MetricInfo SDApiKey stackdriver.Params_ApiKey SDAppCredentials stackdriver.Params_AppCredentials SDServiceAccountPath stackdriver.Params_ServiceAccountPath Statsd statsd.Params StatsdMetricInfo statsd.Params_MetricInfo Stdio stdio.Params Zipkin zipkin.Params APIKey apikey.InstanceMsg Authorization authorization.InstanceMsg CheckNothing checknothing.InstanceMsg Edge edge.InstanceMsg ListEntry listentry.InstanceMsg LogEntry logentry.InstanceMsg Metric metric.InstanceMsg Quota quota.InstanceMsg ReportNothing reportnothing.InstanceMsg TraceSpan tracespan.InstanceMsg AuthorizationPolicy security.AuthorizationPolicy Instance policy.Instance Handler policy.Handler } // code adapted from https://kgrz.io/reading-files-in-go-an-overview.html#scanning-comma-seperated-string func readDescriptors() []schemagen.PackageDescriptor { var descriptors = make([]schemagen.PackageDescriptor, 0, 20) file, err := os.Open("istio-common/src/main/resources/packages.csv") if err != nil { fmt.Println(err) return descriptors } defer file.Close() scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) for scanner.Scan() { line := scanner.Text() // ignore commented out lines if strings.HasPrefix(line, "#") { continue } lineScanner := bufio.NewScanner(strings.NewReader(line)) lineScanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) { commaidx := bytes.IndexByte(data, ',') if commaidx > 0 { // we need to return the next position buffer := data[:commaidx] return commaidx + 1, bytes.TrimSpace(buffer), nil } // if we are at the end of the string, just return the entire buffer if atEOF { // but only do that when there is some data. If not, this might mean // that we've reached the end of our input CSV string if len(data) > 0 { return len(data), bytes.TrimSpace(data), nil } } // when 0, nil, nil is returned, this is a signal to the interface to read // more data in from the input reader. In this case, this input is our // string reader and this pretty much will never occur. return 0, nil, nil }) var packageInfo = make([]string, 3) var i = 0 for lineScanner.Scan() { packageInfo[i] = lineScanner.Text() i = i + 1 } descriptors = append(descriptors, schemagen.PackageDescriptor{GoPackage: packageInfo[0], JavaPackage: packageInfo[1], Prefix: packageInfo[2]}) } return descriptors } type class struct { Class string `json:"class"` Fields map[string]string `json:"fields"` } type classData struct { Classes []class `json:"classes"` } func loadInterfacesData(crds map[string]schemagen.CrdDescriptor) (map[string]string, map[string]string) { impls := make(map[string]string) interfaces := make(map[string]string) path := "istio-common/src/main/resources/classes-with-interface-fields.yml" source, err := ioutil.ReadFile(path) if err != nil { panic(err) } var classes classData err = yaml.Unmarshal(source, &classes) if err != nil { log.Fatal(err) } for _, class := range classes.Classes { className := class.Class _, ok := crds[strings.ToLower(className[strings.LastIndex(className, ".")+1:])] if ok { className += "Spec" } // we need to qualify the interface name to avoid collisions: we use the Java package name minus the "me.snowdrop.istio" prefix // note that this qualifying must match was is done in schemagen/generate#getQualifiedInterfaceName pkgName := className[len("me.snowdrop.istio.") : strings.LastIndex(className, ".")+1] interfaceName := className + "." // to define inner classes for interface fields interfaceSet := false for key, field := range class.Fields { if strings.HasPrefix(field, "is") { lastUnderscore := strings.LastIndex(field, "_") if !interfaceSet { interfaceName += field[lastUnderscore+1:] interfaceSet = true } impl := field[2:lastUnderscore+1] + strings.Title(key) impls[pkgName+impl] = interfaceName interfaces[pkgName+field] = interfaceName } } } return impls, interfaces } func loadCRDs() map[string]schemagen.CrdDescriptor { crds := make(map[string]schemagen.CrdDescriptor) path := "istio-common/src/main/resources/istio-crd.properties" file, err := os.Open(path) if err != nil { fmt.Println(err) return crds } defer file.Close() scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) for scanner.Scan() { line := scanner.Text() split := strings.Split(line, "|") crd := strings.ToLower(split[0][:strings.IndexRune(split[0], '=')]) crdType := strings.TrimSpace(split[1][strings.IndexRune(split[1], '=')+1:]) crds[crd] = schemagen.CrdDescriptor{ Name: crd, Visited: false, CrdType: crdType, } } return crds } func main() { strict := flag.Bool("strict", false, "Toggle strict mode to check for missing types") flag.Parse() crds := loadCRDs() interfacesImpl, interfacesMap := loadInterfacesData(crds) packages := readDescriptors() enumMap := map[string]string{ "istio.mesh.v1alpha1.MeshConfig_AccessLogEncoding": "me.snowdrop.istio.api.mesh.v1alpha1.AccessLogEncoding", "istio.mesh.v1alpha1.MeshConfig_IngressControllerMode": "me.snowdrop.istio.api.mesh.v1alpha1.IngressControllerMode", "istio.mesh.v1alpha1.MeshConfig_AuthPolicy": "me.snowdrop.istio.api.mesh.v1alpha1.AuthenticationPolicy", "istio.mesh.v1alpha1.MeshConfig_H2UpgradePolicy": "me.snowdrop.istio.api.mesh.v1alpha1.H2UpgradePolicy", "istio.mesh.v1alpha1.AuthenticationPolicy": "me.snowdrop.istio.api.mesh.v1alpha1.AuthenticationPolicy", "istio.mesh.v1alpha1.ProxyConfig_InboundInterceptionMode": "me.snowdrop.istio.api.mesh.v1alpha1.InboundInterceptionMode", "istio.mesh.v1alpha1.MeshConfig_OutboundTrafficPolicy_Mode": "me.snowdrop.istio.api.mesh.v1alpha1.Mode", "istio.mesh.v1alpha1.Resource": "me.snowdrop.istio.api.mesh.v1alpha1.Resource", "istio.mesh.v1alpha1.Topology_ForwardClientCertDetails": "me.snowdrop.istio.api.mesh.v1alpha1.ForwardClientCertDetails", "istio.mixer.v1.HeaderOperation_Operation": "me.snowdrop.istio.api.mixer.v1.Operation", "istio.mixer.v1.ReferencedAttributes_Condition": "me.snowdrop.istio.api.mixer.v1.Condition", "istio.mixer.v1.ReportRequest_RepeatedAttributesSemantics": "me.snowdrop.istio.api.mixer.v1.RepeatedAttributesSemantics", "istio.mixer.v1.config.descriptor.ValueType": "me.snowdrop.istio.api.mixer.v1.config.descriptor.ValueType", "istio.networking.v1alpha3.EnvoyFilter_RouteConfigurationMatch_RouteMatch_Action": "me.snowdrop.istio.api.networking.v1alpha3.Action", "istio.networking.v1alpha3.ClientTLSSettings_TLSmode": "me.snowdrop.istio.api.networking.v1alpha3.ClientTLSSettingsMode", "istio.networking.v1alpha3.EnvoyFilter_DeprecatedListenerMatch_ListenerType": "me.snowdrop.istio.api.networking.v1alpha3.ListenerType", "istio.networking.v1alpha3.EnvoyFilter_DeprecatedListenerMatch_ListenerProtocol": "me.snowdrop.istio.api.networking.v1alpha3.ListenerProtocol", "istio.networking.v1alpha3.EnvoyFilter_InsertPosition_Index": "me.snowdrop.istio.api.networking.v1alpha3.Index", "istio.networking.v1alpha3.EnvoyFilter_Filter_FilterType": "me.snowdrop.istio.api.networking.v1alpha3.FilterType", "istio.networking.v1alpha3.EnvoyFilter_ApplyTo": "me.snowdrop.istio.api.networking.v1alpha3.ApplyTo", "istio.networking.v1alpha3.EnvoyFilter_PatchContext": "me.snowdrop.istio.api.networking.v1alpha3.PatchContext", "istio.networking.v1alpha3.EnvoyFilter_Patch_Operation": "me.snowdrop.istio.api.networking.v1alpha3.Operation", "istio.networking.v1alpha3.CaptureMode": "me.snowdrop.istio.api.networking.v1alpha3.CaptureMode", "istio.networking.v1alpha3.ServerTLSSettings_TLSmode": "me.snowdrop.istio.api.networking.v1alpha3.ServerTLSSettingsMode", "istio.networking.v1alpha3.ServerTLSSettings_TLSProtocol": "me.snowdrop.istio.api.networking.v1alpha3.ServerTLSSettingsProtocol", "istio.networking.v1alpha3.ConnectionPoolSettings_HTTPSettings_H2UpgradePolicy": "me.snowdrop.istio.api.networking.v1alpha3.H2UpgradePolicy", "istio.networking.v1alpha3.LoadBalancerSettings_SimpleLB": "me.snowdrop.istio.api.networking.v1alpha3.SimpleLB", "istio.networking.v1alpha3.ServiceEntry_Location": "me.snowdrop.istio.api.networking.v1alpha3.ServiceEntryLocation", "istio.networking.v1alpha3.ServiceEntry_Resolution": "me.snowdrop.istio.api.networking.v1alpha3.ServiceEntryResolution", "istio.networking.v1alpha3.OutboundTrafficPolicy_Mode": "me.snowdrop.istio.api.networking.v1alpha3.OutboundTrafficPolicyMode", "istio.networking.v1beta1.CaptureMode": "me.snowdrop.istio.api.networking.v1beta1.CaptureMode", "istio.networking.v1beta1.ServerTLSSettings_TLSmode": "me.snowdrop.istio.api.networking.v1beta1.ServerTLSSettingsMode", "istio.networking.v1beta1.ServerTLSSettings_TLSProtocol": "me.snowdrop.istio.api.networking.v1beta1.ServerTLSSettingsProtocol", "istio.networking.v1beta1.ClientTLSSettings_TLSmode": "me.snowdrop.istio.api.networking.v1beta1.ClientTLSSettingsMode", "istio.networking.v1beta1.ConnectionPoolSettings_HTTPSettings_H2UpgradePolicy": "me.snowdrop.istio.api.networking.v1beta1.H2UpgradePolicy", "istio.networking.v1beta1.LoadBalancerSettings_SimpleLB": "me.snowdrop.istio.api.networking.v1beta1.SimpleLB", "istio.networking.v1beta1.ServiceEntry_Location": "me.snowdrop.istio.api.networking.v1beta1.ServiceEntryLocation", "istio.networking.v1beta1.ServiceEntry_Resolution": "me.snowdrop.istio.api.networking.v1beta1.ServiceEntryResolution", "istio.networking.v1beta1.OutboundTrafficPolicy_Mode": "me.snowdrop.istio.api.networking.v1beta1.OutboundTrafficPolicyMode", "istio.policy.v1beta1.Rule_HeaderOperationTemplate_Operation": "me.snowdrop.istio.api.policy.v1beta1.Operation", "istio.policy.v1beta1.FractionalPercent_DenominatorType": "me.snowdrop.istio.api.policy.v1beta1.DenominatorType", "istio.rbac.v1alpha1.EnforcementMode": "me.snowdrop.istio.api.rbac.v1alpha1.EnforcementMode", "istio.rbac.v1alpha1.RbacConfig_Mode": "me.snowdrop.istio.api.rbac.v1alpha1.Mode", "istio.security.v1beta1.AuthorizationPolicy_Action": "me.snowdrop.istio.api.security.v1beta1.Action", "istio.security.v1beta1.PeerAuthentication_MutualTLS_Mode": "me.snowdrop.istio.api.security.v1beta1.Mode", "adapter.circonus.config.Params_MetricInfo_Type": "me.snowdrop.istio.mixer.adapter.circonus.Type", "adapter.cloudwatch.config.Params_MetricDatum_Unit": "me.snowdrop.istio.mixer.adapter.cloudwatch.Unit", "adapter.prometheus.config.Params_MetricInfo_Kind": "me.snowdrop.istio.mixer.adapter.prometheus.Kind", "adapter.dogstatsd.config.Params_MetricInfo_Type": "me.snowdrop.istio.mixer.adapter.dogstatsd.Type", "adapter.list.config.Params_ListEntryType": "me.snowdrop.istio.mixer.adapter.list.ListEntryType", "adapter.redisquota.config.Params_QuotaAlgorithm": "me.snowdrop.istio.mixer.adapter.redisquota.QuotaAlgorithm", "adapter.signalfx.config.Params_MetricConfig_Type": "me.snowdrop.istio.mixer.adapter.signalfx.Type", "adapter.statsd.config.Params_MetricInfo_Type": "me.snowdrop.istio.mixer.adapter.statsd.Type", "adapter.stdio.config.Params_Stream": "me.snowdrop.istio.mixer.adapter.stdio.Stream", "adapter.stdio.config.Params_Level": "me.snowdrop.istio.mixer.adapter.stdio.Level", "google.api.MetricDescriptor_MetricKind": "me.snowdrop.istio.mixer.adapter.stackdriver.MetricKind", "google.api.MetricDescriptor_ValueType": "me.snowdrop.istio.mixer.adapter.stackdriver.ValueType", "google.protobuf.NullValue": "me.snowdrop.istio.api.NullValue", } schema, err := schemagen.GenerateSchema(reflect.TypeOf(Schema{}), packages, enumMap, interfacesMap, interfacesImpl, crds, *strict) if err != nil { fmt.Fprint(os.Stderr, err) fmt.Fprintln(os.Stderr, "\n") os.Exit(1) } b, err := json.Marshal(&schema) if err != nil { log.Fatal(err) } result := string(b) result = strings.Replace(result, "\"additionalProperty\":", "\"additionalProperties\":", -1) var out bytes.Buffer err = json.Indent(&out, []byte(result), "", " ") if err != nil { log.Fatal(err) } fmt.Println(out.String()) } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/cexl/TypedValue.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.api.cexl; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.sundr.builder.annotations.Buildable; import lombok.EqualsAndHashCode; import lombok.ToString; import me.snowdrop.istio.api.cexl.parser.CEXLLexer; import me.snowdrop.istio.api.cexl.parser.CEXLParser; import me.snowdrop.istio.api.cexl.parser.CEXLTypeResolver; import me.snowdrop.istio.api.mixer.config.descriptor.ValueType; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; /** * @author <a href="<EMAIL>"><NAME></a> */ @Buildable(builderPackage = "io.fabric8.kubernetes.api.builder", generateBuilderPackage = true, editableEnabled = false) @EqualsAndHashCode @ToString @JsonSerialize(using = TypedValue.TypedValueSerializer.class) @JsonDeserialize(using = TypedValue.TypedValueDeserializer.class) public class TypedValue { private final ValueType type; private String expression; public TypedValue(ValueType type, String expression) { this.type = type; this.expression = expression; } @JsonIgnore public ValueType getType() { return type; } public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } public static TypedValue from(String value) { // Get our lexer CEXLLexer lexer = new CEXLLexer(CharStreams.fromString(value)); // Get a list of matched tokens CommonTokenStream tokens = new CommonTokenStream(lexer); // Pass the tokens to the parser CEXLParser parser = new CEXLParser(tokens); // Specify our entry point final CEXLParser.ExpressionContext context = parser.expression(); // Walk it and attach our listener ParseTreeWalker walker = new ParseTreeWalker(); final CEXLTypeResolver resolver = new CEXLTypeResolver(); walker.walk(resolver, context); return new TypedValue(resolver.getExpressionType(), value); } public static TypedValue unparsed(String value) { return new TypedValue(ValueType.STRING, value); } static class TypedValueSerializer extends JsonSerializer<TypedValue> { @Override public void serialize(TypedValue value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(value.expression); } } static class TypedValueDeserializer extends JsonDeserializer<TypedValue> { @Override public TypedValue deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { final String text = p.getText(); try { return TypedValue.from(text); } catch (IllegalArgumentException e) { // fallback to unparsed return TypedValue.unparsed(text); } } } } <file_sep>/cmd/packageGen/packageGen.go package main import ( "bufio" "fmt" "os" "strings" ) // Expects directory names in the form: 'istio.io/istio/mixer/adapter/dogstatsd/config' // Extracts salient part from directory path which depends on type of target directory and creates a comma-separated line entry func main() { // scanner := bufio.NewScanner(os.Stdin) const projectPkgPrefix = "me.snowdrop.istio." const projectJsonPrefix = "istio_" const sep = string(os.PathSeparator) if len(os.Args) != 2 { panic("Expecting one of 'api' | 'adapter' | 'template' as sole argument") } kind := os.Args[1] var pkgPrefix, jsonPrefix string switch kind { case "api": pkgPrefix = projectPkgPrefix + "api." jsonPrefix = projectJsonPrefix case "adapter": pkgPrefix = projectPkgPrefix + "mixer.adapter." jsonPrefix = projectJsonPrefix + "adapter_" case "template": pkgPrefix = projectPkgPrefix + "mixer.template." jsonPrefix = projectJsonPrefix + "mixer_" } //istio.io/api/networking/v1alpha3 fmt.Println("# " + kind) var component string for scanner.Scan() { line := scanner.Text() // remove any trailing separator if strings.HasSuffix(line, sep) { line = line[:len(line)-len(sep)] } elements := strings.Split(line, sep) for i, value := range elements { if value == kind { if kind != "api" { component = elements[i+1] } else { component = elements[i+1] + "." + elements[i+2] } break } } fmt.Println(line + "," + pkgPrefix + component + "," + jsonPrefix + strings.Replace(component, ".", "_", -1) + "_") } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) } } func concatenate(prefix string, element string) string { return prefix + element } func prefixOnly(prefix string, element string) string { // if we want a prefix only remove any trailing . but leave _ as-is if strings.HasSuffix(prefix, ".") { prefix = prefix[:len(prefix)-1] } return prefix } <file_sep>/README.adoc **Note** = This project is now deprecated. Please use the Istio client in the https://github.com/fabric8io/kubernetes-client project starting with version 5.11.0. = istio-java-api A project to generate a Java API for https://istio.io[Istio]'s domain allowing, in particular, the generation of Istio deployment descriptors.This project is inspired by https://github.com/fabric8io/kubernetes-model[Fabric8's kubernetes-model] and relies on the same approach: a Go program uses Go reflection to generate a http://json-schema.org[JSON Schema] which is then used by https://github.com/joelittlejohn/jsonschema2pojo[jsonschema2pojo] to generate Java classes. jsonschema2pojo is configured to use a custom annotator, `IstioTypeAnnotator` (found in the `istio-model-annotator` module), to add (https://github.com/fasterxml/jackson[Jackson], https://jcp.org/en/jsr/detail?id=380[Bean Validation - JSR 380] and https://github.com/sundrio/sundrio[sundrio] annotations.Sundrio is used generate idiomatic builder and DSL Java classes. Jackson is used to output JSON or YAML representation of the Java objects when needed. == Usage Please take a look at the tests in `istio-model/src/test/java` to see how the API can be used. You can also take a look at the https://github.com/metacosm/istio-test-dsl project which demonstrates an end-to-end scenario using the Fabric8 OpenShift adapter and this API to send Istio artifacts to a running OpenShift cluster configured on which Istio is set up. [Note] ==== Starting with the `1.7.7` of this API, the bundled version of the Fabric8 Kubernetes client has been upgraded to use the non-backwards compatible `5.x` versions. While this might not be an issue for most users of this API, it's still worth noting. ==== == Building instructions If you only want to build the current version of the API and don't intend on modifying how the JSON Schema is generated, you can build simply using `mvn clean install` as the project contains a pre-generated version of the schema.If you need to re-generate the classes from a newer version of the API, since the build relies on Go introspection, you will need to set up a Go programming environment. === Building the Java API You will need to https://golang.org/doc/install[install Go] and `make`. Run `make`. This will build the `generate` command line tool from Go and then run it to generate a JSON Schema in `istio-model/src/main/resources/schema/istio-schema.json`. A Maven build is then issued using the `jsonschema2pojo` Maven plugin to generate Java classes in `istio-model/target/generated-sources` and generate a Jar file containing the compiled version of these classes along with the JSON schema, ready to be used. You can *clean* everything using `make clean`, only *generate the schema* using `make schema` or only generate the Java classes from an already generated schema such as the provided one using `mvn clean install`. === Updating the Java API when Istio is updated NOTE: The process is not completely reproducible at this time. :( [source,bash] ---- # update to the latest istio version, rebuild crd list and packages make metadata # build using strict mode make strict # fix any issue, iterate… :) ---- You can also re-generate the properties files that are used to determine which https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/[Kubernetes Custom Resource Definitions (CRDs)] are specified by Istio. These files are located in `istio-common/src/main/resources/`, one for each kind of supported CRDs and can be generated using `make metadata`. You can also re-generate the CSV file that is used to map Istio Go packages to Java packages. The file is located at `istio-common/src/main/resources/packages.csv` and can be generated using `make metadata`. <file_sep>/istio-client/src/main/java/me/snowdrop/istio/client/IstioClient.java package me.snowdrop.istio.client; import java.io.InputStream; import java.util.Collection; import java.util.List; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.dsl.NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable; import io.fabric8.kubernetes.client.dsl.NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicable; import io.fabric8.kubernetes.client.dsl.ParameterNamespaceListVisitFromServerGetDeleteRecreateWaitApplicable; import me.snowdrop.istio.api.IstioResource; public interface IstioClient extends Client, IstioDsl { ParameterNamespaceListVisitFromServerGetDeleteRecreateWaitApplicable<HasMetadata> load(InputStream is); NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable<HasMetadata> resourceList(KubernetesResourceList item); NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable<HasMetadata> resourceList(HasMetadata... items); NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable<HasMetadata> resourceList(Collection<HasMetadata> items); ParameterNamespaceListVisitFromServerGetDeleteRecreateWaitApplicable<HasMetadata> resourceList(String s); NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicable<HasMetadata> resource(HasMetadata item); NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicable<HasMetadata> resource(String s); List<IstioResource> registerCustomResources(final String specFileAsString); List<IstioResource> registerCustomResources(final InputStream resource); List<IstioResource> getResourcesLike(final IstioResource resource); IstioResource registerCustomResource(final IstioResource resource); IstioResource registerOrUpdateCustomResource(final IstioResource resource); Boolean unregisterCustomResource(final IstioResource istioResource); } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/mesh/v1alpha1/ForwardClientCertDetails.java /** * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package me.snowdrop.istio.api.mesh.v1alpha1; /** * @author <a href="<EMAIL>"><NAME></a> */ public enum ForwardClientCertDetails { /** * Field is not set */ UNDEFINED(0), /** * Do not send the XFCC header to the next hop. This is the default value. */ SANITIZE(1), /** * When the client connection is mTLS (Mutual TLS), forward the XFCC header in the request. */ FORWARD_ONLY(2), /** * When the client connection is mTLS, append the client certificate information to the request’s XFCC header and * forward it. */ APPEND_FORWARD(3), /** * When the client connection is mTLS, reset the XFCC header with the client certificate information and send it to * the next hop. */ SANITIZE_SET(4), /** * Always forward the XFCC header in the request, regardless of whether the client connection is mTLS. */ ALWAYS_FORWARD_ONLY(5); private final int intValue; ForwardClientCertDetails(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/istio-model/pom.xml <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2011 Red Hat, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>me.snowdrop</groupId> <artifactId>istio-java-api</artifactId> <version>1.7.8-SNAPSHOT</version> </parent> <artifactId>istio-model</artifactId> <packaging>jar</packaging> <name>Snowdrop :: Istio Java API :: Model</name> <properties> <schema.dir>${basedir}/src/main/resources/schema</schema.dir> <antlr4.version>4.7.1</antlr4.version> </properties> <dependencies> <dependency> <groupId>me.snowdrop</groupId> <artifactId>istio-common</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.joda/joda-convert --> <dependency> <groupId>org.joda</groupId> <artifactId>joda-convert</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>io.fabric8</groupId> <artifactId>kubernetes-model</artifactId> </dependency> <dependency> <groupId>org.antlr</groupId> <artifactId>antlr4-runtime</artifactId> <version>${antlr4.version}</version> </dependency> <dependency> <groupId>io.sundr</groupId> <artifactId>builder-annotations</artifactId> <scope>provided</scope> <exclusions> <exclusion> <groupId>com.sun</groupId> <artifactId>tools</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.sundr</groupId> <artifactId>transform-annotations</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> </dependencies> <profiles> <profile> <id>jdk9</id> <activation> <jdk>[1,1.9)</jdk> </activation> <dependencies> <dependency> <groupId>com.sun</groupId> <artifactId>tools</artifactId> <version>1.7</version> <scope>system</scope> <systemPath>${java.home}/../lib/tools.jar</systemPath> </dependency> </dependencies> </profile> </profiles> <build> <plugins> <plugin> <groupId>org.antlr</groupId> <artifactId>antlr4-maven-plugin</artifactId> <version>${antlr4.version}</version> <executions> <execution> <id>antlr</id> <goals> <goal>antlr4</goal> </goals> <!-- If we want to put the generated ANTLR classes in the proper package with other sources --> <!--<configuration> <outputDirectory>${project.build.sourceDirectory}/me/snowdrop/istio/api/cexl/parser</outputDirectory> </configuration>--> </execution> </executions> </plugin> <plugin> <groupId>org.jsonschema2pojo</groupId> <artifactId>jsonschema2pojo-maven-plugin</artifactId> <version>${jsonschema2pojo.version}</version> <configuration> <sourceDirectory>${schema.dir}</sourceDirectory> <targetPackage>me.snowdrop.istio.api</targetPackage> <includeConstructors>true</includeConstructors> <!-- <includeJsr303Annotations>true</includeJsr303Annotations>--> <includeToString>false</includeToString> <serializable>true</serializable> <targetVersion>1.8</targetVersion> <includeHashcodeAndEquals>false</includeHashcodeAndEquals> <inclusionLevel>NON_EMPTY</inclusionLevel> <outputDirectory>${project.build.directory}/generated-sources/jsonschema2pojo</outputDirectory> <customAnnotator>me.snowdrop.istio.annotator.IstioTypeAnnotator</customAnnotator> <annotationStyle>none</annotationStyle> </configuration> <executions> <execution> <goals> <goal>generate</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>me.snowdrop</groupId> <artifactId>istio-model-annotator</artifactId> <version>${project.version}</version> </dependency> </dependencies> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>remove-classes-pre-generation</id> <phase>generate-sources</phase> <configuration> <target> <echo>removing the duplicate / useless generated classes</echo> <delete file="${basedir}/target/generated-sources/jsonschema2pojo/me/snowdrop/istio/api/Duration.java" verbose="true" /> <delete file="${basedir}/target/generated-sources/jsonschema2pojo/me/snowdrop/istio/api/IstioSchema.java" verbose="true" /> <delete file="${basedir}/target/generated-sources/jsonschema2pojo/me/snowdrop/istio/api/TimeStamp.java" verbose="true" /> <delete file="${basedir}/target/generated-sources/jsonschema2pojo/me/snowdrop/istio/api/cexl/TypedValue.java" verbose="true" /> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>attach-artifacts</id> <phase>package</phase> <goals> <goal>attach-artifact</goal> </goals> <configuration> <artifacts> <artifact> <file>${schema.dir}/istio-schema.json</file> <type>json</type> <classifier>schema</classifier> </artifact> </artifacts> </configuration> </execution> <execution> <!-- Add the generated sources as maven looked-at sources so that we can use them in tests --> <id>add-sources</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>${project.build.directory}/generated-sources/annotations</source> <source>${project.build.directory}/generated-sources/jsonschema2pojo</source> <!-- Useful when locally generating ANTLR parser classes (outside of maven) e.g. to work on CEXLTypeResolver. Note that project won't compile with locally generated classes since we then have duplicated classes with what is generated by the maven plugin. --> <source>${project.basedir}/gen/</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/internal/TypedValueMapDeserializer.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.api.internal; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.node.ObjectNode; import me.snowdrop.istio.api.cexl.TypedValue; /** * @author <a href="<EMAIL>"><NAME></a> */ public class TypedValueMapDeserializer extends JsonDeserializer<Map<String, TypedValue>> { @Override public Map<String, TypedValue> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectCodec codec = p.getCodec(); ObjectNode root = codec.readTree(p); final int size = root.size(); if (size > 0) { final Map<String, TypedValue> values = new HashMap<>(size); root.fields().forEachRemaining(field -> values.put(field.getKey(), TypedValue.from(field.getValue().textValue()))); return values; } else { return null; } } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/util/YAML.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.util; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import me.snowdrop.istio.api.IstioResource; import me.snowdrop.istio.api.IstioSpec; import static me.snowdrop.istio.api.internal.IstioSpecRegistry.getCRDInfo; /** * @author <a href="<EMAIL>"><NAME></a> */ public class YAML { private final static Pattern DOCUMENT_DELIMITER = Pattern.compile("---"); private final static YAMLMapper objectMapper = new YAMLMapper(); private static final String KIND = "kind"; public static <T> T loadIstioResource(final String specFileAsString, Class<T> clazz) { return loadIstioResources(specFileAsString, clazz).get(0); } public static <T> List<T> loadIstioResources(final String specFileAsString, Class<T> clazz) { List<T> results = new ArrayList<>(); String[] documents = DOCUMENT_DELIMITER.split(specFileAsString); final boolean wantSpec = IstioSpec.class.isAssignableFrom(clazz); if (!wantSpec && !IstioResource.class.equals(clazz)) { throw new IllegalArgumentException("Can only load either IstioSpec implementations or IstioResources. Asked to " + "load: " + clazz.getName()); } for (String document : documents) { try { document = document.trim(); if (!document.isEmpty()) { final Map<String, Object> resourceYaml = objectMapper.readValue(document, Map.class); if (resourceYaml.containsKey(KIND)) { final String kind = (String) resourceYaml.get(KIND); final String version = (String) resourceYaml.get("version"); getCRDInfo(kind, version).orElseThrow(() -> new IllegalArgumentException(String.format("%s/%s is not a known Istio resource.", kind, version))); final IstioResource resource = objectMapper.convertValue(resourceYaml, IstioResource.class); if (wantSpec) { results.add(clazz.cast(resource.getSpec())); } else { results.add(clazz.cast(resource)); } } else { throw new IllegalArgumentException(String.format("%s is not specified in provided resource.", KIND)); } } } catch (IOException e) { throw new IllegalArgumentException(e); } } return results; } public static <T> List<T> loadIstioResources(final InputStream resource, Class<T> clazz) { return loadIstioResources(Utils.writeStreamToString(resource), clazz); } public static <T> T loadIstioResource(final InputStream resource, Class<T> clazz) { return loadIstioResources(resource, clazz).get(0); } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/internal/TypedValueMapSerializer.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.api.internal; import java.io.IOException; import java.util.Map; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import me.snowdrop.istio.api.cexl.TypedValue; /** * @author <a href="<EMAIL>"><NAME></a> */ public class TypedValueMapSerializer extends JsonSerializer<Map<String, TypedValue>> { @Override public void serialize(Map<String, TypedValue> value, JsonGenerator gen, SerializerProvider serializers) throws IOException { value.forEach((s, typedValue) -> { try { gen.writeStringField(s, typedValue.getExpression()); } catch (IOException e) { throw new RuntimeException(e); } }); } } <file_sep>/istio-common/src/main/java/me/snowdrop/istio/api/internal/MixerAdapter.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.api.internal; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author <a href="<EMAIL>"><NAME></a> */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.FIELD}) public @interface MixerAdapter { String compiledAdapter() default "unknown"; } <file_sep>/istio-client/src/main/java/me/snowdrop/istio/client/CodeGen.java package me.snowdrop.istio.client; import io.sundr.codegen.annotations.ResourceSelector; import io.sundr.transform.annotations.VelocityTransformation; import io.sundr.transform.annotations.VelocityTransformations; @VelocityTransformations( value = { @VelocityTransformation("/resource-operation.vm"), @VelocityTransformation("/resource-handler.vm"), @VelocityTransformation(value = "/resource-handler-services.vm", gather = true, outputPath = "META-INF/services/io.fabric8.kubernetes.client.ResourceHandler") }, resources = { @ResourceSelector("crd.properties") } ) public class CodeGen { } <file_sep>/istio-common/src/main/resources/templates.properties apikey=me.snowdrop.istio.mixer.template.apikey.ApiKey authorization=me.snowdrop.istio.mixer.template.authorization.Authorization checknothing=me.snowdrop.istio.mixer.template.checknothing.CheckNothing edge=me.snowdrop.istio.mixer.template.edge.Edge listentry=me.snowdrop.istio.mixer.template.listentry.ListEntry logentry=me.snowdrop.istio.mixer.template.logentry.LogEntry metric=me.snowdrop.istio.mixer.template.metric.Metric quota=me.snowdrop.istio.mixer.template.quota.Quota reportnothing=me.snowdrop.istio.mixer.template.reportnothing.ReportNothing tracespan=me.snowdrop.istio.mixer.template.tracespan.TraceSpan<file_sep>/istio-model/src/test/java/me/snowdrop/istio/api/mesh/v1alpha1/MeshConfigTest.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api.mesh.v1alpha1; import me.snowdrop.istio.tests.BaseIstioTest; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * @author <a href="<EMAIL>"><NAME></a> */ public class MeshConfigTest extends BaseIstioTest { @Test public void checkDefaultMeshConfig() throws Exception { String configString = "# Set the following variable to true to disable policy checks by the Mixer.\n" + "# Note that metrics will still be reported to the Mixer.\n" + "disablePolicyChecks: false\n" + "\n" + "# Set enableTracing to false to disable request tracing.\n" + "enableTracing: true\n" + "\n" + "# Set accessLogFile to empty string to disable access log.\n" + "accessLogFile: \"/dev/stdout\"\n" + "#\n" + "# Deprecated: mixer is using EDS\n" + "mixerCheckServer: istio-policy.istio-system.svc.cluster.local:9091\n" + "mixerReportServer: istio-telemetry.istio-system.svc.cluster.local:9091\n" + "\n" + "# Unix Domain Socket through which envoy communicates with NodeAgent SDS to get\n" + "# key/cert for mTLS. Use secret-mount files instead of SDS if set to empty. \n" + "sdsUdsPath: \"\"\n" + "\n" + "# How frequently should Envoy fetch key/cert from NodeAgent.\n" + "sdsRefreshDelay: 15s\n" + "\n" + "#\n" + "defaultConfig:\n" + " ### ADVANCED SETTINGS #############\n" + " # Where should envoy's configuration be stored in the istio-proxy container\n" + " configPath: \"/etc/istio/proxy\"\n" + " binaryPath: \"/usr/local/bin/envoy\"\n" + " # The pseudo service name used for Envoy.\n" + " serviceCluster: istio-proxy\n" + " # These settings that determine how long an old Envoy\n" + " # process should be kept alive after an occasional reload.\n" + " drainDuration: 45s\n" + " parentShutdownDuration: 1m0s\n" + " #\n" + " # The mode used to redirect inbound connections to Envoy. This setting\n" + " # has no effect on outbound traffic: iptables REDIRECT is always used for\n" + " # outbound connections.\n" + " # If \"REDIRECT\", use iptables REDIRECT to NAT and redirect to Envoy.\n" + " # The \"REDIRECT\" mode loses source addresses during redirection.\n" + " # If \"TPROXY\", use iptables TPROXY to redirect to Envoy.\n" + " # The \"TPROXY\" mode preserves both the source and destination IP\n" + " # addresses and ports, so that they can be used for advanced filtering\n" + " # and manipulation.\n" + " # The \"TPROXY\" mode also configures the sidecar to run with the\n" + " # CAP_NET_ADMIN capability, which is required to use TPROXY.\n" + " #interceptionMode: REDIRECT\n" + " #\n" + " # Port where Envoy listens (on local host) for admin commands\n" + " # You can exec into the istio-proxy container in a pod and\n" + " # curl the admin port (curl http://localhost:15000/ ) to obtain\n" + " # diagnostic information from Envoy. See\n" + " # https://lyft.github.io/envoy/docs/operations/admin.html \n" + " # for more details\n" + " proxyAdminPort: 15000\n" + " #\n" + " # Zipkin trace collector\n" + " zipkinAddress: zipkin.istio-system:9411\n" + " #\n" + " # Statsd metrics collector converts statsd metrics into Prometheus metrics.\n" + " statsdUdpAddress: istio-statsd-prom-bridge.istio-system:9125\n" + " #\n" + " # Mutual TLS authentication between sidecars and istio control plane.\n" + " controlPlaneAuthPolicy: NONE\n" + " #\n" + " # Address where istio Pilot service is running\n" + " discoveryAddress: istio-pilot.istio-system:15007"; MeshConfig meshConfig = mapper.readValue(configString, MeshConfig.class); assertNotNull(meshConfig); final ProxyConfig config = meshConfig.getDefaultConfig(); assertEquals(AuthenticationPolicy.NONE, config.getControlPlaneAuthPolicy()); assertEquals("istio-pilot.istio-system:15007", config.getDiscoveryAddress()); assertEquals("zipkin.istio-system:9411", config.getZipkinAddress()); assertEquals("istio-statsd-prom-bridge.istio-system:9125", config.getStatsdUdpAddress()); } @Test public void checkAuthMeshConfig() throws Exception { String configString = "authPolicy: MUTUAL_TLS\n" + "enableTracing: true\n" + "mixerAddress: istio-mixer.istio-system:15004\n" + "ingressService: istio-ingress\n" + "ingressControllerMode: DEFAULT\n" + "rdsRefreshDelay: 1s\n" + "defaultConfig:\n" + " discoveryRefreshDelay: 1s\n" + " configPath: \"/etc/istio/proxy\"\n" + " binaryPath: \"/usr/local/bin/envoy\"\n" + " serviceCluster: istio-proxy\n" + " drainDuration: 45s\n" + " parentShutdownDuration: 1m0s\n" + " proxyAdminPort: 15000\n" + " discoveryAddress: istio-pilot.istio-system:15003\n" + " zipkinAddress: zipkin.istio-system:9411\n" + " statsdUdpAddress: istio-mixer.istio-system:9125\n" + " controlPlaneAuthPolicy: MUTUAL_TLS"; MeshConfig meshConfig = mapper.readValue(configString, MeshConfig.class); assertNotNull(meshConfig); assertEquals(AuthenticationPolicy.MUTUAL_TLS, meshConfig.getAuthPolicy()); assertEquals(IngressControllerMode.DEFAULT, meshConfig.getIngressControllerMode()); assertEquals(AuthenticationPolicy.MUTUAL_TLS, meshConfig.getDefaultConfig().getControlPlaneAuthPolicy()); } } <file_sep>/istio-client/src/test/java/me/snowdrop/istio/client/IstioClientTest.java package me.snowdrop.istio.client; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import io.fabric8.kubernetes.api.model.HasMetadata; import me.snowdrop.istio.api.IstioResource; import me.snowdrop.istio.api.networking.v1beta1.DestinationRule; import me.snowdrop.istio.api.networking.v1beta1.VirtualService; import org.junit.Assert; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class IstioClientTest { private final static YAMLMapper objectMapper = new YAMLMapper(); @Test public void shouldApplyVirtualServiceIstioResource() { checkInput("virtual-service.yaml", VirtualService.class); } @Test public void shouldApplyDestinationRuleIstioResource() { checkInput("destination-rule.yaml", DestinationRule.class); } private void checkInput(String inputFileName, Class<? extends IstioResource> expectedSpecClass) { final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(inputFileName); IstioClient client = new DefaultIstioClient(); List<HasMetadata> result = client.load(inputStream).get(); assertThat(result).isNotEmpty(); assertThat(result.size()).isEqualTo(1); final HasMetadata hasMetadata = result.get(0); try { assertThat(hasMetadata.getKind()).isEqualTo(expectedSpecClass.newInstance().getKind()); } catch (Exception e) { Assert.fail("Failed to read resource kind."); } // check roundtrip try { final ByteArrayInputStream output = new ByteArrayInputStream(objectMapper.writeValueAsBytes(hasMetadata)); List<HasMetadata> fromOutput = client.load(output).get(); assertThat(fromOutput).isEqualTo(result); } catch (JsonProcessingException e) { Assert.fail("Couldn't output resource back to string"); } } } <file_sep>/istio-common/src/main/java/me/snowdrop/istio/api/IstioSpec.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnore; import me.snowdrop.istio.api.internal.IstioKind; /** * @author <a href="<EMAIL>"><NAME></a> */ public interface IstioSpec extends Serializable { @JsonIgnore default String getKind() { final IstioKind kind = getClass().getAnnotation(IstioKind.class); if (kind != null) { return kind.name(); } throw new IllegalStateException(getClass().getName() + " should have been annotated with @IstioKind!"); } } <file_sep>/istio-model/src/test/java/me/snowdrop/istio/api/security/v1beta1/AuthorizationPolicyTest.java /** * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.snowdrop.istio.api.security.v1beta1; import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.kubernetes.api.model.HasMetadata; import me.snowdrop.istio.tests.BaseIstioTest; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author <a href="<EMAIL>"><NAME></a> */ public class AuthorizationPolicyTest extends BaseIstioTest { @Test public void roundtripShouldWork() throws JsonProcessingException { /* apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: httpbin namespace: foo spec: action: ALLOW rules: - from: - source: principals: ["cluster.local/ns/default/sa/sleep"] - source: namespaces: ["test"] to: - operation: methods: ["GET"] paths: ["/info*"] - operation: methods: ["POST"] paths: ["/data"] when: - key: request.auth.claims[iss] values: ["https://accounts.google.com"] */ final AuthorizationPolicy policy = new AuthorizationPolicyBuilder() .withNewMetadata().withName("httpbin").withNamespace("foo").endMetadata() .withNewSpec() .withAction(Action.ALLOW) .addNewRule() .addNewFrom() .withNewSource().addNewPrincipal("cluster.local/ns/default/sa/sleep").endSource() .withNewSource().addNewNamespace("test").endSource() .endFrom() .addNewTo().withNewOperation().addNewMethod("GET").addNewPath("/info*").endOperation().endTo() .addNewTo().withNewOperation().addNewMethod("POST").addNewPath("/data").endOperation().endTo() .addNewWhen().withKey("request.auth.claims[iss]").addNewValue("https://accounts.google.com").endWhen() .endRule() .endSpec() .build(); final String output = mapper.writeValueAsString(policy); HasMetadata reloaded = mapper.readValue(output, HasMetadata.class); assertEquals(policy, reloaded); } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/mixer/adapter/dogstatsd/Type.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.mixer.adapter.dogstatsd; /** * Describes the type of metric * * @author <a href="<EMAIL>"><NAME></a> */ public enum Type { /** * Default Unknown Type */ UNKNOWN_TYPE(0), /** * Increments a DataDog counter */ COUNTER(1), /** * Sets the new value of a DataDog gauge */ GAUGE(2), /** * DISTRIBUTION is converted to a Timing Histogram for metrics with a time unit and a Histogram for all other units */ DISTRIBUTION(3); private final int intValue; Type(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/mesh/v1alpha1/InboundInterceptionMode.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api.mesh.v1alpha1; /** * The mode used to redirect inbound traffic to Envoy. * This setting has no effect on outbound traffic: {@code iptables REDIRECT} is always used for outbound connections. * * @author <a href="<EMAIL>"><NAME></a> */ public enum InboundInterceptionMode { /** * The REDIRECT mode uses iptables REDIRECT to NAT and redirect to Envoy. This mode loses source IP addresses during redirection. */ REDIRECT(0), /** * The TPROXY mode uses iptables TPROXY to redirect to Envoy. This mode preserves both the source and destination IP * addresses and ports, so that they can be used for advanced filtering and manipulation. This mode also configures the * sidecar to run with the CAP_NET_ADMIN capability, which is required to use TPROXY. */ TPROXY(1); private final int intValue; InboundInterceptionMode(int value) { this.intValue = value; } public int value() { return intValue; } } <file_sep>/Makefile # # Copyright (C) 2011 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # SHELL := /bin/bash PWD=$(shell pwd) SCHEMA_DIR=$(PWD)/istio-model/src/main/resources/schema DECL_DIR=$(PWD)/istio-common/src/main/resources CRD_FILE=$(DECL_DIR)/istio-crd.properties all: build strict: metadata go run ./cmd/generate/generate.go -strict > $(SCHEMA_DIR)/istio-schema.json ISTIO_STRICT=true ./mvnw clean install -e clean: ./mvnw clean metadata: ./scripts/generate_metadata.sh "${version}" schema: go run ./cmd/generate/generate.go > $(SCHEMA_DIR)/istio-schema.json build: schema ./mvnw clean install -e istio_version: @./scripts/generate_metadata.sh version<file_sep>/istio-common/src/main/resources/adapters.properties bypass=me.snowdrop.istio.mixer.adapter.bypass.Bypass circonus=me.snowdrop.istio.mixer.adapter.circonus.Circonus cloudwatch=me.snowdrop.istio.mixer.adapter.cloudwatch.Cloudwatch denier=me.snowdrop.istio.mixer.adapter.denier.Denier dogstatsd=me.snowdrop.istio.mixer.adapter.dogstatsd.Dogstatsd fluentd=me.snowdrop.istio.mixer.adapter.fluentd.Fluentd kubernetesenv=me.snowdrop.istio.mixer.adapter.kubernetesenv.Kubernetesenv list=me.snowdrop.istio.mixer.adapter.list.BaseKubernetesList memquota=me.snowdrop.istio.mixer.adapter.memquota.Memquota opa=me.snowdrop.istio.mixer.adapter.opa.Opa prometheus=me.snowdrop.istio.mixer.adapter.prometheus.Prometheus redisquota=me.snowdrop.istio.mixer.adapter.redisquota.Redisquota solarwinds=me.snowdrop.istio.mixer.adapter.solarwinds.Solarwinds stackdriver=me.snowdrop.istio.mixer.adapter.stackdriver.Stackdriver statsd=me.snowdrop.istio.mixer.adapter.statsd.Statsd stdio=me.snowdrop.istio.mixer.adapter.stdio.Stdio zipkin=me.snowdrop.istio.mixer.adapter.zipkin.Zipkin<file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/networking/v1beta1/CaptureMode.java /* * * * Copyright (C) 2019 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api.networking.v1beta1; /** * CaptureMode describes how traffic to a listener is expected to be captured. Applicable only when the listener is * bound to an IP. * * @author <a href="<EMAIL>"><NAME></a> */ public enum CaptureMode { /** * The default capture mode defined by the environment */ DEFAULT(0), /** * Capture traffic using IPtables redirection */ IPTABLES(1), /** * No traffic capture. When used in egress listener, the application is * expected to explicitly communicate with the listener port/unix * domain socket. When used in ingress listener, care needs to be taken * to ensure that the listener port is not in use by other processes on * the host. */ NONE(2); private final int intValue; CaptureMode(int intValue) { this.intValue = intValue; } public int value() { return intValue; } } <file_sep>/istio-common/src/main/java/me/snowdrop/istio/util/Utils.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * @author <a href="<EMAIL>"><NAME></a> */ public class Utils { public static String writeStreamToString(InputStream inputStream) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; try { while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } return outputStream.toString(); } catch (IOException e) { throw new RuntimeException("Unable to read InputStream.", e); } } } <file_sep>/istio-common/src/test/java/me/snowdrop/istio/api/internal/IstioRegistryTest.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api.internal; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author <a href="<EMAIL>"><NAME></a> */ public class IstioRegistryTest { @Test public void shouldReturnKindWithProperCase() { assertThat(IstioSpecRegistry.getCRDInfo("Handler", "v1alpha2").get().getKind()).isEqualTo("handler"); assertThat(IstioSpecRegistry.getCRDInfo("Handler", "v1beta1").get().getKind()).isEqualTo("handler"); assertThat(IstioSpecRegistry.getCRDInfo("Gateway", "v1alpha3").get().getKind()).isEqualTo("Gateway"); assertThat(IstioSpecRegistry.getCRDInfo("Gateway", "v1beta1").get().getKind()).isEqualTo("Gateway"); } } <file_sep>/istio-model/src/main/java/me/snowdrop/istio/api/cexl/AttributeVocabulary.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.api.cexl; import me.snowdrop.istio.api.mixer.config.descriptor.ValueType; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * @author <a href="<EMAIL>"><NAME></a> */ public class AttributeVocabulary { private static final Map<String, AttributeInfo> ATTRIBUTE_INFO_MAP = new ConcurrentHashMap<>(); public static Optional<AttributeInfo> getInfoFor(String attributeName) { return Optional.ofNullable(ATTRIBUTE_INFO_MAP.get(attributeName)); } public static class AttributeInfo { public final String name; public final ValueType type; public final String description; public final String example; private AttributeInfo(String name, String istioType, String description, String example) { this.name = name; this.type = ValueType.valueOf(istioType.toUpperCase()); this.description = description; this.example = example; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AttributeInfo info = (AttributeInfo) o; if (!name.equals(info.name)) return false; return type == info.type; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + type.hashCode(); return result; } } public static Set<String> getKnownAttributes() { return Collections.unmodifiableSet(ATTRIBUTE_INFO_MAP.keySet()); } // generated from https://github.com/istio/istio.io/blob/master/content/en/docs/reference/config/policy-and-telemetry/attribute-vocabulary/index.md static { ATTRIBUTE_INFO_MAP.put("source.uid", new AttributeInfo("source.uid", "string", "Platform-specific unique identifier for the source workload instance.", "`kubernetes://redis-master-2353460263-1ecey.my-namespace` ")); } static { ATTRIBUTE_INFO_MAP.put("source.ip", new AttributeInfo("source.ip", "ip_address", "Source workload instance IP address.", "`10.0.0.117` ")); } static { ATTRIBUTE_INFO_MAP.put("source.labels", new AttributeInfo("source.labels", ValueType.STRING_MAP.name() , "A map of key-value pairs attached to the source instance.", "version => v1 ")); } static { ATTRIBUTE_INFO_MAP.put("source.name", new AttributeInfo("source.name", "string", "Source workload instance name.", "`redis-master-2353460263-1ecey` ")); } static { ATTRIBUTE_INFO_MAP.put("source.namespace", new AttributeInfo("source.namespace", "string", "Source workload instance namespace.", "`my-namespace` ")); } static { ATTRIBUTE_INFO_MAP.put("source.principal", new AttributeInfo("source.principal", "string", "Authority under which the source workload instance is running.", "`service-account-foo` ")); } static { ATTRIBUTE_INFO_MAP.put("source.owner", new AttributeInfo("source.owner", "string", "Reference to the workload controlling the source workload instance.", "`kubernetes://apis/apps/v1/namespaces/istio-system/deployments/istio-policy` ")); } static { ATTRIBUTE_INFO_MAP.put("source.workload.uid", new AttributeInfo("source.workload.uid", "string", "Unique identifier of the source workload.", "`istio://istio-system/workloads/istio-policy` ")); } static { ATTRIBUTE_INFO_MAP.put("source.workload.name", new AttributeInfo("source.workload.name", "string", "Source workload name.", "`istio-policy` ")); } static { ATTRIBUTE_INFO_MAP.put("source.workload.namespace", new AttributeInfo("source.workload.namespace", "string", "Source workload namespace. ", "`istio-system` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.uid", new AttributeInfo("destination.uid", "string", "Platform-specific unique identifier for the server instance.", "`kubernetes://my-svc-234443-5sffe.my-namespace` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.ip", new AttributeInfo("destination.ip", "ip_address", "Server IP address.", "`10.0.0.104` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.port", new AttributeInfo("destination.port", "int64", "The recipient port on the server IP address.", "`8080` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.labels", new AttributeInfo("destination.labels", ValueType.STRING_MAP.name() , "A map of key-value pairs attached to the server instance.", "version => v2 ")); } static { ATTRIBUTE_INFO_MAP.put("destination.name", new AttributeInfo("destination.name", "string", "Destination workload instance name.", "`istio-telemetry-2359333` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.namespace", new AttributeInfo("destination.namespace", "string", "Destination workload instance namespace.", "`istio-system` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.principal", new AttributeInfo("destination.principal", "string", "Authority under which the destination workload instance is running.", "`service-account` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.workload.uid", new AttributeInfo("destination.workload.uid", "string", "Unique identifier of the destination workload.", "`istio://istio-system/workloads/istio-telemetry` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.workload.name", new AttributeInfo("destination.workload.name", "string", "Destination workload name.", "`istio-telemetry` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.workload.namespace", new AttributeInfo("destination.workload.namespace", "string", "Destination workload namespace.", "`istio-system` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.container.name", new AttributeInfo("destination.container.name", "string", "Name of the destination workload instance's container.", "`mixer` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.container.image", new AttributeInfo("destination.container.image", "string", "Image of the destination workload instance's container.", "`gcr.io/istio-testing/mixer:0.8.0` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.service.host", new AttributeInfo("destination.service.host", "string", "Destination host address.", "`istio-telemetry.istio-system.svc.cluster.local` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.service.uid", new AttributeInfo("destination.service.uid", "string", "Unique identifier of the destination service.", "`istio://istio-system/services/istio-telemetry` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.service.name", new AttributeInfo("destination.service.name", "string", "Destination service name.", "`istio-telemetry` ")); } static { ATTRIBUTE_INFO_MAP.put("destination.service.namespace", new AttributeInfo("destination.service.namespace", "string", "Destination service namespace.", "`istio-system` ")); } static { ATTRIBUTE_INFO_MAP.put("origin.ip", new AttributeInfo("origin.ip", "ip_address", "IP address of the proxy client, e.g. origin for the ingress proxies.", "`127.0.0.1` ")); } static { ATTRIBUTE_INFO_MAP.put("request.headers", new AttributeInfo("request.headers", ValueType.STRING_MAP.name() , "HTTP request headers with lowercase keys. For gRPC, its metadata will be here.", "")); } static { ATTRIBUTE_INFO_MAP.put("request.id", new AttributeInfo("request.id", "string", "An ID for the request with statistically low probability of collision.", "")); } static { ATTRIBUTE_INFO_MAP.put("request.path", new AttributeInfo("request.path", "string", "The HTTP URL path including query string", "")); } static { ATTRIBUTE_INFO_MAP.put("request.url_path", new AttributeInfo("request.url_path", "string", "The path part of HTTP URL, with query string being stripped", "")); } static { ATTRIBUTE_INFO_MAP.put("request.query_params", new AttributeInfo("request.query_params", ValueType.STRING_MAP.name() , "A map of query parameters extracted from the HTTP URL.", "")); } static { ATTRIBUTE_INFO_MAP.put("request.host", new AttributeInfo("request.host", "string", "HTTP/1.x host header or HTTP/2 authority header.", "`redis-master:3337` ")); } static { ATTRIBUTE_INFO_MAP.put("request.method", new AttributeInfo("request.method", "string", "The HTTP method.", "")); } static { ATTRIBUTE_INFO_MAP.put("request.reason", new AttributeInfo("request.reason", "string", "The request reason used by auditing systems.", "")); } static { ATTRIBUTE_INFO_MAP.put("request.referer", new AttributeInfo("request.referer", "string", "The HTTP referer header.", "")); } static { ATTRIBUTE_INFO_MAP.put("request.scheme", new AttributeInfo("request.scheme", "string", "URI Scheme of the request", "")); } static { ATTRIBUTE_INFO_MAP.put("request.size", new AttributeInfo("request.size", "int64", "Size of the request in bytes. For HTTP requests this is equivalent to the Content-Length header.", "")); } static { ATTRIBUTE_INFO_MAP.put("request.total_size", new AttributeInfo("request.total_size", "int64", "Total size of HTTP request in bytes, including request headers, body and trailers.", "")); } static { ATTRIBUTE_INFO_MAP.put("request.time", new AttributeInfo("request.time", "timestamp", "The timestamp when the " + "destination receives the request. This should be equivalent to Firebase \"now\").", "")); } static { ATTRIBUTE_INFO_MAP.put("request.useragent", new AttributeInfo("request.useragent", "string", "The HTTP User-Agent header.", "")); } static { ATTRIBUTE_INFO_MAP.put("response.headers", new AttributeInfo("response.headers", ValueType.STRING_MAP.name() , "HTTP response headers with lowercase keys.", "")); } static { ATTRIBUTE_INFO_MAP.put("response.size", new AttributeInfo("response.size", "int64", "Size of the response body in bytes", "")); } static { ATTRIBUTE_INFO_MAP.put("response.total_size", new AttributeInfo("response.total_size", "int64", "Total size of HTTP response in bytes, including response headers and body.", "")); } static { ATTRIBUTE_INFO_MAP.put("response.time", new AttributeInfo("response.time", "timestamp", "The timestamp when the destination produced the response.", "")); } static { ATTRIBUTE_INFO_MAP.put("response.duration", new AttributeInfo("response.duration", "duration", "The amount of time the response took to generate.", "")); } static { ATTRIBUTE_INFO_MAP.put("response.code", new AttributeInfo("response.code", "int64", "The response's HTTP status code.", "")); } static { ATTRIBUTE_INFO_MAP.put("response.grpc_status", new AttributeInfo("response.grpc_status", "string", "The response's gRPC status.", "")); } static { ATTRIBUTE_INFO_MAP.put("response.grpc_message", new AttributeInfo("response.grpc_message", "string", "The response's gRPC status message.", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.id", new AttributeInfo("connection.id", "string", "An ID for a TCP connection with statistically low probability of collision.", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.event", new AttributeInfo("connection.event", "string", "Status of a TCP connection, its value is one of \"open\", \"continue\" and \"close\".", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.received.bytes", new AttributeInfo("connection.received.bytes", "int64", "Number of bytes received by a destination service on a connection since the last Report() for a connection.", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.received.bytes_total", new AttributeInfo("connection.received.bytes_total", "int64", "Total number of bytes received by a destination service during the lifetime of a connection.", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.sent.bytes", new AttributeInfo("connection.sent.bytes", "int64", "Number of bytes sent by a destination service on a connection since the last Report() for a connection.", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.sent.bytes_total", new AttributeInfo("connection.sent.bytes_total", "int64", "Total number of bytes sent by a destination service during the lifetime of a connection.", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.duration", new AttributeInfo("connection.duration", "duration", "The total amount of time a connection has been open.", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.mtls", new AttributeInfo("connection.mtls", "bool", "Indicates whether a " + "request is received over a mutual TLS enabled downstream connection.", "")); } static { ATTRIBUTE_INFO_MAP.put("connection.requested_server_name", new AttributeInfo("connection.requested_server_name", "string", "The requested server name (SNI) of the connection", "")); } static { ATTRIBUTE_INFO_MAP.put("context.protocol", new AttributeInfo("context.protocol", "string", "Protocol of the request or connection being proxied.", "`tcp` ")); } static { ATTRIBUTE_INFO_MAP.put("context.time", new AttributeInfo("context.time", "timestamp", "The timestamp of Mixer operation.", "")); } static { ATTRIBUTE_INFO_MAP.put("context.reporter.kind", new AttributeInfo("context.reporter.kind", "string", "Contextualizes the reported attribute set. Set to `inbound` for the server-side calls from sidecars and `outbound` for the client-side calls from sidecars and gateways", "`inbound` ")); } static { ATTRIBUTE_INFO_MAP.put("context.reporter.uid", new AttributeInfo("context.reporter.uid", "string", "Platform-specific identifier of the attribute reporter.", "`kubernetes://my-svc-234443-5sffe.my-namespace` ")); } static { ATTRIBUTE_INFO_MAP.put("context.proxy_error_code", new AttributeInfo("context.proxy_error_code", "string", "Additional details about the response or connection from proxy. In case of Envoy, see `%RESPONSE_FLAGS%` in [Envoy Access Log](https://www.envoyproxy.io/docs/envoy/latest/configuration/observability/access_log/usage#config-access-log-format-response-flags) for more detail", "`UH` ")); } static { ATTRIBUTE_INFO_MAP.put("api.service", new AttributeInfo("api.service", "string", "The public service name. This is different than the in-mesh service identity and reflects the name of the service exposed to the client.", "`my-svc.com` ")); } static { ATTRIBUTE_INFO_MAP.put("api.version", new AttributeInfo("api.version", "string", "The API version.", "`v1alpha1` ")); } static { ATTRIBUTE_INFO_MAP.put("api.operation", new AttributeInfo("api.operation", "string", "Unique string used to identify the operation. The id is unique among all operations described in a specific &lt;service, version&gt;.", "`getPetsById` ")); } static { ATTRIBUTE_INFO_MAP.put("api.protocol", new AttributeInfo("api.protocol", "string", "The protocol type of the API call. Mainly for monitoring/analytics. Note that this is the frontend protocol exposed to the client, not the protocol implemented by the backend service.", "`http`, `https`, or `grpc` ")); } static { ATTRIBUTE_INFO_MAP.put("request.auth.principal", new AttributeInfo("request.auth.principal", "string", "The " + "authenticated principal of the request. This is a string of the issuer (`iss`) and subject (`sub`) " + "claims within a JWT concatenated with \"/\" with a percent - encoded subject value.This attribute may " + "come from the peer or the origin in the Istio authentication policy, depending on the binding rule defined in the Istio authentication policy.", "`<EMAIL>/sub @foo.com`")); } static { ATTRIBUTE_INFO_MAP.put("request.auth.audiences", new AttributeInfo("request.auth.audiences", "string", "The intended audience(s) for this authentication information. This should reflect the audience (`aud`) claim within a JWT.", "`aud1` ")); } static { ATTRIBUTE_INFO_MAP.put("request.auth.presenter", new AttributeInfo("request.auth.presenter", "string", "The authorized presenter of the credential. This value should reflect the optional Authorized Presenter (`azp`) claim within a JWT or the OAuth2 client id.", "123456789012.my-svc.com ")); } static { ATTRIBUTE_INFO_MAP.put("request.auth.claims", new AttributeInfo("request.auth.claims", ValueType.STRING_MAP.name() , "all raw string claims from the `origin` JWT", "`iss`: `<EMAIL>`, `sub`: `<EMAIL>`, `aud`: `aud1` ")); } static { ATTRIBUTE_INFO_MAP.put("request.api_key", new AttributeInfo("request.api_key", "string", "The API key used for the request.", "abcde12345 ")); } static { ATTRIBUTE_INFO_MAP.put("check.error_code", new AttributeInfo("check.error_code", "int64", "The error [code](https://github.com/google/protobuf/blob/master/src/google/protobuf/stubs/status.h) for Mixer Check call.", "5 ")); } static { ATTRIBUTE_INFO_MAP.put("check.error_message", new AttributeInfo("check.error_message", "string", "The error message for Mixer Check call.", "Could not find the resource ")); } static { ATTRIBUTE_INFO_MAP.put("check.cache_hit", new AttributeInfo("check.cache_hit", "bool", "Indicates whether Mixer check call hits local cache.", "")); } static { ATTRIBUTE_INFO_MAP.put("quota.cache_hit", new AttributeInfo("quota.cache_hit", "bool", "Indicates whether Mixer" + " quota call hits local cache.", "")); } static { ATTRIBUTE_INFO_MAP.put("destination.owner", new AttributeInfo("destination.owner", "string", "Reference to the workload controlling the destination workload instance.", "`kubernetes://apis/apps/v1/namespaces/istio-system/deployments/istio-telemetry`")); } private AttributeVocabulary() { } } <file_sep>/istio-model/src/test/java/me/snowdrop/istio/tests/BaseIstioTest.java /** * Copyright 2018 Red Hat, Inc. and/or its affiliates. * <p> * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package me.snowdrop.istio.tests; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; /** * @author <a href="<EMAIL>"><NAME></a> */ public class BaseIstioTest { protected final YAMLMapper mapper = new YAMLMapper(); } <file_sep>/istio-model/src/test/java/me/snowdrop/istio/api/networking/v1beta1/VirtualServiceTest.java /* * * * * Copyright (C) 2018 Red Hat, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package me.snowdrop.istio.api.networking.v1beta1; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import io.fabric8.kubernetes.api.model.HasMetadata; import me.snowdrop.istio.tests.BaseIstioTest; import org.junit.Test; import org.yaml.snakeyaml.Yaml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class VirtualServiceTest extends BaseIstioTest { /* --- apiVersion: "networking.istio.io/v1beta1" kind: "VirtualService" metadata: annotations: {} finalizers: [] labels: {} name: "details" ownerReferences: [] spec: hosts: - "details" http: - route: - destination: host: "details" subset: "v1" */ @Test public void checkBasicVirtualService() throws Exception { final VirtualService virtualService = new VirtualServiceBuilder() .withNewMetadata() .withName("details") .endMetadata() .withNewSpec() .withHosts("details") .addNewHttp() .addNewRoute() .withNewDestination() .withHost("details") .withSubset("v1") .endDestination() .endRoute() .endHttp() .endSpec() .build(); final String output = mapper.writeValueAsString(virtualService); Yaml parser = new Yaml(); final Map<String, Map> reloaded = parser.loadAs(output, Map.class); assertEquals("VirtualService", reloaded.get("kind")); final Map metadata = reloaded.get("metadata"); assertNotNull(metadata); assertEquals("details", metadata.get("name")); final Map<String, Map> spec = reloaded.get("spec"); assertNotNull(spec); final List<Map> https = (List) spec.get("http"); assertNotNull(https); final Map<String, Map> http = https.get(0); assertNotNull(http); final List<Map> routes = (List) http.get("route"); assertNotNull(routes); final Map<String, Map> route = routes.get(0); assertNotNull(route); final Map<String, Map> destination = route.get("destination"); assertNotNull(destination); assertEquals("details", destination.get("host")); assertEquals("v1", destination.get("subset")); } /* apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: reviews-route spec: hosts: - reviews.prod.svc.cluster.local http: - match: - uri: prefix: "/wpcatalog" - uri: prefix: "/consumercatalog" rewrite: uri: "/newcatalog" route: - destination: host: reviews.prod.svc.cluster.local subset: v2 - route: - destination: host: reviews.prod.svc.cluster.local subset: v1 */ @Test public void checkVirtualServiceWithMatch() throws IOException { final String reviewsHost = "reviews.prod.svc.cluster.local"; final VirtualService resource = new VirtualServiceBuilder() .withNewMetadata().withName("reviews-route").endMetadata() .withNewSpec() .addToHosts(reviewsHost) .addNewHttp() .addNewMatch().withNewUri().withNewPrefixMatchType("/wpcatalog").endUri().endMatch() .addNewMatch().withNewUri().withNewPrefixMatchType("/consumercatalog").endUri().endMatch() .withNewRewrite().withUri("/newcatalog").endRewrite() .addNewRoute() .withNewDestination().withHost(reviewsHost).withSubset("v2").endDestination() .endRoute() .endHttp() .addNewHttp() .addNewRoute() .withNewDestination().withHost(reviewsHost).withSubset("v1").endDestination() .endRoute() .endHttp() .endSpec() .build(); final String output = mapper.writeValueAsString(resource); assertEquals(resource, mapper.readValue(output, HasMetadata.class)); Yaml parser = new Yaml(); final Map<String, Map> reloaded = parser.loadAs(output, Map.class); assertEquals("VirtualService", reloaded.get("kind")); final Map metadata = reloaded.get("metadata"); assertNotNull(metadata); assertEquals("reviews-route", metadata.get("name")); final Map<String, Map> spec = reloaded.get("spec"); assertNotNull(spec); assertEquals(reviewsHost, ((List) spec.get("hosts")).get(0).toString()); final List<Map> https = (List) spec.get("http"); assertNotNull(https); Map<String, Map> http = https.get(0); assertNotNull(http); final List<Map> matches = (List) http.get("match"); assertNotNull(matches); assertEquals(2, matches.size()); assertEquals("/wpcatalog", ((Map) matches.get(0).get("uri")).get("prefix")); assertEquals("/consumercatalog", ((Map) matches.get(1).get("uri")).get("prefix")); assertEquals("/newcatalog", http.get("rewrite").get("uri")); Map destination = (Map) ((List<Map>) http.get("route")).get(0).get("destination"); assertEquals(reviewsHost, destination.get("host")); assertEquals("v2", destination.get("subset")); http = https.get(1); destination = (Map) ((List<Map>) http.get("route")).get(0).get("destination"); assertEquals(reviewsHost, destination.get("host")); assertEquals("v1", destination.get("subset")); } /* apiVersion: "networking.istio.io/v1beta1" kind: "VirtualService" metadata: name: "reviews-route" spec: hosts: - "reviews.prod.svc.cluster.local" http: - route: - destination: host: "reviews.prod.svc.cluster.local" port: number: 9090 subset: "v2" - route: - destination: host: "reviews.prod.svc.cluster.local" port: number: 9090 subset: "v1" */ @Test public void checkVirtualServiceWithPortSelector() throws IOException { final String reviewsHost = "reviews.prod.svc.cluster.local"; final VirtualService resource = new VirtualServiceBuilder() .withNewMetadata().withName("reviews-route").endMetadata() .withNewSpec() .addToHosts(reviewsHost) .addNewHttp() .addNewRoute() .withNewDestination().withHost(reviewsHost).withSubset("v2").withNewPort() .withNumber(9090).endPort().endDestination() .endRoute() .endHttp() .addNewHttp() .addNewRoute() .withNewDestination().withHost(reviewsHost).withSubset("v1").withNewPort() .withNumber(9090).endPort().endDestination() .endRoute() .endHttp() .endSpec() .build(); final String output = mapper.writeValueAsString(resource); assertEquals(resource, mapper.readValue(output, HasMetadata.class)); Yaml parser = new Yaml(); final Map<String, Map> reloaded = parser.loadAs(output, Map.class); assertEquals("VirtualService", reloaded.get("kind")); final Map metadata = reloaded.get("metadata"); assertNotNull(metadata); assertEquals("reviews-route", metadata.get("name")); final Map<String, Map> spec = reloaded.get("spec"); assertNotNull(spec); assertEquals(reviewsHost, ((List) spec.get("hosts")).get(0).toString()); final List<Map> https = (List) spec.get("http"); assertNotNull(https); Map<String, Map> http = https.get(0); assertNotNull(http); Map destination = (Map) ((List<Map>) http.get("route")).get(0).get("destination"); assertEquals(reviewsHost, destination.get("host")); assertEquals("v2", destination.get("subset")); final Map<String, Integer> portSelector1 = (Map<String, Integer>) (destination.get("port")); assertNotNull(portSelector1); assertEquals(9090, portSelector1.get("number").intValue()); http = https.get(1); destination = (Map) ((List<Map>) http.get("route")).get(0).get("destination"); assertEquals(reviewsHost, destination.get("host")); assertEquals("v1", destination.get("subset")); final Map<String, Integer> portSelector2 = (Map<String, Integer>) (destination.get("port")); assertNotNull(portSelector2); assertEquals(9090, portSelector2.get("number").intValue()); } @Test public void roundtripBasicVirtualServiceShouldWork() throws Exception { final VirtualService virtualService = new VirtualServiceBuilder() .withApiVersion("networking.istio.io/v1beta1") .withNewMetadata() .withName("details") .endMetadata() .withNewSpec() .withHosts("details") .addNewHttp() .addNewRoute().withNewDestination().withHost("details").withSubset("v1").endDestination().endRoute() .endHttp() .endSpec() .build(); final String output = mapper.writeValueAsString(virtualService); HasMetadata reloaded = mapper.readValue(output, HasMetadata.class); assertEquals(virtualService, reloaded); } @Test public void loadingFromYAMLShouldWork() throws Exception { final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("virtual-service.yaml"); /* apiVersion: networking.istio.io/v1beta1 metadata: kind: VirtualService name: ratings-route spec: hosts: - ratings.prod.svc.cluster.local http: - route: - destination: host: ratings.prod.svc.cluster.local subset: v1 fault: abort: percent: 10 httpStatus: 400 */ final VirtualService virtualService = mapper.readValue(inputStream, me.snowdrop.istio.api.networking.v1beta1.VirtualService.class); assertEquals("ratings.prod.svc.cluster.local", virtualService.getSpec().getHosts().get(0)); final List<HTTPRoute> http = virtualService.getSpec().getHttp(); assertEquals(1, http.size()); final HTTPRoute route = http.get(0); final List<HTTPRouteDestination> destinations = route.getRoute(); assertEquals(1, destinations.size()); final Destination destination = destinations.get(0).getDestination(); assertEquals("ratings.prod.svc.cluster.local", destination.getHost()); assertEquals("v1", destination.getSubset()); assertNull(route.getFault().getDelay()); final Abort abort = route.getFault().getAbort(); assertEquals(10, abort.getPercentage().getValue().intValue()); assertEquals(400, ((HttpStatusErrorType) abort.getErrorType()).getHttpStatus().intValue()); } @Test public void loadingFromYAMLIssue48() throws Exception { final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("virtual-service-issue48.yaml"); final VirtualService virtualService = mapper.readValue(inputStream, VirtualService.class); /* ... spec: hosts: - recommendation http: - match: - headers: baggage-user-agent: regex: .*DarkLaunch.* ... */ final Map<String, StringMatch> headers = virtualService.getSpec().getHttp().get(0).getMatch().get(0).getHeaders(); final StringMatch stringMatch = headers.get("baggage-user-agent"); assertEquals(RegexMatchType.class, stringMatch.getMatchType().getClass()); RegexMatchType regex = (RegexMatchType) stringMatch.getMatchType(); assertEquals(".*DarkLaunch.*", regex.getRegex()); } @Test public void allowCredentialsShouldWork() throws IOException { final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("virtual-service-issue119.yaml"); final VirtualService virtualService = mapper.readValue(inputStream, VirtualService.class); assertFalse(virtualService.getSpec().getHttp().get(0).getCorsPolicy().getAllowCredentials()); } }
f2dfd32799d1e8a0de661f42e361bca7731b7011
[ "Maven POM", "Makefile", "AsciiDoc", "INI", "Java", "Go", "Go Module", "Shell" ]
50
Shell
snowdrop/istio-java-api
ae90eed49f42c10f66cd8f89448695e4139bdedf
9ff5d04b2d8faad33992ca731c1ddfdf7650e5e7
refs/heads/main
<file_sep>module github.com/glassechidna/lambdaeip go 1.16 require ( github.com/aws/aws-lambda-go v1.24.0 github.com/aws/aws-sdk-go v1.40.0 github.com/pkg/errors v0.9.1 ) <file_sep>package main import ( "context" "encoding/json" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/pkg/errors" "os" ) func main() { sess, err := session.NewSession() if err != nil { fmt.Printf("%+v\n", err) panic(err) } h := &handler{ sentinelGroupId: os.Getenv("SENTINEL_SECURITY_GROUP_ID"), api: ec2.New(sess), } lambda.Start(h.handle) } type handler struct { sentinelGroupId string api ec2iface.EC2API } func (h *handler) handle(ctx context.Context, event *events.CloudWatchEvent) error { fmt.Println(string(event.Detail)) detail := CloudTrailDetail{} err := json.Unmarshal(event.Detail, &detail) if err != nil { return errors.WithStack(err) } switch detail.EventName { case "CreateNetworkInterface": return h.create(ctx, detail) case "DeleteNetworkInterface": return h.delete(ctx, detail) } return nil } type CloudTrailDetail struct { EventName string `json:"eventName"` RequestParameters json.RawMessage `json:"requestParameters"` ResponseElements json.RawMessage `json:"responseElements"` } <file_sep>package main import ( "context" "encoding/json" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/pkg/errors" ) func (h *handler) create(ctx context.Context, detail CloudTrailDetail) error { resp := CreateNetworkInterfaceResponseElements{} err := json.Unmarshal(detail.ResponseElements, &resp) if err != nil { return errors.WithStack(err) } eni := resp.NetworkInterface.NetworkInterfaceId allocate, err := h.api.AllocateAddressWithContext(ctx, &ec2.AllocateAddressInput{ Domain: aws.String(ec2.DomainTypeVpc), TagSpecifications: []*ec2.TagSpecification{ { ResourceType: aws.String(ec2.ResourceTypeElasticIp), Tags: []*ec2.Tag{ {Key: aws.String("lambdaeip:owned"), Value: aws.String("true")}, {Key: aws.String("lambdaeip:eni"), Value: aws.String(eni)}, }, }, }, }) if err != nil { return errors.WithStack(err) } associate, err := h.api.AssociateAddressWithContext(ctx, &ec2.AssociateAddressInput{ AllocationId: allocate.AllocationId, NetworkInterfaceId: &eni, }) if err != nil { return errors.WithStack(err) } j, _ := json.Marshal(map[string]string{ "eni": eni, "eip": *allocate.AllocationId, "association": *associate.AssociationId, }) fmt.Println(string(j)) return nil } type CreateNetworkInterfaceResponseElements struct { NetworkInterface struct { NetworkInterfaceId string `json:"networkInterfaceId"` } `json:"networkInterface"` } <file_sep># lambdaeip ## _Internet connectivity for your VPC-attached Lambda functions without a NAT Gateway_ ### Background I occasionally have serverless applications that need to be attached to VPCs *and* have access to the Internet. The standard solution for that is to deploy NAT Gateways into each availability zone at a cost of $43/mo per zone. For that money I could have invoked my function 215 million times. Today I learned there's a ~better~ different way, courtesy of [<NAME>][tweet]. I immediately went about generalising it so that I could set it and forget it in all my personal environments. ### Deployment You have two options. The first is deploying the following CloudFormation template: ```yaml Transform: AWS::Serverless-2016-10-31 Resources: App: Type: AWS::Serverless::Application Properties: Location: ApplicationId: arn:aws:serverlessrepo:us-east-1:607481581596:applications/lambdaeip SemanticVersion: 0.1.0 Parameters: VpcId: vpc-abc123 ``` The second option is clicking [this link][console] to open the AWS web console, fill in the VPC ID and click the _Deploy_ button. It should look like the following screenshot: ![console screenshot](deploy.png) ### How it works When a VPC-attached Lambda function is created, the Lambda service will create a network interface for it. This issues an EventBridge event, which triggers `lambdaeip` to execute and associate an Elastic IP address with that ENI. It releases the EIP when the Lambda function's ENI is deleted (e.g. if the function itself is deleted). The way you identify whether a Lambda function should receive this special treatment is by associating a "sentinel" security group with it. Here's a complete example of how to do that: ```yaml Transform: AWS::Serverless-2016-10-31 Parameters: SubnetIds: Type: List<AWS::EC2::Subnet::Id> SentinelGroupId: Type: AWS::SSM::Parameter::Value<AWS::EC2::SecurityGroup::Id> Default: /lambdaeip/security-group-id Resources: Function: Type: AWS::Serverless::Function Properties: Runtime: python3.8 Handler: index.handler Timeout: 5 VpcConfig: SecurityGroupIds: [!Ref SentinelGroupId, sg-whatever-else, sg-you-want] SubnetIds: !Ref SubnetIds InlineCode: | import urllib.request def handler(a, b): content = urllib.request.urlopen("https://www.cloudflare.com/cdn-cgi/trace").read() print(content) ``` ### Caveats Chaz says not to use this in production, but YOLO if you care that much about saving tens of dollars a month, it's probably not _really_ a production env, right?! [tweet]: https://twitter.com/schlarpc/status/1415393605330501632 [console]: https://console.aws.amazon.com/lambda/home?region=us-east-1#/create/app?applicationId=arn:aws:serverlessrepo:us-east-1:607481581596:applications/lambdaeip <file_sep>package main import ( "context" "encoding/json" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/pkg/errors" ) func (h *handler) delete(ctx context.Context, detail CloudTrailDetail) error { req := DeleteNetworkInterfaceRequestParameters{} err := json.Unmarshal(detail.RequestParameters, &req) if err != nil { return errors.WithStack(err) } describe, err := h.api.DescribeAddressesWithContext(ctx, &ec2.DescribeAddressesInput{ Filters: []*ec2.Filter{ {Name: aws.String("tag:lambdaeip:eni"), Values: aws.StringSlice([]string{req.NetworkInterfaceId})}, }, }) if err != nil { return errors.WithStack(err) } for _, address := range describe.Addresses { _, _ = h.api.DisassociateAddressWithContext(ctx, &ec2.DisassociateAddressInput{ AssociationId: address.AssociationId, }) _, err = h.api.ReleaseAddressWithContext(ctx, &ec2.ReleaseAddressInput{ AllocationId: address.AllocationId, }) if err != nil { return errors.WithStack(err) } } return nil } type DeleteNetworkInterfaceRequestParameters struct { NetworkInterfaceId string `json:"networkInterfaceId"` }
0928277d2b59a51b99d6d9741233f75c79e12ede
[ "Go", "Go Module", "Markdown" ]
5
Go Module
syllogy/lambdaeip
a9f1b4cf58b83338c4e203e838e14554df8f3f34
35d4c3ae5765a03cd24f8d10b9ef19b514f103e5
refs/heads/main
<repo_name>mapurva49/Hacktoberfest2021<file_sep>/Overloading of [ ] operator.cpp #include<iostream> using namespace std; class array { private: int a[10]; public: void insertdata(int index, int value) { a[index]=value; } int operator [](int index) { return(a[index]);} }; int main() { array obj; int i; for(i=0;i<=9;i++) obj.insertdata(i,10*(i+1)); for(i=0;i<=9;i++) cout<<obj[i]<<" "; return 0; } <file_sep>/const_bin_tree.py #Construct a full binary tree using preorder and mirror preorder traversals class newNode: def __init__(self,data): self.data = data self.left = self.right = None # A utility function to print inorder # traversal of a Binary Tree def prInorder(node): if (node == None) : return prInorder(node.left) print(node.data, end = " ") prInorder(node.right) # A recursive function to construct Full # binary tree from pre[] and preM[]. # preIndex is used to keep track of index # in pre[]. l is low index and h is high # index for the current subarray in preM[] def constructBinaryTreeUtil(pre, preM, preIndex, l, h, size): # Base case if (preIndex >= size or l > h) : return None , preIndex # The first node in preorder traversal # is root. So take the node at preIndex # from preorder and make it root, and # increment preIndex root = newNode(pre[preIndex]) preIndex += 1 # If the current subarray has only # one element, no need to recur if (l == h): return root, preIndex # Search the next element of # pre[] in preM[] i = 0 for i in range(l, h + 1): if (pre[preIndex] == preM[i]): break # construct left and right subtrees # recursively if (i <= h): root.left, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, i, h, size) root.right, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, l + 1, i - 1, size) # return root return root, preIndex # function to construct full binary tree # using its preorder traversal and preorder # traversal of its mirror tree def constructBinaryTree(root, pre, preMirror, size): preIndex = 0 preMIndex = 0 root, x = constructBinaryTreeUtil(pre, preMirror, preIndex, 0, size - 1, size) prInorder(root) # Driver code if __name__ =="__main__": preOrder = [1, 2, 4, 5, 3, 6, 7] preOrderMirror = [1, 3, 7, 6, 2, 5, 4] size = 7 root = newNode(0) constructBinaryTree(root, preOrder, preOrderMirror, size) <file_sep>/next_great_elem.py #Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1. class Solution: def nextLargerElement(self,arr,n): #code here s=[] for i in range(len(arr)): while s and s[-1].get("value") < arr[i]: d = s.pop() arr[d.get("ind")] = arr[i] s.append({"value": arr[i], "ind": i}) while s: d = s.pop() arr[d.get("ind")] = -1 return arr if __name__ == "__main__": print(Solution().nextLargerElement([6,8,0,1,3],5)) <file_sep>/README.md # Hacktoberfest2021 Pull requests can be made in any participating GitHub or GitLab hosted repository/projects. Look for the 'hacktoberfest' topic to know if a project is participating in Hacktoberfest. You can sign up anytime between October 1 and October 31. Just be sure to sign up on the official Hacktoberfest website for your pull requests to count. # Hacktoberfest2021 Hacktoberfest encourages participation in the open source community, which grows bigger every year. Complete the 2021 challenge and earn a limited edition T-shirt. 📢 Register Yourself for Hacktoberfest and make four pull requests (PRs) between October 1st-31st to grab free SWAGS 🔥. # What's in it for you? Say hello to everyone in the discussion and tell us about your skills and experiences Get your questions answered and help others by answering theirs. Share your creative ideas about improving this community. Showcase you previous works as a motivation for others and get feedback from experts. Resources to get you started and sharpening the skills. And lot of things coming from you. Feel Free to Ask anything without any hesitation. # How to do contributions 1. Fork the Project Fork this repository and make changes in code as required. You can change it online or by cloning it in your device. Then Pust it on your Forked Repo for furteher Actions. Do not use special characters in the template above. 2. Write a Good Commit Message You have written some code in your branch, and are ready to commit. So, make sure to written good, clean commit messages. Let's review the anatomy of a commit message. First line, no more than 50 characters Details section, as long as you want. Not always necessary, but available if you need it. Wrapped at 72 characters. Present imperative tense is preferred for commits. That means "fix bug", not "fixes bug" or "fixed bug". Use bullets if you need Bullets are a good way to summarize a few things If you have too much info here, it might be a good candidate to break down into multiple commits. You can use emoji here too ✨ 3. Lastly, submit your Pull Request Go through the checklist on the pull request template to guarantee your submission is valid. Our team will review your application, approve and merge your submission if everything is correct. Otherwise, you will get notified of the changes requested in the pull request comment section. Please check first and then send your codes with description. *All the best for the event * <file_sep>/frogmaze.cpp ?* Alef the Frog is in an nxm two-dimensional maze represented as a table. The maze has the following characteristics: Each cell can be free or can contain an obstacle, an exit, or a mine. Any two cells in the table considered adjacent if they share a side. The maze is surrounded by a solid wall made of obstacles. Some pairs of free cells are connected by a bidirectional tunnel. When Alef is in any cell, he can randomly and with equal probability choose to move into one of the adjacent cells that don't contain an obstacle in it. If this cell contains a mine, the mine explodes and Alef dies. If this cell contains an exit, then Alef escapes the maze. When Alef lands on a cell with an entrance to a tunnel, he is immediately transported through the tunnel and is thrown into the cell at the other end of the tunnel. Thereafter, he won't fall again, and will now randomly move to one of the adjacent cells again. (He could possibly fall in the same tunnel later.) It's possible for Alef to get stuck in the maze in the case when the cell in which he was thrown into from a tunnel is surrounded by obstacles on all sides. Your task is to write a program which calculates and prints a probability that Alef escapes the maze. Input Format The first line contains three space-separated integers , and denoting the dimensions of the maze and the number of bidirectional tunnels. The next lines describe the maze. The 'th line contains a string of length denoting the 'th row of the maze. The meaning of each character is as follows: # denotes an obstacle. A denotes a free cell where Alef is initially in. * denotes a cell with a mine. % denotes a cell with an exit. O denotes a free cell (which may contain an entrance to a tunnel). The next lines describe the tunnels. The 'th line contains four space-separated integers , , , . Here, and denote the coordinates of both entrances of the tunnel. denotes the row and column number, respectively. Output Format Print one real number denoting the probability that Alef escapes the maze. Your answer will be considered to be correct if its (absolute) difference from the true answer is not greater than 10^-6. */ #include <bits/stdc++.h> #define endl '\n' #define double long double using namespace std; const int MAXN = (42); const double eps = 1e-12; vector<double> gauss(vector<vector<double>> &a) { int n = a.size(), m = a[0].size() - 1; vector<int> where(m, -1); for(int col = 0, row = 0; col < m && row < n; col++) { int sel = row; for(int i = row; i < n; i++) if(abs(a[i][col]) > abs(a[sel][col])) sel = i; if(abs(a[sel][col]) < eps) { where[col] = -1; continue; } for(int i = col; i <= m; i++) swap(a[sel][i], a[row][i]); where[col] = row; for(int i = 0; i < n; i++) if(i != row) { if(abs(a[i][col]) < eps) continue; double c = a[i][col] / a[row][col]; for(int j = 0; j <= m; j++) a[i][j] -= c * a[row][j]; } row++; } vector<double> ans(m, 0); for(int i = 0; i < m; i++) if(where[i] != -1) ans[i] = a[where[i]][m] / a[where[i]][i]; for(int i = 0; i < n; i++) { double sum = a[i][m]; for(int j = 0; j < m; j++) sum -= ans[j] * a[i][j]; if(abs(sum) > eps) return vector<double>(); } return ans; } int n, m, k; string a[MAXN]; int nxt_x[MAXN][MAXN], nxt_y[MAXN][MAXN]; void read() { cin >> n >> m >> k; for(int i = 0; i < n; i++) cin >> a[i]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) nxt_x[i][j] = i, nxt_y[i][j] = j; for(int i = 0; i < k; i++) { int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; x1--; y1--; x2--; y2--; nxt_x[x1][y1] = x2; nxt_y[x1][y1] = y2; nxt_x[x2][y2] = x1; nxt_y[x2][y2] = y1; } } int N; int encode(int x, int y) { return x * m + y; } int dirx[4] = {0, 0, 1, -1}; int diry[4] = {1, -1, 0, 0}; bool ok(int x, int y) { if(x >= n || y >= m || x < 0 || y < 0) return false; return a[x][y] != '#'; } void solve() { N = n * m; vector<vector<double> > matr; vector<double> zero(N + 1, 0); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { if(a[i][j] == '#') { matr.push_back(zero); continue; } else if(a[i][j] == '*') { matr.push_back(zero), matr[matr.size() - 1][encode(i, j)] = 1; continue; } else if(a[i][j] == '%') { matr.push_back(zero), matr[matr.size() - 1][encode(i, j)] = 1; matr[matr.size() - 1][N] = 1; continue; } vector<int> adj; for(int d = 0; d < 4; d++) if(ok(i + dirx[d], j + diry[d])) adj.push_back(encode(nxt_x[i + dirx[d]][j + diry[d]], nxt_y[i + dirx[d]][j + diry[d]])); matr.push_back(zero); matr[matr.size() - 1][encode(i, j)] = 1; for(int v: adj) matr[matr.size() - 1][v] = -((double)1 / (double)adj.size()); } vector<double> ans = gauss(matr); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(a[i][j] == 'A') { cout << setprecision(9) << fixed << ans[encode(i, j)] << endl; return; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); read(); solve(); return 0; } <file_sep>/Local_max.py #Given an array of N integers. The task is to print the elements from the array which are greater than their immediate previous and next elements. def printElements(arr, n): # Traverse array from index 1 to n-2 # and check for the given condition for i in range(1, n - 1, 1): if (arr[i] > arr[i - 1] and arr[i] > arr[i + 1]): print(arr[i], end = " ") # Driver Code if __name__ == '__main__': arr = [2, 3, 1, 5, 4, 9, 8, 7, 5] n = len(arr) printElements(arr, n) <file_sep>/Trap_water.py #Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. def maxWater(arr, n): # indices to traverse the array left = 0 right = n-1 # To store Left max and right max # for two pointers left and right l_max = 0 r_max = 0 # To store the total amount # of rain water trapped result = 0 while (left <= right): # We need check for minimum of left # and right max for each element if r_max <= l_max: # Add the difference between #current value and right max at index r result += max(0, r_max-arr[right]) # Update right max r_max = max(r_max, arr[right]) # Update right pointer right -= 1 else: # Add the difference between # current value and left max at index l result += max(0, l_max-arr[left]) # Update left max l_max = max(l_max, arr[left]) # Update left pointer left += 1 return result # Driver code arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] n = len(arr) print(maxWater(arr, n))
fd93f79cc01e61034abfc6c09008335a2357f357
[ "Markdown", "Python", "C++" ]
7
C++
mapurva49/Hacktoberfest2021
2cd8cf6690b92ad0b946ed6842d6e953fe617acd
4da42527074751a4798fdfd73ea15342214f292a
refs/heads/master
<repo_name>mdullah10/MyFirstWork<file_sep>/DataType.java package Core.java; public class DataType { // class-- access modifier of a object --blueprint of a object public static void main(String[] args) { String firstName = "Md"; String lastName = "Ullah"; System.out.println(firstName+" "+lastName); System.out.println("firstName,lastName"); System.out.println("firstNamelastName"); //Byte 8 bit byte number = -128; byte number2 = 127; //Short -16 bit Short x = -32_768; Short y = 32_767; //int -32 bit int a = -2147483648; int b = 2147483647; //long 64 bit long z = 32544665566545525l; //double 64 bit double d = 1.34; //float 32 bit float f = 2.677f; //character 16 bit char c = '\u00e5';// Unicode table System.out.println(c); //boolean true or falls boolean s = false; boolean s1 = true; double volume = momin(number, number2); System.out.println("square is" + volume); } private static double momin(byte number, byte number2) { return (number*number2); } }<file_sep>/Bmw.java package Core.java; public class Bmw { int year=2019; String model= "xdrive"; static int door=4; public Bmw(){ } public Bmw(int year) { this.year= year; System.out.println(year); } public Bmw(String model) { this.model=model; System.out.println(model); } } <file_sep>/execution.java package Core.java; public class execution { public static void main(String[]args) { //class name + reference variable = new + constructor name Bmw obj = new Bmw(); Bmw obj1= new Bmw(); System.out.println(obj.year); System.out.println(obj1.model); System.out.println(Bmw.door); } }<file_sep>/IfElseConcept.java package Core.java; public class IfElseConcept { public static void main(String[] args) { int a = 10; int b = 20; if (b>a) { System.out.println("b is greater than a"); } else { System.out.println("a is greater than b"); } //Comparison operator (< > <= >= == !=) int c = 30; int d = 40; if (c==d) { System.out.println("c and d are equal"); } else { System.out.println("c and d are not equal"); } int a1 = 100; int b1 = 200; int c1 = 300; if (a1>b1 & a1>c1) { System.out.println("a1 is the highest"); } else if (b1>c1) { System.out.println("b1 is the highest"); } else { System.out.println("c1 is the higtest"); } } }
491ef3bd58844015cdda39f221c4eddbec127be8
[ "Java" ]
4
Java
mdullah10/MyFirstWork
10cdf9593a985098b0bb061df4dd8f2894cbea3f
803d20317277c244a8e67b19c848b64a99939f7f
refs/heads/master
<repo_name>Buyaya/spider<file_sep>/venv/Lib/site-packages/pooled_multiprocessing/__init__.py from multiprocessing import get_context, current_process from threading import Thread, RLock, Event from time import time from psutil import cpu_count from more_itertools import chunked import logging import os from .waiter import Waiter cpu_un_logical = cpu_count(False) cpu_logical = cpu_count(True) if cpu_logical and cpu_un_logical: cpu_num = min(cpu_logical, cpu_un_logical) elif cpu_un_logical and cpu_logical is None: cpu_num = cpu_un_logical elif cpu_logical and cpu_un_logical is None: cpu_num = cpu_logical else: cpu_num = os.cpu_count() processes = list() process_index = 0 lock = RLock() def _process(index, input_que, output_que): while True: try: fnc, args_list, kwargs, t = input_que.get() # print("S", index, round((time() - t) * 1000, 3), "mSec") if isinstance(args_list[0], tuple) or isinstance(args_list[0], list): result = [fnc(*args, **kwargs) for args in args_list] else: result = [fnc(args, **kwargs) for args in args_list] # print("E", index, round((time() - t) * 1000, 3), "mSec") output_que.put(result) del fnc, args_list, kwargs, result except Exception as e: error = "Error on pool {}: {}".format(index, e) logging.error(error) output_que.put([error]) def add_pool_process(add_num): if current_process().name != "MainProcess": return if add_num == 0: return global process_index with lock: # create cxt = get_context('spawn') for index in range(1 + process_index, add_num + process_index + 1): event = Event() event.set() input_que = cxt.Queue() output_que = cxt.Queue() p = cxt.Process(target=_process, name="Pool{}".format(index), args=(index, input_que, output_que)) p.daemon = True p.start() processes.append((p, input_que, output_que, event)) logging.info("Start pooled process {}".format(index)) process_index += 1 def mp_map(fnc, data_list, **kwargs): assert len(processes) > 0, "It's not main process?" chunk_list = [list() for i in range(cpu_num)] for index, data in enumerate(data_list): chunk_list[index % cpu_num].append(data) result = list() work = list() task = 0 # throw a tasks with lock: failed_num = 0 for p in processes.copy(): process, input_que, output_que, event = p if not process.is_alive(): processes.remove(p) failed_num += 1 add_pool_process(failed_num) for (process, input_que, output_que, event), args_list in zip(processes, chunk_list): if not process.is_alive(): raise RuntimeError('Pool process is dead. (task throw)') if len(args_list) == 0: continue s = time() event.wait() # print(round((time()-s)*1000, 3), "mSec wait") event.clear() input_que.put((fnc, args_list, kwargs, time())) work.append(process) task += 1 # wait results for process, input_que, output_que, event in processes: if process not in work: continue if not process.is_alive(): raise RuntimeError('Pool process is dead. (waiting)') if not event.is_set(): result.extend(output_que.get()) event.set() task -= 1 if task != 0: raise RuntimeError('complete task is 0 but {}'.format(task)) # return result return result def mp_map_async(fnc, data_list, callback=None, chunk=50, **kwargs): def _return(data, w): r = mp_map(fnc, data, **kwargs) if callback: callback(r) w.put_data(r) assert len(processes) > 0, "It's not main process?" chunk_list = list(chunked(data_list, chunk)) _w = Waiter(task=len(chunk_list)) for d in chunk_list: Thread(target=_return, name="Pooled", args=(d, _w), daemon=True).start() return _w, _w.result def mp_close(): with lock: for process, input_que, output_que, event in processes: process.terminate() input_que.close() output_que.close() processes.clear() # pre-create # add_pool_process(cpu_num) __all__ = [ "cpu_num", "add_pool_process", "mp_map", "mp_map_async", "mp_close" ] <file_sep>/spider.py import requests import re import os import json from multiprocessing import Pool from fontTools.ttLib import TTFont def get_one_response(url): headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } response = requests.get(url,headers = headers) if response.status_code == 200: data = response.content return data return None # 下载新字体 def dow_font(data): pattern = re.compile(r"url\('(.*?)'\) format\('woff'\)") font_url = re.findall(pattern,data)[0] font_url = "http:" + font_url font_name = font_url.split('/')[-1] file_list = os.listdir('./fonts') if font_name not in file_list: print('不在字体库中,下载...',font_name) response = get_one_response(font_url) with open('./fonts/' + font_name, 'wb') as f: f.write(response) f.close() newFont = TTFont('./fonts/' + font_name) return newFont # 字体破解 def crk_font(newFont, data): baseFont = TTFont('./be72b0e480d2416358ab91e576f7237f2076.woff') uniList = newFont['cmap'].tables[0].ttFont.getGlyphOrder() numList = [] baseNumList = ['1','8','0','4','9','7','2','6','3','5',] baseUniCode = ['uniF837','uniE187','uniE7B7','uniF300','uniF4BD','uniEEF9','uniE94E','uniE9E2','uniE6C5','uniE649'] for i in range(1,12): newGlyph = newFont['glyf'][uniList[i]] for j in range(10): baseGlyph = baseFont['glyf'][baseUniCode[j]] if newGlyph == baseGlyph: numList.append(baseNumList[j]) break rowList = [] for i in uniList[2:]: i = i.replace('uni','&#x').lower() + ';' rowList.append(i) dictory = dict(zip(rowList,numList)) for key in dictory: if key in data: data = data.replace(key,str(dictory[key])) return data def parse_one_data(data): pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?title="(.*?)".*?data-src="(.*?)"' '.*?class="star">(.*?)</p>.*?class="releasetime">(.*?)</p>.*?class="stonefont">' '(.*?)</span>.*?class="stonefont">(.*?)</span>.*?</dd>',re.S) items = re.findall(pattern,data) for item in items: yield { '排名:': item[0], '电影名:': item[1], '封面:': item[2], '主演:': item[3].strip()[3:], '上映时间:': item[4].strip()[5:], '本月新增想看:': item[5], '总想看:': item[6] } def write_to_file(content): with open('result.txt','a',encoding="utf-8") as f: f.write(json.dumps(content,ensure_ascii=False) + '\n') f.close() def main(offset): url = 'https://maoyan.com/board/6?offset=' + str(offset) data = get_one_response(url).decode('utf-8') newFont = dow_font(data) data = crk_font(newFont,data) for item in parse_one_data(data): print(item) write_to_file(item) if __name__ == '__main__': for i in range(5): main(i * 10) <file_sep>/venv/Lib/site-packages/pooled_multiprocessing/waiter.py from threading import Event, Lock class Waiter(Event): """ waiter = Waiter(3) # wait for 3 tasks waiter.wait() # wait for task complete waiter.result # list of result """ def __init__(self, task): super(Waiter, self).__init__() self.result = list() self.task = task self.lock = Lock() def __repr__(self): return "<Event-{} finish={} task={} result={}>" \ .format(id(self.result), self.is_set(), self.task, len(self.result)) def put_data(self, result): with self.lock: self.task -= 1 self.result.extend(result) if self.task == 0: self.set()
6f808b0978c4a6907ed07ba693b5fd5bf4db0bb9
[ "Python" ]
3
Python
Buyaya/spider
d19cd6d78115e342484f905103370024173d5c45
ca308fbf4cc61c13b1ad2fa54b3b94e013889a0b
refs/heads/master
<repo_name>mariiapaniutina/js_application_design<file_sep>/src/js/controller.js var controller = function(){ return 'CONTROLLER!'; }; console.log(controller());<file_sep>/CHANGELOG.md <a name="1.1.12"></a> ## [1.1.12](https://github.com/mariiapaniutina/js_application_design/compare/v1.1.11...v1.1.12) (2016-01-31) # --- RELEASE NOTES --- <a name="1.1.11"></a> ## [1.1.11](https://github.com/mariiapaniutina/js_application_design/compare/v1.1.10...v1.1.11) (2016-01-08) ### Bug Fixes * added hardcoded path in courcemap ([2175c33](https://github.com/mariiapaniutina/js_application_design/commit/2175c33)) <a name="1.1.10"></a> ## [1.1.10](https://github.com/mariiapaniutina/js_application_design/compare/v1.1.9...v1.1.10) (2015-12-31) ### Bug Fixes * **warn:** all files are public ([e297c8b](https://github.com/mariiapaniutina/js_application_design/commit/e297c8b)) <a name="1.1.9"></a> ## [1.1.9](https://github.com/mariiapaniutina/js_application_design/compare/v1.1.8...v1.1.9) (2015-12-31) ### Features * updated app.json ([5e314ac](https://github.com/mariiapaniutina/js_application_design/commit/5e314ac)) <file_sep>/src/js/notes.js /** * JavaScript Application Design & extra features */ /** * Returns the sum of a and b * @param {Number} a * @param {Number} b * @param {Boolean} retArr If set to true, the function will return an array * @returns {Number|Array} Sum of a and b or an array that contains a, b and the sum of a and b. */ function sum(a, b, retArr) { if (retArr) { return [a, b, a + b]; } return a + b; } /** * @name pureFunction * @description Pure function: the result can only depend on the arguments passed to it, * and it cann not depend on state variables, services, or objects that are not part of the argument body */ var avarageSum = function(nums){ var sum = 0; for (var i=0; i<nums.length; i++){ sum += nums[i]; } return sum/nums.length; }; var test1 = avarageSum([1, 2, 3, 4, 5]); console.log('avarageSum [1, 2, 3, 4, 5] ===>', test1); /** * @name functionalFactory * @description This is a function, which returns a function, which do what you want to. */ var averageFactory = function () { var sum = 0; var count = 0; return function (value) { sum += value; count++; return sum / count; }; }; var test2 = averageFactory(); test2(1); test2(2); test2(3); test2(4); var test2result = test2(5); console.log('averageFactory [1, 2, 3, 4, 5] ===>', test2result); /** * @name modulePattern * @description MODULE pattern using slosures */ var myModule = (function(){ var privateVar = 'this is private :: myModule'; var privateMethod = function(){ return privateVar; }; var publicAPI = { publicMethod: function(){ return 'this is public :: myModule'; } }; return publicAPI; })(); console.log(myModule.publicMethod()); /** * @name exposePublicModule * @description Expose the public module/object through closures * */ (function (myModule) { var privateThing = 'Private variable :: exposed from global object :: myModule'; function privateMethod () { return privateThing; } myModule.api = { tellPrivate: function(){ return privateMethod(); } }; })(myModule); console.log(myModule.api.tellPrivate()); /** * @name PromiseExample * @description Example of Promise with pure JS (not supporting in IE, use Polyfill instead) */ var promise = new Promise(function(resolve, reject){ resolve(); }); promise.then(function(){ console.log('promise :: first callback'); }).then(function(){ console.log('promise :: second callback'); }); /** * Returns trimed string - any string with whitespaces * @param {String} Str * @returns {String} */ function trim(str) { return str.replace(/^\s+|\s+$/g, ''); } /** * Check if input is Number * @param {Any} x * @returns {Boolean} */ function isInteger(x) { return x === Math.floor(x); }<file_sep>/notes.txt JavaScript Application Design ——————————————————————— BUILD PROCESS: Debug => Compilation, Testing, Watching Release => Compilation, Testing, Optimization, Release notes ——————————————————————— Continuous Testing => Unit testing => Integration testing => CI ——————————————————————— Development distribution -> Optimized for debugging Release distribution -> Optimized for performance ——————————————————————— DRY- Dont Repeat Yourself WET - We Enjoy Typing || Write Everything Twice ——————————————————————— nodemon - way to reload application, when any file was changed grunt-rev grunt-critical Travis CI node-inspector => allows to debug nodeJs source code in Chrome as regular client-side source code ——————————————————————— npm install winston => A multi-transport async logging library for Node.js npm install winston-express => Express middleware to let you use winston from the browser npm install wavi => Generate a class diagram for node.js web application inspired by the Web Application Extension (WAE) for UML. Document your application with wavi. npm install autodoc => documentation generation. (https://www.npmjs.com/package/autodoc) ——————————————————————— dev - x.x.X release - x.X.x prod - X.x.x semantic versioning -> major.minor.patch ——————————————————————— CLI: command-line interface SRP: Single Responsibility Principle => Build package, function, component that do one thing and do it well Idempotence: no matter how many times you invoke the operation, the result will be the same. Pure function: the result can only depend on the arguments passed to it, and it can’t depend on state variables, services, or objects that aren’t part of the argument body Prototypes in JavaScript are most useful when dealing with DOM interaction ES6 Modules - read later! grunt-traceur allowing to “translate” ES6 features into ES5 (The best features of ES6 - import and export) async -utility module which provides functions to work with asynchronous js. Can be installed with bower: bower install async async.concurrent: few async functions without interdependencies, but when all of them are done - another function should be called async.series: few async functions with interdependencies (the result is passing as an argument), when all of them are done - another function should be called async.waterfall: few async functions with interdependencies (the result is passing as an argument), when all of them are done - another function should be called Promises -> ability to add callback in .then() method <file_sep>/src/js/components/ArrayToString.js define(function () { return function (input) { var result = ''; if (input && input.prototype.constructor == 'Array'){ for (var i=0; i<input.length; i++){ result += input[i] + ' '; } } return result; }; });<file_sep>/build/js/app.min.js define('components/ArrayToString',[],function () { return function (input) { var result = ''; if (input && input.prototype.constructor == 'Array'){ for (var i=0; i<input.length; i++){ result += input[i] + ' '; } } return result; }; }); require(['components/ArrayToString'], function(ArrayToString) { var result = ArrayToString(['word1', 'word2']); console.log(result); // <- 'word1 word2' }); define("app", function(){}); <file_sep>/Gruntfile.js module.exports = function(grunt) { var config = { pkg: grunt.file.readJSON('package.json'), banner_title: '/* App Name: <%= pkg.name %> */\n' + '/* Created: <%= grunt.template.today("yyyy-mm-dd HH:MM") %> */\n' + '/* Author: <%= pkg.author %> */\n' }; //minifying grunt.loadNpmTasks('grunt-contrib-uglify'); config.uglify = { options: { mangle: false, banner: '<%= banner_title %>', sourceMap: true }, build: { src: ['src/js/*.js', '!src/js/components/*', '!src/js/app.js'], dest: 'build/js/<%= pkg.name %>.min.js' } }; //js validation grunt.loadNpmTasks('grunt-contrib-jshint'); config.jshint = { files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'], options: { globals: { //jQuery: true } } }; //from less to css grunt.loadNpmTasks('grunt-contrib-less'); config.less = { compile: { files: { 'build/style/compiled.css': [ 'src/style/main.less' ] } } }; //making sprites => doesnt work properly with large images grunt.loadNpmTasks('grunt-spritesmith'); config.sprite = { all: { src: 'src/images/*.png', dest: 'build/images/main.png', destCss: 'src/style/icons.less' } }; //lets replace path is icons.less => to make it public grunt.loadNpmTasks('grunt-text-replace'); config.replace = { icons_less: { src: ['src/style/icons.less'], overwrite: true, replacements: [{ from: "../../build/images/", to: "../images/" }] }, source_map: { src: ['build/js/js_application_design.min.js.map'], overwrite: true, replacements: [{ from: "../../src/js", to: "https://immense-scrubland-4552.herokuapp.com/src/js" }] } }; //image minifying grunt.loadNpmTasks('grunt-contrib-imagemin'); config.imagemin = { all: { options: { optimizationLevel: 3 }, files: [{ expand: true, cwd: 'src/images/', src: ['*.{png,jpg,gif}'], dest: 'build/images/original/' }] } }; //js concatenation grunt.loadNpmTasks('grunt-contrib-concat'); config.concat = { js: { options: { // define a string to put between each file in the concatenated output separator: '\n\n' }, files: { 'js_application_design.js': [ 'src/js/*.js' ] } } }; //bundling with require grunt.loadNpmTasks('grunt-contrib-requirejs'); config.requirejs = { options: { name: 'app', baseUrl: 'src/js', out: 'js/app.min.js' }, debug: { options: { optimize: 'none' } }, release: { options: {} } }; /* Versioning (x.x.x-y) grunt bump-only >> Version bumped to 0.0.1 (in package.json) grunt bump-only:minor >> Version bumped to 0.1.0 (in package.json) grunt bump-only:major >> Version bumped to 1.0.0 (in package.json) */ grunt.loadNpmTasks('grunt-bump'); config.bump = { options: { files: ['package.json'], //updateConfigs: [], commit: true, commitMessage: 'Release v%VERSION%', commitFiles: ['package.json', 'CHANGELOG.md'], createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: true, pushTo: 'origin' } }; //changelog grunt.loadNpmTasks('grunt-conventional-changelog'); config.conventionalChangelog = { options: { changelogOpts: { // conventional-changelog options go here preset: 'angular' }, context: { // context goes here }, gitRawCommitsOpts: { // git-raw-commits options go here }, parserOpts: { // conventional-commits-parser options go here }, writerOpts: { // conventional-changelog-writer options go here } }, release: { src: 'CHANGELOG.md' } }; //watcher grunt.loadNpmTasks('grunt-contrib-watch'); config.watch = { files: ['<%= jshint.files %>'], tasks: ['jshint'] }; grunt.loadNpmTasks('grunt-browserify'); /* config.browserify = { debug: { files: { 'build/js/app.js': 'js/app.js' }, options: { debug: true } } }; */ // Tasks grunt.registerTask('default', ['jshint', 'sprite','replace:icons_less', 'imagemin', 'less', 'concat', 'uglify', 'replace:source_map']); grunt.registerTask('debug', ['default', 'watch']); grunt.registerTask('notes', ['bump-only', 'conventionalChangelog', 'bump-commit']); grunt.registerTask('develop', ['default', 'bump:patch']); grunt.registerTask('release', ['default', 'bump:minor']); grunt.initConfig(config); };<file_sep>/src/js/app.js require(['components/ArrayToString'], function(ArrayToString) { var result = ArrayToString(['word1', 'word2']); console.log(result); // <- 'word1 word2' });<file_sep>/js_application_design.js require(['components/ArrayToString'], function(ArrayToString) { var result = ArrayToString(['word1', 'word2']); console.log(result); // <- 'word1 word2' }); var controller = function(){ return 'CONTROLLER!'; }; console.log(controller()); /* === PURE FUNCTION === * Pure function: the result can only depend on the arguments passed to it, * and it can’t depend on state variables, services, or objects that aren’t part of the argument body */ var avarageSum = function(nums){ var sum = 0; for (var i=0; i<nums.length; i++){ sum += nums[i]; } return sum/nums.length; }; var test1 = avarageSum([1, 2, 3, 4, 5]); console.log('avarageSum [1, 2, 3, 4, 5] ===>', test1); /* === FUNCTIONAL FACTORY === * This is a function, which returns a function, which do what you want to. */ var averageFactory = function () { var sum = 0; var count = 0; return function (value) { sum += value; count++; return sum / count; }; }; var test2 = averageFactory(); test2(1); test2(2); test2(3); test2(4); var test2result = test2(5); console.log('averageFactory [1, 2, 3, 4, 5] ===>', test2result); /* * MODULE pattern using slosures */ var myModule = (function(){ var privateVar = 'this is private :: myModule'; var privateMethod = function(){ return privateVar; }; var publicAPI = { publicMethod: function(){ return 'this is public :: myModule'; } }; return publicAPI; })(); console.log(myModule.publicMethod()); /* * Expose the public module/object through closures */ (function (myModule) { var privateThing = 'Private variable :: exposed from global object :: myModule'; function privateMethod () { return privateThing; } myModule.api = { tellPrivate: function(){ return privateMethod(); } }; })(myModule); console.log(myModule.api.tellPrivate()); /* * Example of Promise with pure JS (not supporting in IE, use Polyfill instead) */ var promise = new Promise(function(resolve, reject){ resolve(); }); promise.then(function(){ console.log('promise :: first callback'); }).then(function(){ console.log('promise :: second callback'); }); var view = function(){ return 'VIEW!'; }; console.log(view());<file_sep>/README.md <h1>js_application_design</h1> <p>Here will be all notes from book "JavaScript Application Design". Author: <b><NAME></b></p> | Used grunt plugins | ---------------------- | grunt-contrib-jshint | | grunt-contrib-uglify | | grunt-contrib-less | | grunt-contrib-concat | | grunt-contrib-watch | | grunt-spritesmith (doesnt work properly with large images) | | grunt-contrib-imagemin | | grunt-conventional-changelog | | grunt-bump | <h4>Notes:</h4> <ul> <li><b>grunt-conventional-changelog</b> works from git commits. Key words: "feat:", "warn:", "chore:", "fix:" etc</li> <li><b>heroku</b> doesnt install "node_modules", thats why this folder is present on github in this project</li> </ul> <h4>Enter *.html doesnt have any attacthed stylesheet yet</h4>
a14ac983503ef5248def8ba7a99e92eca1ff42c6
[ "JavaScript", "Text", "Markdown" ]
10
JavaScript
mariiapaniutina/js_application_design
f279fb7f0534623a7f140c05810a97c0a3169c84
d9c097f211382dd6d5c76189f97a29f7224e2b39
refs/heads/master
<file_sep>#grpup1: #The Goal: Like the title suggests, this project involves writing a program that simulates rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function that randomly grabs a number within that range and prints it. #Concepts to keep in mind: #Random #Integer #Print #While Loops import random roll_again="yes" while(roll_again=="yes" or roll_again=="y"): print(random.randint(1,7)) roll_again=input("Do you want to roll again:y/yes or n/no")
aa6fbadadda8df988f83c9eaa20497d774b2a05f
[ "Python" ]
1
Python
NehaAgarwal20/Rolling-dice
f4c4fc2cce9456d658be4de04f47b6bca63ff10c
44e2a9529d16558eda8629942ac53c399508ce14
refs/heads/master
<file_sep><?php /** * patching arc eslint into an extension so we can * version control it in Site development */ phutil_register_library_map(array( '__library_version__' => 2, 'class' => array( 'ArcanistESLintLinter' => 'src/ArcanistESLintLinter.php', ), 'function' => array( ), 'xmap' => array( 'ArcanistESLintLinter' => 'ArcanistExternalLinter', ), )); <file_sep># Arcanist Extensions AddThis uses certain extensions for [Arcanist](https://github.com/phacility/arcanist). This submodule is a fork of https://github.com/tagview/arcanist-extensions.git In the `load` key of your project's `.arcconfig` file: ```json { "project_id": "my-awesome-project", "conduit_uri": "https://example.org", "load": [ ".arcanist-extensions/[extension_name]" ] } ``` ## Available extensions ### `eslint` alpha version of [Arcanist ESLint](https://secure.phabricator.com/D12198) For more information regarding Arcanist linters configuration, access the [Arcanist Lint User Guide](https://secure.phabricator.com/book/phabricator/article/arcanist_lint/). ### `tap_test_engine` This extension implements a generic [TAP](http://testanything.org/) test engine, so Arcanist may run tests from any tool that has a TAP compatible output. To use this extension, you must inform the command that will run your tests (just make sure that this command returns a TAP formatted output on `STDOUT`): ```json { "project_id": "my-awesome-project", "conduit_uri": "https://example.org", "load": [ ".arcanist-extensions/tap_test_engine" ], "unit.engine": "TAPTestEngine", "unit.engine.tap.command": "bundle exec rake spec" } ``` # License (The MIT License) Copyright (c) 2015 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
560956c43d516e7789754ab06868a5268a27915d
[ "Markdown", "PHP" ]
2
PHP
ninacfgarcia/arcanist-extensions
578eed691cc69043b97fee951803f2e94929b608
9c0761c057cec5484abe2d975e438c4b6e97dd9f
refs/heads/master
<repo_name>edgrduan/gitdemo<file_sep>/src/com/duan/log/Log.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.duan.log; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; /** * * @author illusion <<EMAIL>> */ public class Log { public static final Logger logger = Logger.getLogger(Log.class); static { PropertyConfigurator.configure(Log.class.getResource("log4j.properties")); } public static void showInfo(String msg) { logger.info(msg); } public static void showError(String msg) { logger.error(msg); } public static void showDebug(String msg) { logger.debug(msg); } }
a9b1778500a0b67c80a498ecaf7dd82775480521
[ "Java" ]
1
Java
edgrduan/gitdemo
2f9c65cce739339ec80a8dc6c5d1cfcdef96d6bd
816503302c9ae8aee99e2b9fdae54dceb2d9a688
refs/heads/master
<file_sep>var app = angular.module('trip', []); (function () { 'use strict'; app.config(function () { }); })(); 'use strict'; describe('TU : Flights controller ', function () { var createController; var ryanAirFlightsService; beforeEach(module('trip')); beforeEach(module(function ($provide, $controllerProvider) { ryanAirFlightsService = jasmine.createSpyObj('ryanAirFlightsService', ['getRyanAirFlights', 'getRyanAirFlightsForDestination']); ryanAirFlightsService.getRyanAirFlights.and.callFake(function () { return { then: function (callback) { callback({ fares: [ { outbound: { arrivalDate: "2016-02-16T08:35:00", arrivalAirport: { countryName: "Danemark", iataCode: "CPH", name: "Copenhague", seoName: "copenhagen" }, departureAirport: { countryName: "Belgique", iataCode: "CRL", name: "Bruxelles-Charleroi", seoName: "bruxelles-charleroi" }, departureDate: "2016-02-16T07:05:00", price: { currencyCode: "EUR", currencySymbol: "€", value: 9.99, valueFractionalUnit: "9", valueMainUnit: "9" }, }, summary: { price: { currencyCode: "EUR", currencySymbol: "€", value: 9.99, valueFractionalUnit: "9", valueMainUnit: "9" } } }] }); } }; }); ryanAirFlightsService.getRyanAirFlightsForDestination.and.callFake(function () { return { then: function (callback) { callback({ "trips": [ { "origin": "CRL", "destination": "CPH", "dates": [ { "dateOut": "2016-02-24T00:00:00.000", "flights": [] }, { "dateOut": "2016-02-25T00:00:00.000", "flights": [] }, { "dateOut": "2016-02-26T00:00:00.000", "flights": [ { "flightNumber": "FR 6375", "time": [ "2016-02-26T09:00:00.000", "2016-02-26T10:45:00.000" ], "duration": "01:45", "regularFare": { "fareKey": "<KEY>", "fareClass": "E", "fares": [ { "type": "ADT", "amount": 96.9900, "count": 1, "hasDiscount": false, "publishedFare": 96.9900 } ] }, }, { "flightNumber": "FR 6356", "time": [ "2016-02-26T21:20:00.000", "2016-02-26T23:05:00.000" ], "duration": "01:45", "regularFare": { "fareKey": "<KEY>", "fareClass": "L", "fares": [ { "type": "ADT", "amount": 116.9900, "count": 1, "hasDiscount": false, "publishedFare": 116.9900 } ] } } ] } ] } ], "serverTimeUTC": "2016-02-25T17:18:33.970Z" }); } }; }); })); beforeEach(function () { angular.mock.inject([ '$rootScope', '$controller', '$compile', '$filter', '$q', function ($rootScope, $controller, _$compile_, _$filter_, _$q_) { createController = function () { return $controller('Flights', { 'ryanAirFlightsService': ryanAirFlightsService }); }; } ]); }); it("Context doit être défini", function () { //Init var ctrl = createController(); //Expectations expect(ctrl.context).toBeDefined(); }); it("Le controlleur appelle la méthode getFlights", function () { //Init var ctrl = createController(); //Expectations expect(ctrl.getFlights()).toEqual("Flights"); }); it("Le controlleur doit mapper correctement les objets vols et ses détails après appel à la méthode getRyanAirFlights()", function () { //Init var ctrl = createController(); //Execute ctrl.getRyanAirFlights(); //Expectations expect(ctrl.context.ryanAirFlights).toBeDefined(); expect(ctrl.context.ryanAirFlights[0]).toBeDefined(); expect(ctrl.context.ryanAirFlights[0].arrivalDate).toEqual("2016-02-16"); expect(ctrl.context.ryanAirFlights[0].departureAirport).toBeDefined(); expect(ctrl.context.ryanAirFlights[0].departureAirport.country).toEqual("Belgique"); expect(ctrl.context.ryanAirFlights[0].departureAirport.iataCode).toEqual("CRL"); expect(ctrl.context.ryanAirFlights[0].departureAirport.name).toEqual("Bruxelles-Charleroi"); expect(ctrl.context.ryanAirFlights[0].arrivalAirport).toBeDefined(); expect(ctrl.context.ryanAirFlights[0].arrivalAirport.country).toEqual("Danemark"); expect(ctrl.context.ryanAirFlights[0].arrivalAirport.iataCode).toEqual("CPH"); expect(ctrl.context.ryanAirFlights[0].arrivalAirport.name).toEqual("Copenhague"); expect(ctrl.context.ryanAirFlights[0].flights).toBeDefined(); expect(ctrl.context.ryanAirFlights[0].flights.length).toEqual(2); expect(ctrl.context.ryanAirFlights[0].flights[0]).toBeDefined(); expect(ctrl.context.ryanAirFlights[0].flights[0].departureDate).toEqual("2016-02-26T09:00:00.000"); expect(ctrl.context.ryanAirFlights[0].flights[0].arrivalDate).toEqual("2016-02-26T10:45:00.000"); expect(ctrl.context.ryanAirFlights[0].flights[0].duration).toEqual("01h45"); expect(ctrl.context.ryanAirFlights[0].flights[0].flightNumber).toEqual("FR 6375"); expect(ctrl.context.ryanAirFlights[0].flights[0].amount).toEqual(96.9900); expect(ctrl.context.ryanAirFlights[0].flights[1]).toBeDefined(); expect(ctrl.context.ryanAirFlights[0].flights[1].departureDate).toEqual("2016-02-26T21:20:00.000"); expect(ctrl.context.ryanAirFlights[0].flights[1].arrivalDate).toEqual("2016-02-26T23:05:00.000"); expect(ctrl.context.ryanAirFlights[0].flights[1].duration).toEqual("01h45"); expect(ctrl.context.ryanAirFlights[0].flights[1].flightNumber).toEqual("FR 6356"); expect(ctrl.context.ryanAirFlights[0].flights[1].amount).toEqual(116.9900); }); });<file_sep>(function () { 'use strict'; app.factory('ryanAirFlightsService', ryanAirFlightsService); ryanAirFlightsService.$inject = ['$http', '$q']; /** * @function ryanAirFlightsService. * @description : Service renvoyant les vols Ryan air. */ function ryanAirFlightsService($http, $q) { return { getRyanAirFlights: getRyanAirFlights, getRyanAirFlightsForDestination: getRyanAirFlightsForDestination, }; /** * @function getRyanAirFlights. * @description : fonction renvoyant les vols à partir d'un aéroport et de 2 dates. * @param airportCode: code de l'aéroport de départ. * @param outboundDepartureDateFrom: date de départ. * @param outboundDepartureDateTo: date d'arrivée. */ function getRyanAirFlights(airportCode, outboundDepartureDateFrom, outboundDepartureDateTo) { var response = null; var deferred = $q.defer(); var apiUrl = 'https://api.ryanair.com/farefinder/3/oneWayFares?&departureAirportIataCode=' + airportCode + '&language=fr&offset=0&outboundDepartureDateFrom=' + outboundDepartureDateFrom + '&outboundDepartureDateTo=' + outboundDepartureDateTo; $http.get(apiUrl) .success(function (result) { response = result; deferred.resolve(response); }).error(function (data, error) { deferred.reject(error); }); return deferred.promise; } /** * @function getRyanAirFlights. * @description : fonction renvoyant les vols entre 2 aéroports pour une date donnée et un nombre de jours de flexibilité. * @param departureDate: date de départ. * @param departureAirportCode: code de l'aéroport de départ. * @param arrivalAirportCode: code de l'aéroport d'arrivée. * @param flexDaysOut: nombre de jours de flexibilité. */ function getRyanAirFlightsForDestination(departureDate, departureAirportCode, arrivalAirportCode, flexDaysOut) { var response = null; var deferred = $q.defer(); var apiUrl = 'https://desktopapps.ryanair.com/fr-fr/availability?ADT=1&CHD=0&DateOut=' + departureDate + '&Destination=' + arrivalAirportCode + '&FlexDaysOut=' + flexDaysOut + '&INF=0&Origin=' + departureAirportCode + '&RoundTrip=false&TEEN=0'; $http.get(apiUrl) .success(function (result) { response = result; deferred.resolve(response); }).error(function (data, error) { deferred.reject(error); }); return deferred.promise; } }; })();<file_sep>(function () { 'use strict'; angular.module('trip', []).config(function () { }); })(); 'use strict'; describe('module Test', function () { beforeEach(module('trip', [])); it('doit etre defini', function () { expect(true).toBeDefined(); }); });<file_sep>(function () { 'use strict'; app.directive('ryanAirFlights', ryanAirFlightsDirective); /** * @function ryanAirFlightsDirective. * @description : Directive renvoyant les vols Ryan air. */ function ryanAirFlightsDirective(ryanAirFlightsService) { var directive = { scope: { ryanAirFaresData: "=ryanAirFaresData", }, link: link, templateUrl: 'app/templates/ryanAirFlights.html' }; return directive; /** * @function link. * @description : link. */ function link(scope, element, attrs) { scope.getFlights = getFlights; scope.$watch('ryanAirFaresData', function (newValue) { scope.fares = scope.ryanAirFaresData; }, true); } /** * @function getFlights. * @description : fonction renvoyant les vols Ryan air. */ function getFlights() { return "test"; } }; })();
59eba28a07b3cebabd5d7668838200863f3d4b0e
[ "JavaScript" ]
4
JavaScript
frasp/fair
227cca61e69869f365ddd63d293b4ad07dc57c71
99a82343b1e6c2e7a9cabf1b688d05285c1f3c72
refs/heads/master
<file_sep>import binascii string_input = open('s1c8.txt').read().splitlines() for line in string_input: line_bytes = binascii.unhexlify(line) blocks = [line_bytes[start:start+16] for start in range(0, len(line_bytes), 16)] for block in blocks: if blocks.count(block) > 1: print("Detected!") print(line_bytes) <file_sep># Cryptoplas-Set1 > These are the solutions to the cryptopals set1 problems. <file_sep>from Crypto.Cipher import AES import base64 a = base64.b64decode(open('s1c7.txt').read()) print(len(a)) obj = AES.new(b'YELLOW SUBMARINE', AES.MODE_ECB) print(obj.decrypt(a)) <file_sep>str1 = raw_input("Enter string 1 : ") a = str1.decode("hex") str2 = raw_input("Enter string 2 : ") b = str2.decode("hex") xored = ''.join([hex(ord(a[i%len(a)]) ^ ord(b[i%(len(b))]))[2:] for i in range(max(len(a), len(b)))]) print(xored) <file_sep>a = raw_input("Enter string 1 : ") j = len(a) print(j) b = "" while j > 0: b += "ICE" j=j-3 print(a) print(b) xored = ''.join(chr(ord(a[i])^ord(b[i])) for i in range(0, len(a))) encoded = xored.encode("hex") print(encoded) <file_sep>str = raw_input("Enter string: ") encoded = str.decode("hex").encode("base64") print(encoded)
80d7f27159f99fe0834c74ff67b7ec7191689101
[ "Markdown", "Python" ]
6
Python
allrounder27/cryptopals_set1
4cf23fe0ff73298b01a59653b5a138ff4234d7d5
0433474b1dedd12fc8e64ccada89fddc231c5169
refs/heads/master
<file_sep>spring.application.name=eureka-consumer server.port=8101 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/ eureka.instance.lease-renewal-interval-in-seconds=5 eureka.instance.lease-expiration-duration-in-seconds=5<file_sep>spring.application.name=upload-server server.port=8004 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/ eureka.instance.lease-renewal-interval-in-seconds=5 eureka.instance.lease-expiration-duration-in-seconds=5<file_sep>/** * */ package com.eureka.service; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import feign.codec.Encoder; import feign.form.spring.SpringFormEncoder; /** * @author PC * */ @FeignClient(value = "upload-server", configuration = UploadService.MultipartSupportConfig.class) public interface UploadService { @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) String handleFileUpload(@RequestPart(value = "file") MultipartFile file); @Configuration class MultipartSupportConfig { @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(); } } } <file_sep>spring.application.name=eureka-server server.port=8000 eureka.instance.hostname=localhost eureka.client.register-with-eureka=false eureka.client.fetch-registry=false eureka.server.enable-self-preservation=false eureka.instance.lease-renewal-interval-in-seconds=5 eureka.server.eviction-interval-timer-in-ms=6000<file_sep>/** * */ package com.eureka.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; /** * @author PC * */ @RestController public class DcController { @Autowired LoadBalancerClient loadBalancerClient; @Autowired RestTemplate restTemplate; @GetMapping("consumer") public String consumer() { System.out.println("this is consumer-ribbon"); return restTemplate.getForObject("http://eureka-client/info", String.class); } } <file_sep>spring.application.name=eureka-consumer-feign server.port=8103 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/ eureka.instance.lease-renewal-interval-in-seconds=5 eureka.instance.lease-expiration-duration-in-seconds=5<file_sep>spring.application.name=eureka-client server.port=8003 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/ eureka.instance.lease-renewal-interval-in-seconds=5 eureka.instance.lease-expiration-duration-in-seconds=5
ec524762cd494313fbd44cbf87a1132b642f0f71
[ "Java", "INI" ]
7
INI
kevinYuan2017/spring-eureka-server-quickstarter
f3bd6340dd68aa6a205db35a8cd5c2749a9d43a3
fe37666daf4b655ec3dffbfb95d9d886709f2963
refs/heads/main
<file_sep>import numpy as np def update_mspk(mspk, sspk, nspk_vec, group_units, clu, ignoredClu=[]): unique_clu = np.unique(clu) unique_clu = np.setdiff1d(unique_clu, ignoredClu) n = len(group_units) x = np.where(unique_clu == group_units[0]) sum_spk = np.squeeze(mspk[:, :, x] * nspk_vec[x]) new_mspk = mspk new_nspk_vec = nspk_vec new_sspk = sspk for i in range(n, 1, -1): mean1 = sum_spk / new_nspk_vec[x] n1 = new_nspk_vec[x] idx = np.where(unique_clu == group_units[i-1]) nspk = new_nspk_vec[idx] sum_spk = sum_spk + (np.squeeze(new_mspk[:, :, idx] * nspk)) new_nspk_vec[x] = new_nspk_vec[x] + new_nspk_vec[idx] n2 = new_nspk_vec[idx] mean2 = np.squeeze(mspk[:, :, idx]) mean12 = sum_spk / new_nspk_vec[x] d1 = mean1 - mean12 d2 = mean2 - mean12 s1 = np.squeeze(new_sspk[:, :, x]) s2 = np.squeeze(sspk[:, :, idx]) tmp = np.expand_dims(np.sqrt((n1 * (s1 ** 2 + d1 ** 2) + n2 * (s2 ** 2 + d2 ** 2)) / (n1 + n2)), axis=2) new_sspk[:, :, x] = np.expand_dims(tmp, axis=3) new_nspk_vec = np.delete(new_nspk_vec, idx) new_mspk = np.delete(new_mspk, idx, axis=2) new_sspk = np.delete(new_sspk, idx, axis=2) tmp = np.expand_dims(sum_spk / new_nspk_vec[x], axis=2) new_mspk[:, :, x] = np.expand_dims(tmp, axis=3) return new_mspk, new_sspk, new_nspk_vec #clu = np.load('/home/tali/matlab/AUSS_python/mP31_04.clu.1.npy') #mspk = np.load('/home/tali/matlab/AUSS_python/mP31_04.mspk.1.npy') #sspk = np.load('/home/tali/matlab/AUSS_python/mP31_04.sspk.1.npy') #nspk_vec = np.load('/home/tali/matlab/AUSS_python/mP31_04.nspk_vec.1.npy') #nspk_vec = np.squeeze(nspk_vec) #group_units = [6, 15] #f = update_mspk(mspk, sspk, nspk_vec, group_units, clu, [0, 1])<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 22 15:12:11 2022 run in bash: source /home/tali/anaconda3/etc/profile.d/conda.sh && conda activate fastai && python running_AI_pipeline_bash.py filebase shank Nchannels @author: lidor """ import numpy as np from ccg import * import create_feat_tsc as tsc import sort_shank as MC from loading_data import * from noise_classifier import get_preds import sys def getX(item): x = X1[:,item].float().unsqueeze(0) return x def getY(item): y = str(int(Y[item])) return y # inputs k = len(sys.argv)-1 filebase = '' for i in range(k-2): if i == 0: filebase += sys.argv[i+1] else: filebase = filebase + ' ' + sys.argv[i+1] shank = int(sys.argv[-2]) Nchannels = int(sys.argv[-1]) # filebase = '/home/lidor/data/AUSS_project/Automated_curation/test_data/mP31_04' # shank = 2 # Nchannels = 10 # Loading data clu,res = load_clures(filebase,shank) mspk,sspk = make_mSPK(filebase,shank,Nchannels=Nchannels) cc = get_CCmat(filebase,shank) u_clu = np.unique(clu) # generating time mat for NC time_mat = get_time_mat1(res, clu) # get porpabilities form NC pred = get_preds(clu, mspk, sspk, cc, time_mat, u_clu) # generate a clu which noise and multi units are labeled as zero cleanClu = tsc.tsc(pred,clu) ind,Z = tsc.get_cleanClu_idx(clu,cleanClu) # make new featurs for the MC nspk_vec = tsc.compute_Nvec(cleanClu)[1:] cluster_ids = np.unique(cleanClu) time_mat = tsc.compute_timeMat(cleanClu,res,cluster_ids)[1:,:] mean_spk,std_spk = tsc.orgnize_WF(mspk,sspk,ind,Z) sample_rate = 20000 cc = compCCG(res,cleanClu,FS=sample_rate,window_size=0.042)[0] cc = cc[1:-1,1:,1:] newCLu = MC.main_loop(cleanClu, res, cc, mean_spk, std_spk, nspk_vec, time_mat) clu1 = clu clu2 = newCLu U_id = np.unique(clu2) reco_list = list() for i in U_id: idx = np.where(clu2==i)[0] l = np.unique(clu1[idx]) if len(l) > 1: reco_list.append(l) print(reco_list) <file_sep>from fastai.vision.all import * from inception_time import * from fastai.callback import * from fastai.text.all import * import numpy as np import torch from prepare_features_nc import * def getX(item): x = X1[:, :, item].float() x[2, 0:41] += -0.5 return x def getY(item): y = str(int(Y[item])) return y def predict(fet_mat): learn = load_learner('new_nc_301022.pkl') dl = learn.dls.test_dl(fet_mat) preds = learn.get_preds(dl=dl) p = preds[0].numpy() p1 = np.argmax(p, axis=1) p1 = p1 + 1 return p def get_preds(clu, mean_spk, std_spk, cc, time_mat, u_clu): uclu = np.unique(clu) fet_mat = np.zeros((len(uclu),3,128)) for i in range(len(uclu)): fet1 = prepare_features_nc(i, clu, mean_spk, std_spk, cc, time_mat, uclu) fet_mat[i,:,:]= fet1 fet_mat =torch.tensor(fet_mat).float() preds = predict(fet_mat) return preds <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 3 12:30:57 2022 @author: lidor """ import numpy as np import pandas as pd from ccg import * def load_clures(filebase,shank): shank = str(shank) clu_ex = '.clu.' res_ex = '.res.' cluFname =filebase+clu_ex+shank resFname = filebase+res_ex+shank clu = pd.read_table(cluFname, delimiter=" ",header=None).to_numpy() clu = np.delete(clu,0) res = pd.read_table(resFname, delimiter=" ",header=None).to_numpy() res = np.squeeze(res) return clu,res def make_mSPK(filebase,shank,Nchannels=10,Nsamp= 32): clu,res = load_clures(filebase,shank) shank = str(shank) spk_ex = '.spk.' spkFname = filebase+spk_ex+shank Nvar = Nsamp*Nchannels Nspkblock = 10000 Nspk = len(res) vec = np.append(np.arange(0,Nspk,Nspkblock),Nspk) Uclu = np.unique(clu) mSPK = np.zeros((len(Uclu),Nsamp,Nchannels)) sSPK = np.zeros((len(Uclu),Nsamp,Nchannels)) nSPK =np.zeros_like(Uclu) for i,j in enumerate(vec[:-1]): dif = vec[i+1]-j count = dif*Nchannels*Nsamp ofset = j*Nchannels*Nsamp spk = np.fromfile(spkFname,dtype=np.int16,count=count,offset=ofset*2) spk = np.reshape(spk,(dif,Nsamp,Nchannels),order='C') spk = np.int64(spk) A = int(ofset/Nvar) B = int((ofset+count)/Nvar) clu1 = clu[A:B] uclu1 = np.unique(clu1) for zz in range(len(uclu1)): ci = np.where(Uclu==uclu1[zz])[0] idx1 = np.where(clu1==uclu1[zz])[0] mSPK[ci,:,:] = mSPK[ci,:,:] + np.expand_dims(np.sum(spk[idx1,:,:],axis=0),0) sSPK[ci,:,:] = sSPK[ci,:,:] + np.expand_dims(np.sum(spk[idx1,:,:]**2,axis=0),0) nSPK[ci] = nSPK[ci]+np.sum(clu1==uclu1[zz]) mspk = mSPK/np.expand_dims(nSPK,(1,2)) sspk = np.sqrt( sSPK/np.expand_dims(nSPK,(1,2)) - mspk**2 ) mspk = np.transpose(mspk,(2,1,0)) sspk = np.transpose(sspk,(2,1,0)) return(mspk,sspk) def get_CCmat(filebase,shank): clu,res = load_clures(filebase,shank) cc = compCCG(res,clu,FS=20000,window_size=0.042) cc = cc[0][1:-1,:,:] return cc def get_time_mat1(res, clu): if len(res) == 0: T = []; else: timeVec = np.linspace(res[0],res[-1],num=88) timeVec = np.int64(timeVec) uClu = np.unique(clu) T = np.zeros((len(uClu),87)) for i in range(len(uClu)): uName = uClu[i] idx = clu == uName t1 = res[idx] v1 = np.zeros((87,1)) for k in range(87): start = timeVec[k] end1 = timeVec[k+1] n1 = len(t1[(t1>start) & (t1<end1)]) v1[k] = n1 m1 = np.mean(v1) threshold1 = m1*0.1 v1[v1<=threshold1] = 0; v3 = np.zeros((87,1)) for k in range(87): if v1[k] == 0: v3[k] = -0.5 else: v3[k] = 0.5 T[i,:] = np.squeeze(v3) return T if __name__ == '__main__': filebase = '/home/lidor/data/AUSS_project/Automated_curation/test_data/mP31_04' shank = 2 clu,res = load_clures(filebase,shank) mspk,sspk = make_mSPK(filebase,shank,Nchannels=10) cc =get_CCmat(filebase,shank) time_mat = get_time_mat1(res, clu) <file_sep>import numpy as np def update_cc(cc, group_units, clu=[]): if clu == []: all_units = np.array(group_units) else: all_units = np.unique(clu) x = np.where(all_units == group_units[0]) new_cc = cc n = len(group_units) for i in range(n-1, 0, -1): idx = np.where(all_units == group_units[i]) new_cc[:, x, :] = new_cc[:, x, :] + new_cc[:, idx, :] new_cc = np.delete(new_cc, idx, axis=1) for i in range(n-1, 0, -1): idx = np.where(all_units == group_units[i]) new_cc[:, :, x] = new_cc[:, :, x] + new_cc[:, :, idx] new_cc = np.delete(new_cc, idx, axis=2) return new_cc #clu = np.load('/home/tali/matlab/AUSS_python/mP31_04.clu.1.npy') #cc = np.load('/home/tali/matlab/AUSS_python/mP31_04.cc.1.npy') #group_units = [6, 15] #new = update_cc(cc, group_units) <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 20 12:14:04 2022 @author: lidor """ import numpy as np def tsc(pred,cluS): m = np.max(pred,1) i = np.argmax(pred,1) pred2 = pred Npred = np.zeros((pred.shape[0],1)) idx = i==2 Npred[idx,0] = pred2[idx,2]+((pred2[idx,2]-pred2[idx,0]))+10 idx = i==1 idx2 = np.logical_and(idx ,pred2[:,2]>=pred2[:,0]) Npred[idx2,0] = pred2[idx2,1]+5 +(pred2[idx2,2]-pred2[idx2,0]) idx3 = np.logical_and(idx, pred2[:,2]<pred2[:,0]) Npred[idx3,0] = pred2[idx3,1]+2 +(pred2[idx3,0]-pred2[idx3,2]) idx = i==0 #Npred[idx,0] =1-( pred2[idx,0]+(pred2[idx,0]-pred2[idx,2])) Npred[idx,0] =1-( pred2[idx,0]) pred = Npred # orgenize new clu file sortPred = np.sort(pred,axis=0)[::-1] idxP = np.argsort(pred,axis=0)[::-1] newClu = np.zeros_like(cluS) cleanClu = np.zeros_like(cluS) u = np.unique(cluS) nclu = len(u) for i in range(nclu): ind = cluS == u[idxP[i,0]] newClu[ind] = i+2 if pred[idxP[i,0]]>0.01: cleanClu[ind] = i+2 elif pred[idxP[i,0]]<=0.01: cleanClu[ind] = 0 return cleanClu def get_cleanClu_idx(clu,cleanClu): clu1 = np.int32(clu) clu2 = np.int32(cleanClu) Uclu1 = np.unique(clu1) Uclu2 = np.unique(clu2) ind = np.zeros_like(Uclu1) Z = np.zeros_like(Uclu1)>1 C = 0 for i,u1 in enumerate(Uclu2): idx = clu2==u1 idx2 = np.isin(Uclu1,np.unique(clu1[idx])) l = np.where(idx2)[0] ind[C:len(l)+C] = l Z[C:len(l)+C] = np.unique(clu2[idx])>1 C = C+len(l) return ind,Z def orgnize_WF(mspk,sspk,ind,Z): new_mspk = mspk[:,:,ind] new_mspk = new_mspk[:,:,Z] new_sspk = sspk[:,:,ind] new_sspk = new_sspk[:,:,Z] return new_mspk,new_sspk def compute_timeMat(clu,res,cluster_ids): div_fac = 44 timeVec = np.linspace(res[0],res[len(res)-1],div_fac+1,dtype="int32") T = np.zeros((len(cluster_ids),div_fac)) for index, unit in enumerate(cluster_ids): idx = clu == unit t1 = res[idx] v1 = np.zeros((div_fac)) for k in range(div_fac): start = timeVec[k] end1 = timeVec[k+1] n1 = len( np.where(((t1>start) & (t1<end1) ) )[0] ) v1[k] = n1 T[index] = v1 return T def compute_Nvec(clu): uni , counts = np.unique(clu, return_counts=True) return counts <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 22 15:12:11 2022 @author: lidor """ import numpy as np from ccg import * import create_feat_tsc as tsc import sort_shank as MC from loading_data import * from noise_classifier import get_preds def getX(item): x = X1[:,item].float().unsqueeze(0) return x def getY(item): y = str(int(Y[item])) return y # inputs filebase = '/home/lidor/data/AUSS_project/Automated_curation/test_data/mP31_04' shank = 2 Nchannels = 10 Nsamp = 32 # Loading data clu,res = load_clures(filebase,shank) mspk,sspk = make_mSPK(filebase,shank,Nchannels=Nchannels,Nsamp=Nsamp) cc = get_CCmat(filebase,shank) u_clu = np.unique(clu) # generating time mat for NC time_mat = get_time_mat1(res, clu) # get porpabilities form NC pred = get_preds(clu, mspk, sspk, cc, time_mat, u_clu) # generat a clu which noise and multuybuts are lebeled as zero cleanClu = tsc.tsc(pred,clu) ind,Z = tsc.get_cleanClu_idx(clu,cleanClu) # make new featurs for the MC nspk_vec = tsc.compute_Nvec(cleanClu)[1:] cluster_ids = np.unique(cleanClu) time_mat = tsc.compute_timeMat(cleanClu,res,cluster_ids)[1:,:] mean_spk,std_spk = tsc.orgnize_WF(mspk,sspk,ind,Z) sample_rate = 20000 cc = compCCG(res,cleanClu,FS=sample_rate,window_size=0.042)[0] cc = cc[1:-1,1:,1:] newCLu = MC.main_loop(cleanClu, res, cc, mean_spk, std_spk, nspk_vec, time_mat) clu1 = clu clu2 = newCLu U_id = np.unique(clu2) reco_list = list() for i in U_id: idx = np.where(clu2==i)[0] l = np.unique(clu1[idx]) if len(l) > 1: reco_list.append(l) print(reco_list) <file_sep>import numpy as np import joblib from fastai.text.all import * from prepare_features_MC import prepare_features_MC from uptade_all import update_all2 def predict2(feat_mat): #clf = load_learner('incep_25_10.pkl') clf = load_learner('MC_v1.pkl') feat_mat = tensor(feat_mat) feat_mat[:, 4, 0:83] += -0.5 dl = clf.dls.test_dl(feat_mat) preds = clf.get_preds(dl=dl) a = preds[0].numpy() return a def load_data(filebase, shank_num): f = open(filebase+'/info') info = f.read() lst_info = info.split('\n') session_name = lst_info[0] clu = np.load(filebase + '/' + session_name + '.clu.' + shank_num + '.npy') res = np.load(filebase + '/' + session_name + '.res.' + shank_num + '.npy') cc = np.load(filebase + '/' + session_name + '.cc.' + shank_num + '.npy') mspk = np.load(filebase + '/' + session_name + '.mspk.' + shank_num + '.npy') sspk = np.load(filebase + '/' + session_name + '.sspk.' + shank_num + '.npy') nspk_vec = np.load(filebase + '/' + session_name + '.nspk_vec.' + shank_num + '.npy') time_mat = np.load(filebase + '/' + session_name + '.timeMat.' + shank_num + '.npy') nspk_vec = np.squeeze(nspk_vec) return clu, res, cc, mspk, sspk, nspk_vec, time_mat def load_data2(filebase, shank_num, name): #f = open(filebase+'/info') #info = f.read() #lst_info = info.split('\n') #session_name = lst_info[0] clu = np.load(filebase + '/' + name + '.clu.' + shank_num + '.npy') res = np.load(filebase + '/' + name + '.res.' + shank_num + '.npy') cc = np.load(filebase + '/' + name + '.cc.' + shank_num + '.npy') time_mat = np.load(filebase + '/' + name + '.timeMat.' + shank_num + '.npy') mspk = np.load(filebase + '/' + name + '.mspk.' + shank_num + '.npy') sspk = np.load(filebase + '/' + name + '.sspk.' + shank_num + '.npy') nspk_vec = np.load(filebase + '/' + name + '.nspk_vec.' + shank_num + '.npy') nspk_vec = np.squeeze(nspk_vec) return clu, res, cc, mspk, sspk, nspk_vec, time_mat def clu_organize2(filebase, sorted_clu, idx_ignored, n_original,shank_num, name): new_clu = np.ones((n_original, 1)) new_clu[idx_ignored] = 0 c = 0 for i in range(n_original): if new_clu[i][0] == 1: new_clu[i][0] = sorted_clu[c] c += 1 fname = filebase + "/" + name + ".clu." + shank_num + "_2" np.save(fname, new_clu) return new_clu def main_loop(clu, res, cc, mean_spk, std_spk, nspk_vec, time_mat): n_original = len(clu) idx_ignored = np.where((clu == 0) | (clu == 1)) clu = np.delete(clu, idx_ignored[0], 0) #thresholds = [0.999, 0.995, 0.98, 0.7, 0.6, 0.5] #thresholds = [0.999, 0.8, 0.6] thresholds = [0.999, 0.995, 0.95, 0.9] unique_clu = np.unique(clu) for k in range(2): for i in thresholds: j = 0 while j < len(unique_clu)-1: con = True while con: feat_mat = np.empty((1, 5, 128)) n = len(unique_clu) for m in range(j+1, n): x = prepare_features_MC(j, m, clu, mean_spk, std_spk, cc, time_mat, unique_clu,k) feat_mat = np.concatenate((feat_mat, x), 0) if len(feat_mat) > 1: feat_mat = np.delete(feat_mat, 0, axis=0) a = predict2(feat_mat) idx = np.where(a[:, 1] > i) idx = idx[0] else: idx = np.empty(0) if len(idx) < 1: con = False j += 1 else: idx += (j+1) if np.max(idx) <= len(unique_clu)-1: g1 = unique_clu[idx] g2 = np.array([unique_clu[j]]) group_units = np.concatenate((g1, g2)) clu, mean_spk, std_spk, nspk_vec, cc, time_mat = update_all2(cc, group_units, clu, mean_spk, std_spk, nspk_vec, time_mat, [0, 1]) unique_clu = np.unique(clu) new_clu = clu_organize(clu, idx_ignored, n_original) return new_clu def clu_organize(sorted_clu, idx_ignored, n_original): new_clu = np.ones((n_original, 1)) new_clu[idx_ignored] = 0 c = 0 for i in range(n_original): if new_clu[i][0] == 1: new_clu[i][0] = sorted_clu[c] c += 1 # save_clu(filebase, new_clu, shank_num) return new_clu def save_clu(filebase, new_clu, shank_num): f = open(filebase + '/info') info = f.read() lst_info = info.split('\n') session_name = lst_info[0] fname = filebase + "/" + session_name + ".clu." + shank_num + "_2" np.save(fname, new_clu) return def getX(file): data = np.load(file) x = data[:, :128] x[4,0:83] += -0.5 return torch.FloatTensor(x) def getY(file): data = np.load(file) y = data[0, -1] y = str(int(y)) return y <file_sep>import numpy as np def prepare_features_nc(i, clu, mean_spk, std_spk, cc, time_mat, u_clu): mean_spk1 = mean_spk[:, :, i] [mean_spk1, ind] = trim_spk_4ch(mean_spk1) mean_spk1 = mean_spk1.flatten() max1 = max(abs(mean_spk1)) std_spk1 = (std_spk[ind, :, i]).flatten() if np.sum(cc[:, i, i]) == 0: acc1 = cc[:, i, i] else: acc1 = cc[:, i, i] / np.max(cc[:, i, i]) t = time_mat[i,:] last_row = np.concatenate((acc1.T, t.flatten())) last_row[0:41]+=-0.5 x = (np.concatenate((mean_spk1, std_spk1))) / max1 x = np.concatenate((x, last_row)) x = np.reshape(x, (3, 128, 1)) x = np.moveaxis(x, -1, 0) return x def trim_spk_4ch(mean_spk): n_channels = np.size(mean_spk, 0) if n_channels < 4: new_mspk = mean_spk channels_idx = np.arange(0, n_channels) channels_idx = channels_idx.T else: M1 = np.amax(mean_spk, axis=1) M2 = np.amin(mean_spk, axis=1) I = np.argsort(np.abs(M1 - M2)) channels_idx = I[-4:] channels_idx = np.flip(channels_idx) new_mspk = mean_spk[channels_idx.T, :] return new_mspk, channels_idx <file_sep>from update_cc import * from update_mspk import * from update_timeMat import * def update_all(cc, group_units, clu, mspk, sspk, nspk_vec, ignored_clu=[]): new_cc = cc new_clu = clu new_mspk = mspk new_sspk = sspk new_spk_vec = nspk_vec # Removes 0 from clu, maybe move to another function # idx = np.where(new_clu == 0) # new_clu = np.delete(new_clu, idx) group_units.sort() new_mspk, new_sspk, new_spk_vec = update_mspk(new_mspk, new_sspk, new_spk_vec, group_units, new_clu, ignored_clu) new_cc = update_cc(new_cc, group_units, new_clu) new_clu = update_clu(new_clu, group_units) return new_clu, new_mspk, new_sspk, new_spk_vec, new_cc def update_clu(clu, group_units): new_clu = clu n = len(group_units) for j in range(1, n): idx = np.where(new_clu == group_units[j]) new_clu[idx] = group_units[0] return new_clu def update_all2(cc, group_units, clu, mspk, sspk, nspk_vec, time_mat, ignored_clu=[]): group_units.sort() mspk, sspk, nspk_vec = update_mspk(mspk, sspk, nspk_vec, group_units, clu, ignored_clu) cc = update_cc(cc, group_units, clu) time_mat = update_time_mat(time_mat, group_units, clu, ignored_clu) clu = update_clu(clu, group_units) return clu, mspk, sspk, nspk_vec, cc, time_mat #clu = np.load('/home/tali/matlab/AUSS_python/mP31_04.clu.1.npy') #cc = np.load('/home/tali/matlab/AUSS_python/mP31_04.cc.1.npy') #mspk = np.load('/home/tali/matlab/AUSS_python/mP31_04.mspk.1.npy') #sspk = np.load('/home/tali/matlab/AUSS_python/mP31_04.sspk.1.npy') #nspk_vec = np.load('/home/tali/matlab/AUSS_python/mP31_04.nspk_vec.1.npy') #nspk_vec = np.squeeze(nspk_vec) #group_units = [3, 4, 5, 29, 6] #update_all(cc, group_units, clu, mspk, sspk, nspk_vec, [0,1]) #Nmspk = np.load('/home/tali/matlab/AUSS_python/mP31_04/mP31_04.Nmspk_t.npy') #Nsspk = np.load('/home/tali/matlab/AUSS_python/mP31_04/mP31_04.Nsspk_t.npy') #Nspk_vec = np.load('/home/tali/matlab/AUSS_python/mP31_04/mP31_04.Nspk_vec_t.npy')<file_sep>import numpy as np from scipy.spatial import distance def get_time_fet(time_mat, i, j): v1 = time_mat[i, :] v2 = time_mat[j, :] m1 = np.mean(v1) m2 = np.mean(v2) threshold1 = m1 * 0.1 threshold2 = m2 * 0.1 v1[np.where(v1 <= threshold1)] = 0 v2[np.where(v2 <= threshold2)] = 0 v3 = np.zeros((44, 1)) for k in range(44): if v1[k] == 0: if v2[k] != 0: v3[k] = 0.5 else: v3[k] = 0 elif v2[k] == 0: v3[k] = -0.5 else: v3[k] = 1 return v3 def prepare_features_MC(i, j, clu, mean_spk, std_spk, cc, time_mat, u_clu, k): if (sum(cc[:, i, j]) < 400) & (k == 0): return np.ones((1, 5, 128)) idx1 = np.where(clu == u_clu[i]) idx2 = np.where(clu == u_clu[j]) mean_spk1 = mean_spk[:, :, i] [mean_spk1, ind] = trim_spk_4ch(mean_spk1) mean_spk1 = mean_spk1.flatten() mean_spk2 = (mean_spk[ind, :, j]).flatten() max1 = max(max(abs(mean_spk1)), max(abs(mean_spk2))) std_spk1 = (std_spk[ind, :, i]).flatten() std_spk2 = (std_spk[ind, :, j]).flatten() if np.sum(cc[:, i, i]) == 0: acc1 = cc[:, i, i] else: acc1 = cc[:, i, i] / np.max(cc[:, i, i]) acc1 = acc1[20:] if np.sum(cc[:, j, j]) == 0: acc2 = cc[:, j, j] else: acc2 = cc[:, j, j] / np.max(cc[:, j, j]) acc2 = acc2[20:] if np.sum(cc[:, i, j]) == 0: ccgtag = cc[:, i, j] else: ccgtag = cc[:, i, j] / np.max(cc[:, i, j]) i1 = len(idx1[0]) i2 = len(idx2[0]) n = np.minimum(i1, i2) / np.maximum(i1, i2) t = get_time_fet(time_mat, i, j) last_row = np.concatenate((acc1.T, acc2.T, ccgtag.T, np.array([n]), t.flatten())) x = (np.concatenate((mean_spk1, mean_spk2, std_spk1, std_spk2))) / max1 x = np.concatenate((x, last_row)) x = np.reshape(x, (5, 128, 1)) x = np.moveaxis(x, -1, 0) return x def trim_spk_4ch(mean_spk): n_channels = np.size(mean_spk, 0) # max_idx = np.argmax(mean_spk[:, 15], 0) if n_channels < 4: new_mspk = mean_spk channels_idx = np.arange(0, n_channels) channels_idx = channels_idx.T else: M1 = np.amax(mean_spk, axis=1) M2 = np.amin(mean_spk, axis=1) I = np.argsort(np.abs(M1 - M2)) channels_idx = I[-4:] channels_idx = np.flip(channels_idx) new_mspk = mean_spk[channels_idx.T, :] return new_mspk, channels_idx <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 7 10:21:12 2022 @author: lidor """ import numpy as np from phylib.io.array import _clip from phylib.utils import Bunch from phylib.stats import ccg as CCG import pandas as pd def upsampCCG(lags2,lags,jit,cc1): upsampcc =np.zeros_like(lags2) for i in range(len(lags2)): T = lags2[i] idx = np.where([(lags>=T-jit) & (lags<T+jit)] ) upsampcc[i] = np.sum(cc1[idx[1]]) return upsampcc # compute CCG with 1 ms bin size def compCCG(res,clu,FS=20000,window_size=0.05): res = np.int64(np.squeeze(res)) clu = np.int64(np.squeeze(clu)) Uclu = np.unique(clu) BinSize = 0.001 ms = 1000 jit = ms*BinSize/2 if np.mod(window_size*ms, 2)!=0: window_size = np.round(window_size*ms+1)/ms cc =CCG.correlograms(res/FS,clu,Uclu,sample_rate=FS,bin_size=0.0001,window_size=window_size) lags = np.arange((-window_size/2)*ms,(window_size/2)*ms+0.0001*ms,0.1) lags2 = np.arange((-window_size/2)*ms,(window_size/2)*ms+BinSize*ms,BinSize*ms) Ncc = np.zeros((len(Uclu),len(Uclu),len(lags2,))) for i in range(len(Uclu)): for j in range(len(Uclu)): cc1 = cc[i,j,:] Ncc[i,j,:] = upsampCCG(lags2,lags,jit,cc1) Ncc = np.transpose(Ncc, (2, 1, 0)) return Ncc,lags2 # clu =np.load('mP79_16.clu.1.npy') # res =np.load('mP79_16.res.1.npy') # Ncc =compCCG(res,clu,20000,window_size=0.05) # cluFname = '/home/lidor/data/DBC/Code/AUSS_py/mP31_04.clu.2' # resFname = '/home/lidor/data/DBC/Code/AUSS_py/mP31_04.res.2' #spkFname = '/home/lidor/data/DBC/Code/AUSS_py/mP31_04.spk.2' # clu = pd.read_table(cluFname, delimiter=" ",header=None).to_numpy() # clu = np.delete(clu,0) # res = pd.read_table(resFname,delimiter=" ",header=None).to_numpy() # res = np.squeeze(res) # Ncc = compCCG(res,clu,FS=20000,window_size=0.040) <file_sep># Automated spike sorting curation This repository contains the code of automated spike sorting curation, recently presented as “Multi-channel automated spike sorting achieves near-human performance”, in FENS forum 2022, Paris, France, July 2022. ## Overview Identifying spike timing of individual neurons recorded simultaneously is essential for investigating the neuronal circuits that underlie cognitive functions. Recent developments allow the simultaneous recording of multi-channel extracellular spikes from hundreds of neurons. Yet classifying extracellular spikes into putative source neurons remains a challenge. Here, we set out to develop a fully automated algorithm which can replace manual curation for an existing multi-channel spike sorting solution. As an input to the automated curator (AC), we use [KlustaKwik](https://github.com/klusta-team/klustakwik) to over-cluster the spikes automatically, yielding numerous spike clusters. From that point onwards, we refer to spike sorting not as a clustering problem, but rather as a sequence of two binary classification problems. To perform automatic curation, we first use a “noise classifier” to remove non-neuronal clusters. Second, we use a “merge classifier” to determine whether any given pair of clusters should be merged. The output of the AC is a set of well-isolated units. ## Requirements Dataset: The input for the automated curator should be a dataset in a [neurosuite](https://neurosuite.sourceforge.net/) format (Hazan et al., 2006). Specifically, the following three files are required: - clu: spike labels, e.g. session_name.clu.1 - res: spike times in samples, e.g. session_name.res.1 - spk: spike waveforms, e.g. session_name.spk.1 The current version of the AC works only with data which were recorded at 20 kHz, and spike waveforms which are 32 samples long. ### Operating system: The code was tested on machines running Linux (Ubuntu 18), but is expected to work on any OS ### Prerequisites - Conda (both Miniconda and Anaconda are fine) - Python>3.6 ## Installation For installing the automated curator, first create an activate a virtual environment using conda: ``` $ conda create --name myenv $ conda activate myenv ``` Second, install the [FastAi](https://docs.fast.ai/) package, if you are using Miniconda run: ``` conda install -c fastchan fastai ``` or if you are using Anaconda then run: ``` conda install -c fastchan fastai anaconda ``` Third, install the [Phylib](https://github.com/cortex-lab/phylib) package with pip: ``` $ pip install phylib ``` Finally, clone the repository to your machine: ``` $ git clone https://github.com/EranStarkLab/Automated-curation.git ``` ## Running the automated curator ### Running the automated curator using Python IDE - Open the running_AC_pipeline.py file in your Python IDE - Change lines 24-26 according to your dataset which you want to curate - Run the running_AC_pipeline.py script ### Running the automated curator using bash (Linux/mac OS): - Navigate to the automated curator folder ``` $ cd filebase/to/automated/curator/folder ``` - Activate conda virtual environment ``` $ conda activate myenv ``` - Run the automated curator script with three inputs: 1. Filebase: full path to session dataset with session name, e.g. ~/home/data/session_name 2. shank_number: shank number, e.g. 1 3. n_channels: number of channels in the spk file, e.g 10 ``` $ python running_AI_pipeline_bash.py Filebase n_shanks n_channels ``` ## Automated curator output The output of the automated curator is a list of lists. Every list is a recommendation for an action, that can be carried out in the environment of [klusters](https://neurosuite.sourceforge.net/). The first list (index 0) contains the “Noise/Multi-units”, clusters which are either non-neuronal units or multi-neuronal units which cannot be separated into single units. Every other list (index 1 and higher) contains two or more units which should be merged with one another. ![merge](merge.png) <file_sep>import numpy as np def update_time_mat(time_mat, group_units, clu, ignoredClu): unique_clu = np.unique(clu) unique_clu = np.setdiff1d(unique_clu, ignoredClu) n = len(group_units) x = np.where(unique_clu == group_units[0]) new_mat = time_mat for i in range(n, 1, -1): y = np.where(unique_clu == group_units[i - 1]) new_mat[x, :] = new_mat[x, :] + new_mat[y, :] new_mat = np.delete(new_mat, y, axis=0) return new_mat # time_mat = np.load('/home/tali/data/mA234_35_all/npy_files/mA234_35_Shirly.timeMat.1.npy') # clu = np.load('/home/tali/data/mA234_35_all/npy_files/mA234_35_Shirly.clu.1.npy') # group_units = [7,15,40] # update_time_mat(time_mat, group_units, clu, [0,1])
0bf96987c91e043c5a97bd3b83a0fb4ea080cbba
[ "Markdown", "Python" ]
14
Python
EranStarkLab/AutomatedCurator
35760cb7482ea7b2bb5224bc501a16470f8e2345
5422e13f7eb0f55b9b3918bd1411b9a5016cee30
refs/heads/master
<file_sep>// CRUD: Simple Create, Read, Update, Delete api operations for data management. import { Router } from 'express'; const request = require('request'); const path = require('path'); const fs = require('fs'); import log from '../../helpers/bunyan'; import appConfig from '../../helpers/config'; import { Results } from '../../models/results'; import Config from '../../models/config'; import { appDefaultConfig } from '../../../src/app/_internal/configuration/configuration'; const modelName = 'config'; // This needs to exactly match the corresponding file name under /server/models/, minus the extension const endpointUrl = appConfig.api_domain + '/' + appConfig.api_path + '/' + appConfig.api_selfTenant; const crudRouter = Router(); log.info(`Creating CRUD routes for ${modelName}`); // Create routes for singular object fetching crudRouter.route('/' + modelName) // R(ead) all documents from model .get((req: any, res: any, next: any) => { const results: Results = {}; const config: Config = appDefaultConfig; // By default the config is set to match that from /src/app/_internal/configuration/configuration results.info = 'Retrieved ' + modelName + ' from BFF'; results.success = true; results.data = config; return res.json(results); }); export default crudRouter; <file_sep>FROM node:10.15.1-alpine EXPOSE 3000 ENV HOME=/home/app WORKDIR $HOME # This assumes that the application has been built first COPY node_modules/ node_modules/ COPY package.json . COPY configuration/ configuration/ COPY data/ data/ COPY dist/ dist/ CMD ["npm", "run", "run:server:prod"] <file_sep># Changelog Keeps track of changes made to the base building and packaging of the common components. Each package keeps their own [changelog.md](http://keepachangelog.com/en/1.0.0/) file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## [2.0.3] - 2019-03-21 ### Added - Adding ngx-translate - Adding sidedrawer and some example utilities in the header ## [2.0.3] - 2019-03-19 ### Changed - Changing server config system to use local.config - Moving data files around. Ensuring configuration files and data files are available in the docker image. ## [2.0.2] - 2019-03-11 ### Changed - Improved package.json scripts. Config now comes from BFF. ## [2.0.1] - 2019-03-05 ### Changed - Trim down the fake backend, enable it by default, and remove the user route from the BFF. The fake backend will now serve fake user data by default. ## [2.0.0] - 2019-03-01 ### Added - Adding a [Backend for Frontend](https://samnewman.io/patterns/architectural/bff/) to the Quick Start app for handing API requests from the front-end. ## [2.0.0-rc.1] - 2019-02-14 ### Changed - Upgrade style guide, packages, and projects from WUF, Angular 6 version, to WUF Angular 7 version #### BREAKING - Removing origami polyfills for polymer support due to overhead. - Removing polymer components, including Vaadin Grid. WUF no longer supports polymer in favor of native angular and web components only. Polyfills for polymer can be added to a Quick Start application-based instance as needed. ## [1.0.0] - Initial version of WUF Quick Start application based on Style Guide from the [WUF](https://github.com/anvil-open-software/wuf).
f695145478c620f9c10bef9d6e4594002c17cac4
[ "Markdown", "TypeScript", "Dockerfile" ]
3
TypeScript
fyun89/whos_next
785f1dcc3ffa3f3a6441ae733c635bcc7a03ce4d
a92e196e12102a23074dbca98e41bb3d1ca8361a
refs/heads/master
<file_sep>package core; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import util.Constants; import util.Constants.CellColor; public class ColorCell extends Cell { private CellColor cellColor ; public ColorCell(int row, int col, CellColor cellColor , GridCell gridCell) { super(row, col , gridCell ); // TODO Auto-generated constructor stub this.cellColor = cellColor ; } CellColor getCellColor() { return cellColor ; } @Override public void draw(GraphicsContext gc) { // TODO Auto-generated method stub Color color = getCellColor( this ) ; gc.setFill( color ); gc.fillRect( (col-1) * Constants.CELL_SIZE + col , (row-1) * Constants.CELL_SIZE + row , Constants.CELL_SIZE , Constants.CELL_SIZE ); gc.restore(); return ; } public Color getCellColor( ColorCell colorCell ) { switch ( colorCell.getCellColor() ) { case RED : return Color.RED ; case BLUE : return Color.BLUE ; case GREEN : return Color.GREEN ; case PURPLE : return Color.PURPLE ; case YELLOW : return Color.YELLOW ; } return null; } @Override public void clickAction() { // TODO Auto-generated method stub } @Override public void howerAction() { // TODO Auto-generated method stub } @Override public boolean isInside(int x, int y) { // TODO Auto-generated method stub if( x < (col-1) * Constants.CELL_SIZE + col ) return false ; if( x > (col-1) * Constants.CELL_SIZE + col + Constants.CELL_SIZE ) return false ; if( y < (row-1) * Constants.CELL_SIZE + row ) return false ; if( y > (row-1) * Constants.CELL_SIZE + row + Constants.CELL_SIZE ) return false ; return true; } @Override public int getZ() { // TODO Auto-generated method stub return 0; } @Override public boolean isVisible() { // TODO Auto-generated method stub return false; } } <file_sep>package core; import javafx.event.EventHandler; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import util.Constants; public class GameScreen extends StackPane { private Canvas canvas ; private GridCell gridCell ; public GameScreen( GridCell gridCell ) { super() ; this.canvas = new Canvas( Constants.DEFAULT_SCREEN_SIZE.getWidth() , Constants.DEFAULT_SCREEN_SIZE.getHeight() ) ; this.getChildren().add( canvas ) ; this.gridCell = gridCell ; addListener(); } public GridCell getGridCell() { return gridCell ; } public void drawComponenet(){ GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.WHITE); gc.clearRect( 0, 0, canvas.getWidth(), canvas.getHeight()); gc.fillRect ( 0, 0, canvas.getWidth(), canvas.getHeight()); gc.restore(); for(IRenderable renderable : IRenderableHolder.getInstance().getEntities() ) { renderable.draw(gc); } } private void addListener() { this.canvas.setOnMouseReleased(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { System.out.println("MouseReleased : " + event.getButton().toString()); if (event.getButton() == MouseButton.PRIMARY) InputUtility.setMouseLeftDown(false); if (event.getButton() == MouseButton.SECONDARY) InputUtility.setMouseRightDown(false); } }); this.canvas.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { System.out.println("MousePressed : " + event.getButton().toString()); if (event.getButton() == MouseButton.PRIMARY) { InputUtility.setMouseLeftDown(true); InputUtility.setMouseLeftLastDown(true); if( InputUtility.isMouseLeftTriggered() ){ InputUtility.setMouseLeftTriggered(false); } } if (event.getButton() == MouseButton.SECONDARY) { InputUtility.setMouseRightDown(true); InputUtility.setMouseRightLastDown(true); } } }); this.canvas.setOnMouseExited(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { // TODO Auto-generated method stub InputUtility.setMouseOnScreen(false); } }); this.canvas.setOnMouseEntered(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { // TODO Auto-generated method stub InputUtility.setMouseOnScreen(true); } }); this.canvas.setOnMouseMoved(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { // TODO Auto-generated method stub if (InputUtility.isMouseOnScreen()) { InputUtility.setMouseX((int) event.getX()); InputUtility.setMouseY((int) event.getY()); } } }); this.canvas.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { // TODO Auto-generated method stub if (InputUtility.isMouseOnScreen()) { InputUtility.setMouseX((int) event.getX()); InputUtility.setMouseY((int) event.getY()); } } }); } } <file_sep>package core; import com.sun.prism.impl.BaseMesh.FaceMembers; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import util.Constants; public class Main extends Application { @Override public void start(Stage primaryStage) { GameScreen root = new GameScreen( new GridCell() ); Scene scene = new Scene( root ); primaryStage.setScene( scene ); primaryStage.setTitle( Constants.GAME_NAME ); GameLogic gameLogic = new GameLogic( root ) ; new AnimationTimer() { long updateTime ; final long maximumWaitTime = 1000000000l / Constants.MAX_FRAME_PER_SECOND; @Override public void handle( long currentTime ) { // TODO Auto-generated method stub // updateTime = currentTime ; // StageManager.getInstance().update() ; // updateTime = currentTime ; // // if ( updateTime < maximumWaitTime ) { // try { // Thread.sleep( (maximumWaitTime - updateTime) / 1000000l ); // } catch (InterruptedException e) { // // TODO: handle exception // Thread.interrupted() ; // e.printStackTrace(); // } // } gameLogic.updateLogic(); gameLogic.updateScreen(); } }.start(); primaryStage.show(); } public static void main(String[] args) { launch(args); } } <file_sep>package core; public interface MouseActionable { public void clickAction(); public void howerAction(); public boolean isInside( int x , int y ); }
322ecbf22f247e2e818091eaf5f9fb95fa00ad8c
[ "Java" ]
4
Java
cuviengchai/progmeth-1
c1e2b2b119172bebf26324878e04075be693ccbe
4ade229c3456ff994abb4bd1d7da0dc08614cd5f
refs/heads/master
<repo_name>YosefLehrer/pokemon-teams-nyc-web-062419<file_sep>/pokemon-teams-frontend/src/index.js const BASE_URL = "http://localhost:3000" const TRAINERS_URL = `${BASE_URL}/trainers` const POKEMONS_URL = `${BASE_URL}/pokemons` const whereTheStuffGoes = document.getElementById("whereTheStuffGoes") let fetchArr; fetch(TRAINERS_URL) .then(resp => resp.json()) .then(function(response) { fetchArr = response response.forEach(addNewTrainer); }); function addNewTrainer(trainer){ const pokemonArr = trainer.pokemons const singleInstanceOfPokemon = pokemonArr.map(addPokemon).join("") whereTheStuffGoes.insertAdjacentHTML("beforeend", ` <div class="card" data-id="${trainer.id}"> <p>${trainer.name}</p> <button class="addButton" data-trainer-id="${trainer.id}">Add Pokemon</button> <ul> ${singleInstanceOfPokemon} </ul> </div>`) } function addPokemon(pokemon) { return `<li>${pokemon.species} (${pokemon.nickname}) <button class="release" data-pokemon-id="${pokemon.id}">Release</button>` } whereTheStuffGoes.addEventListener('click', function(e){ if (e.target.className === "release"){ removePokemon(e.target) } else if (e.target.className === "addButton") { if (e.target.parentNode.querySelector("ul").children.length < 6) { createNewPokemon(e.target) } else { alert("You cannot train more than 6 Pokemon at a time, please release a Pokemon to train a new one") } } }) function removePokemon(pokemon){ fetch(`${POKEMONS_URL}/${pokemon.dataset.pokemonId}`, {method: 'DELETE'}) .then(response => response.json()) .then(response => { console.log('Deleted:', pokemon.dataset.pokemonId) pokemon.parentNode.remove() return response }) .catch(err => console.error(err)) } function createNewPokemon(pokemon) { fetch(POKEMONS_URL, { method: 'POST', headers:{ "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({ "trainer_id": `${pokemon.dataset.trainerId}` }) }) .then(response => response.json()) .then(response => {let returnValue = addPokemon(response) pokemon.parentNode.querySelector("ul").insertAdjacentHTML("beforeend", returnValue) }) } console.log("pokemon")
afaca0d87066c7ab3deeec43311110ac0d9e63aa
[ "JavaScript" ]
1
JavaScript
YosefLehrer/pokemon-teams-nyc-web-062419
92d302910b20cfd118010f5eb131ebeb9f22fe5e
caab07aaad0dcada8a364b9bedb69b3fd7dc0d84
refs/heads/master
<file_sep>package level3.maps; public class PathMap { } <file_sep>package level2.web.diagrams; public class IncludesViewer { } <file_sep>package utils.storage; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FileHashMap { void putTrigger(){ } public FileStorage fs = FileStorage.getInstance(); public int storageID; public FileHashMap() { this.storageID = 0; } public FileHashMap(String path) { String RootID = Root.getInstance().get(path); if (RootID == null){ storageID = fs.allocate(Integer.BYTES * blockSize); Root.getInstance().put(path, String.valueOf(storageID)); RootID = Root.getInstance().get(path); System.out.println(RootID); } else storageID = Integer.valueOf(RootID); } int hash(String str) { //LY hash int hash = 1; for (int i = 0; i < str.length(); i++) hash = (hash * 1664525) + str.charAt(i) + 1013904223; return hash; } final int linksCount = 16; public final int blockSize = 19; final int keyIndex = 16; final int valueIndex = 17; final int nextIndex = 18; final int entryKeyIndex = 0; final int entryValueIndex = 1; final int entryNextIndex = 2; public String get(String key) { return get(hash(key), key); } String get(int hash, String key) { String hashstr = String.format("%08X", hash); if (storageID == 0) return null; int thisBlock = storageID; for (int i = 0; i < hashstr.length(); i++) { int index = Integer.parseInt("" + hashstr.charAt(i), 16); int nextBlock = fs.getInt(thisBlock, index); if (nextBlock == 0) { return null; } thisBlock = nextBlock; if (i == hashstr.length() - 1) { byte[] lastBlock = fs.getBytes(thisBlock); IntBuffer intBuffer = ByteBuffer.wrap(lastBlock).asIntBuffer(); int keyLink = intBuffer.get(keyIndex); int valueLink = intBuffer.get(valueIndex); int nextLink = intBuffer.get(nextIndex); if (keyLink == 0) { return null; } else { if (fs.get(keyLink).equals(key)) { return fs.get(valueLink); } else if (nextLink == 0) { return null; } else { int thisEntryLink = nextLink; while (true) { byte[] getEntry = fs.getBytes(thisEntryLink); IntBuffer entryIntBuffer = ByteBuffer.wrap(getEntry).asIntBuffer(); keyLink = entryIntBuffer.get(entryKeyIndex); valueLink = entryIntBuffer.get(entryValueIndex); nextLink = entryIntBuffer.get(entryNextIndex); if (fs.get(keyLink).equals(key)) { return fs.get(valueLink); } else if (nextLink == 0) { return null; } thisEntryLink = nextLink; } } } } } return null; } public Map<String, String> get(int hash) { if (storageID == 0) return null; Map<String, String> result = new HashMap<>(); String hashstr = String.format("%08X", hash); int thisBlock = storageID; for (int i = 0; i < hashstr.length(); i++) { //первый раз читать сразу блок из 8 метаданных int index = Integer.parseInt("" + hashstr.charAt(i), 16); int nextBlock = fs.getInt(thisBlock, index); if (nextBlock == 0) { return null; } thisBlock = nextBlock; if (i == hashstr.length() - 1) { byte[] lastBlock = fs.getBytes(thisBlock); IntBuffer intBuffer = ByteBuffer.wrap(lastBlock).asIntBuffer(); int keyLink = intBuffer.get(keyIndex); int valueLink = intBuffer.get(valueIndex); int nextLink = intBuffer.get(nextIndex); if (keyLink == 0) { return null; } else { result.put(fs.get(keyLink), fs.get(valueLink)); if (nextLink != 0) { int thisEntryLink = nextLink; while (true) { byte[] getEntry = fs.getBytes(thisEntryLink); IntBuffer entryIntBuffer = ByteBuffer.wrap(getEntry).asIntBuffer(); keyLink = entryIntBuffer.get(entryKeyIndex); valueLink = entryIntBuffer.get(entryValueIndex); nextLink = entryIntBuffer.get(entryNextIndex); result.put(fs.get(keyLink), fs.get(valueLink)); if (nextLink == 0) { return result; } thisEntryLink = nextLink; } } } } } return result; } public void put(String key, String value) { put(hash(key), key, value); } //put first 8byte is type of var //array string int //save the history public void put(int hash, String key, String value) { String hashstr = String.format("%08X", hash); if (storageID == 0) storageID = fs.allocate(Integer.BYTES * blockSize); int thisBlock = storageID; for (int i = 0; i < hashstr.length(); i++) { int index = Integer.parseInt("" + hashstr.charAt(i), 16); int nextBlock = fs.getInt(thisBlock, index); if (nextBlock == 0) { int childBlock = fs.allocate(Integer.BYTES * blockSize); fs.setInt(thisBlock, index, childBlock); nextBlock = childBlock; } thisBlock = nextBlock; if (i == hashstr.length() - 1) { byte[] lastBlock = fs.getBytes(thisBlock); IntBuffer intBuffer = ByteBuffer.wrap(lastBlock).asIntBuffer(); int keyLink = intBuffer.get(keyIndex); int valueLink = fs.put(value); int nextLink = intBuffer.get(nextIndex); if (keyLink == 0) { keyLink = fs.put(key); fs.setInt(thisBlock, keyIndex, keyLink); fs.setInt(thisBlock, valueIndex, valueLink); } else { if (fs.get(keyLink).equals(key)) { fs.setInt(thisBlock, valueIndex, valueLink); } else if (nextLink == 0) { keyLink = fs.put(key); byte[] newEntry = fs.newBuffer(keyLink, valueLink, 0); int entryLink = fs.put(newEntry); fs.setInt(thisBlock, nextIndex, entryLink); } else { int thisEntryLink = nextLink; while (true) { byte[] getEntry = fs.getBytes(thisEntryLink); IntBuffer entryIntBuffer = ByteBuffer.wrap(getEntry).asIntBuffer(); keyLink = entryIntBuffer.get(entryKeyIndex); nextLink = entryIntBuffer.get(entryNextIndex); if (fs.get(keyLink).equals(key)) { fs.setInt(thisEntryLink, entryValueIndex, valueLink); break; } else if (nextLink == 0) { keyLink = fs.put(key); byte[] newEntry = fs.newBuffer(keyLink, valueLink, 0); int entryLink = fs.put(newEntry); fs.setInt(thisEntryLink, entryNextIndex, entryLink); break; } thisEntryLink = nextLink; } } } } } } int next(int hash) { if (storageID == 0) return 0; String hashstr = String.format("%08X", hash); IntBuffer[] path = new IntBuffer[hashstr.length()]; int thisBlock = storageID; for (int i = 0; i < hashstr.length(); i++) { int index = Integer.parseInt("" + hashstr.charAt(i), 16); path[i] = fs.getBuffer(thisBlock).asIntBuffer(); int nextBlock = path[i].get(index); thisBlock = nextBlock; if (i == hashstr.length() - 1 || thisBlock == 0) { String resultStr = null; int goUpBlock = 0; for (; i >= 0 && goUpBlock == 0; i--) for (int k = Integer.parseInt("" + hashstr.charAt(i), 16) + 1; k < linksCount && goUpBlock == 0; k++) if (path[i].get(k) != 0) { goUpBlock = path[i].get(k); resultStr = hashstr.substring(0, i) + Integer.toHexString(k); } if (goUpBlock == 0) return 0; IntBuffer intBuffer = fs.getBuffer(goUpBlock).asIntBuffer(); for (int j = 0; j < linksCount; j++) { if (intBuffer.get(j) != 0) { intBuffer = fs.getBuffer(intBuffer.get(j)).asIntBuffer(); resultStr += Integer.toHexString(j); j = -1; } } return Integer.parseInt(resultStr, 16); } } return 0; } int prev(int hash) { if (storageID == 0) return 0; String hashstr = String.format("%08X", hash); IntBuffer[] path = new IntBuffer[hashstr.length()]; int thisBlock = storageID; for (int i = 0; i < hashstr.length(); i++) { int index = Integer.parseInt("" + hashstr.charAt(i), 16); path[i] = fs.getBuffer(thisBlock).asIntBuffer(); int nextBlock = path[i].get(index); if (nextBlock == 0) return 0; thisBlock = nextBlock; if (i == hashstr.length() - 1) { String resultStr = null; int goUpBlock = 0; for (; i >= 0 && goUpBlock == 0; i--) for (int k = Integer.parseInt("" + hashstr.charAt(i), 16) - 1; k >= 0 && goUpBlock == 0; k--) if (path[i].get(k) != 0) { goUpBlock = path[i].get(k); resultStr = hashstr.substring(0, i) + Integer.toHexString(k); } if (goUpBlock == 0) return 0; IntBuffer intBuffer = fs.getBuffer(goUpBlock).asIntBuffer(); for (int j = linksCount - 1; j >= 0; j--) { if (intBuffer.get(j) != 0) { intBuffer = fs.getBuffer(intBuffer.get(j)).asIntBuffer(); resultStr += Integer.toHexString(j); j = linksCount; } } return Integer.parseInt(resultStr, 16); } } return 0; } public List<Integer> interval(int begin, int end) { List<Integer> result = new ArrayList<>(); int min = Math.min(begin, end); int max = Math.max(begin, end); int now = min; while (now != 0 && now <= max){ if (get(now) != null) result.add(now); now = next(now); } return result; } } <file_sep>package templates.utils; public class AvgValue { double avg; double countNumbersToAvg; public AvgValue(double startValue, double countNumbersToAvg) { avg = startValue * countNumbersToAvg; this.countNumbersToAvg = countNumbersToAvg; } public double add(double value) { avg = avg - (avg / countNumbersToAvg); avg += value; return avg / countNumbersToAvg; } } <file_sep>package templates; public class Visualization { } <file_sep>package level2.web.client; import com.google.gson.Gson; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import level2.consolidator.Consolidator; import utils.Http; import java.io.IOException; public class ClientActionList implements HttpHandler { @Override public void handle(HttpExchange httpExchange) throws IOException { Http.Response(httpExchange, new Gson().toJson(Consolidator.getInstance().actions.eventsGroup.arrayCountersCash)); } } <file_sep>package level1.codegenerator; import java.util.ArrayList; public class Generator implements Runnable { static class Time { double func; double par1; double par2; double trueto; double result; } int blockID; ArrayList<FuncID> result = new ArrayList<FuncID>(); Generator(int blockID) { this.blockID = blockID; } void sendResult() { Block block = Sync.data.getBlock(blockID); block.result = result; block.threadEnd = true; Sync.data.putBlock(block); } public void run() { double funcRun = 0; double[] inputVars = {1, 6, 3}; //set time and func index of generate block double funcCount = 8; double blockSize = 200; double timeIndex = 0; double funcIndex = blockSize * blockID;; while (funcIndex > Math.pow(funcCount, timeIndex)) { funcIndex -= Math.pow(funcCount, timeIndex); timeIndex++; } //set next time and func index of block double nextId = blockID + 1; double maxTimeIndex = 0; double maxFuncIndex = blockSize * nextId; while (maxFuncIndex > Math.pow(funcCount, maxTimeIndex)) { maxFuncIndex -= Math.pow(funcCount, maxTimeIndex); maxTimeIndex++; } boolean firstFuncGenerate = true; long beginTime = System.currentTimeMillis(); while (true) { ArrayList<Time> timeLine = new ArrayList<Time>(); for (double i = 0; i <= timeIndex; i++) timeLine.add(new Time()); if (firstFuncGenerate == false) funcIndex = 0; firstFuncGenerate = false; for (; funcIndex < Math.pow(funcCount, timeIndex); funcIndex++) { funcRun++; //exit if generate last func if (timeIndex >= maxTimeIndex && funcIndex >= maxFuncIndex) { Sync.log("block " +(int)blockID + " time " + (int)timeIndex + " func " + (int)maxFuncIndex + " size " + (int)funcRun + " runtime " + (int)((System.currentTimeMillis() - beginTime) / 1000) + " s"); sendResult(); return; } //exit if tread is stop from main thread if (Thread.interrupted()) return; /*if (funcRun % 200 == 0) { log(timeIndex + " line " + funcRun + " count " + (System.currentTimeMillis() - beginTime) + " ms"); beginTime = System.currentTimeMillis(); }*/ double funcIndex2 = funcIndex; /*0 * Math.pow(funcCount, 0) + //add 1 * Math.pow(funcCount, 1) + //sub 4 * Math.pow(funcCount, 2) + //== 5 * Math.pow(funcCount, 3) + //!= 2 * Math.pow(funcCount, 4); //mul */ for (double i = 0; i < timeLine.size(); i++) { Time time = timeLine.get((int) i); double razm = Math.pow(funcCount, i + 1); time.func = (funcIndex2 % razm) / Math.pow(funcCount, i); funcIndex2 -= funcIndex2 % razm; } //prepare to consolidator generate ArrayList<Double> maxIndex = new ArrayList<Double>(); for (double i = 0; i < timeLine.size(); i++) maxIndex.add(Math.pow(inputVars.length + i, 2)); Double maxIndexSum = 0.0; for (double i = 0; i < maxIndex.size(); i++) maxIndexSum += maxIndex.get((int) i); ArrayList<Double> valIndex = new ArrayList<Double>(); for (double i = 0; i < maxIndex.size(); i++) valIndex.add(0.0); //set consolidator for (double parIndex = 0; parIndex < maxIndexSum; parIndex++) { double parIndex2 = parIndex; /*(0 + 2 * Math.sqrt(maxIndex.get(0))) * 1 + (3 + 2 * Math.sqrt(maxIndex.get(1))) * 1 * maxIndex.get(1) + (0 + 0 * Math.sqrt(maxIndex.get(2))) * 1 * maxIndex.get(1) * maxIndex.get(2) + (5 + 5 * Math.sqrt(maxIndex.get(3))) * 1 * maxIndex.get(1) * maxIndex.get(2) * maxIndex.get(3) + (6 + 1 * Math.sqrt(maxIndex.get(4))) * 1 * maxIndex.get(1) * maxIndex.get(2) * maxIndex.get(3) * maxIndex.get(4); */ for (double i = 0; i < valIndex.size(); i++) { double razm = 1; for (double j = 1; j < maxIndex.size() - i; j++) razm *= maxIndex.get((int) j); double val = (double) (int) (parIndex2 / razm); valIndex.set((int) (maxIndex.size() - i - 1), val); parIndex2 -= val * razm; if (val == 15) { double x = 1; } /*double razm = Math.pow(funcCount, i + 1); time.func = (funcIndex2 % razm) / Math.pow(funcCount, i); funcIndex2 -= funcIndex2 % razm; */ } for (double i = 0; i < valIndex.size(); i++) { double val = valIndex.get((int) i); Time time = timeLine.get((int) i); double razm = Math.pow(funcCount, i + 1); time.par1 = (int) (val % Math.sqrt(maxIndex.get((int) i))); time.par2 = (int) (val / Math.sqrt(maxIndex.get((int) i))); } //set trueto ArrayList<Double> equalsFuncIndexes = new ArrayList<Double>(); for (double i = 0; i < timeLine.size(); i++) if (timeLine.get((int) i).func > 3) equalsFuncIndexes.add((double) i); for (double trueIndex = 0; trueIndex < Math.pow(timeLine.size() - 1, equalsFuncIndexes.size()); trueIndex++) { double trueIndex2 = trueIndex; // 1 + 3 * Math.pow(timeLine.size() - 1, 1); for (double i = 0; i < equalsFuncIndexes.size(); i++) { Time time = timeLine.get((int) equalsFuncIndexes.get((int) i).doubleValue()); double razm = Math.pow(timeLine.size() - 1, i + 1); time.trueto = (trueIndex2 % razm) / Math.pow(timeLine.size() - 1, i); trueIndex2 -= trueIndex2 % razm; if (time.trueto >= equalsFuncIndexes.get((int) i)) time.trueto++; } //run double maxRunTime = 10000; double runTime = 0; double i = 0; while ((i < timeLine.size()) & (runTime < maxRunTime)) { runTime++; Time time = timeLine.get((int) i); double par1 = 0; if (time.par1 < inputVars.length) par1 = inputVars[(int) time.par1]; else par1 = timeLine.get((int) time.par1 - inputVars.length).result; double par2 = 0; try { if (time.par2 < inputVars.length) par2 = inputVars[(int) time.par2]; else par2 = timeLine.get((int) time.par2 - inputVars.length).result; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } switch ((int) time.func) { case 0: time.result = par1 + par2; break; case 1: time.result = par1 - par2; break; case 2: time.result = par1 * par2; break; case 3: time.result = par1 / par2; break; case 4: time.result = (par1 == par2) ? 1 : 0; break; case 5: time.result = (par1 != par2) ? 1 : 0; break; case 6: time.result = (par1 > par2) ? 1 : 0; break; case 7: time.result = (par1 < par2) ? 1 : 0; break; } if (time.func > 3) if (time.result == 1) { i = (double) time.trueto; continue; } i++; } double rightResult = 3.14; if (runTime < maxRunTime) { for (double resultIndex = 0; resultIndex < timeLine.size(); resultIndex++) { Time time = timeLine.get((int) resultIndex); double roundResult = Math.round(time.result * 100.0) / 100.0; if (roundResult == rightResult) { FuncID funcID = new FuncID(); funcID.timeIndex = timeIndex; funcID.funcIndex = funcIndex; funcID.linkIndex = parIndex; funcID.trueIndex = trueIndex; funcID.resultIndex = resultIndex; // // for (int j = 0; j < data.generateList.size(); j++) // if (data.generateList.get(j).blockID == blockID) // data.generateList.get(j).result.add(funcID); } } } } } } timeIndex++; } } } <file_sep>package brain; import java.util.ArrayList; public class IndexTree { String index; IndexTree parent; ArrayList<IndexTree> childs = new ArrayList<IndexTree>(); Neuron neuron; public IndexTree(String index) { this.index = index; } public IndexTree root(){ IndexTree root = this; while (root.parent != null) root = root.parent; return root; } public Neuron getNeuron(String[] indexes) { if (indexes.length == 1) { indexes = new String[index.length()]; for (int i=0; i<index.length(); i++) indexes[i] = "" + index.charAt(i); } IndexTree node = this; for (int i=0; i<indexes.length; i++) { int subIndexPos = -1; for (int j=0; j<node.childs.size(); j++) if (node.childs.get(j).index.equals(indexes[i])) { subIndexPos = j; break; } if (subIndexPos == -1) { node.childs.add(new IndexTree(indexes[i])); node.childs.get(node.childs.size() - 1).parent = node; node = node.childs.get(node.childs.size() - 1); } else node = node.childs.get(subIndexPos); } if (node.neuron == null) node.neuron = new Neuron(node); return node.neuron; } public ArrayList<String> toStrings() { IndexTree node = this; ArrayList<String> result = new ArrayList<String>(); while (node != null) { result.add(node.index); node = node.parent; } return result; } public String toString() { ArrayList<String> indexes = toStrings(); String delimeter = ""; for (int i=0; i<indexes.size(); i++) if (indexes.get(i).length() > 1) { delimeter = Const.FileDelimeter; break; } String result = null; for (int i=0; i<indexes.size(); i++) { if (result == null) result = index; else result = indexes.get(i) + delimeter + result; } return result; } public String getIndexFileName() { ArrayList<String> indexes = toStrings(); String result = ""; //percent encoding for (int i=0; i<indexes.size(); i++) { String index = indexes.get(i); if (index.length() == 1) { if (!( // if not ((index.charAt(0) >= 48) && (index.charAt(0) <= 57)) || //numbers ((index.charAt(0) >= 65) && (index.charAt(0) <= 90)) || //eng uppercase ((index.charAt(0) >= 97) && (index.charAt(0) <= 122)) //eng lowercase )) index = String.format("%02X", index.charAt(0)); } else { for (int j=0; j<Const.IllegalFileNames.length; j++) if (index == Const.IllegalFileNames[j]) index = index + '1'; //recode } result = index + Const.FileDelimeter + result; } return result + Const.NodeFileName; } }<file_sep>package level2.planer; import com.google.gson.JsonObject; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; public class Types { Map<String, String> getProperties(String str) { Map<String, String> result = new HashMap<String, String>(); result.put("value", str); try { double value = Double.valueOf(str); result.put("type", "number"); result.put("int", ((int) value) - value == 0.0 ? "true" : "false"); result.put("div2", value % 2 == 0.0 ? "true" : "false"); //Разница с предыдущим 4 -> 1 = -3 } catch (NumberFormatException e) { } if (result.get("type") == null) { try { URL url = new URL(str); result.put("type", "object"); JsonObject obj = new JsonObject(); obj.addProperty("file", url.getFile()); JsonObject params = new JsonObject(); String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { int idx = pair.indexOf("="); params.addProperty(pair.substring(0, idx), pair.substring(idx + 1)); } obj.add("consolidator", params); } catch (MalformedURLException e) { } } if (result.get("type") == null) { result.put("type", "string"); } return result; } class PropOfProp { int count; int multiplier; //!! int power; public PropOfProp(int count, int power) { this.count = count; this.power = power; //counter1,2,3 power1,2,3 } } Map<String, String> prevProp = new HashMap<>(); Map<String, PropOfProp> counters = new HashMap<>(); /*Map<String, String> stableProperties(){ Map<String, String> result = new HashMap<>(); //for in counters where propofprop.counters >= 3 { result.put("key", "counter"); } return result; }*/ // analysis PropertiesValue likePermutation type=number -> type=string or length=3 -> length=4 void update(String value){ Map<String, String> nextProp = getProperties(value); for(String prevKey: prevProp.keySet()){ String prevValue = prevProp.get(prevKey); for (String nextKey: nextProp.keySet()){ String nextValue = nextProp.get(nextKey); PropOfProp propOfProp = counters.get(nextValue); if (propOfProp == null) propOfProp = new PropOfProp(0, 0); try { double prevDoubleValue = Double.parseDouble(prevValue); double nextDoubleValue = Double.parseDouble(nextValue); // prev 3 next 9 power 2 count 3 -> count 4 // prev 3 next 9 power 3 count 3 -> count 1 for (int i = 1; i < 3; i++) { if (Math.pow(prevDoubleValue, i) == nextDoubleValue){ if (propOfProp.power == i){ propOfProp.count++; }else { propOfProp.power = i; propOfProp.count = 1; } break; } } } catch (NumberFormatException e) { if (nextValue.equals(prevValue) && propOfProp.power == 0){ propOfProp.count++; } } } } prevProp = nextProp; } } <file_sep>package level5; public class Imagination { } <file_sep>package sync; import java.io.Serializable; class FuncID implements Serializable { Double timeIndex; Double funcIndex; Double linkIndex; Double trueIndex; Double resultIndex; }<file_sep>package level2.executor; import com.google.gson.JsonObject; import level2.consolidator.Action; import level2.consolidator.Consolidator; import java.io.InputStream; import java.util.*; public class Executor { static Executor executor; public static Executor getInstance(){ if (executor == null) executor = new Executor(); return executor; } static Map<String, String> groupAddress = new HashMap<>(); static Map<String, JsonObject> groupApi = new HashMap<>(); public static void regystry(InputStream requestBody) { //Json Parse JsonObject json = new JsonObject(); groupAddress.put(json.get("groupID").getAsString(), json.get("address").getAsString()); groupApi.put(json.get("groupID").getAsString(), json.get("api").getAsJsonObject()); } public void exec(Action action){ } static Consolidator execConsolidator; static long beginStart; public static void addExecConsolidator(Consolidator consolidator){ execConsolidator = consolidator; beginStart = new Date().getTime(); } Timer execTimer; class execTimerTask extends TimerTask { @Override public void run() { // Consolidator lastConsolidator = (Consolidator) Main.consolidatorTimeLine.lastObject(); // execConsolidator.getTimeLineLocalTime(100); //Провести сравнение консолидаторов по времени и по последовательсноти и по пермутейшенам //equals time block //оценка выполненыз работ и награда за соответсвие предыдущему разу //эту оценку нужно учитывать в планировании } } public Executor() { execTimer.schedule(new execTimerTask(), 100); } } <file_sep>package utils; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TimeMap { static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } static class SumNode { HashMap<String, Integer> toLink = new HashMap<>(); HashMap<String, Integer> sumLinks = new HashMap<>(); } static HashMap<String, SumNode> list = new HashMap<>(); static class Node { String name; public Node(String name) { this.name = name; } } static class Edge { String src; String dest; String data; public Edge(String src, String dest, String data) { this.src = src; this.dest = dest; this.data = data; } } static class Graph { List<Node> nodes = new ArrayList<>(); List<Edge> edges = new ArrayList<>(); } private static final Map<String, String> letters = new HashMap<String, String>(); static { letters.put("А", "A"); letters.put("Б", "B"); letters.put("В", "V"); letters.put("Г", "G"); letters.put("Д", "D"); letters.put("Е", "E"); letters.put("Ё", "E"); letters.put("Ж", "ZH"); letters.put("З", "Z"); letters.put("И", "I"); letters.put("Й", "I"); letters.put("К", "K"); letters.put("Л", "L"); letters.put("М", "M"); letters.put("Н", "N"); letters.put("О", "O"); letters.put("П", "P"); letters.put("Р", "R"); letters.put("С", "S"); letters.put("Т", "T"); letters.put("У", "U"); letters.put("Ф", "F"); letters.put("Х", "H"); letters.put("Ц", "C"); letters.put("Ч", "CH"); letters.put("Ш", "SH"); letters.put("Щ", "SH"); letters.put("Ъ", "'"); letters.put("Ы", "Y"); letters.put("Ъ", "'"); letters.put("Э", "E"); letters.put("Ю", "U"); letters.put("Я", "YA"); letters.put("а", "a"); letters.put("б", "b"); letters.put("в", "v"); letters.put("г", "g"); letters.put("д", "d"); letters.put("е", "e"); letters.put("ё", "e"); letters.put("ж", "zh"); letters.put("з", "z"); letters.put("и", "i"); letters.put("й", "i"); letters.put("к", "k"); letters.put("л", "l"); letters.put("м", "m"); letters.put("н", "n"); letters.put("о", "o"); letters.put("п", "p"); letters.put("р", "r"); letters.put("с", "s"); letters.put("т", "t"); letters.put("у", "u"); letters.put("ф", "f"); letters.put("х", "h"); letters.put("ц", "c"); letters.put("ч", "ch"); letters.put("ш", "sh"); letters.put("щ", "sh"); letters.put("ъ", "'"); letters.put("ы", "y"); letters.put("ъ", "'"); letters.put("э", "e"); letters.put("ю", "u"); letters.put("я", "ya"); } static int max = 0; static void addList(String word) { for (int i = 0; i < word.length(); i++) { SumNode sumNode = list.get("" + word.charAt(i)); if (sumNode == null) { sumNode = new SumNode(); list.put("" + word.charAt(i), sumNode); } for (int j = 0; j < word.length(); j++) { if (i != j) { Integer sum = sumNode.toLink.get("" + word.charAt(j)); sum = sum == null ? 1 : sum + 1; sumNode.toLink.put("" + word.charAt(j), sum); if (max < sum) max = sum; Integer sumLink = sumNode.sumLinks.get("" + word.charAt(j)); if (sumLink == null){ int min = Integer.MAX_VALUE; String minKey = ""; for (String key: sumNode.sumLinks.keySet()){ if (sumNode.sumLinks.get(key) < min) { min = sumNode.sumLinks.get(key); minKey = key; } } if (min != Integer.MAX_VALUE && min < sum && sumNode.sumLinks.keySet().size() > 3){ sumNode.sumLinks.remove(minKey); } } if (sumNode.sumLinks.keySet().size() <= 3) sumNode.sumLinks.put("" + word.charAt(j), sum); } } } } public static void main(String[] args) { try { String file = readFile("test.txt", Charset.forName("cp1251")); String word = ""; for (int i = 0; i < 100000; i++) { if (file.charAt(i) == ' ') { addList(word); word = ""; } else { if (file.charAt(i) >= 'а' && file.charAt(i) <= 'я') word += file.charAt(i); } } Graph graph = new Graph(); for (String key : list.keySet()) if (key.charAt(0) >= 'а' && key.charAt(0) <= 'я') graph.nodes.add(new Node(key)); for (String fromKey : list.keySet()) { SumNode sumNode = list.get(fromKey); for (String toKey : sumNode.sumLinks.keySet()) if (fromKey.charAt(0) >= 'а' && fromKey.charAt(0) <= 'я') if (toKey.charAt(0) >= 'а' && toKey.charAt(0) <= 'я') if (fromKey.charAt(0) != toKey.charAt(0)) if (letters.get(String.valueOf((char)(fromKey.charAt(0)))) != null) if (letters.get(String.valueOf((char)(toKey.charAt(0)))) != null) if (sumNode.sumLinks.get(toKey) > 1000) { //graph.edges.add(new Edge(fromKey, toKey, "" + sumNode.toLink.get(toKey))); System.out.println( "graph.addLink('" + letters.get(String.valueOf((char) (fromKey.charAt(0)))) + "', '" + letters.get(String.valueOf((char) (toKey.charAt(0)))) + "', { connectionStrength: " + (double) ((max - 1000) - (sumNode.sumLinks.get(toKey) - 1000)) / (double) (max - 1000) + " });" ); list.get("" + toKey.charAt(0)).sumLinks.remove("" + fromKey.charAt(0)); } } //System.out.println(new Gson().toJsonTree(graph)); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>ROOTPATH=c:\data SERVERPORT=82<file_sep>package app.VK; import com.google.gson.Gson; import level2.consolidator.EventData; import level2.consolidator.InputConsolidator; import utils.Http; import java.io.IOException; import java.util.*; public class Main { static VkApi vkApi; private static Timer mTimer; private static MyTimerTask mMyTimerTask; static class MyTimerTask extends TimerTask { @Override public void run() { } } public Main() throws IOException { vkApi = new VkApi("4941994", "820cf71db53f1ca411439e21fd6c26e31b11eea1c44d73e8e3980e21d4c0ca76f39152b61829c8e897a21"); /*mMyTimerTask = new MyTimerTask(); mTimer.schedule(mMyTimerTask, 1000);*/ Wall wall = (Wall)vkApi.invoke("wall.get", VkApi.Params.create().add("filter", "owner").add("count", "100"), Wall.class); List<EventData> events = new ArrayList<>(); for (int i = 0; i < wall.response.items.size(); i++) { Wall.Item item = wall.response.items.get(i); List<String> data = new ArrayList<>(); data.add(String.valueOf(item.id)); Map<String, String> controls = new HashMap<>(); controls.put("likes", String.valueOf(item.likes.count)); events.add(new EventData("wall", data)); } InputConsolidator inputConsolidator = new InputConsolidator(events); Http.Post("localhost:8080\\level2.consolidator", new Gson().toJson(inputConsolidator).toString()); } public static void main(String[] args) throws IOException { Main main = new Main(); } } <file_sep>package templates; import templates.utils.AvgValue; import templates.utils.Permutation; import templates.utils.Sequences; import java.util.*; public abstract class FunctionModule { public Permutation permutation = new Permutation(); public Sequences sequences = new Sequences(); public List<Object> result = new ArrayList<Object>(); public List<String> hash = new ArrayList<String>(); public Map<String, Object> cache = new HashMap<String, Object>(); public Map<String, Map<String, String>> meta = new HashMap<String, Map<String, String>>(); public Map<String, AvgValue> avgMeta = new HashMap<String, AvgValue>(); public Object input(List<Object> inputs) { /*if (plan.isNotEnd or plan.isError) { inputMapping(); findPermutations / objs(); // sequence / objs(); //video fragment borders(); objects(); repair(); template(); group(); position(); speed(); acceleration(); traectory(); planer / tactic(); choice / task(); run(); } else { findPermutations / blocks(); sequence / blocks(); // video film template / tact(); borders / pause(); objects / words(); repair(); group / sentense(); position / triangylation(); speed(); acceleration(); planer / strategy(); choice / task / money(); run(); }*/ return null; } private void createCache() { for (int i = 0; i < result.size(); i++) cache.put(hash.get(i), result.get(i)); } void createStatistics() { for (Map.Entry<String, Map<String, String>> entry : meta.entrySet()) { Map<String, String> metaData = entry.getValue(); for (Map.Entry<String, String> metaEntry : metaData.entrySet()) { //statistics.createStat(metaEntry.getKey(), metaEntry.getValue()); } } } public double getAvgMeta(String key, double value) { AvgValue avgValue = avgMeta.get(key); if (avgValue == null) { avgValue = new AvgValue(value, 5); avgMeta.put(key, avgValue); } return avgValue.add(value); } public void pause() { sequences.put(sequences.buffer); sequences.buffer.clear(); } } <file_sep>package NodeBase; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Utils { static String deleteStr(String str, int fromindex, int toindex) { if ((fromindex < toindex) && (fromindex > -1) && (toindex < str.length())) return str.substring(0, fromindex) + str.substring(toindex, str.length()); return str; } public static String Inc(String number) { return Integer.toString((Integer.parseInt(number) + 1)); } public static String LoadFromFile(String path) { try { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded); } catch (IOException e){ return null; } } public static void SaveToFile(String fileName, String text) { try { PrintWriter out = new PrintWriter(fileName); out.print(text); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static Map<String, String> slice(String string, String delimeter) { Map<String, String> result = new HashMap<String, String>(); String[] strings = string.split(delimeter); for (int i=0; i<strings.length; i++) { String[] var = strings[i].split(Const.sEqual); if (var.length == 2) result.put(var[0], var[1]); else result.put(var[0], null); } return result; } static String encodeStr(String str) { String result = null; for (int i=0; i<str.length(); i++) if ( // if ((str.charAt(i) >= 48) && (str.charAt(i) <= 57)) || //numbers ((str.charAt(i) >= 65) && (str.charAt(i) <= 90)) || //eng uppercase ((str.charAt(i) >= 97) && (str.charAt(i) <= 122)) //eng lowercase ) result += "" + str.charAt(i); else result += "%" + String.format("%02X", str.charAt(i)); return result; } static String decodeStr(String str) { String result = null; int i=1; while (i <= str.length()) { if (str.charAt(i) != '%') result += "" + str.charAt(i); else { i++; String esc = str.substring(i, i + 2); i++; int charCode = Integer.parseInt(esc, 16); result += (char)charCode; } i++; } return result; } } <file_sep>package templates.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Permutation { public Integer groupId = 0; public Map<String, ArrayList<String>> allGroups = new HashMap<String, ArrayList<String>>(); public Map<String, ArrayList<String>> allSortGroups = new HashMap<String, ArrayList<String>>(); public Map<String, ArrayList<String>> allObjects = new HashMap<String, ArrayList<String>>(); public ArrayList<String> groups(List<String> input) { ArrayList<String> result = new ArrayList<String>(); for (int i = 0; i < input.size(); i++) { ArrayList<String> groups = allObjects.get(input.get(i)); if (groups != null) for (int j = 0; j < groups.size(); j++) if (result.indexOf(groups.get(j)) == -1) result.add(groups.get(j)); } return result; } public Map<String, Double> permutation(ArrayList<String> input) { ArrayList<String> sortInput = (ArrayList<String>) input.clone(); java.util.Collections.sort(sortInput); ArrayList<String> groups = groups(sortInput); Map<String, Double> likes = new HashMap<String, Double>(); for (int k = 0; k < groups.size(); k++) { ArrayList<String> objects = allSortGroups.get(groups.get(k)); double count = 0; for (int i = 0; i < objects.size(); i++) { String object = objects.get(i); for (int j = 0; j < sortInput.size(); j++) if (object.equals(sortInput.get(j))) count++; } likes.put(groups.get(k), count / sortInput.size()); } return likes; } public String max(Map<String, Double> likes) { double max = 0; String result = null; for (String groupId: likes.keySet()){ if (likes.get(groupId) > max){ result = groupId; max = likes.get(groupId); } } return result; } public String get(ArrayList<String> input){ return max(permutation(input)); } public String put(String newGroupName, ArrayList<String> input) { Map<String, Double> permutation = permutation(input); String groupName = max(permutation); //update group if (groupName == null || permutation.get(groupName) != 1.0) { groupName = newGroupName; allGroups.put(groupName, (ArrayList<String>) input.clone()); ArrayList<String> sortInput = (ArrayList<String>) input.clone(); java.util.Collections.sort(sortInput); allSortGroups.put(groupName, sortInput); } //update allObjects for (int i = 0; i < input.size(); i++) { String objName = input.get(i); ArrayList<String> object = allObjects.get(input.get(i)); if (object == null) { object = new ArrayList<String>(); allObjects.put(objName, object); } if (object.indexOf(groupName) == -1) object.add(groupName); } return groupName; } public String put(ArrayList<String> input) { String newGroupName = "" + groupId + 1; String group = put(newGroupName, input); if (newGroupName.equals(group)) groupId++; return group; } /*public void main(String[] args) { AssociativeArray analysing = new AssociativeArray(); ArrayList<String> data = new ArrayList<String>(); data.add("1"); data.add("2"); data.add("3"); analysing.put(data); data.set(2, "5"); analysing.put(data); System.out.println(analysing.allArrays); data.add("4"); System.out.println("new " + data); System.out.println("per" + analysing.findPermutations(data) + "=" + analysing.allArrays.get(analysing.max(analysing.findPermutations(data)))); System.out.println("seq" + analysing.findSequences(data) + "=" + analysing.allArrays.get(analysing.max(analysing.findSequences(data)))); data.add(0, "5"); }*/ } <file_sep>package level3.storage; public class DoubleHashMap { } <file_sep>package level1.codegenerator; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; class Host implements Serializable { String ip = "localhost"; String port = "8080"; String mac = ""; Integer lastID = 0; public ArrayList<Block> blocks = new ArrayList<Block>(); public Host(String ip, String port) { this.ip = ip; this.port = port; } public Host() { } synchronized Block getBlock(int ID) { for (int i = 0; i < blocks.size(); i++) { Block block = blocks.get(i); if (block.ID.equals(ID)) return block; } return null; } synchronized void putBlock(Block putBlock) { for (int i = 0; i < blocks.size(); i++) { Block block = blocks.get(i); if (block.ID.equals(putBlock.ID)) { blocks.set(i, putBlock); return; } } blocks.add(putBlock); } public ArrayList<String> hosts = new ArrayList<String>(); synchronized public void removeBlock(Block remove) { for (Iterator<Block> it = blocks.iterator(); it.hasNext(); ) { Block block = it.next(); if (block == remove) it.remove(); } } }<file_sep>package level3.threedem; public class ThreeDemMap { } <file_sep>package level2.consolidator; public class ArrayID { public String groupName; public String arrayID; public ArrayID(String groupName, String arrayID) { this.groupName = groupName; this.arrayID = arrayID; } public ArrayID(String unionID) { String[] groupIdAndArrayID = unionID.split(","); groupName = groupIdAndArrayID[0]; arrayID = groupIdAndArrayID[1]; } @Override public String toString() { return groupName + "," + arrayID; } } <file_sep>package level3.detectors; public class Stereographics { } <file_sep>package level2.consolidator; import java.util.*; public class Arrays { //groupName/groupID public Integer arrayLastID = 0; public Map<String, ArrayList<String>> allArrays = new HashMap<>(); public Map<String, ArrayList<String>> allSortArrays = new HashMap<>(); public Map<String, ArrayList<String>> allObjects = new HashMap<>(); //link objectid to groupid public Map<String, Double> arrayCounters = new HashMap<>(); final int arrayCountersCashSize = 20; public Map<String, Double> arrayCountersCash = new HashMap<>(); //нечеткий поиск по значениям public Arrays() { } public Arrays(String storagePath) { } public ArrayList<String> getArray(String groupID) { return allArrays.get(groupID); } public ArrayList<String> arrays(List<String> input) { ArrayList<String> result = new ArrayList<String>(); for (int i = 0; i < input.size(); i++) { ArrayList<String> groups = allObjects.get(input.get(i)); if (groups != null) for (int j = 0; j < groups.size(); j++) if (result.indexOf(groups.get(j)) == -1) result.add(groups.get(j)); } return result; } public Map<String, Double> findPermutations(ArrayList<String> input) { ArrayList<String> sortInput = (ArrayList<String>) input.clone(); java.util.Collections.sort(sortInput); ArrayList<String> groups = arrays(sortInput); Map<String, Double> likes = new HashMap<String, Double>(); for (int k = 0; k < groups.size(); k++) { ArrayList<String> objects = allSortArrays.get(groups.get(k)); double count = 0; for (int i = 0; i < objects.size(); i++) { String object = objects.get(i); for (int j = 0; j < sortInput.size(); j++) if (object.equals(sortInput.get(j))) { count++; break; } } likes.put(groups.get(k), count / sortInput.size()); } return likes; } public Map<String, Double> findSequences(ArrayList<String> input) { ArrayList<String> groups = arrays(input); Map<String, Double> likes = new HashMap<>(); for (int k = 0; k < groups.size(); k++) { ArrayList<String> objects = allArrays.get(groups.get(k)); double count = 0; for (int i = 0; i < objects.size(); i++) if (objects.get(i).equals(input.get(i))) count++; likes.put(groups.get(k), count / input.size()); } return likes; } public static String max(Map<String, Double> likes) { double max = 0; String result = null; for (String groupId : likes.keySet()) { if (likes.get(groupId) > max) { result = groupId; max = likes.get(groupId); } } return result; } public static String min(Map<String, Double> array) { double min = Double.POSITIVE_INFINITY; String result = null; for (String groupId : array.keySet()) { if (array.get(groupId) < min) { result = groupId; min = array.get(groupId); } } return result; } ArrayList<String> objectBuffer = new ArrayList<>(); void putToArrayBuffer(String object) { objectBuffer.add(object); } String saveArrayBuffer() { String arrayID = put(objectBuffer); objectBuffer.clear(); return arrayID; } String prevArrayID = null; ArrayList<String> lastTemplate = null; public String put(ArrayList<String> input) { Map<String, Double> permutation = findSequences(input); //findPermutations включает в себя поиск по findSequences String arrayID = max(permutation); //update group if (arrayID == null || permutation.get(arrayID) != 1.0) { arrayID = "" + arrayLastID++; allArrays.put(arrayID, (ArrayList<String>) input.clone()); ArrayList<String> sortInput = (ArrayList<String>) input.clone(); java.util.Collections.sort(sortInput); allSortArrays.put(arrayID, sortInput); } //update allObjects for (int i = 0; i < input.size(); i++) { String objName = input.get(i); ArrayList<String> object = allObjects.get(input.get(i)); if (object == null) { object = new ArrayList<>(); allObjects.put(objName, object); } if (object.indexOf(arrayID) == -1) object.add(arrayID); } //template //using last event from FileHashMap if (prevArrayID != null) { ArrayList<String> prevArray = getArray(prevArrayID); ArrayList<String> thisArray = getArray(arrayID); lastTemplate = template(prevArray, thisArray); } prevArrayID = arrayID; //counters Double arrayCounter = arrayCounters.get(arrayID); if (arrayCounter == null) arrayCounter = 0.0; arrayCounters.put(arrayID, arrayCounter + 1); //arrayCountersCash arrayCountersCash.put(arrayID, arrayCounter); if (arrayCountersCash.size() > arrayCountersCashSize) { String minCounter = min(arrayCountersCash); arrayCountersCash.remove(minCounter); } return arrayID; } ArrayList<String> template(ArrayList<String> from, ArrayList<String> to) { ArrayList<String> result = (ArrayList<String>) to.clone(); for (int i = 0; i < from.size(); i++) if (i >= to.size()) { result.add(i, from.get(i)); } else { if ((from.size() < i + 1) || (to.size() < i + 1) || !from.get(i).equals(to.get(i))) //изменение -1 //добавление -2 //удаление -3 result.set(i, null); } return result; } public static ArrayList<Integer> fuzzyEqualsArray(ArrayList<String> from, ArrayList<String> to) { //1 2 n 4 5 //1 2 3 4 5 6 //result //0 1 2 3 4 5 return null; } static Double fuzzyEquals(ArrayList<String> from, ArrayList<String> to) { ArrayList<Integer> fuzzy = fuzzyEqualsArray(from, to); double equalsCounter = 0; for (int i = 0; i < fuzzy.size(); i++) { // -1 -2 -3 if (fuzzy.get(i) == null){ equalsCounter++; } } return equalsCounter / fuzzy.size(); } public static Map<String, Double> equalsSequences(ArrayList<String> interval, Map<String, ArrayList<String>> arrays) { Map<String, Double> result = new HashMap<>(); for (String arrayID: arrays.keySet()){ ArrayList<String> array = arrays.get(arrayID); result.put(arrayID, fuzzyEquals(interval, array)); } return result; } /* static void recursivePermutationPut(JsonObject eventObject, String path) { } */ public ArrayList<ArrayList<String>> templatesOfPermutation(ArrayList<String> input) { ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>(); Map<String, Double> permutation = findPermutations(input); for (String groupId : permutation.keySet()) { if (permutation.get(groupId) != 1.0) { //получаем список похожих кроме себя //походу придутся убрать ArrayList<String> perGroup = allSortArrays.get(groupId); ArrayList<String> temGroup = (ArrayList<String>) perGroup.clone(); for (int i = 0; i < perGroup.size(); i++) if ((perGroup.size() < i + 1) || (input.size() < i + 1) || !perGroup.get(i).equals(input.get(i))) temGroup.set(i, null); list.add(temGroup); } } return list; } public ArrayList<ArrayList<String>> templatesOfSequences(ArrayList<String> input) { ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>(); Map<String, Double> sequences = findSequences(input); for (String groupId : sequences.keySet()) { if (sequences.get(groupId) != 1.0) { ArrayList<String> seqGroup = allArrays.get(groupId); ArrayList<String> temGroup = (ArrayList<String>) seqGroup.clone(); for (int i = 0; i < temGroup.size(); i++) if (!temGroup.get(i).equals(input.get(i))) temGroup.set(i, null); list.add(temGroup); } } return list; } Map<Integer, String> tacts = new HashMap<>(); //Такты //Поиск зависимостей в событиях public Object getInterval(long time) { return null; } public Object putInterval(long begin, long end) { return null; } public Object selectEvents(long begin, long end) { return null; } public String lastEvent() { return null; } public String nextEvent(long time) { return null; } public String getEvent(long time) { return null; } public static void main(String[] args) { //test of find likes Arrays arrays = new Arrays(); ArrayList<String> data = new ArrayList<String>(); data.add("1"); data.add("2"); data.add("3"); arrays.put(data); data.set(2, "5"); arrays.put(data); System.out.println(arrays.allArrays); data.add("4"); System.out.println("new " + data); System.out.println("per" + arrays.findPermutations(data) + "=" + arrays.allArrays.get(arrays.max(arrays.findPermutations(data)))); System.out.println("seq" + arrays.findSequences(data) + "=" + arrays.allArrays.get(arrays.max(arrays.findSequences(data)))); } } <file_sep>package level3.storage; public class Point { } <file_sep># K5 B3 Name of Project: NodeBrean Neuro-information model What a NodeBase? NodeBase is file system NodeBase is compilator Project including: sheduler planner admin console(client) reciving tech(teleport) builder creator generator Create to: language for machines, not for human Read more: documetation Readme.md to github video tutor documentation add link to TNode [basic task] Create Pi Code [principles] All fucked-up! Let's start with a clean list. Shut up and show me! interactivity better speed speed better ram [admin console] multitreading active_kernel = 2 $transaction=992402 access to Node http auntification admin settings swap file > 90% hdd MaxAddrSpace=200 admin console auto find ports find bases in any hdd or ssd restart nodebase using adb to switch phone and pc or wifi [Kernel <v5] find func search in branch cash branch cash ! @ 1 Link Type naPointer Parse and Build Type is SubStructure (subnodes) is a continue IndexNode Link Like new branch "Group" (sentence, params) Like: ANode Link History AString standart /from_exe_file //local local\local\local history and dump using delimiter chr(0) control math 160 count 14 min not delete free func addevent if parent local using language GarbageCollector dump func save arhive Nodes in DUMP file merge all module to one file stackoverflow delete first element in stack when stack out rec code access trues (root param) [builder v3] Data8Count=2 LocalVarCount=2 SubLevel=1 SubFuncCount=3 SubFuncParamsCount=2 SequenceCount=10 IfWhileElseCount=1 IntBeginRange=-3 IntCenterRange=0 IntEndRange=10 FracBeginRange=0 FracCenterRange=0 FracEndRange=10 IfCount=1 WhileCount=0 ElseCount=0 search and replace best function ANext AHistory ALocal Delete word random Delete word range [kernel v5] Kernel to Java load save set get run //free //dump save node to xml<file_sep>package level2.controllers; import com.google.gson.JsonObject; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; public class Controllers { static Map<String, Controller> indexators = new HashMap<>(); //генерация static Map<String, Summator> summators = new HashMap<>(); //настроение Timer updateTimer; public Controllers() { indexators.put(UsageController.class.getName(), new UsageController()); summators.put(UsageController.class.getName(), new Summator(100, 0, 0, 0, 50)); updateTimer.schedule(new UpdateTimerTask(), 100); } public static void index(String path, JsonObject eventObject) { Controller controller = indexators.get(path); double index = controller.index(path, eventObject); JsonObject json = new JsonObject(); json.addProperty("groupID", controller.getClass().getName()); json.addProperty("value", index); //Consolidator.event(json); Summator summator = summators.get(path); summator.add(index); } class UpdateTimerTask extends TimerTask{ @Override public void run() { Map<String, String> order = new HashMap<>(); for (String key: summators.keySet()){ Summator summator = summators.get(key); if (summator.now >= summator.border){ order.put(key, "" + (summator.border - summator.now)); } } //Planer.order(order); } } } <file_sep>package level2.controllers; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class ControllerParser { static Map<String, String> map = new HashMap<>(); public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true){ String str = scanner.nextLine(); System.out.println(str); String[] splitStr = str.split("\n"); for (int i = 0; i <splitStr.length; i++) { String string = splitStr[i]; int begin = string.indexOf('('); int end = string.indexOf(')'); int tire = string.indexOf('–'); if (begin != -1 && tire != -1){ String substring = string.substring(begin + 1, end); map.put(substring, "sdf"); } } for (String key: map.keySet()){ System.out.println(key); } System.out.println(map.keySet().size()); } } } <file_sep>package level3.threedem; public class Model { } <file_sep>package level3.detectors; public class Acselerometer { } <file_sep>package level2.syncronizator; public class Syncronizator { //балансировка ресурсов компа+ } <file_sep>package templates.utils; import java.util.ArrayList; import java.util.Map; public class PermutationWithTemplates extends Permutation{ public Permutation allTemplates = new Permutation(); public ArrayList<ArrayList<String>> templateList(ArrayList<String> input){ ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>(); Map<String, Double> permutation = permutation(input); for (String groupId: permutation.keySet()) { if (permutation.get(groupId) != 1.0) { ArrayList<String> perGroup = allSortGroups.get(groupId); ArrayList<String> temGroup = new ArrayList<String>(); for (int i = 0; i < perGroup.size(); i++) if ((perGroup.size() < i+1)|| (input.size() < i+1) || !perGroup.get(i).equals(input.get(i))) temGroup.set(i, null); list.add(temGroup); } } return list; } @Override public String put(ArrayList<String> input) { String group = super.put(input); ArrayList<ArrayList<String>> list = templateList(input); for (int i = 0; i < list.size(); i++) allTemplates.put(list.get(i)); return group; } public static void main(String[] args) { PermutationWithTemplates templates = new PermutationWithTemplates(); ArrayList<String> data = new ArrayList<String>(); data.add("1"); data.add("2"); data.add("3"); templates.put(data); data.add("5"); templates.put(data); data.set(2, "6"); data.add("7"); templates.put(data); data.set(3, "6"); templates.put(data); System.out.println(templates.allTemplates.allGroups); } } <file_sep>package templates; import java.util.HashMap; import java.util.Map; abstract public class RootModule { public abstract InputModule ear(); public abstract InputModule eye(); public abstract InputModule feel(); public abstract InputModule temperature(); public abstract InputModule accelerometer(); public abstract SystemModule reliable(); public abstract SystemModule abstracts(); public abstract SystemModule neurolan(); public abstract SystemModule logic(); public abstract SystemModule unique(); Object globalPlan; void activation() { // выполнение скрипта действий для реализации плана /* * выход если произошло несоответсвие * */ } public Map<String, SystemModule> modules = new HashMap<String, SystemModule>(); void getRequest(String dataType, String Data) { for (String moduleName : modules.keySet()) { SystemModule module = modules.get(dataType); } } public static void main(String[] args) { } } <file_sep>package templates; import templates.utils.Permutation; import templates.utils.Sequences; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; abstract public class InputModule { public Map<String, Map<String, Object>> storage = new HashMap<String, Map<String, Object>>(); public Permutation permutation = new Permutation(); public Sequences sequences = new Sequences(); public abstract List<Object> listData(Object data); public abstract Map<String, Object> dataToPoints(Object data); public abstract String hashObject(Object object); public void findShapes(Map<String, Object> points){ } public void input(Object data){ Map<String, Object> points = dataToPoints(data); for (String inputId: points.keySet()){ Map<String, Object> inputData = storage.get(inputId); if (inputData == null) storage.put(inputId, inputData = new HashMap<String, Object>()); inputData.put(hashObject(points.get(inputId)), points.get(inputId)); } findShapes(points); sequences.buffer.add(permutation.put((ArrayList<String>) points.keySet())); } public void pause(){ sequences.put(sequences.buffer); sequences.buffer.clear(); } } <file_sep>package level2.controllers; public class Summator { double begin; double end; double now; double factor; double border; public Summator(double begin, double end, double now, double factor, double border) { this.begin = begin; this.end = end; this.now = now; this.factor = factor; this.border = border; } void add(double value){ now += value; } } <file_sep>package level3.storage; public class Region { } <file_sep>package level3.maps; public class TargetMap { }
a029dbcf746c6f74b9cdf3420a4e6e32b5ff5595
[ "Markdown", "Java", "INI" ]
37
Java
x29a100/NodeBase
40124ddd3d8b2fbf47b6a97049f59ede48caf46d
02c585caaf561db32ee8916916b522f470532f3b
refs/heads/main
<repo_name>abdelrahim-hentabli/Skychart.js<file_sep>/src/padzeroes.js function padzeroes(number, size){ return number.toString().padStart(size, "0"); } export default padzeroes;<file_sep>/src/csvreader.js import stars from './topstars.js' import Star from './star.js' import {currentTime} from './globalvars.js' var starArray = []; function parseFile(){ var starsStringArray = stars.split('\n'); var currentLine; starArray = []; for(var i = 0; i < starsStringArray.length; i++){ currentLine = starsStringArray[i].split(','); starArray.push(new Star(parseInt(currentLine[0]), currentLine[1], currentLine[2], parseFloat(currentLine[3])+ parseFloat(currentLine[4])/60, parseFloat(currentLine[5]), parseFloat(currentLine[6]))); starArray[i].update(0, 0, currentTime); } } export {parseFile, starArray}<file_sep>/src/skychart.js import { useEffect, useRef } from 'react' import printLatLong from './coordinates'; import { starArray, parseFile } from './csvreader' import {currentTime} from './globalvars' function draw(canvas){ const context = canvas.getContext('2d'); var fontSize = canvas.height/16; context.font = fontSize.toString() + "px Arial"; context.fillStyle = "lightgray" context.fillRect(0,0,canvas.width, canvas.height) context.fillStyle = "gray" context.beginPath() context.arc(canvas.width / 2, canvas.height/2, canvas.height/2, 0, 2* Math.PI) context.fill(); context.fillStyle = "black" context.beginPath() context.arc(canvas.width / 2, canvas.height/2, canvas.height/2 - fontSize, 0, 2* Math.PI) context.fill(); context.translate(canvas.width / 2, canvas.height / 2); var currentCompassAngle; for(var theta = 0; theta < 360; theta +=30){ switch(theta){ case 0: currentCompassAngle = "N"; break; case 90: currentCompassAngle = "E"; break; case 180: currentCompassAngle = "S"; break; case 270: currentCompassAngle = "W"; break; default: currentCompassAngle = theta.toString() + "°"; break; } context.fillText(currentCompassAngle, -(context.measureText(currentCompassAngle).width / 2), (-context.canvas.height / 2) + .9 * fontSize); context.rotate(-Math.PI / 6); } context.translate(-canvas.width / 2, -canvas.height / 2); const center = canvas.width/2; var starCenterX; var starCenterY; var starRadius = 3; const compassRadius = .5 * canvas.width - fontSize; const scale = compassRadius / 90; context.font = "8px Arial"; context.fillStyle = "white"; var toRadians = Math.PI / 180; for(var i = 0; i < starArray.length; i++){ if(starArray[i].altitude > 0){ starCenterX = center - (scale * (90 - starArray[i].altitude) * (Math.sin(toRadians * starArray[i].azimuth))); starCenterY = center - (scale * (90 - starArray[i].altitude) * (Math.cos(toRadians * starArray[i].azimuth))); context.beginPath(); context.arc(starCenterX, starCenterY, starRadius, 0, 2* Math.PI); context.fill(); if(starArray[i].magnitude <= 2 && starArray[i].name !== ""){ context.fillText(starArray[i].name, starCenterX+3, starCenterY+3); } } } } const Skychart = props => { const canvas = useRef(null) useEffect(() => { parseFile(); const can= canvas.current; draw(can); function handleResize() { var size = Math.min(window.innerHeight - Math.ceil(15 * (Math.min(window.innerHeight, window.innerWidth) / 100)), window.innerWidth); can.height = size; can.width = size; can.innerHeight = size; can.innerHeight = size; draw(can); } window.addEventListener("resize", handleResize); handleResize(); return () => window.removeEventListener("resize", handleResize); },[]); useEffect(() => { for(var i = 0; i < starArray.length; i++){ starArray[i].update(props.latitude, props.longitude, currentTime); } const can = canvas.current; draw(can); }, [props.latitude, props.longitude]); return (<canvas ref={canvas} {...props}/>) } export default Skychart<file_sep>/src/App.js import logo from './images/logo.png' import github_logo from './images/GitHub-Mark-32px.png'; import linkedin_logo from './images/LI-In-Bug.png'; import portfolio_logo from './images/portfolio.png' import './App.css' import Skychart from './skychart.js' import TimeComponent from './timecomponent.js' import { useEffect, useState } from 'react'; function App() { const [latitude, setLatitudeUpdate] = useState(0); const [longitude, setLongitudeUpdate] = useState(0); const [time, setTimeUpdate] = useState(0); useEffect(() => { var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }; function success(pos) { var crd = pos.coords; setLatitudeUpdate(crd.latitude); setLongitudeUpdate(crd.longitude); } function error(err) { console.warn(`ERROR(${err.code}): ${err.message}`); } navigator.geolocation.getCurrentPosition(success, error, options); }, []); return ( <div className="App"> <header className="App-header"> <div className="App-title"> <img src={logo} className="App-logo" alt="logo" /> <div> skychart.js </div> </div> <TimeComponent latitude={latitude} longitude={longitude} time={time} /> </header> <main className="App-body"> <Skychart id="main-canvas" className="App-skychart" latitude={latitude} longitude={longitude} time={time} > Canvas element did not load. </Skychart> </main> <footer className="App-footer" > <a className="App-link" href="https://github.com/abdelrahim-hentabli/skychart.js" target="_blank" rel="noopener noreferrer" > <img src={github_logo} className="App-icons" alt="github logo"/> GitHub </a> <a className="App-link" href="https://www.linkedin.com/in/abdelrahim-hentabli/" target="_blank" rel="noopener noreferrer" > <img src={linkedin_logo} className="App-icons" alt="linkedin logo"/> Linkedin </a> <a className="App-link" href="https://rhentabli.com" target="_blank" rel="noopener noreferrer" > <img src={portfolio_logo} className="App-icons" alt="portfolio logo"/> Portfolio </a> </footer> </div> ); } export default App; <file_sep>/src/time.js import padzeroes from './padzeroes.js' import roundN from './roundn.js' export class Time { /* Basic class which stores time * uses javascript Date() object * only updates on now() and setters */ constructor(){ this.date = new Date(); this.now(); } //Setters now(){ this.date.setTime(Date.now()); this.updateSiderealTime(); } updateSiderealTime(){ var gmst = this.gmst(); var remainder = gmst; this.sHour = Math.trunc(remainder); remainder = (remainder - this.sHour) * 60; this.sMinute = Math.trunc(remainder); remainder = (remainder - this.sMinute) * 60; this.sSecond = Math.trunc(remainder); } gmst(){ var d = this.jd_disc() - 2451545.0; var T = d/ 36525; var temp = 6.697374558+ (.06570982441908 * d) + 1.00273790935 * (this.date.getUTCHours() + (this.date.getUTCMinutes() / 60.0) + (this.date.getUTCSeconds()/3600.0)) + .000026 * Math.pow(T,2); return (temp - (Math.trunc(temp/24) *24)); } jd_disc(){ //jd date, date changes once a day //rework this function and update a stored value, this function is getting called multiple times needlessly var m = this.date.getUTCMonth() +1; var y = this.date.getUTCFullYear(); if (m <= 2){ y--; m+=12; } var a = Math.trunc(y /100); var b = Math.trunc(a/4); var c = 2-a+b; var e = Math.trunc(365.25*(y + 4716)); var f = Math.trunc(30.6001 * (m + 1)); return c+this.date.getUTCDate()+e+f-1524.5; } jd(){ //exact jd time return roundN(this.jd_disc() + (this.date.getUTCHours() + (this.date.getUTCMinutes() / 60.0) + (this.date.getUTCSeconds()/3600.0))/24, 5); } //Getters getDay(){ return this.date.getDate(); } getMonth(){ return this.date.getMonth(); } getYear(){ return this.date.getFullYear(); } getHour(){ return this.date.getHours(); } getMinute(){ return this.date.getMinutes(); } getSecond(){ return this.date.getSeconds(); } getSiderealTime(){ return (this.sHour + (this.sMinute / 60) + (this.sSecond / 3600)); } //Print lTime(){ var output = padzeroes(this.date.getHours(),2) + ":" + padzeroes(this.date.getMinutes(),2) + ":" + padzeroes(this.date.getSeconds(),2) + " " ; output += padzeroes(this.date.getMonth()+1,2) + "/" + padzeroes(this.date.getDate(),2) + "/" + this.date.getFullYear() + " "; return output; } UTCTime(){ var output = padzeroes(this.date.getUTCHours(),2) + ":" + padzeroes(this.date.getUTCMinutes(),2) + ":" + padzeroes(this.date.getUTCSeconds(),2) + " " ; output += padzeroes(this.date.getUTCMonth()+1,2) + "/" + padzeroes(this.date.getUTCDate(),2) + "/" + this.date.getUTCFullYear() + " "; return output; } sTime(){ return padzeroes(this.sHour,2) + ":" + padzeroes(this.sMinute,2) + ":" + padzeroes(this.sSecond,2); } toString(){ var output = padzeroes(this.date.getHours(),2) + ":" + padzeroes(this.date.getMinutes(),2) + ":" + padzeroes(this.date.getSeconds(),2) + " " ; output += padzeroes(this.date.getMonth()+1,2) + "/" + padzeroes(this.date.getDate(),2) + "/" + this.date.getFullYear() + " "; output += padzeroes(this.sHour,2) + ":" + padzeroes(this.sMinute,2) + ":" +this.padzeroes( this.sSecond,2); return output; } }<file_sep>/src/coordinates.js import roundN from './roundn.js' export function printLatLong(latitude, longitude){ var output; if(latitude < 0){ output = -roundN(latitude, 2) + " S "; } else{ output = roundN(latitude, 2) + " N "; } if(longitude < 0){ output += -roundN(longitude, 2) + " W"; } else{ output += roundN(longitude, 2) + " E"; } return output; } export default printLatLong;<file_sep>/src/topstars.js /******************************************** * List of top 300 brightest(by visible magnitude) stars in the sky * Stars are stored in string format and can be parsed the same way as a basic CSV File * Columns are: Number, Proper Name, Common Name (can be empty), Right Ascension (RA) Hour, RA Minute, Declination, Visible Magnitude, Absolute Magnitude */ const stars = "1,Alpha Canis Majoris,Sirius,6,45,-16.7,-1.46,1.43\n\ 2,Alpha Carinae,Canopus,6,24,-52.7,-0.73,-5.64\n\ 3,Alpha Centauri,Rigil Kentaurus,14,40,-60.8,-0.29,4.06\n\ 4,Alpha Boötis,Arcturus,14,16,19.2,-0.05,-0.31\n\ 5,Alpha Lyrae,Vega,18,37,38.8,0.03,0.58\n\ 6,Alpha Aurigae,Capella,5,17,46,0.07,-0.49\n\ 7,Beta Orionis,Rigel,5,15,-8.2,0.15,-6.72\n\ 8,Alpha Canis Minoris,Procyon,7,39,5.2,0.36,2.64\n\ 9,Alpha Eridani,Achernar,1,38,-57.2,0.45,-2.77\n\ 10,Alpha Orionis,Betelgeuse,5,55,7.4,0.55,-5.04\n\ 11,Beta Centauri,Hadar,14,4,-60.4,0.61,-5.42\n\ 12,Alpha Aquilae,Altair,19,51,8.9,0.77,2.21\n\ 13,Alpha Crucis,Acrux,12,27,-63.1,0.79,-4.17\n\ 14,Alpha Tauri,Aldebaran,4,36,16.5,0.86,-0.64\n\ 15,Alpha Scorpii,Antares,16,29,-26.4,0.95,-5.39\n\ 16,Alpha Virginis,Spica,13,25,-11.2,0.97,-3.56\n\ 17,Beta Geminorum,Pollux,7,45,28,1.14,1.07\n\ 18,Alpha Piscis Austrini,Fomalhaut,22,58,-29.6,1.15,1.72\n\ 19,Alpha Cygni,Deneb,20,41,45.3,1.24,-8.74\n\ 20,Beta Crucis,Mimosa,12,48,-59.7,1.26,-3.91\n\ 21,Alpha Leonis,Regulus,10,8,12,1.36,-0.52\n\ 22,Epsilon Canis Majoris,Adhara,6,59,-29,1.5,-4.1\n\ 23,Alpha Geminorum,Castor,7,35,31.9,1.58,0.59\n\ 24,Lambda Scorpii,Shaula,17,34,-37.1,1.62,-5.05\n\ 25,Gamma Crucis,Gacrux,12,31,-57.1,1.63,-0.52\n\ 26,Gamma Orionis,Bellatrix,5,25,6.3,1.64,-2.72\n\ 27,Beta Tauri,Elnath,5,26,28.6,1.66,-1.36\n\ 28,Beta Carinae,Miaplacidus,9,13,-69.7,1.67,-0.99\n\ 29,Epsilon Orionis,Alnilam,5,36,-1.2,1.69,-6.38\n\ 30,Alpha Gruis,Alnair,22,8,-47,1.74,-0.72\n\ 31,Zeta Orionis,Alnitak,5,41,-1.9,1.75,-5.25\n\ 32,Epsilon Ursae Majoris,Alioth,12,54,56,1.77,-0.2\n\ 33,Alpha Persei,Mirfak,3,24,49.9,1.8,-4.49\n\ 34,Alpha Ursae Majoris,Dubhe,11,4,61.8,1.8,-1.09\n\ 35,Gamma Velorum,Regor,8,10,-47.3,1.81,-5.25\n\ 36,Delta Canis Majoris,Wezen,7,8,-26.4,1.83,-6.87\n\ 37,Epsilon Sagittarii,Kaus Australis,18,24,-34.4,1.84,-1.39\n\ 38,Eta Ursae Majoris,Alkaid,13,48,49.3,1.86,-0.59\n\ 39,Theta Scorpii,Sargas,17,37,-43,1.86,-2.75\n\ 40,Epsilon Carinae,Avior,8,23,-59.5,1.87,-4.57\n\ 41,Beta Aurigae,Menkalinan,6,0,44.9,1.9,-0.1\n\ 42,Alpha Trianguli Australis,Atria,16,49,-69,1.92,-3.61\n\ 43,Gamma Geminorum,Alhena,6,38,16.4,1.93,-0.6\n\ 44,Alpha Pavonis,Peacock,20,26,-56.7,1.93,-1.82\n\ 45,Delta Velorum,Koo She,8,45,-54.7,1.95,0.01\n\ 46,Beta Canis Majoris,Mirzam,6,23,-18,1.98,-3.95\n\ 47,Alpha Hydrae,Alphard,9,28,-8.7,1.98,-1.7\n\ 48,Alpha Ursae Minoris,Polaris,2,32,89.3,1.99,-3.62\n\ 49,Gamma Leonis,Algieba,10,20,19.8,2,-0.93\n\ 50,Alpha Arietis,Hamal,2,7,23.5,2.01,0.48\n\ 51,Beta Ceti,Diphda,0,44,-18,2.04,-0.3\n\ 52,Sigma Sagittarii,Nunki,18,55,-26.3,2.05,-2.14\n\ 53,Theta Centauri,Menkent,14,7,-36.4,2.06,0.7\n\ 54,Alpha Andromedae,Alpheratz,0,8,29.1,2.07,-0.3\n\ 55,Beta Andromedae,Mirach,1,10,35.6,2.07,-1.86\n\ 56,Kappa Orionis,Saiph,5,48,-9.7,2.07,-4.65\n\ 57,Beta Ursae Minoris,Kochab,14,51,74.2,2.07,-0.87\n\ 58,Beta Gruis,Al Dhanab,22,43,-46.9,2.07,-1.52\n\ 59,Alpha Ophiuchi,Rasalhague,17,35,12.6,2.08,1.3\n\ 60,Beta Persei,Algol,3,8,41,2.09,-0.18\n\ 61,Gamma Andromedae,Almach,2,4,42.3,2.1,-3.08\n\ 62,Beta Leonis,Denebola,11,49,14.6,2.14,1.92\n\ 63,Gamma Cassiopeiae,Cih,0,57,60.7,2.15,-4.22\n\ 64,Gamma Centauri,Muhlifain,12,42,-49,2.2,-0.81\n\ 65,Zeta Puppis,Naos,8,4,-40,2.21,-5.95\n\ 66,Iota Carinae,Aspidiske,9,17,-59.3,2.21,-4.42\n\ 67,Alpha Coronae Borealis,Alphecca,15,35,26.7,2.22,0.42\n\ 68,Lambda Velorum,Suhail,9,8,-43.4,2.23,-3.99\n\ 69,Zeta Ursae Majoris,Mizar,13,24,54.9,2.23,0.33\n\ 70,Gamma Cygni,Sadr,20,22,40.3,2.23,-6.12\n\ 71,Alpha Cassiopeiae,Schedar,0,41,56.5,2.24,-1.99\n\ 72,Gamma Draconis,Eltanin,17,57,51.5,2.24,-1.04\n\ 73,Delta Orionis,Mintaka,5,32,-0.3,2.25,-4.99\n\ 74,Beta Cassiopeiae,Caph,0,9,59.2,2.28,1.17\n\ 75,Epsilon Centauri,,13,40,-53.5,2.29,-3.02\n\ 76,Delta Scorpii,Dschubba,16,0,-22.6,2.29,-3.16\n\ 77,Epsilon Scorpii,Wei,16,50,-34.3,2.29,0.78\n\ 78,Alpha Lupi,Men,14,42,-47.4,2.3,-3.83\n\ 79,Eta Centauri,,14,36,-42.2,2.33,-2.55\n\ 80,Beta Ursae Majoris,Merak,11,2,56.4,2.34,0.41\n\ 81,Epsilon Boötis,Izar,14,45,27.1,2.35,-1.69\n\ 82,Epsilon Pegasi,Enif,21,44,9.9,2.38,-4.19\n\ 83,Kappa Scorpii,Girtab,17,42,-39,2.39,-3.38\n\ 84,Alpha Phoenicis,Ankaa,0,26,-42.3,2.4,0.52\n\ 85,Gamma Ursae Majoris,Phecda,11,54,53.7,2.41,0.36\n\ 86,Eta Ophiuchi,Sabik,17,10,-15.7,2.43,0.37\n\ 87,Beta Pegasi,Scheat,23,4,28.1,2.44,-1.49\n\ 88,Eta Canis Majoris,Aludra,7,24,-29.3,2.45,-7.51\n\ 89,Alpha Cephei,Alderamin,21,19,62.6,2.45,1.58\n\ 90,Kappa Velorum,Markeb,9,22,-55,2.47,-3.62\n\ 91,Epsilon Cygni,Gienah,20,46,34,2.48,0.76\n\ 92,Alpha Pegasi,Markab,23,5,15.2,2.49,-0.67\n\ 93,Alpha Ceti,Menkar,3,2,4.1,2.54,-1.61\n\ 94,Zeta Ophiuchi,Han,16,37,-10.6,2.54,-3.2\n\ 95,Zeta Centauri,Al Nair al Kent.,13,56,-47.3,2.55,-2.81\n\ 96,Delta Leonis,Zosma,11,14,20.5,2.56,1.32\n\ 97,Beta Scorpii,Graffias,16,5,-19.8,2.56,-3.5\n\ 98,Alpha Leporis,Arneb,5,33,-17.8,2.58,-5.4\n\ 99,Delta Centauri,,12,8,-50.7,2.58,-2.84\n\ 100,Gamma Corvi,Gienah Ghurab,12,16,-17.5,2.58,-0.94\n\ 101,Zeta Sagittarii,Ascella,19,3,-29.9,2.6,0.42\n\ 102,Beta Librae,Zubeneschamali,15,17,-9.4,2.61,-0.84\n\ 103,Alpha Serpentis,Unukalhai,15,44,6.4,2.63,0.87\n\ 104,Beta Arietis,Sheratan,1,55,20.8,2.64,1.33\n\ 105,Alpha Librae,Zubenelgenubi,14,51,-16,2.64,0.77\n\ 106,Alpha Columbae,Phact,5,40,-34.1,2.65,-1.93\n\ 107,Theta Aurigae,,6,0,37.2,2.65,-0.98\n\ 108,Beta Corvi,Kraz,12,34,-23.4,2.65,-0.51\n\ 109,Delta Cassiopeiae,Ruchbah,1,26,60.2,2.66,0.24\n\ 110,Eta Boötis,Muphrid,13,55,18.4,2.68,2.41\n\ 111,Beta Lupi,Ke Kouan,14,59,-43.1,2.68,-3.35\n\ 112,Iota Aurigae,Hassaleh,4,57,33.2,2.69,-3.29\n\ 113,Mu Velorum,,10,47,-49.4,2.69,-0.06\n\ 114,Alpha Muscae,,12,37,-69.1,2.69,-2.17\n\ 115,Upsilon Scorpii,Lesath,17,31,-37.3,2.7,-3.31\n\ 116,Pi Puppis,,7,17,-37.1,2.71,-4.92\n\ 117,Delta Sagittarii,Kaus Meridionalis,18,21,-29.8,2.72,-2.14\n\ 118,Gamma Aquilae,Tarazed,19,46,10.6,2.72,-3.03\n\ 119,Delta Ophiuchi,Yed Prior,16,14,-3.7,2.73,-0.86\n\ 120,Eta Draconis,Aldhibain,16,24,61.5,2.73,0.58\n\ 121,Theta Carinae,,10,43,-64.4,2.74,-2.91\n\ 122,Gamma Virginis,Porrima,12,42,-1.5,2.74,2.38\n\ 123,Iota Orionis,Hatysa,5,35,-5.9,2.75,-5.3\n\ 124,Iota Centauri,,13,21,-36.7,2.75,1.48\n\ 125,Beta Ophiuchi,Cebalrai,17,43,4.6,2.76,0.76\n\ 126,Beta Eridani,Kursa,5,8,-5.1,2.78,0.6\n\ 127,Beta Herculis,Kornephoros,16,30,21.5,2.78,-0.5\n\ 128,Delta Crucis,,12,15,-58.7,2.79,-2.45\n\ 129,Beta Draconis,Rastaban,17,30,52.3,2.79,-2.43\n\ 130,Alpha Canum Venaticorum,Cor Caroli,12,56,38.3,2.8,0.16\n\ 131,Gamma Lupi,,15,35,-41.2,2.8,3.4\n\ 132,Beta Leporis,Nihal,5,28,-20.8,2.81,-0.63\n\ 133,Zeta Herculis,Rutilicus,16,41,31.6,2.81,2.64\n\ 134,Beta Hydri,,0,26,-77.3,2.82,3.45\n\ 135,Tau Scorpii,,16,36,-28.2,2.82,-2.78\n\ 136,Lambda Sagittarii,Kaus Borealis,18,28,-25.4,2.82,0.95\n\ 137,Gamma Pegasi,Algenib,0,13,15.2,2.83,-2.22\n\ 138,Rho Puppis,Turais,8,8,-24.3,2.83,1.41\n\ 139,Beta TrianguliAustralis,,15,55,-63.4,2.83,2.38\n\ 140,Zeta Persei,,3,54,31.9,2.84,-4.55\n\ 141,Beta Arae,,17,25,-55.5,2.84,-3.49\n\ 142,Alpha Arae,Choo,17,32,-49.9,2.84,-1.51\n\ 143,Eta Tauri,Alcyone,3,47,24.1,2.85,-2.41\n\ 144,Epsilon Virginis,Vindemiatrix,13,2,11,2.85,0.37\n\ 145,Delta Capricorni,Deneb Algedi,21,47,-16.1,2.85,2.49\n\ 146,Alpha Hydri,Head of Hydrus,1,59,-61.6,2.86,1.16\n\ 147,Delta Cygni,,19,45,45.1,2.86,-0.74\n\ 148,Mu Geminorum,Tejat,6,23,22.5,2.87,-1.39\n\ 149,Gamma Trianguli Australis,,15,19,-68.7,2.87,-0.87\n\ 150,Alpha Tucanae,,22,19,-60.3,2.87,-1.05\n\ 151,Theta Eridani,Acamar,2,58,-40.3,2.88,-0.59\n\ 152,Pi Sagittarii,Albaldah,19,10,-21,2.88,-2.77\n\ 153,Beta Canis Minoris,Gomeisa,7,27,8.3,2.89,-0.7\n\ 154,Pi Scorpii,,15,59,-26.1,2.89,-2.85\n\ 155,Epsilon Persei,,3,58,40,2.9,-3.19\n\ 156,Sigma Scorpii,Alniyat,16,21,-25.6,2.9,-3.86\n\ 157,Beta Cygni,Albireo,19,31,28,2.9,-2.31\n\ 158,Beta Aquarii,Sadalsuud,21,32,-5.6,2.9,-3.47\n\ 159,Gamma Persei,,3,5,53.5,2.91,-1.57\n\ 160,Upsilon Carinae,,9,47,-65.1,2.92,-5.56\n\ 161,Eta Pegasi,Matar,22,43,30.2,2.93,-1.16\n\ 162,Tau Puppis,,6,50,-50.6,2.94,-0.8\n\ 163,Delta Corvi,Algorel,12,30,-16.5,2.94,0.79\n\ 164,Alpha Aquarii,Sadalmelik,22,6,-0.3,2.95,-3.88\n\ 165,Gamma Eridani,Zaurak,3,58,-13.5,2.97,-1.19\n\ 166,Zeta Tauri,Alheka,5,38,21.1,2.97,-2.56\n\ 167,Epsilon Leonis,Ras Elased Austr.,9,46,23.8,2.97,-1.46\n\ 168,Gamma² Sagittarii,Alnasl,18,6,-30.4,2.98,0.63\n\ 169,Gamma Hydrae,,13,19,-23.2,2.99,-0.05\n\ 170,Iota¹ Scorpii,,17,48,-40.1,2.99,-5.71\n\ 171,Zeta Aquilae,Deneb el Okab,19,5,13.9,2.99,0.96\n\ 172,Beta Trianguli,,2,10,35,3,0.09\n\ 173,Psi Ursae Majoris,,11,10,44.5,3,-0.27\n\ 174,Gamma Ursae Minoris,Pherkad Major,15,21,71.8,3,-2.84\n\ 175,Mu¹ Scorpii,,16,52,-38,3,-4.01\n\ 176,Gamma Gruis,,21,54,-37.4,3,-0.97\n\ 177,Delta Persei,,3,43,47.8,3.01,-3.04\n\ 178,Zeta Canis Majoris,Phurad,6,20,-30.1,3.02,-2.05\n\ 179,Omicron² Canis Majoris,,7,3,-23.8,3.02,-6.46\n\ 180,Epsilon Corvi,Minkar,12,10,-22.6,3.02,-1.82\n\ 181,Epsilon Aurigae,Almaaz,5,2,43.8,3.03,-5.95\n\ 182,Beta Muscae,,12,46,-68.1,3.04,-1.86\n\ 183,Gamma Boötis,Seginus,14,32,38.3,3.04,0.96\n\ 184,Beta Capricorni,Dabih,20,21,-14.8,3.05,-2.07\n\ 185,Epsilon Geminorum,Mebsuta,6,44,25.1,3.06,-4.15\n\ 186,Mu Ursae Majoris,Tania Australis,10,22,41.5,3.06,-1.35\n\ 187,Delta Draconis,Tais,19,13,67.7,3.07,0.63\n\ 188,Eta Sagittarii,,18,18,-36.8,3.1,-0.2\n\ 189,Zeta Hydrae,,8,55,5.9,3.11,-0.21\n\ 190,Nu Hydrae,,10,50,-16.2,3.11,-0.03\n\ 191,Lambda Centauri,,11,36,-63,3.11,-2.39\n\ 192,Alpha Indi,Persian,20,38,-47.3,3.11,0.65\n\ 193,Beta Columbae,Wazn,5,51,-35.8,3.12,1.02\n\ 194,I<NAME>,Talita,8,59,48,3.12,2.29\n\ 195,Zeta Arae,,16,59,-56,3.12,-3.11\n\ 196,Delta Herculis,Sarin,17,15,24.8,3.12,1.21\n\ 197,Kappa Centauri,Ke Kwan,14,59,-42.1,3.13,-2.96\n\ 198,Alpha Lyncis,,9,21,34.4,3.14,-1.02\n\ 199,N Velorum,,9,31,-57,3.16,-1.15\n\ 200,Pi Herculis,,17,15,36.8,3.16,-2.1\n\ 201,Nu Puppis,,6,38,-43.2,3.17,-2.39\n\ 202,Theta Ursae Majoris,Al Haud,9,33,51.7,3.17,2.52\n\ 203,Zeta Draconis,Aldhibah,17,9,65.7,3.17,-1.92\n\ 204,Phi Sagittarii,,18,46,-27,3.17,-1.08\n\ 205,Eta Aurigae,Hoedus II,5,7,41.2,3.18,-0.96\n\ 206,Alpha Circini,,14,43,-65,3.18,2.11\n\ 207,Pi³ Orionis,Tabit,4,50,7,3.19,3.67\n\ 208,Epsilon Leporis,,5,5,-22.4,3.19,-1.02\n\ 209,Kappa Ophiuchi,,16,58,9.4,3.19,1.09\n\ 210,G Scorpii,,17,50,-37,3.19,0.24\n\ 211,Zeta Cygni,,21,13,30.2,3.21,-0.12\n\ 212,Gamma Cephei,Errai,23,39,77.6,3.21,2.51\n\ 213,Delta Lupi,,15,21,-40.6,3.22,-2.75\n\ 214,Epsilon Ophiuchi,Yed Posterior,16,18,-4.7,3.23,0.64\n\ 215,Eta Serpentis,Alava,18,21,-2.9,3.23,1.84\n\ 216,Beta Cephei,Alphirk,21,29,70.6,3.23,-3.08\n\ 217,Alpha Pictoris,,6,48,-61.9,3.24,0.83\n\ 218,Theta Aquilae,,20,11,-0.8,3.24,-1.48\n\ 219,Sigma Puppis,,7,29,-43.3,3.25,-0.51\n\ 220,Pi Hydrae,,14,6,-26.7,3.25,0.79\n\ 221,Sigma Librae,Brachium,15,4,-25.3,3.25,-1.51\n\ 222,Gamma Lyrae,Sulaphat,18,59,32.7,3.25,-3.2\n\ 223,Gamma Hydri,,3,47,-74.2,3.26,-0.83\n\ 224,Delta Andromedae,,0,39,30.9,3.27,0.81\n\ 225,Theta Ophiuchi,,17,22,-25,3.27,-2.92\n\ 226,Delta Aquarii,Skat,22,55,-15.8,3.27,-0.18\n\ 227,Mu Leporis,,5,13,-16.2,3.29,-0.47\n\ 228,Omega Carinae,,10,14,-70,3.29,-1.99\n\ 229,Iota Draconis,Edasich,15,25,59,3.29,0.81\n\ 230,Alpha Doradus,,4,34,-55,3.3,-0.36\n\ 231,p Carinae,,10,32,-61.7,3.3,-2.62\n\ 232,Mu Centauri,,13,50,-42.5,3.3,-2.74\n\ 233,Eta Geminorum,Propus,6,15,22.5,3.31,-1.84\n\ 234,Alpha Herculis,Rasalgethi,17,15,14.4,3.31,-2.04\n\ 235,Gamma Arae,,17,25,-56.4,3.31,-4.4\n\ 236,Beta Phoenicis,,1,6,-46.7,3.32,-0.55\n\ 237,Rho Persei,Gorgonea Tertia,3,5,38.8,3.32,-1.67\n\ 238,Delta Ursae Majoris,Megrez,12,15,57,3.32,1.33\n\ 239,Eta Scorpii,,17,12,-43.2,3.32,1.61\n\ 240,Nu Ophiuchi,,17,59,-9.8,3.32,-0.03\n\ 241,Tau Sagittarii,,19,7,-27.7,3.32,0.48\n\ 242,Alpha Reticuli,,4,14,-62.5,3.33,-0.17\n\ 243,Theta Leonis,Chort,11,14,15.4,3.33,-0.35\n\ 244,Xi Puppis,Asmidiske,7,49,-24.9,3.34,-4.74\n\ 245,Epsilon Cassiopeiae,Segin,1,54,63.7,3.35,-2.31\n\ 246,Eta Orionis,Algjebbah,5,24,-2.4,3.35,-3.86\n\ 247,Xi Geminorum,Alzirr,6,45,12.9,3.35,2.13\n\ 248,Omicron Ursae Majoris,Muscida,8,30,60.7,3.35,-0.4\n\ 249,Delta Aquilae,,19,25,3.1,3.36,2.43\n\ 250,Epsilon Lupi,,15,23,-44.7,3.37,-2.58\n\ 251,Zeta Virginis,Heze,13,35,-0.6,3.38,1.62\n\ 252,Epsilon Hydrae,,8,47,6.4,3.38,0.29\n\ 253,Lambda Orionis,Meissa,5,35,9.9,3.39,-4.16\n\ 254,q Carinae,,10,17,-61.3,3.39,-3.38\n\ 255,Delta Virginis,Auva,12,56,3.4,3.39,-0.57\n\ 256,Zeta Cephei,,22,11,58.2,3.39,-3.35\n\ 257,Theta² Tauri,,4,29,15.9,3.4,0.1\n\ 258,Gamma Phoenicis,,1,28,-43.3,3.41,-0.87\n\ 259,Lambda Tauri,,4,1,12.5,3.41,-1.87\n\ 260,Nu Centauri,,13,50,-41.7,3.41,-2.41\n\ 261,Zeta Lupi,,15,12,-52.1,3.41,0.65\n\ 262,Eta Cephei,,20,45,61.8,3.41,2.63\n\ 263,Zeta Pegasi,Homam,22,41,10.8,3.41,-0.62\n\ 264,Alpha Trianguli,Mothallah,1,53,29.6,3.42,1.95\n\ 265,Eta Lupi,,16,0,-38.4,3.42,-2.48\n\ 266,Mu Herculis,,17,46,27.7,3.42,3.8\n\ 267,Beta Pavonis,,20,45,-66.2,3.42,0.29\n\ 268,a Carinae,,9,11,-58.9,3.43,-2.11\n\ 269,Zeta Leonis,Adhafera,10,17,23.4,3.43,-1.08\n\ 270,Lambda Aquilae,Althalimain,19,6,-4.9,3.43,0.51\n\ 271,Lambda Ursae Majoris,Tania Borealis,10,17,42.9,3.45,0.38\n\ 272,Beta Lyrae,Sheliak,18,50,33.4,3.45,-3.71\n\ 273,Eta Cassiopeiae,Achird,0,49,57.8,3.46,4.59\n\ 274,Eta Ceti,Dheneb,1,9,-10.2,3.46,0.67\n\ 275,Chi Carinae,,7,57,-53,3.46,-1.91\n\ 276,Delta Bootis,,15,16,33.3,3.46,0.69\n\ 277,Gamma Ceti,Kaffaljidhma,2,43,3.2,3.47,1.47\n\ 278,Eta Leonis,,10,7,16.8,3.48,-5.6\n\ 279,Eta Herculis,,16,43,38.9,3.48,0.8\n\ 280,Tau Ceti,,1,44,-15.9,3.49,5.68\n\ 281,Sigma Canis Majoris,,7,2,-27.9,3.49,-4.37\n\ 282,Nu Ursae Majoris,Alula Borealis,11,18,33.1,3.49,-2.07\n\ 283,Beta Bootis,Nekkar,15,2,40.4,3.49,-0.64\n\ 284,Alpha Telescopii,,18,27,-46,3.49,-0.93\n\ 285,Epsilon Gruis,,22,49,-51.3,3.49,0.49\n\ 286,Kappa Canis Majoris,,6,50,-32.5,3.5,-3.42\n\ 287,Delta Geminorum,Wasat,7,20,22,3.5,2.22\n\ 288,Iota Cephei,,22,50,66.2,3.5,0.76\n\ 289,Gamma Sagittae,,19,59,19.5,3.51,-1.11\n\ 290,Mu Pegasi,Sadalbari,22,50,24.6,3.51,0.74\n\ 291,Delta Eridani,Rana,3,43,-9.8,3.52,3.74\n\ 292,Omicron Leonis,Subra,9,41,9.9,3.52,0.43\n\ 293,Phi Velorum,Tseen Ke,9,57,-54.6,3.52,-5.34\n\ 294,Xi² Sagittarii,,18,58,-21.1,3.52,-1.77\n\ 295,Theta Pegasi,Baham,22,10,6.2,3.52,1.16\n\ 296,Epsilon Tauri,Ain,4,29,19.2,3.53,0.15\n\ 297,Beta Cancri,Tarf,8,17,9.2,3.53,-1.24\n\ 298,Xi Hydrae,,11,33,-31.9,3.54,0.55\n\ 299,Mu Serpentis,,15,50,-3.4,3.54,0.14\n\ 300,Xi Serpentis,,17,38,-15.4,3.54,0.99" export default stars;
05599a7f39e61af3ed5f4c9e4f8b8b0ca74ccca7
[ "JavaScript" ]
7
JavaScript
abdelrahim-hentabli/Skychart.js
2354635bc596c3ecb8200eeb9caaa217bf655e3e
b03bdcff7465aa03d5424bb70d58532545d8a241
refs/heads/master
<file_sep> #include <thread> #include <ros/ros.h> #include <nodelet/nodelet.h> #include <image_transport/image_transport.h> #include <sensor_msgs/image_encodings.h> #include <gst/gst.h> #include <gst/app/app.h> namespace gst_video_server { namespace enc = sensor_msgs::image_encodings; GstClockTime operator "" _sec (unsigned long long sec) { return sec * GST_SECOND; } GstClockTime operator "" _ms (unsigned long long millisec) { return millisec * GST_MSECOND; } /** * Video server nodelet class */ class GstVideoServerNodelet : public nodelet::Nodelet { public: GstVideoServerNodelet(); ~GstVideoServerNodelet(); virtual void onInit(); private: std::unique_ptr<image_transport::ImageTransport> image_transport_; image_transport::Subscriber image_sub_; //! GStreamer pipeline string std::string gsconfig_; //! Restart counter size_t restart_counter_; static constexpr size_t RESTART_LIM = 5; //! event loop, needed for gstreamer callbacks GMainLoop *loop_; std::thread loop_thread_; //! GStreamer pipeline GstElement *pipeline_; GstElement *appsrc_; guint bus_watch_id_; //! create and initialize pipeline object bool configure_pipeline(); //! create GstCaps for sensor_msgs::Image GstCaps* gst_caps_new_from_image(const sensor_msgs::Image::ConstPtr &msg); //! calculate gst time from image stamp //GstClockTime gst_time_from_stamp(const ros::Time &stamp); //! create GstSample from sendor_msgs::Image GstSample* gst_sample_new_from_image(const sensor_msgs::Image::ConstPtr &msg); //! image_raw topic callback void image_cb(const sensor_msgs::Image::ConstPtr &msg); //! gstreamer error printer static gboolean bus_message_cb_wrapper(GstBus *bus, GstMessage *message, gpointer data); gboolean bus_message_cb(GstBus *bus, GstMessage *message); }; GstVideoServerNodelet::GstVideoServerNodelet() : nodelet::Nodelet(), pipeline_(nullptr), appsrc_(nullptr), bus_watch_id_(0), loop_(nullptr), restart_counter_(0) { } GstVideoServerNodelet::~GstVideoServerNodelet() { NODELET_INFO("Terminating gst_video_server..."); // pipeline bin manage appsrc deletion if (pipeline_ != nullptr) { gst_app_src_end_of_stream(GST_APP_SRC_CAST(appsrc_)); gst_element_set_state(pipeline_, GST_STATE_NULL); gst_object_unref(GST_OBJECT(pipeline_)); pipeline_ = nullptr; appsrc_ = nullptr; } // but if pipeline not created appsrc will be deleted here if (appsrc_ != nullptr) { gst_object_unref(GST_OBJECT(appsrc_)); appsrc_ = nullptr; } if (loop_ != nullptr) { g_main_loop_quit(loop_); if (loop_thread_.joinable()) loop_thread_.join(); } } void GstVideoServerNodelet::onInit() { NODELET_INFO("Starting gst_video_server instance: %s", getName().c_str()); // init image transport ros::NodeHandle &nh = getNodeHandle(); ros::NodeHandle &priv_nh = getPrivateNodeHandle(); image_transport_.reset(new image_transport::ImageTransport(nh)); // load configuration if (!priv_nh.getParam("pipeline", gsconfig_)) { NODELET_WARN("No pipeline configuration found! Used default testing bin."); gsconfig_ = "autovideoconvert ! autovideosink"; } // create and run main event loop loop_ = g_main_loop_new(nullptr, FALSE); g_assert(loop_); loop_thread_ = std::thread( [&]() { NODELET_DEBUG("GMainLoop started."); // blocking g_main_loop_run(loop_); // terminated! g_main_loop_unref(loop_); loop_ = nullptr; NODELET_INFO("GMainLoop terminated."); }); // NOTE(vooon): may cause a problem on non Linux, but i'm not care. pthread_setname_np(loop_thread_.native_handle(), "g_main_loop_run"); // configure pipeline configure_pipeline(); // finally: subscribe image_sub_ = image_transport_->subscribe("image_raw", 10, &GstVideoServerNodelet::image_cb, this); } bool GstVideoServerNodelet::configure_pipeline() { if (!gst_is_initialized()) { NODELET_DEBUG("Initializing gstreamer"); gst_init(nullptr, nullptr); } NODELET_INFO("Gstreamer version: %s", gst_version_string()); NODELET_INFO("Pipeline: %s", gsconfig_.c_str()); GError *error = nullptr; pipeline_ = gst_parse_launch(gsconfig_.c_str(), &error); if (pipeline_ == nullptr) { NODELET_ERROR("GST: %s", error->message); g_error_free(error); return false; } appsrc_ = gst_element_factory_make("appsrc", "source"); if (appsrc_ == nullptr) { NODELET_ERROR("GST: failed to create appsrc!"); return false; } gst_app_src_set_stream_type(GST_APP_SRC_CAST(appsrc_), GST_APP_STREAM_TYPE_STREAM); gst_app_src_set_latency(GST_APP_SRC_CAST(appsrc_), 0, -1); g_object_set(GST_OBJECT(appsrc_), "format", GST_FORMAT_TIME, "is-live", true, "max-bytes", 0, "do-timestamp", true, NULL); // gst_parse_launch() may produce not a pipeline // thanks to gscam for example if (GST_IS_PIPELINE(pipeline_)) { // find pipeline sink (where we may link appsrc) GstPad *inpad = gst_bin_find_unlinked_pad(GST_BIN(pipeline_), GST_PAD_SINK); g_assert(inpad); GstElement *inelement = gst_pad_get_parent_element(inpad); g_assert(inelement); gst_object_unref(GST_OBJECT(inpad)); NODELET_DEBUG("GST: inelement: %s", gst_element_get_name(inelement)); if (!gst_bin_add(GST_BIN(pipeline_), appsrc_)) { NODELET_ERROR("GST: gst_bin_add() failed!"); gst_object_unref(GST_OBJECT(pipeline_)); gst_object_unref(GST_OBJECT(inelement)); return false; } if (!gst_element_link(appsrc_, inelement)) { NODELET_ERROR("GST: cannot link %s -> %s", gst_element_get_name(appsrc_), gst_element_get_name(inelement)); gst_object_unref(GST_OBJECT(pipeline_)); gst_object_unref(GST_OBJECT(inelement)); return false; } gst_object_unref(GST_OBJECT(inelement)); } else { // we have one sink element, create bin and link it. GstElement *launchpipe = pipeline_; pipeline_ = gst_pipeline_new(nullptr); g_assert(pipeline_); gst_object_unparent(GST_OBJECT(launchpipe)); NODELET_DEBUG("GST: launchpipe: %s", gst_element_get_name(launchpipe)); gst_bin_add_many(GST_BIN(pipeline_), appsrc_, launchpipe, nullptr); if (!gst_element_link(appsrc_, launchpipe)) { NODELET_ERROR("GST: cannot link %s -> %s", gst_element_get_name(appsrc_), gst_element_get_name(launchpipe)); gst_object_unref(GST_OBJECT(pipeline_)); return false; } } // Register bus watch callback. auto bus = gst_element_get_bus(pipeline_); bus_watch_id_ = gst_bus_add_watch(bus, &GstVideoServerNodelet::bus_message_cb_wrapper, this); gst_object_unref(GST_OBJECT(bus)); // pause pipeline gst_element_set_state(pipeline_, GST_STATE_PAUSED); if (gst_element_get_state(pipeline_, nullptr, nullptr, 1_sec) == GST_STATE_CHANGE_FAILURE) { NODELET_ERROR("GST: state change error. Check your pipeline."); return false; } else { NODELET_INFO("GST: pipeline paused."); } return true; } GstCaps* GstVideoServerNodelet::gst_caps_new_from_image(const sensor_msgs::Image::ConstPtr &msg) { // http://gstreamer.freedesktop.org/data/doc/gstreamer/head/pwg/html/section-types-definitions.html static const ros::M_string known_formats = {{ {enc::RGB8, "RGB"}, {enc::RGB16, "RGB16"}, {enc::RGBA8, "RGBA"}, {enc::RGBA16, "RGBA16"}, {enc::BGR8, "BGR"}, {enc::BGR16, "BGR16"}, {enc::BGRA8, "BGRA"}, {enc::BGRA16, "BGRA16"}, {enc::MONO8, "GRAY8"}, {enc::MONO16, "GRAY16_LE"}, }}; if (msg->is_bigendian) { NODELET_ERROR("GST: big endian image format is not supported"); return nullptr; } auto format = known_formats.find(msg->encoding); if (format == known_formats.end()) { NODELET_ERROR("GST: image format '%s' unknown", msg->encoding.c_str()); return nullptr; } return gst_caps_new_simple("video/x-raw", "format", G_TYPE_STRING, format->second.c_str(), "width", G_TYPE_INT, msg->width, "height", G_TYPE_INT, msg->height, "framerate", GST_TYPE_FRACTION, 0, 1, // 0/1 = dynamic nullptr); } #if 0 GstClockTime GstVideoServerNodelet::gst_time_from_stamp(const ros::Time &stamp) { #if 1 // 3. use pipeline time. g_assert(pipeline_); auto clock = gst_pipeline_get_pipeline_clock(GST_PIPELINE(pipeline_)); auto ct = gst_clock_get_time(clock); gst_object_unref(GST_OBJECT(clock)); return ct; #else static GstClockTime ct_prev = 0; GstClockTime ct = ct_prev; ct_prev += gst_util_uint64_scale_int(1, GST_SECOND, 40); return ct; #endif } #endif GstSample* GstVideoServerNodelet::gst_sample_new_from_image(const sensor_msgs::Image::ConstPtr &msg) { // unfortunately we may not move image data because it is immutable. copying. auto buffer = gst_buffer_new_allocate(nullptr, msg->data.size(), nullptr); g_assert(buffer); /* NOTE(vooon): * I found that best is to use `do-timestamp=true` parameter * and forgot about stamping stamp problem (PTS). */ //auto ts = gst_time_from_stamp(msg->header.stamp); //NODELET_INFO("TS: %lld, %lld", ts, gst_util_uint64_scale_int(1, GST_SECOND, 40)); gst_buffer_fill(buffer, 0, msg->data.data(), msg->data.size()); GST_BUFFER_FLAG_SET(buffer, GST_BUFFER_FLAG_LIVE); //GST_BUFFER_PTS(buffer) = ts; auto caps = gst_caps_new_from_image(msg); if (caps == nullptr) { gst_object_unref(GST_OBJECT(buffer)); return nullptr; } auto sample = gst_sample_new(buffer, caps, nullptr, nullptr); gst_buffer_unref(buffer); gst_caps_unref(caps); return sample; } void GstVideoServerNodelet::image_cb(const sensor_msgs::Image::ConstPtr &msg) { NODELET_DEBUG("Image: %d x %d, stamp %f", msg->width, msg->height, msg->header.stamp.toSec()); GstState state, next_state; auto state_change = gst_element_get_state(pipeline_, &state, &next_state, 1_ms); if (state_change == GST_STATE_CHANGE_ASYNC) { NODELET_INFO_THROTTLE(5, "GST: pipeline changing state..."); } else if (state_change == GST_STATE_CHANGE_FAILURE) { if (restart_counter_++ < RESTART_LIM) { NODELET_WARN("GST: pipeline state change failure. will retry..."); gst_element_set_state(pipeline_, GST_STATE_NULL); return; } else { NODELET_ERROR("GST: pipeline restart limit reached. terminating."); ros::shutdown(); } } // pipeline not yet playing, configure and start if (state != GST_STATE_PLAYING && next_state != GST_STATE_PLAYING) { auto caps = gst_caps_new_from_image(msg); auto capsstr = gst_caps_to_string(caps); // really not needed because GstSample may change that anyway gst_app_src_set_caps(GST_APP_SRC_CAST(appsrc_), caps); NODELET_INFO("GST: appsrc caps: %s", capsstr); gst_caps_unref(caps); g_free(capsstr); gst_element_set_state(pipeline_, GST_STATE_PLAYING); } auto sample = gst_sample_new_from_image(msg); if (sample == nullptr) return; #if GST_CHECK_VERSION(1, 5, 0) auto push_ret = gst_app_src_push_sample(GST_APP_SRC_CAST(appsrc_), sample); #else // NOTE: that function does not increase ref count // manual ref prevent problem with bush_buffer auto buffer = gst_sample_get_buffer(sample); g_assert(buffer); gst_buffer_ref(buffer); auto caps = gst_sample_get_caps(sample); gst_app_src_set_caps(GST_APP_SRC_CAST(appsrc_), caps); // that function steal buffer, so ref count should be 2 (sample + buffer) auto push_ret = gst_app_src_push_buffer(GST_APP_SRC_CAST(appsrc_), buffer); #endif gst_sample_unref(sample); // TODO(vooon): check push_ret value! if (push_ret == GST_FLOW_OK && state == GST_STATE_PLAYING) { // reset counter restart_counter_ = 0; } } gboolean GstVideoServerNodelet::bus_message_cb_wrapper(GstBus *bus, GstMessage *message, gpointer data) { auto self = static_cast<GstVideoServerNodelet*>(data); g_assert(self); return self->bus_message_cb(bus, message); } gboolean GstVideoServerNodelet::bus_message_cb(GstBus *bus, GstMessage *message) { gchar *debug = nullptr; GError *error = nullptr; switch (GST_MESSAGE_TYPE(message)) { case GST_MESSAGE_ERROR: { gst_message_parse_error(message, &error, &debug); NODELET_ERROR("GST: bus: %s", error->message); if (debug != nullptr) NODELET_ERROR("GST: debug: %s", debug); // ->DEBUG break; } case GST_MESSAGE_WARNING: { gst_message_parse_warning(message, &error, &debug); NODELET_WARN("GST: bus: %s", error->message); if (debug != nullptr) NODELET_WARN("GST: debug: %s", debug); break; } case GST_MESSAGE_INFO: { gst_message_parse_info(message, &error, &debug); NODELET_INFO("GST: bus: %s", error->message); if (debug != nullptr) NODELET_INFO("GST: debug: %s", debug); break; } case GST_MESSAGE_EOS: NODELET_ERROR("GST: bus EOS"); // TODO(vooon): self terminate. Error not recoverable. ros::shutdown(); break; default: break; } if (error != nullptr) g_error_free(error); g_free(debug); return TRUE; } }; // namespace gst_video_server // Register nodelet #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(gst_video_server::GstVideoServerNodelet, nodelet::Nodelet); <file_sep># rtp-streamer <file_sep>cmake_minimum_required(VERSION 2.8.3) project(gst_video_server) ## Find catkin macros and libraries find_package(catkin REQUIRED COMPONENTS nodelet image_transport roscpp sensor_msgs std_msgs ) ## GStreamer 1.0 package required find_package(PkgConfig) macro(find_gstreamer_component prefix pkg lib) pkg_check_modules(PC_${prefix} REQUIRED ${pkg}) find_library(${prefix}_LIBRARIES NAMES ${lib} HINTS ${PC_${prefix}_LIBRARY_DIRS} ${PC_${prefix}_LIBDIR}) list(APPEND gstreamer_INCLUDE_DIRS ${PC_${prefix}_INCLUDE_DIRS}) list(APPEND gstreamer_LIBRARIES ${${prefix}_LIBRARIES}) mark_as_advanced(${prefix}_LIBRARIES gstreamer_LIBRARIES gstreamer_INCLUDE_DIRS) endmacro() find_gstreamer_component(gst gstreamer-1.0 gstreamer-1.0) find_gstreamer_component(gstbase gstreamer-base-1.0 gstbase-1.0) find_gstreamer_component(gstapp gstreamer-app-1.0 gstapp-1.0) find_gstreamer_component(gstvideo gstreamer-video-1.0 gstvideo-1.0) #message(STATUS "inc: ${gstreamer_INCLUDE_DIRS}") #message(STATUS "lib: ${gstreamer_LIBRARIES}") # C++11 required! include(CheckCXXCompilerFlag) check_cxx_compiler_flag("-std=c++11" COMPILER_SUPPORTS_STD_CXX11) if (COMPILER_SUPPORTS_STD_CXX11) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") else () message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.") endif () ################################### ## catkin specific configuration ## ################################### ## The catkin_package macro generates cmake config files for your package ## Declare things to be passed to dependent projects ## INCLUDE_DIRS: uncomment this if you package contains header files ## LIBRARIES: libraries you create in this project that dependent projects also need ## CATKIN_DEPENDS: catkin_packages dependent projects also need ## DEPENDS: system dependencies of this project that dependent projects also need catkin_package( # INCLUDE_DIRS include LIBRARIES gstvideoserver CATKIN_DEPENDS nodelet image_transport roscpp sensor_msgs std_msgs DEPENDS libgstreamer1.0-dev ) ########### ## Build ## ########### include_directories( ${catkin_INCLUDE_DIRS} ${gstreamer_INCLUDE_DIRS} ) add_library(gstvideoserver src/server_nodelet.cpp ) target_link_libraries(gstvideoserver ${catkin_LIBRARIES} ${gstreamer_LIBRARIES} ) add_executable(server_node src/node.cpp ) target_link_libraries(server_node ${catkin_LIBRARIES} ) ############# ## Install ## ############# # all install targets should use catkin DESTINATION variables # See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html ## Mark executables and/or libraries for installation install(TARGETS gstvideoserver server_node ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) #install(DIRECTORY include/${PROJECT_NAME}/ # DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} # FILES_MATCHING PATTERN "*.h" #) ## Mark other files for installation (e.g. launch and bag files, etc.) install(FILES nodelet_plugins.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) #install(DIRECTORY launch/ # DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch #) ############# ## Testing ## ############# ## Add gtest based cpp test target and link libraries # catkin_add_gtest(${PROJECT_NAME}-test test/test_rtsp_streamer.cpp) # if(TARGET ${PROJECT_NAME}-test) # target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME}) # endif() ## Add folders to be run by python nosetests # catkin_add_nosetests(test) # vim:set ts=2 sw=2 et : <file_sep> #include <ros/ros.h> #include <nodelet/loader.h> int main(int argc, char **argv) { ros::init(argc, argv, "gst_video"); nodelet::Loader manager(false); nodelet::M_string remappings(ros::names::getRemappings()); nodelet::V_string my_argv; const auto node_name = ros::this_node::getName(); // load server nodelet manager.load(node_name, "gst_video_server/server", remappings, my_argv); // code from bebop_autonomy package const auto loaded_nodelets = manager.listLoadedNodelets(); if (std::find(loaded_nodelets.begin(), loaded_nodelets.end(), node_name) == loaded_nodelets.end()) { ROS_FATAL("Can not load gst_video_server/server nodelet!"); return 1; } ros::spin(); return 0; }
884b8634842c2691e92367cd27d39d11db738aaf
[ "Markdown", "CMake", "C++" ]
4
C++
kuang93/gst_video_server
0eef9857f32b509769f630d78dacc5275e0a2724
1e724421f7eecc6c3d7a3a3f0a4eae0b81647976
refs/heads/master
<file_sep>source 'http://rubygems.org' used_installer = File.exist?("USED_INSTALLER") USING_WINDOWS = !!((RUBY_PLATFORM =~ /(win|w)(32|64)$/) || (RUBY_PLATFORM=~ /mswin|mingw/)) # to avoid bundle install problems in Windows if USING_WINDOWS gem 'eventmachine'#, '1.0.0.beta.4.1' else gem 'spawn', '0.1.4' end gem 'rails', '3.0.19' # NOTE: Shamisen version is defined in lib/version.rb # gem 'rake', '0.9.2.2' # Bundle edge Rails instead: # gem 'rails', :git => 'http://github.com/rails/rails.git' gem 'app', '~> 1.0.3' gem 'ffi', '1.1.1' #NOTE : was 1.1.0, updated to 1.1.1 platforms :jruby do gem 'jdbc-mysql', '5.1.13' gem 'jruby-openssl', '0.7.7' gem 'jruby-rack', '1.1.10' gem 'activerecord-jdbc-adapter', '1.2.2.1', :require => false gem 'rmagick4j', '0.3.7' gem 'warbler', '1.3.6' gem 'jruby-jars', '1.7.0' end platforms :ruby do gem 'thin', '1.4.1' gem 'mysql2', '< 0.3' # gem 'mysql2' # will update with rails 3.1 end gem 'redis-retry', :git => 'http://github.com/ramontayag/redis-retry' # NOTE: temporary requirement until this can be published as a gem gem 'awetest-common', :git => 'https://github.com/3qilabs/awetest-common.git', :branch => 'release-2.0' # :tag => 'v1.18.27' gem 'resque', :git => 'http://github.com/radamanthus/resque.git', :tag => 'v1.19.7' gem 'andand', '1.3.1' gem 'sane', '0.23.5' gem 'haml' gem 'haml-rails' gem 'authlogic', '3.1.0' # gem 'annotate', '2.4.0' # generate/write the table schema in the model files gem "declarative_authorization", '0.5.4' gem 'ar_fixtures', '0.0.4' # so we can do rails g runner "Company.to_fixtures" gem 'random_data', '1.5.2' # for generating random_data like faker gem 'will_paginate', '3.0.2' gem 'inherited_resources', '~> 1.3' # provides common restful actions to our controllers so we don't need to repeat code gem 'render_inheritable', '1.0.0' #gem 'hpricot' # this and ruby_parser only needed for inherited_views generator, uncomment if generating again. gem 'ruby_parser', '2.3.1' gem 'formtastic', '2.0.2' gem 'rails3_acts_as_paranoid', '0.0.9' gem 'wicked_pdf', '~> 0.9.0' gem 'backbone-rails' gem 'userstamp', '2.0.1' gem 'rdoc', '3.11' # gem 'delayed_job' gem 'rufus-scheduler', '2.0.14' gem 'selenium-client', '1.2.18' gem 'selenium-selenese', '1.1.13' gem 'mysql2', '< 0.3' gem 'roo', '1.10.1' gem 'spreadsheet', '0.6.9' gem 'ekuseru', '0.3.10' gem 'google-spreadsheet-ruby', '0.1.6' gem 'rubyzip', '0.9.5' gem 'nokogiri', '1.5.0' gem 'minizip', '0.0.12' gem 'draper', '~> 0.11.1' gem 'parse-cron', '0.1.1', :require => 'cron_parser' gem 'alm-rest-api' gem 'nokogiri-happymapper', :require => 'happymapper' # Rails Gem for providing inline Edit. gem "best_in_place", "~> 0.2.0" if USING_WINDOWS gem 'win32-open3' gem 'sys-uname', '0.8.5' # gem "vapir-ie" gem "watir", '1.8.1' # watirloo is not working - appears not to be used #gem "watirloo", :git => '<EMAIL>:stalcottsmith/watirloo.git' gem "win32-process",'0.6.5' end # Support gems gem "paperclip", '2.8.0' gem "delayed_paperclip", '2.4.5.2' gem "acts_as_versioned", '0.6.0' # for versioning info on models group :assets do gem 'compass', "0.11.5" gem 'compass-960-plugin', "0.10.4" end group :development do gem 'active_reload' gem 'require_relative' gem 'pry' # gem 'capistrano', '2.13.5' # gem 'rvm-capistrano' gem 'ruby-debug' # gem 'ruby-prof', '0.10.7' #NOTE: does not run on Jruby end gem 'faker', '1.0.1' # Put this here for now to stop warbler from complaining group :test do gem 'steak' gem 'chronic' gem 'jasmine' # gem 'autotest-rails' gem 'capybara', '1.1.2' gem 'capybara-firebug' gem 'cucumber-rails' gem 'database_cleaner' gem 'email_spec' gem 'factory_girl_rails', '1.7.0' gem 'faker', '1.0.1' gem 'launchy' gem 'require_relative' gem 'rspec' gem 'rspec-rails' gem 'spork', '0.8.5' gem 'timecop', '0.3.5' gem 'ZenTest', '4.8.1' end # gem 'newrelic_rpm' <file_sep>Windows-Gemfile =============== Ruby on rails Installation on windows... 1. Download Ruby (1.8.7 p370) and install it. 2. Download ruby-devKit, then follow the link :"https://github.com/oneclick/rubyinstaller/wiki/Development-Kit" step by step 3. Install bundler with "gem install bundler" command. 4. Install rails with "gem install rails 3.0.19" 4. "bundle install" Thats all for ruby setup on windows. Following are some changes in Gemfile before bundle install in awetest setup. Follow the link for Mysql connectivity with our App: http://blog.mmediasys.com/2011/07/07/installing -mysql-on-windows-7-x64-and-using-ruby-with-it/ Comment the line#10 in "config => initializers => redis-check.rb" (fail "ERROR: Redis database should be running. Run: redis-start" end) Comment "capistrano" in gemfile Replace : gem 'mysql2' => gem 'mysql2', '< 0.3' gem 'eventmachine', '1.0.0.beta.4.1' => gem 'eventmachine' gem "win32-process" => gem "win32-process",'0.5.5' "git@github.com:3qilabs/awetest-common.git" => "https://github.com/3qilabs/awetest-common.git" For Awetest Following worker should be started: 1.bundle exec rake environment resque:work PID_FILE=/awetest/tmp/pids/resque_workers.pid QUEUE=regression_test_logs,notifications,documentation RAILS_ENV=development VVERBOSE=1 --trace 2. bundle exec resque-web -p 8282 -F 3. In shamisen=> shamisen.bat 4. redis-server
8d0ad559d4ec94e365e37f41a755956ad1b5d324
[ "Markdown", "Ruby" ]
2
Ruby
sunil-sharma/awetest_windows_gemfile
1858c432cccb2c1d2fb007ff173dd6308779928d
a92c706f8d3b0145fb524e5196572751a484b122
refs/heads/master
<repo_name>baldguysoftware/postfix_exporter<file_sep>/postfix_exporter.go package main import ( "flag" "fmt" "net/http" "os" "sync" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/log" ) const ( namespace = "postfix" // For Prometheus metrics. ) var ( listenAddress = flag.String("telemetry.address", ":9115", "Address on which to expose metrics.") metricsPath = flag.String("telemetry.endpoint", "/metrics", "Path under which to expose metrics.") queueDir = flag.String("postfix.queue_root", "/var/spool/postfix", "Path to Postfix queue directories") ) // Exporter collects postfix stats from machine of a specified user and exports them using // the prometheus metrics package. type Exporter struct { mutex sync.RWMutex totalQ prometheus.Gauge incomingQ prometheus.Gauge activeQ prometheus.Gauge maildropQ prometheus.Gauge deferredQ prometheus.Gauge holdQ prometheus.Gauge bounceQ prometheus.Gauge connects prometheus.Gauge delays prometheus.Histogram } // NewPostfixExporter returns an initialized Exporter. func NewPostfixExporter() *Exporter { return &Exporter{ totalQ: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Name: "total_queue_length", Help: "length of mail queue", }), incomingQ: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Name: "incoming_queue_length", Help: "length of incoming mail queue", }), activeQ: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Name: "active_queue_length", Help: "length of active mail queue", }), maildropQ: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Name: "maildrop_queue_length", Help: "length of maildrop queue", }), deferredQ: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Name: "deferred_queue_length", Help: "length of deferred mail queue", }), holdQ: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Name: "hold_queue_length", Help: "length of hold mail queue", }), bounceQ: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Name: "bounce_queue_length", Help: "length of bounce mail queue", }), connects: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Name: "smtpd_connections_initiated", Help: "Number of new smtpd connections", }), delays: prometheus.NewHistogram(prometheus.HistogramOpts{ Namespace: namespace, Name: "message_delays", Help: "Time the message spent on the server until removed", }), } } // Describe describes all the metrics ever exported by the postfix exporter. It // implements prometheus.Collector. func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { e.totalQ.Describe(ch) e.incomingQ.Describe(ch) e.activeQ.Describe(ch) e.maildropQ.Describe(ch) e.deferredQ.Describe(ch) e.holdQ.Describe(ch) e.bounceQ.Describe(ch) e.connects.Describe(ch) e.delays.Describe(ch) } func countDir(tgt string) (float64, error) { root, err := os.Open(tgt) if err != nil { log.Fatal("[0] error opening %s: %v", tgt, err.Error()) } res, err := root.Readdir(-1) count := 0.0 if err != nil { log.Fatal(err.Error()) } for _, fi := range res { if fi.IsDir() { newtgt := fmt.Sprintf("%s/%s", tgt, fi.Name()) mycount, err := countDir(newtgt) if err != nil { log.Printf("error opening %s: %+v", newtgt, err) } count += mycount } else { count++ } } return count, nil } func (e *Exporter) scrape(ch chan<- prometheus.Metric) error { total_length := 0.0 incoming_queue, _ := countDir(fmt.Sprintf("%s/incoming", *queueDir)) e.incomingQ.Set(incoming_queue) total_length += incoming_queue active_queue, _ := countDir(fmt.Sprintf("%s/active", *queueDir)) e.activeQ.Set(active_queue) total_length += active_queue maildrop_queue, _ := countDir(fmt.Sprintf("%s/maildrop", *queueDir)) e.maildropQ.Set(maildrop_queue) total_length += maildrop_queue deferred_queue, _ := countDir(fmt.Sprintf("%s/deferred", *queueDir)) e.deferredQ.Set(deferred_queue) total_length += deferred_queue hold_queue, _ := countDir(fmt.Sprintf("%s/hold", *queueDir)) e.holdQ.Set(hold_queue) total_length += hold_queue bounce_queue, _ := countDir(fmt.Sprintf("%s/bounce", *queueDir)) e.bounceQ.Set(bounce_queue) total_length += bounce_queue e.totalQ.Set(total_length) //readLogFile(e) return nil } // Collect fetches the stats of a user and delivers them // as Prometheus metrics. It implements prometheus.Collector. func (e *Exporter) Collect(ch chan<- prometheus.Metric) { e.mutex.Lock() // To protect metrics from concurrent collects. defer e.mutex.Unlock() if err := e.scrape(ch); err != nil { log.Printf("Error scraping postfix: %s", err) } e.totalQ.Collect(ch) e.incomingQ.Collect(ch) e.activeQ.Collect(ch) e.maildropQ.Collect(ch) e.deferredQ.Collect(ch) e.holdQ.Collect(ch) e.bounceQ.Collect(ch) return } func main() { flag.Parse() exporter := NewPostfixExporter() prometheus.MustRegister(exporter) http.Handle(*metricsPath, prometheus.Handler()) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`<html> <head><title>Postfix exporter</title></head> <body> <h1>Postfix exporter</h1> <p><a href='` + *metricsPath + `'>Metrics</a></p> </body> </html> `)) }) log.Infof("Starting Server: %s", *listenAddress) log.Fatal(http.ListenAndServe(*listenAddress, nil)) } <file_sep>/README.md # Postfix Exporter for Prometheus This is a simple server that periodically scrapes postfix queue status and exports them via HTTP for Prometheus consumption. # Installation To install it: ```bash git clone https://github.com/baldguysoftware/postfix_exporter.git cd postfix_exporter make ``` # Running To run it manually... ```bash sudo ./postfix_exporter [flags] ``` # Configuration Help on flags: ```bash ./postfix_exporter --help ``` A default installation of Postfix storing its queue directories under `/var/spool/postfix` will require no options. The exporter will automatically descend all hashed directories when it finds them - no added config needed. # TODO * I want to add native (ie. no shell calls requiring additional tools) breakout of destination domain counts. <file_sep>/Makefile VERSION = $(shell cat .version) GHT = $(GITHUB_TOKEN) release: postfix_exporter ghr --username baldguysoftware --token ${GITHUB_TOKEN} --replace ${VERSION} postfix_exporter postfix_exporter: go get -t ./... go build test: go test go vet
0f2e7c7adccaf800c5ab51e7b22116a0a6394269
[ "Markdown", "Go", "Makefile" ]
3
Go
baldguysoftware/postfix_exporter
979a35dfed564a16c7619e80ecb6293b5eacd9bf
2592b00f4a3e90b8b8d8ccc1d8d54ceaa540198b
refs/heads/master
<repo_name>niftit/learning-strategies<file_sep>/js/scripts.js var SliderProfileTeamItem = function() { $('.profile-team-item').on('click', function() { var index = $(this).index() + 1; console.log(index); // if($('.profile-inf-item:nth-child(' + index + ')')) { $('.profile-inf-item:nth-child(' + index + ')').slideToggle('slow'); } }) } //// Grid Introduction :: Apply Dynamic Height //// function applyDynamicHeightGrid(){ var gridItemWidth = Math.round($(".grid-item-1x1").outerWidth()); $(".grid-item").each(function() { $(this).height(gridItemWidth); }); var gridItemWidth = Math.round($(".grid-item-action").outerWidth()); $(".grid-item-action").each(function() { $(this).height(gridItemWidth); }); }; //// What We Do :: Slide Toggle function toggleSlideDown() { $(".whatwedo-item").each(function(){ $(this).click(function() { $(this).find(".whatwedo-slidedown").slideToggle("slow"); $(this).toggleClass("active"); $(this).find(".plus, .minus").toggle(); }); }); }; function clickfilter() { // add the up arrow to each item of the change post layout drop down list $(".dropdown-menu li a").click(function () { color_title_filter(); $(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>'); $(this).parents(".dropdown").find('.btn').val($(this).data('value')); $('.blur-body').hide(); }); } function showHideBody() { $(".profile-team-item svg").click(function () { $(".profile-inf").addClass('focusDiv'); $('.blur-body').show(); }); $(".blur-body").click(function () { $(this).hide(); }); } $(document).ready(function() { applyDynamicHeightGrid(); // Responsive Window Resize window.addEventListener('resize', function(event){ applyDynamicHeightGrid(); }); toggleSlideDown(); //Init the Get Profile Team Item //SliderProfileTeamItem(); showHideBody(); });
d656afba45b9135b7e9d7ea5a2030f4e20d84f4b
[ "JavaScript" ]
1
JavaScript
niftit/learning-strategies
294784f0ff5cf371219ba1abfdb46ef7bf2b8e43
012d8c34a998b4dcaceedaa9ce1d569f308e19dc
refs/heads/master
<repo_name>Tsite2007/Threejs-vue-webpack<file_sep>/src/router.js var context =require("../src/libs/interface/context.js"); module.exports = [{ path: '/', name: '/', meta: { title: '导航', author:"马腾" }, component: resolve => resolve(require('./views/nav.vue')) }, { path: context.name + '/group/index.html', name:'/group/index.html', meta: { title: '组合测试', author:"--" }, component: resolve=>resolve(require('./views/game/group/index.vue')) }, { path: context.name + '/rotate/index.html', name:'/rotate/index.html', meta: { title: '旋转测试', author:"--" }, component: resolve=>resolve(require('./views/game/rotate/index.vue')) }, { path: context.name + '/ratio/index.html', name:'/ratio/index.html', meta: { title: '占比测试', author:"--" }, component: resolve=>resolve(require('./views/game/ratio/index.vue')) }, { path: context.name + '/line/index.html', name:'/line/index.html', meta: { title: '连线测试', author:"--" }, component: resolve=>resolve(require('./views/game/line/index.vue')) }, { path: context.name + '/grid/index.html', name:'/grid/index.html', meta: { title: '方块测试', author:"--" }, component: resolve=>resolve(require('./views/game/grid/index.vue')) }, { path: context.name + '/draw/index.html', name:'/draw/index.html', meta: { title: '画图测试', author:"--" }, component: resolve=>resolve(require('./views/game/draw/index.vue')) }, { path: context.name + '/bulk/index.html', name:'/bulk/index.html', meta: { title: '体积测试', author:"--" }, component: resolve=>resolve(require('./views/game/bulk/index.vue')) }, { path: context.name + '/area/index.html', name:'/area/index.html', meta: { title: '面积测试', author:"--" }, component: resolve=>resolve(require('./views/game/area/index.vue')) }, { path: context.name + '/index.html', name: '/index.html', meta: { title: '导航', author:"马腾" }, component: resolve => resolve(require('./views/nav.vue')) },{ path: "*", name: '/errorPages.html', meta: { title: '发生错误', author:"陈明" }, component: resolve => resolve(require('../src/libs/modules/errorPages/index.vue')) } ]; <file_sep>/pack/webpack.config.js const path = require('path'); const webpack = require('webpack'); var merge = require('webpack-merge'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const context = require("../src/libs/interface/context.js"); function getConfig(mode) { const devMode=(mode == "development"?true:false); var webpackBaseConfig= { mode: devMode ? "development" : "production", entry: { main: ['./src/main.js'] }, output: { path: path.join(__dirname, '../dist/'), publicPath: mode == "development" ? '/' : "", filename: `.${context.name}/js/[name]-[hash].js`, chunkFilename: `.${context.name}/js/[name]-[hash].js` }, optimization: { runtimeChunk: false, minimize: mode != "development", splitChunks: { cacheGroups: { vendor: { name: "vendor", minChunks: 1, maxInitialRequests: 5, minSize: 0, chunks: "all" } } } }, module: { rules: [ { test: require.resolve("three/examples/js/controls/TrackballControls"), use: "imports-loader?THREE=three" }, { test: require.resolve("three/examples/js/controls/TrackballControls"), use: "exports-loader?THREE.TrackballControls" }, { test: require.resolve("three/examples/js/controls/DragControls"), use: "imports-loader?THREE=three" }, { test: require.resolve("three/examples/js/controls/DragControls"), use: "exports-loader?THREE.DragControls" }, { test: require.resolve("three/examples/js/controls/OrbitControls"), use: "imports-loader?THREE=three" }, { test: require.resolve("three/examples/js/controls/OrbitControls"), use: "exports-loader?THREE.OrbitControls" }, { test: require.resolve("three/examples/js/controls/TransformControls"), use: "imports-loader?THREE=three" }, { test: require.resolve("three/examples/js/controls/TransformControls"), use: "exports-loader?THREE.TransformControls" }, { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { less:(devMode?['css-hot-loader']:[]).concat([ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { url: true, minimize: true } }, "less-loader" ]), css:(devMode?['css-hot-loader']:[]).concat([ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { url: true, minimize: true } } ]) } } }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.mtl$/, use: [{ loader: 'file-loader', options: { name: `${devMode?".":""}${context.name}/images/[name].[ext]` } }] }, { test: /\.obj$/, use: [{ loader: 'file-loader', options: { name: `${devMode?".":""}${context.name}/images/[name].[ext]` } }] }, { test: /\.css$/, use: (devMode?['css-hot-loader']:[]).concat([ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { url: true, minimize: true, sourceMap: true } } ]) }, { test: /\.less$/, use: (devMode?['css-hot-loader']:[]).concat([ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { url: true, minimize: true, sourceMap: true } }, "less-loader" ]) }, { test: /\.(gif|jpe?g|png|svg|hdr)(\?\S*)?$/, use: [{ loader: 'file-loader', options: { /* * 【改动】:图片小于2kb的按base64打包 */ limit: 2048, name: `${devMode?".":""}${context.name}/images/[name].[ext]` } }] }, { test: /\.(eot|svg|ttf|woff|woff2|otf)(\?\S*)?$/, use: [{ loader: 'file-loader', options: { /* * 【改动】:图片小于2kb的按base64打包 */ limit: 2048, name: `${devMode?".":""}${context.name}/images/[name].[ext]` } }] }, { test: /\.(html|tpl)$/, loader: 'html-loader' } ] }, resolve: { extensions: ['.js','.json', '.vue'], alias: { '@': path.resolve(__dirname, "../src"), '@image': path.resolve(__dirname, "../src/libs/images") } }, plugins: [ new MiniCssExtractPlugin({ filename: `.${context.name}/css/[name].css` }), new HtmlWebpackPlugin({ template: './src/index.ejs', filename: './index.html', title: "基础教育大数据应用平台", favicon: "./src/libs/images/favicon/favicon.ico", inject: false, hash: true }) ] } if(devMode){ webpackBaseConfig=merge(webpackBaseConfig,{ module: { rules: [ // { // test: /\.(js|vue)$/, // loader: "eslint-loader", // options: { // failOnWarning: true, // failOnError: true, // configFile: path.resolve(__dirname, "../.eslintrc.json") // }, // enforce: "pre", // include: path.resolve(__dirname,'../src') // } ] } }) } return webpackBaseConfig; } module.exports = getConfig; <file_sep>/pack/dev.js const os = require('os'); const path = require('path'); const axios = require("axios"); const webpack = require('webpack'); const chalk = require("chalk"); const WebpackDevServer = require('webpack-dev-server'); const webpackDevConfig = require('./webpack.config.js')("development"); const allRouter = require('../src/router.js'); const url = "localhost"; const port = 9998; let opened = false; process.env.NODE_ENV = 'development'; webpackDevConfig.entry.main.unshift("webpack-hot-middleware/client?reload=true&" + `http://${url}:${port}`); webpackDevConfig.plugins.push(new webpack.optimize.OccurrenceOrderPlugin()); webpackDevConfig.plugins.push(new webpack.HotModuleReplacementPlugin()); webpackDevConfig.plugins.push(new webpack.NoEmitOnErrorsPlugin()); webpackDevConfig.output.path = path.join(__dirname, "./"); var indexPath=`http://${url}:${port}/index.html`; var indexFilePath="/"+path.basename(indexPath); function getIndex(res) { axios.get(indexPath).then(resData => { res.end(resData.data); }).catch(err => { res.end(err); }) } function if404(req, res, next) { var url=String(req.originalUrl); if (url.substr(-5) == ".html" && url!=indexFilePath) { getIndex(res); } else { next(); } } function forRouter(app) { this.forEach(item => { if (item.children instanceof Array && item.children.length) { forRouter.bind(item.children)(app); } if (item.path !== "*") { app.get(item.path, (req, res, next) => { console.log(item.path); getIndex(res); }) }else{ app.get("*",if404); } }); } const compiler = webpack(webpackDevConfig); new WebpackDevServer( compiler, { contentBase: webpackDevConfig.output.path, publicPath: webpackDevConfig.output.publicPath, inline: true, hot: true, //热更新 quiet: true, port: port, //设置端口号 progress: true, //显示打包的进度 proxy: { '/data': { target: 'http://web.mateng.net.cn', secure: false, changeOrigin: true }, "/mock": { target: 'http://api.mateng.net.cn', secure: false, changeOrigin: true } }, setup(app, ctx) { app.use(require('webpack-hot-middleware')(compiler)); app.use(require('connect-history-api-fallback')()); forRouter.bind(allRouter)(app); } } ).listen(port, url, function(err) { if (err) { console.log(err); return; } console.log(`Listening at http://${url}:${port}`); }); compiler.hooks.done.tap("done", function(stats) { var compilation = stats.compilation; Object.keys(compilation.assets).forEach(key => { console.log(chalk.blue(key)); }) compilation.warnings.forEach(key => { console.log(chalk.yellow(key)); }) compilation.errors.forEach(key => { console.log(chalk.red(`${key}:${stats.compilation.errors[key]}`)); }) console.log(chalk.green(`time:${(stats.endTime-stats.startTime)/1000} s\n`) + chalk.white("调试完毕")); if (!opened) { var cmd = os.platform() == "win32" ? 'explorer' : 'open'; opened = require('child_process').exec(`${cmd} "http://${url}:${port}"`); } }) <file_sep>/README.md Threejs-vue-webpack 使用Threejs完成球体的三维拖拽,并计算位置,也包括面的绘制以及平移旋转等效果。 <file_sep>/src/libs/interface/public.js /* by: tengma 2018年07月27日 name: 公共接口 */ const apiUrl = ""; const testUrl = "/data"; let urlInterface = { }; export default urlInterface;
a0708f8d876e3ef4c19b147c6bfe5e135af61168
[ "JavaScript", "Markdown" ]
5
JavaScript
Tsite2007/Threejs-vue-webpack
a359a7e396336e2be9f0e397c4e560158d8bf8bf
a820f4f71c05810b9905606a34ef91551bfee0df
refs/heads/master
<file_sep>import React, {Component} from 'react'; // 弹出框组件 import { Prompt } from 'react-router-dom'; export default class Add extends Component { constructor() { super(); this.state = { blocking: false, } } handleSubmit = () => { let name = this.name.value; let userStr = localStorage.getItem('users'); let users = userStr?JSON.parse(userStr):[]; users.push({id: Date.now(),name}); localStorage.setItem('users', JSON.stringify(users)); // 先配置状态,在路由跳转 this.setState({ blocking: false }, () => { this.props.history.push('/user/list'); }) } handleChange = (e) => { let value = e.target.value; this.setState({ blocking: value && value.length > 0 }) } render () { return ( <div> <Prompt when={this.state.blocking} message={()=>`你确定要跳转到${this.props.location.pathname}吗`} /> <form onSubmit={this.handleSubmit}> <div className="form-group"> <label htmlFor="name">姓名</label> <input type="text" onChange={this.handleChange} className="form-control" ref={(ref) => this.name = ref}/> </div> <div className="from-group"> <input type="submit" className="btn btn-primary"/> </div> </form> </div> ) } }<file_sep>import React, {Component} from 'react'; import { Link, Route, Switch, Redirect } from 'react-router-dom'; import List from './List'; import Add from './Add'; import Detail from './Detail'; export default class User extends Component { render () { return ( <div className="row"> <div className="col-md-2"> <ul className="nav nav-stacked"> <li><Link to="/user/list">用户列表</Link></li> <li><Link to="/user/add">新增用户</Link></li> </ul> </div> <div className="col-md-10"> <Switch> <Route path="/user/list" component={List} /> <Route path="/user/add" component={Add} /> <Route path="/user/detail/:id" component={Detail} /> </Switch> </div> </div> ) } }<file_sep>import React, {Component} from 'react'; import { Link } from 'react-router-dom'; export default class List extends Component { constructor(){ super(); this.state = { users: [] } } componentWillMount() { let userStr = localStorage.getItem('users'); let users = userStr? JSON.parse(userStr): []; this.setState({ users }) } render () { return ( <ul className="list-group"> { this.state.users.map((user, index) => <li className="list-group-item" key={index}> <Link to={`/user/detail/${user.id}`}>{user.name}</Link> </li> ) } </ul> ) } }<file_sep>## 安装路由 npm install react-router-dom -S ## 跑通路由 组件通信: 非Redux方式: 数据从一个方向父组件流向子组件(通过Props),由于这个特征,两个非父子关系的组件(兄弟组件)之间的通信就比较麻烦。 Redux方式: 通过订阅Store 实现 合并分支: git 命令 **********************************
98a23d40315407fecf605c7adb61cd09c62d45bf
[ "JavaScript", "Markdown" ]
4
JavaScript
zWorker9902/20180807reactrouter
02090492008b5be9b1fecc1680b45771f31f3d67
806e01bb3ecfd16d491cdf8782956072d5f604dc
refs/heads/master
<repo_name>james-zedd/simple-todo<file_sep>/app.js const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); const bodyParser = require('body-parser'); // Express Handlebars Middleware app.engine( 'handlebars', exphbs({ defaultLayout: 'main', layoutsDir: __dirname + '/views/layouts/', partialsDir: __dirname + '/views/partials/' }) ); app.set('view engine', 'handlebars'); // Body Parser Middleware app.use(bodyParser.urlencoded({ extended: true })); // Default to do's let tasks = ['take out garbage', 'buy new socks', 'pick up wife']; // post route for adding new task app.post('/post', (req, res) => { let newTask = req.body.todo; //console.log(newTask); tasks.push(newTask); res.redirect('/'); }); app.get('/', (req, res) => { res.render('index', { tasks: tasks }); }); app.get('/about', (req, res) => { res.render('about'); }); const port = 3000; app.listen(port); console.log(`Server running on port ${port}`);
3e91352d15068da478fb254ac8cc0076cc3f8d35
[ "JavaScript" ]
1
JavaScript
james-zedd/simple-todo
7272ba54ae7590b7ab0021103c8e0d117467fd74
4b0330bee42db553e757552328d3651d5d444f4d
refs/heads/master
<repo_name>samyuktaprabhu/APT-sem4-EndSemQuestionPapers-solution<file_sep>/07-05-2016Q4C.py def decimalToBinary(num): """This function converts decimal number to binary and prints it""" if num > 1: decimalToBinary(num // 2) print(num % 2, end='') def dectohex(num): if num>1: dectohex(num//16) rem=num%16 if(rem<9): print(rem, end='') else: if(rem==10): print('A', end='') elif(rem==11): print('B', end='') elif(rem==12): print('C', end='') elif(rem==13): print('D', end='') elif(rem==14): print('E', end='') elif(rem==15): print('F', end='') def dectooct(num): if num>1: dectooct(num//8) print(num%8,end='') # decimal number number = int(input("Enter any decimal number: ")) decimalToBinary(number) print("") dectohex(number) print("") dectooct(number) <file_sep>/07-05-2016Q2A.py string=input("Enter sentences separated by a full stop : ") #Nested list print("The nested list is :") list=[] list=string.split(".") print(list) list2=[] for i in list: word=i.split(" ") list2.append(word) print(list2) #list palindrome print("Palindrome check : ") for i in list2: print(i) if(i==i[::-1]): print("It is Palindrome") else: print("It is Not a palindrome") #capitalize each word in nested likst n display print("Caps each word : ") list4=[] for i in list2: stri="" for j in i: stri=stri+j+" " stri=stri.title() list3=stri.split(" ") print(list3) list4.append(list3) print(list4) #sentences display for i in list2: stri="" for j in i: stri=stri+j+" " print(stri+".") <file_sep>/07-05-2016Q3A.py #inside the module class Shape: x=0 y=0 def __init__(self,x,y): self.x=x self.y=y def __del__(self,x,y): self.y=y self.x=x class Circle(Shape): radius=0 area=0 def __init__(self,radius): self.radius = radius def __del__(self,radius): self.radius = radius def Area(radius): area=3.142*radius*radius print(area) class Rect(Shape): side1=0 side2=0 area=0 def __init__(self,side1,side2): self.side1 = side1 self.side2 = side2 def __del__(self,side1,side2): self.side1 = side1 self.side2 = side2 def Area(side1,side2): area=side1*side2 print(area) #main prog import pyt #class Shape print("hello") print("enter radius, side1,side2") r=int(input()) s1=int(input()) s2=int(input()) print("Area of circle of radius 1 is :") pyt.Circle.Area(r) print("area of rectangle is") pyt.Rect.Area(s1,s2) <file_sep>/07-05-2016Q5A.py def calci(*op,opr,f): print(op) print(opr) print(f) res=op[0] for i in op[1:]: #print(i) if(opr=="add" or opr==""): res=res+i elif(opr=="sub"): res=res-i elif(opr=="mul"): res=res*i elif(opr=="div"): if(i!=0): res=res/i else: return "div by zero error" else: return "error" if(f=="int"): return res else: return float(res) print(calci(2,3,56,opr="",f="float")) print(calci(1.6,2.8,3,7,9,opr="mul",f="float")) <file_sep>/14-07-2017Q3A.py n=input("Enter a string") list1=[] list1=n.split(" ") print(list1) list2=[] for i in list1: if i not in list2: list2.append(i) print(i) print(list2) list2.sort() print(list2) lc=0 c=0 dc=0 list5=[] for i in list2: for j in i: if j.isdigit(): dc+=1 elif j.isalpha(): lc+=1 if(j in ('a','e','i','o','u','A','E','I','O','U')): list5.append(j) else: c+=1 print(" Digit count : ",dc) print(" letter count : ",lc) print(list5) dictt={'a':0,'e':0,'i':0,'o':0,'u':0} ac=0 ec=0 ic=0 oc=0 uc=0 for i in list5: if(i=='a' or i=='A'): ac+=1 elif(i=='e'or i=='E'): ec+=1 elif(i=='i' or i=='I'): ic+=1 elif(i=='o' or i=='O'): oc+=1 elif(i=='u' or i=='U'): uc+=1 print(ac) print(ec) print(ic) print(oc) print(uc) dictt['a']=ac dictt['e']=ec dictt['i']=ic dictt['o']=oc dictt['u']=uc print(dictt) <file_sep>/07-05-2016Q3B.py n=input("") list1=n.split(",") list2=[] list3=[] list4=[] k=0 kk=0 print(list1) for i in list1: j=i[::-1] k=int(j[0])*1+int(j[1])*2+int(j[2])*4+int(j[3])*8 print(k) if(k%5==0): list3.append(k) else: list4.append(k) print(list3) print(list4) <file_sep>/14-07-2017Q1A.py import copy #n=int(input("Enter the number of element")) list1=[1,2,"str",4.6,True,None,5,5,4.6,7,9,8,7,"str"] #for i in range(0,n): # list1.append(input("Enter element")) #print(list1) sum=0 numerical=[] for i in list1: if isinstance(i,str): print(i," is a string") elif isinstance(i,bool): print(i," is a boolean") elif isinstance(i,int): print(i," is an int") sum+=i numerical.append(i) elif isinstance(i,complex): print(i," is a complex") elif isinstance(i,float): print(i," is a float") elif isinstance(i,list): print(i," is a list") elif isinstance(i,dict): print(i," is an dict") elif isinstance(i,tuple): print(i," is a tuple") elif isinstance(i,set): print(i," is a set") print(numerical) print(sum) list3=[] list3=copy.deepcopy(list1) print(list3) #remove duplicates list4=[] for i in list3: if i not in list4: list4.append(i) list3=list4 print(list3) <file_sep>/14-07-2017Q5A.rb class Acco @@no=0 @@name="" @@bal=0 def initialize(name,no,bal) @name=name @no=no @bal=bal end def deposit print("Enter the amount to deposit") depo=gets.chomp depo=depo.to_f @bal+=depo end def withdraw print("Enter the amount to withdraw") with=gets.chomp with=with.to_f @bal-=with end def checkbal puts"#@bal" end def details puts"#@name" puts"#@no" puts"#@bal" end end print("enter details") name=gets.chomp no=gets.chomp bal=gets.chomp bal=bal.to_f print("1.deposit2.withdraw3.balcheck4.details") wish='y' a=Acco.new(name,no,bal) while wish=='y' or wish =='Y' n=gets.chomp if n=='1' puts"going to deposit" a.deposit elsif n=='2' puts"going to withdraw" a.withdraw elsif n=='3' puts"going to bal" a.checkbal else a.details puts"going to disp" end wish=gets.chomp end <file_sep>/07-05-2016Q1B.py n=int(input("Enter the number of rows:P")) k=2*n-2 for i in range(0, n): for j in range(0, k): print(end=" ") k=k-2 a=1 for j in range(0, i+1): print(a, end=" ") a+=1 print() <file_sep>/07-05-2016Q2B.py str1=input("Enter elements of first set") set1=set(str1.split(" ")) str2=input("Enter elements of second set") set2=set(str2.split(" ")) print(set1) print(set2) print(" Union of set ") print(set1|set2) print(" intersection of set ") print(set1&set2) print(" difference of set ") print(set1^set2) <file_sep>/07-05-2016Q1A.rb print("Enter a string") str=gets().chomp() print("The string is #{str} \n") #printing alternate words arr=str.split len=arr.length puts len print("\n The words alternatively present are : \n") alt="" for i in 0..len-1 if ((i%2)==0) print("") else #print(arr[i]+" ") alt=alt+arr[i]+" " end end puts alt #reverse a string print("\n The string in reverse : \n") for i in arr print(i.reverse()+" ") end print("\n") #palindrome print("\n Palindrome check : \n") if str==str.reverse() print ("\nit is a palindrome...") else print ("\nIt is not a palindrome...") end #vowel vowel="" print("\n The words starting with vowels are : \n") for i in arr if (i.start_with?('a')||i.start_with?('e')||i.start_with?('i')||i.start_with?('o')||i.start_with?('u')) vowel=vowel+i+" " else print("") end end puts vowel #multiply the words #use collect function print("\n The words with repetetions are : \n") repeat="" repeat=arr.collect{|i| i*2} puts repeat <file_sep>/README.md # APT-sem4-EndSemQuestionPapers-solution Ruby and Python
8bd470d383676a47cccc496277fa9928c0dca42b
[ "Markdown", "Python", "Ruby" ]
12
Python
samyuktaprabhu/APT-sem4-EndSemQuestionPapers-solution
c0c966e376211490ef20330ecef53d2a9f97e94c
ccc9972356522ae1e512328ce054154a718fd021
refs/heads/main
<file_sep># Rock-Paper-Scissors-Game My first python program, created a simple rock paper scissors game that compare the users input with a computer generated option selected randomly out of 3 choices. <file_sep>import random rps = ["rock", "paper", "scissors"] pScore = 0 aiScore = 0 rndmPick = "" playerChoice = "" def logic(rps, pScore, aiScore, rndmPick, playerChoice): rndmPick = random.choice(rps) playerChoice = input("Rock paper scissors. Enter r, p or s to choose\n") print(f"Ai chose{rndmPick}\n") # if player choice is rock then... if playerChoice == "r" and rndmPick == "rock": print("You Draw!") print(f"You:{pScore}", f"Ai:{aiScore}") elif playerChoice == "r" and rndmPick == "paper": print("You lose!") aiScore += 1 print(f"You:{pScore}", f"Ai:{aiScore}") elif playerChoice == "r" and rndmPick == "scissors": print("You win!") pScore += 1 print(f"You:{pScore}", f"Ai:{aiScore}") # if player choice is paper then... elif playerChoice == "p" and rndmPick == "rock": print("You win!") pScore += 1 print(f"You:{pScore}", f"Ai:{aiScore}") elif playerChoice == "p" and rndmPick == "paper": print("You draw!") print(f"You:{pScore}", f"Ai:{aiScore}") elif playerChoice == "p" and rndmPick == "scissors": print("You lose!") aiScore += 1 print(f"You:{pScore}", f"Ai:{aiScore}") #if player choice is scissors then... elif playerChoice == "s" and rndmPick == "rock": print("You lose!") aiScore += 1 print(f"You:{pScore}", f"Ai:{aiScore}") elif playerChoice == "s" and rndmPick == "paper": print("You win!") pScore += 1 print(f"You:{pScore}", f"Ai:{aiScore}") elif playerChoice == "s" and rndmPick == "scissors": print("You draw!") print(f"You:{pScore}", f"Ai:{aiScore}") logic(rps, pScore, aiScore, rndmPick, playerChoice) logic(rps, pScore, aiScore, rndmPick, playerChoice)
9b86a1809f6e5064a271e98e082a1644a306d447
[ "Markdown", "Python" ]
2
Markdown
EthanHunter08/Rock-Paper-Scissors-Game
cffc608681abd5f741841d21c03b846554d20ba7
4671f37e3cd3f8769d9960920c736c66c3e82561
refs/heads/main
<repo_name>StewedChickenwithStats/Answers-to-Python-Crash-Course<file_sep>/chap2/2-9.py num=12 message= "My favorite number is "+str(num)+"."#要把非字符串值表示为字符串 print(message) <file_sep>/chap2/2-2.py message="you" print(message) message="me" print(message)<file_sep>/chap5/5-7.py favorite_fruits=['banana','apple','pear'] if 'banana' in favorite_fruits: print("You really like bananas!") if 'apple' in favorite_fruits: print("You really like apples!") if 'pear' in favorite_fruits: print("You really like pears!") if 'lemon' in favorite_fruits: print("You really like lemons!") if 'mango' in favorite_fruits: print("You really like mangoes!")<file_sep>/chap5/5-1.py car='bmw' print("Is car =='bmw'? I predict True.") print(car=='bmw') print("\nIs car =='audi'? I predict False.") print(car=='audi')<file_sep>/chap4/4-11.py pizzas=['pepperoni','pan','chicken'] friend_pizzas=pizzas[:] pizzas.append('beef') friend_pizzas.append('banana') print("My favorite pizzas are:") for pizza in pizzas: print(pizza) print("My friend's favorite pizzas are:") for friend_pizza in friend_pizzas: print(friend_pizza) <file_sep>/chap15/15-1.py import matplotlib.pyplot as plt # define data x_values = [1, 2, 3, 4, 5] cubes = [1, 8, 27, 64, 125] # make plot plt.scatter(x_values, cubes, edgecolor='none', s=40) # customize plot plt.title('cubes', fontsize=24) plt.xlabel('value', fontsize=14) plt.ylabel('cube of value', fontsize=14) plt.tick_params(axis='both', labelsize=14) # show plot plt.show() # define data x_values = list(range(1, 5000)) y_values = [x ** 3 for x in x_values] # make plot plt.scatter(x_values, y_values, edgecolor='none', s=40) # customize plot plt.title('cubes', fontsize=24) plt.xlabel('value', fontsize=14) plt.ylabel('cube of value', fontsize=14) plt.tick_params(axis='both', labelsize=14) plt.axis([0, 5100, 0, 5100 ** 3]) # show plot plt.show() <file_sep>/chap4/4-8.py cubes=[] for value in range(1,11): cube=value**3 cubes.append(cube) for cube in cubes: print(cube)<file_sep>/chap3/3-9.py people=['mom','dad','sister'] print("I have invited "+str(len(people))+" people.")<file_sep>/chap4/4-4.py numbers=list(range(1,1000001)) for number in numbers: print(number)<file_sep>/chap7/7-8.py sandwich_orders = ['chicken', 'beef', 'tuna'] finished_sandwiches = [] while sandwich_orders: current_sandwich = sandwich_orders.pop() print("I made your" + current_sandwich + " sandwich.") finished_sandwiches.append(current_sandwich) print("\nThe following sandwiched have been finished:") for finished_sandwiche in finished_sandwiches: print(finished_sandwiche) <file_sep>/chap8/8-13.py def build_profile(first, last, **user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('stella', 'zhang', location='china', field='physics', age=28) print(user_profile) <file_sep>/chap3/3-7.py people=['mom','dad','sister'] print("Now there will be a larger dining-table.") people.insert(0,'brother') people.insert(2,'friend') people.append('teacher') print("Now you can only invite two guests.") delete_1=people.pop() print("Dear "+delete_1+", I am sorry to tell you that I have to cancel the dinner plan.") delete_2=people.pop() delete_3=people.pop() print("Dear "+delete_3+", I am sorry to tell you that I have to cancel the dinner plan.") print("Dear "+people[0]+", please attend dinner as planned.") print("Dear "+people[1]+", please attend dinner as planned.") del people[0] del people[0] del people[0] print("Now print the list:") print(people)<file_sep>/chap6/6-6.py favorite_languages={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } check_lists=['jen','phil'] for name in favorite_languages.keys(): if name in check_lists: print("Thanks "+name.title()+"!") else: print("Hi "+name.title()+","+"please complete this investigation quickly!") <file_sep>/chap5/5-2.py str1='Water' str2='Milk' print("Is str1 == str2? I predict False.") print(str1==str2) print("\nIs str1 == 'water' when ignoring case? I predict True.") print(str1.lower()=='water') n1=18 n2=16 print("\nIs n1 > n2? I predict True.") print(n1>n2) print("\nAre str1 == str2 and n1 > n2? I predict False.") print(str1==str2 and n1>n2) foods=['milk','water','bread'] print("\nIs 'water' in the foods? I predict True.") print('water' in foods) print("\nIs 'bread' not in the foods? I predict False.") print('water' not in foods) <file_sep>/chap16/highs_lows.py import csv # 导入模块csv(csv模块包含在Python标准库中,可用于分析CSV文件中的数据行,让我们快速提取感兴趣的值 filename = 'sitka_weather_07-2014.csv' # 打开文件,将结果文件对象存储在f中 with open(filename) as f: reader = csv.reader(f) # 创建一个与该文件向关联的阅读器(reader)对象。reader处理文件中以逗号分割的第一行数据,并将每项数据都作为一个元素存储在列表中 header_row = next(reader) # 内置函数next()返回文件的下一行 print(header_row) <file_sep>/chap2/2-8.py print(5+3) print(10-2) print(2*4) print(int(8/1))#注意8/1=8.0,结果为一浮点数。根据题目要求,要转化成整型p <file_sep>/chap8/8-4.py def make_shirt(size='large', words='I love the world'): print("The T-shirt is " + size + " and the words '" + words + "' are on it.") make_shirt() make_shirt('middle') make_shirt(words='I love you') <file_sep>/chap4/4-13.py foods=('milk','soup','rice','noodle','pizza') print("The original foods:") for food in foods: print(food) foods=('water','dumpling','rice','noodle','pizza') print("The new foods:") for food in foods: print(food)<file_sep>/chap8/8-11.py def show_magicians(names): """print each name of all magicians""" for name in names: print(name) def make_great(names): for index in range(len(names)): names[index] = "the Great " + names[index] return names magicians = ['lily', 'anna', 'milk'] modified_list = make_great(magicians[:]) print("\nThe original list is: ") show_magicians(magicians) print("\nThe modified list is: ") show_magicians(modified_list) <file_sep>/chap15/15-2.py from matplotlib import pyplot as plt # explicit expression # define data x_values = list(range(1, 5000)) cubes = [x ** 3 for x in x_values] # make plot plt.scatter(x_values, cubes, edgecolor='none', c=cubes, cmap=plt.cm.BuGn, s=40) # customize plot plt.title('cubes', fontsize=24) plt.xlabel('value', fontsize=14) plt.ylabel('cube of value', fontsize=14) plt.tick_params(axis='both', labelsize=14) plt.axis([0, 5100, 0, 5100 ** 3]) # show plot plt.show() <file_sep>/chap3/3-5.py people=['mom','dad','sister'] print(people[2].title()+" cannot attend this dinner.")#无法赴约的人 people[2]='brother' print("Dear "+people[0]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[1]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[2]+", I'd like to invite you to have dinner with me on Friday at my home.") <file_sep>/chap8/8-5.py def describe_city(city, country='China'): print(city.title() + " is in " + country.title()) describe_city('shanghai') describe_city(city='beijing') describe_city('tokyo', 'japan') <file_sep>/chap5/5-11.py nums=list(range(1,10)) for num in nums: if num==1: print("1st") elif num==2: print("2nd") elif num==3: print("3rd") else: print(str(num)+"th")<file_sep>/chap15/15-7.py import pygal from die import Die # 创建两个D8骰子 die_1 = Die(8) die_2 = Die(8) # 掷几次骰子,并将结果存储在一个列表中 results = [die_1.roll() + die_2.roll() for roll_num in range(1000000)] # 分析结果 frequencies = [] max_result = die_1.num_sides + die_2.num_sides for value in range(2, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # 对结果进行可视化 hist = pygal.Bar() # 创建一个pygal.Bar()实例,并将其存储在hist中 hist.title = "Results of rolling two D8 dice 1,000,000 times" # 设置hist的属性title hist.x_labels = [str(x) for x in range(2, max_result + 1)] # 将掷骰子的可能结果用作x轴的标签 # 给每个轴添加标题 hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('two D8', frequencies) # 第一个参数是指定的标签,第二个参数是一个包含图表中值的列表 hist.render_to_file('twoD8dies_visual.svg') # 将图标渲染为一个SVG文件 <file_sep>/chap3/3-4.py people=['mom','dad','sister'] print("Dear "+people[0]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[1]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[2]+", I'd like to invite you to have dinner with me on Friday at my home.") <file_sep>/chap6/6-5.py rivers={'nile':'egypt','yangtze river':'china','lena river':'russia'} for river, state in rivers.items(): print("The "+river.title()+" runs through "+state.title()+'.') for river in rivers.keys(): print(river.title()) for state in rivers.values(): print(state.title())<file_sep>/chap4/4-9.py cubes=[value**3 for value in range(1,11)] print(cubes)<file_sep>/chap6/6-7.py friend_0={'first_name':'Ming','last_name':'Li','age':20,'city':'Shanghai'} friend_1={'first_name':'Heng','last_name':'Wang','age':10,'city':'Beijing'} friend_2={'first_name':'Mike','last_name':'Tang','age':30,'city':'Zhejiang'} people=[friend_0,friend_1,friend_2] for friend in people: print(friend) <file_sep>/chap8/8-14.py def make_car(manufacturer, model, **car_info): car = {} car['manufacturer'] = manufacturer car['model'] = model for key, value in car_info.items(): car[key] = value return car car = make_car('subaru', 'outback', color='blue', two_package=True) print(car) <file_sep>/chap4/4-5.py numbers=list(range(1,1000001)) print(min(numbers)) print(max(numbers)) print(sum(numbers)) #it took 0.2s<file_sep>/chap6/6-10.py favorite_nums={ 'Lily':[1,2,3], 'Linda':[2,3], 'Mike':[3,6], 'Wendy':[4,9], 'Zoe':[5,4,3], } for name, nums in favorite_nums.items(): print("\n"+name.title()+"'s favorite numbers are:") for num in nums: print(num)<file_sep>/chap5/5-5.py alien_color='red' if alien_color=='green': print("The player can get 5 points.") elif alien_color=='yellow': print("The player can get 10 points.") else: print("The player can get 15 points.") <file_sep>/chap7/7-10.py responses={} polling_active=True while polling_active: name=input("\nWhat is your name?") response=input("If you could visit one place in the world, where could you go?") responses[name]=response repeat=input("Would you like to let another person respond? (yse/no)") if repeat=='no': polling_active=False print("\n--- Poll Results ---") for name, response in responses.items(): print(name.title()+ " would like to visit "+response.title()+".")<file_sep>/chap3/3-2.py names=['Linda','Lily','Zoe'] print(names[0]+", nice to meet you!") print(names[1]+", nice to meet you!") print(names[2]+", nice to meet you!") <file_sep>/chap4/4-6.py odd_numbers=list(range(1,21,2)) for odd_number in odd_numbers: print(odd_number)<file_sep>/chap7/7-9.py sandwich_orders = ['chicken', 'pastrami', 'beef', 'pastrami', 'tuna', 'pastrami'] print("\nThe pastrami have been sold out.") while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') print(sandwich_orders) <file_sep>/chap8/8-10.py def show_magicians(names): """print each name of all magicians""" for name in names: print(name) def make_great(names): for index in range(len(names)): names[index] = "the Great " + names[index] magicians = ['lily', 'anna', 'milk'] make_great(magicians) show_magicians(magicians) <file_sep>/chap7/7-4.py prompt = "\nTell me one topping on the pizza:" prompt += "\nEnter 'quit' to end the program." message = "" while message != 'quit': message = input(prompt) if message != 'quit': print("We will add "+message+" into your pizza.") <file_sep>/chap7/7-3.py nums=input("Please enter a number: ") if int(nums)%10==0: print(nums+" is a multiple of integer 10.") else: print(nums+" is not a multiple of integer 10.") <file_sep>/chap8/8-16/import4.py import pizza as p p.make_pizza(16, 'banana') <file_sep>/chap5/5-3.py alien_color='red' if alien_color=='green': print("The player can get 5 points.") alien_color='green' if alien_color=='green': print("The player can get 5 points.") <file_sep>/chap4/4-2.py animals=['dog','horse','cow'] for animal in animals: print(animal) for animal in animals: print("A "+animal+" has four legs") print("Any of these animals has four legs") <file_sep>/chap15/15-6.py import pygal from die import Die #创建一个D6 die=Die() #掷几次骰子,并将结果存储在一个列表中 results=[die.roll() for roll_num in range(1000)] #分析结果 frequencies = [results.count(value) for value in range(1, die.num_sides+1)] #对结果进行可视化 hist = pygal.Bar()#创建一个pygal.Bar()实例,并将其存储在hist中 hist.title = "Results of rolling one D6 1000 times"#设置hist的属性title hist.x_labels = [str(x) for x in range(1, die.num_sides+1)]#将掷D6骰子的可能结果用作x轴的标签 #给每个轴添加标题 hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('D6', frequencies)#第一个参数是指定的标签,第二个参数是一个包含图表中值的列表 hist.render_to_file('die_visual.svg')#将图标渲染为一个SVG文件 <file_sep>/chap9/9-2.py class Restaurant(): """a simple effort for a restaurant""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(self.restaurant_name) print(self.cuisine_type) def open_restaurant(self): print("This restaurant is opening.") my_restaurant = Restaurant("big brother", "hot pot") your_restaurant = Restaurant("rainbow", "western food") her_restaurant = Restaurant("grandma's home", "chinese food") my_restaurant.describe_restaurant() your_restaurant.describe_restaurant() her_restaurant.describe_restaurant() <file_sep>/chap7/7-1.py car=input("Which car do you want to rent?") print("Let me see if I can find you a "+car)<file_sep>/chap8/8-9.py def show_magicians(names): """print each name of all magicians""" for name in names: print(name) magicians = ['lily', 'anna', 'milk'] show_magicians(magicians) <file_sep>/chap8/8-15/printing_functions.py def print_models(unprinted_designs, completed_models): while unprinted_designs: current_design = unprinted_designs.pop() print("Printing model: " + current_design) completed_models.append(current_design) <file_sep>/chap4/4-1.py pizzas=['pepperoni','pan','chicken'] for pizza in pizzas: print(pizza) for pizza in pizzas: print("I like "+pizza) print("I really love pizza!")<file_sep>/chap3/3-10.py food=['ice-cream','apple','milk','chicken'] print("Print the list:") print(food) print("Print the first element:") print(food[0]) print("Modify the first element as another item:") food[0]="tea" print(food) print("Insert an item at first:") food.insert(0,'ice-cream') print(food) print("Delete the last element:") del food[-1] print(food) print("Sort the list forever:") food.sort() print(food) print("Reverse the list:") food.reverse() print(food) <file_sep>/chap10/10-4.py filename = 'guest_book.txt' prompt = "\nTell me your name: " prompt += "\nEnter 'quit' to end the program." active = True while active: name = input(prompt) if name == 'quit': break else: with open(filename, 'w') as f: f.write(name) print("Hi " + name + ", you've been added to the guest book.") <file_sep>/chap2/2-1.py message="Hello World!" print(message)<file_sep>/chap8/8-16/import3.py from pizza import make_pizza as m m(16, 'banana') <file_sep>/chap2/2-6.py famous_person="<NAME>" message=famous_person+' once said, "A person who never made a mistake never tried anything new."'#注意两个双引号要位于两个撇号间 print(message)<file_sep>/chap6/6-9.py friend={'first_name':'Ming','last_name':'Li','age':20,'city':'Shanghai'} print(friend['first_name']) print(friend['last_name']) print(friend['age']) print(friend['city'])<file_sep>/chap5/5-6.py age=19 if age<2: print("infant") elif age>=2 and age<4: print("toddler") elif age>=4 and age<13: print("child") elif age>=13 and age<20: print("teenager") elif age>=20 and age<65: print("adult") elif age>=65: print("senior")<file_sep>/chap10/10-2.py filename = 'learning_python.txt' with open(filename) as file_object: lines = file_object.readlines() new_file = " " for line in lines: # Get rid of newline, then replace Python with C. print(line.rstrip().replace('Python', 'C')) # Use rstrip() and replace() on the same line (chaining methods). <file_sep>/chap3/3-6.py people=['mom','dad','sister'] print("Now there will be a larger dining-table.") people.insert(0,'brother') people.insert(2,'friend') people.append('teacher') print("Dear "+people[0]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[1]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[2]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[3]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[4]+", I'd like to invite you to have dinner with me on Friday at my home.") print("Dear "+people[5]+", I'd like to invite you to have dinner with me on Friday at my home.")<file_sep>/chap2/2-5.py message='<NAME> once said, "A person who never made a mistake never tried anything new."'#注意两个双引号要位于两个撇号间 print(message)<file_sep>/chap6/6-4.py codewords={ 'array':'an arrangement of aerials spaced to give desired directional characteristics', 'byte':'computer memory unit', 'boolean':'a data type with only two possible values: true or false', 'debug':'locate and correct errors in a computer program code', 'address':'the code that identifies where a piece of information is stored' } # add five words codewords['append']='a procedure for concatenating (linked) lists or arrays in some high-level programming languages' codewords['adapter']='device that enables something to be used in a way different from that for which it was intended or makes different pieces of apparatus compatible' codewords['constant']='a non-varying value' codewords['branch']='a division of a stem' codewords['copy']='reproduce or make an exact copy of' # print all words for k,v in codewords.items(): print(k+": "+v) <file_sep>/chap4/4-7.py triple_numbers=list(range(3,31,3)) for triple_number in triple_numbers: print(triple_number)<file_sep>/chap5/5-4.py alien_color='red' if alien_color=='green': print("The player can get 5 points.") else: print("The player can get 10 points.") <file_sep>/chap3/3-8.py places=['China','America','England','Africa','Japan'] print(places) print("\n") print(sorted(places)) print("\n") print(places) print("\n") print(sorted(places,reverse=True)) print("\n") print(places) print("\n") places.reverse() print(places) print("\n") places.reverse() print(places) print("\n") places.sort() print(places) print("\n") places.sort(reverse=True) print(places) <file_sep>/chap4/4-12.py my_foods=['pizza','falafel','carrot cake'] friend_foods=my_foods[:] print("My foods are:") for my_food in my_foods: print(my_food) print("My friend's foods are:") for friend_food in friend_foods: print(friend_food) <file_sep>/chap6/6-3.py codewords={ 'array':'an arrangement of aerials spaced to give desired directional characteristics', 'byte':'computer memory unit', 'boolean':'a data type with only two possible values: true or false', 'debug':'locate and correct errors in a computer program code', 'address':'the code that identifies where a piece of information is stored' } print("array: "+codewords['array']) print("byte: "+codewords['byte']) print("boolean: "+codewords['boolean']) print("debug: "+codewords['debug']) print("address: "+codewords['address'])<file_sep>/chap8/8-6.py def city_country(city, country): full_name = '"' + city + ", " + country + '"' return full_name.title() n1 = city_country('shanghai', 'china') print(n1) n2 = city_country('tokyo', 'japan') print(n2) n3 = city_country('london', 'england') print(n3) <file_sep>/chap15/15-8.py import pygal from die import Die # 创建三个D6骰子 die_1 = Die() die_2 = Die() die_3 = Die() # 掷几次骰子,并将结果存储在一个列表中 results = [] for roll_num in range(1000000): result = die_1.roll() + die_2.roll() + die_3.roll() results.append(result) # 分析结果 frequencies = [] max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides for value in range(3, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # 对结果进行可视化 hist = pygal.Bar() # 创建一个pygal.Bar()实例,并将其存储在hist中 hist.title = "Results of rolling theree D6 dice 1,000,000 times" # 设置hist的属性title hist.x_labels = [str(x) for x in range(3, max_result + 1)] # 将掷骰子的可能结果用作x轴的标签 # 给每个轴添加标题 hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('D6+D6+D6', frequencies) # 第一个参数是指定的标签,第二个参数是一个包含图表中值的列表 hist.render_to_file('threeD6dice_visual.svg') # 将图标渲染为一个SVG文件 <file_sep>/chap4/4-3.py for value in range(1,21): print(value)<file_sep>/chap8/8-12.py def make_sandwich(*toppings): print(toppings) make_sandwich('chicken') make_sandwich('beef', 'chicken') make_sandwich('beef', 'chicken', 'fish') <file_sep>/chap8/8-7.py def make_album(singer_name, album_name): album = {'singer': singer_name, 'album': album_name} return album a1 = make_album('jaychou', 'love') print(a1) a2 = make_album('amei', 'beauty') print(a2) a3 = make_album('taylor', 'you') print(a3) def new_make_album(singer_name, album_name, album_nums=''): album = {'singer': singer_name, 'album': album_name} if album_nums: album['nums'] = album_nums return album a4 = new_make_album('jaychou', 'love', 6) print(a4) a5 = new_make_album('amei', 'beauty') print(a5) a6 = new_make_album('taylor', 'you') print(a6) <file_sep>/chap6/6-8.py dog={'type':'dog','owner':'lily'} cat={'type':'cat','owner':'mike'} pig={'type':'pig','owner':'linda'} pets=[dog,cat,pig] for pet in pets: print(pet)<file_sep>/chap9/9-1.py class Restaurant(): """a simple effort for a restaurant""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(self.restaurant_name) print(self.cuisine_type) def open_restaurant(self): print("This restaurant is opening.") restaurant = Restaurant("<NAME>", "hot pot") restaurant.describe_restaurant() restaurant.open_restaurant() <file_sep>/chap6/6-2.py favorite_nums={ 'Lily':1, 'Linda':2, 'Mike':3, 'Wendy':4, 'Zoe':5 } print(favorite_nums)<file_sep>/chap2/2-7.py name=" Zoe" print(name) print(name.lstrip()+"\n") print(name.rstrip()+"\t") print(name.strip())<file_sep>/chap7/7-2.py nums = input("how many people will dine?") if int(nums)>8: print("There is no a table available for 8.") else: print("There is an empty table.")<file_sep>/chap3/3-3.py trans=['bike','new energy car','Honda motorcycle'] print("I would like to own a "+trans[0]+".") print("I would like to own a "+trans[1]+".") print("I would like to own a "+trans[2]+".")<file_sep>/chap9/9-4.py class Restaurant(): """a simple effort for a restaurant""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print(self.restaurant_name) print(self.cuisine_type) def open_restaurant(self): print("This restaurant is opening.") def set_number_served(self, number): self.number_served = number def increment_number_served(self, number): self.number_served += number restaurant = Restaurant("big brother", "hot pot") print(restaurant.number_served) restaurant.number_served = 30 print(restaurant.number_served) restaurant.set_number_served(39) print(restaurant.number_served) restaurant.increment_number_served(10) print(restaurant.number_served) <file_sep>/chap8/8-3.py def make_shirt(size, words): print("The T-shirt is " + size + " and the words '" + words + "' are on it.") make_shirt('large', 'I love the world') make_shirt(words='I love the world', size='large') <file_sep>/chap4/4-10.py #choose 4-9.py cubes=[value**3 for value in range(1,11)] print(cubes) print("The first three items in the list are: "+str(cubes[:3])) print("Three items from the middle of the list are: "+str(cubes[4:7])) print("The last three items in the list are: "+str(cubes[-3:])) <file_sep>/chap8/8-1.py def display_message(): """show what you will learn in this chapter""" print("You will learn function in this chapter.") display_message()<file_sep>/chap8/8-8.py def make_album(singer_name, album_name): album = {'singer': singer_name, 'album': album_name} return album while True: print("\nPlease tell me the names of the singer and the album: ") print("(enter 'q' at any time to quit)") s_name = input("Singer name: ") if s_name == 'q': break a_name = input("Album name: ") if a_name == 'q': break a = make_album(s_name, a_name) print(a) <file_sep>/chap6/6-11.py cities={ 'new york':{ 'country':'america', 'population':'8.419 million ', 'fact':'New York City comprises 5 boroughs sitting where the Hudson River meets the Atlantic Ocean.', }, 'tokyo':{ 'country':'japan', 'population':'13.96 million', 'fact':'Tokyo, Japan’s busy capital, mixes the ultramodern and the traditional, from neon-lit skyscrapers to historic temples.', }, 'beijing':{ 'country':'china', 'population':'21.54 million', 'fact':'Beijing, China’s sprawling capital, has history stretching back 3 millennia.', }, } for city_name, city_info in cities.items(): print("\nCity: "+city_name.title()) print(city_info['country']) print(city_info['population']) print(city_info['fact']) <file_sep>/chap9/9-3.py class User(): def __init__(self, first_name, last_name, age, job): self.first_name = first_name self.last_name = last_name self.full_name = self.first_name + ' ' + self.last_name self.age = age self.job = job def describe_user(self): print("The information of the user is:") print("The full name is: " + self.full_name.title()) print("The age is: " + str(self.age)) print("The job is: " + self.job) def greet_user(self): print("Hello, " + self.full_name.title() + "!\n") user1 = User('jimi', 'hendrix', 32, 'teacher') user1.describe_user() user1.greet_user() user2 = User('jay', 'chou', 18, 'singer') user2.describe_user() user2.greet_user() user3 = User('rain', 'zhang', 40, 'actor') user3.describe_user() user3.greet_user() <file_sep>/chap2/2-4.py name="<NAME>" print(name.lower())#小写 print(name.upper())#大写 print(name.title())#首字母大写 <file_sep>/chap8/8-16/import1.py import pizza pizza.make_pizza(16, 'banana') <file_sep>/chap5/5-9.py users=['admin','Anna','Linda','Kim','Zoe'] if users: for user in users: if user=='admin': print("Hello admin, would you like to see a status report?") else: print("Hello "+user+", thank you for logging in again.") else: print("We need to find some users!") <file_sep>/chap3/3-1.py names=['Linda','Lily','Zoe'] print(names[0]) print(names[1]) print(names[2])#也可以写print(names[-1])<file_sep>/chap7/7-5.py prompt = "\nTell me your age:" prompt += "\nEnter 'quit' to end the program." active = True while active: age = input(prompt) if age == 'quit': active = False else: age = int(age) if age < 3: print("free") elif 3 <= age <= 12: print("10 $") elif age > 12: print("15 $") <file_sep>/chap8/8-16/import5.py from pizza import * make_pizza(16, 'banana') <file_sep>/chap5/5-10.py current_users=['Lily','Anna','Linda','Kim','Zoe'] new_users=['Lily','Anna','Sue','Mike','Chen'] for new_user in new_users: if new_user.title() in current_users or new_user.lower() in current_users or new_user.upper() in current_users:#ignore case print("Sorry, you should enter another user name.") else: print("This user name is not used by others.")
647f3dad23077ef7bbdb8bb79c4ad6b78d1b648c
[ "Python" ]
89
Python
StewedChickenwithStats/Answers-to-Python-Crash-Course
9ffbe02abba5d111f702d920db7932303daf59d4
df818245985b092729c92af2f0d80f3b71b8eb20
refs/heads/main
<repo_name>juansevargasc/SwiftUIIntro<file_sep>/Platzi/Platzi/TextMod.swift // // TextMod.swift // Platzi // // Created by <NAME> on 16/09/21. // import SwiftUI struct TextMod: View { var body: some View { Text("Hola mundo!!!,") .font(.largeTitle) .foregroundColor(Color.blue) .frame(width: 300, height: 100, alignment: .leading) .background(Color.black) } } struct TextMod_Previews: PreviewProvider { static var previews: some View { TextMod() } } <file_sep>/Platzi/Platzi/TextFields.swift // // TextFields.swift // Platzi // // Created by <NAME> on 17/09/21. // import SwiftUI struct TextFields: View { @State var textoVista: String = "Holi" // Indica que podemos mantener su estado var body: some View { // option + cmd + click para opciones VStack etc. VStack { Text(textoVista).bold() // Cada ciertos ciclos de reloj el sistema revisa la Estructura Text Fields y si tiene elementos como este Text(textoVista) para ver si han cambiado o no. TextField("Escribe contraseña", text: $textoVista) // Binding: Estamos uniendo TextoVista con lo que se introduce en la caja de texto. Button(action: {textoVista = "Juan"}, label: { Text("Cambia el texto de la vista") }) } } } struct TextFields_Previews: PreviewProvider { static var previews: some View { Group { TextFields() } } } <file_sep>/Platzi/Platzi/Playgrounds/structs.playground/Contents.swift import UIKit var greeting = "Hello, playground" struct calculadora { // propiedades var numero1:Int8 var numero2:Int8 init() { numero1 = 10 numero2 = 20 } // método func suma() -> Int8 { return numero1 + numero2 } func multiplicacion(numero1:Int8, numero2:Int8) -> Int8 { print() return self.numero1 * self.numero2 } } var instanciaSuma = calculadora() print(instanciaSuma.numero1) print(instanciaSuma.numero2) instanciaSuma.numero1 = 4 instanciaSuma.numero2 = 8 print(instanciaSuma.numero1) print(instanciaSuma.numero2) var instanciaSumaDos = instanciaSuma print(instanciaSumaDos.numero1) print(instanciaSumaDos.numero2) instanciaSuma.numero1 = 5 instanciaSuma.numero2 = 7 print(instanciaSuma.numero1) print(instanciaSuma.numero2) print(instanciaSumaDos.numero1) print(instanciaSumaDos.numero2) <file_sep>/Platzi/Platzi/Navigations.swift // // Navigations.swift // Platzi // // Created by <NAME> on 24/09/21. // import SwiftUI struct Navigations: View { @State var isDividersActive :Bool = false var body: some View { NavigationView { VStack { //La vista Text tiene estas características. Text("Hello, World!").navigationTitle("Home") .navigationBarTitleDisplayMode(.inline) .toolbar(content: { ToolbarItem( placement: .navigationBarTrailing) { Button(action: {isDividersActive.toggle()}, label: { Text("+") }) } }) NavigationLink("Navegar a TabViews!", destination: TabViews() ) NavigationLink( destination: Dividers(), isActive: $isDividersActive, label: { EmptyView() // Vista vacía, es buena práctica porque no consume recursos, mientras que Text("") sí lo haría. }) } //TODO: Modularizar el código, con un fondo mejor y con mejor tamaño el reproductor } } } struct Navigations_Previews: PreviewProvider { static var previews: some View { Navigations() } } <file_sep>/Platzi/Platzi/Dividers.swift // // Dividers.swift // Platzi // // Created by <NAME> on 17/09/21. // import SwiftUI struct Dividers: View { var body: some View { VStack { Circle().frame(width: 100, height: 100, alignment: .center) Text("Círculo Negro") Divider().frame(height: 8).background(Color.red) // Lo que está aumentando es el frame. Rectangle().foregroundColor(.blue) .frame(width: 200, height: 100, alignment: .center) Text("Rectángulo azul") } } } struct Dividers_Previews: PreviewProvider { static var previews: some View { Dividers() } } <file_sep>/Platzi/Platzi/PlatziApp.swift // // PlatziApp.swift // Platzi // // Created by <NAME> on 2/09/21. // import SwiftUI @main struct PlatziApp: App { var body: some Scene { WindowGroup { Player() } } } <file_sep>/Platzi/Platzi/Player.swift // // Player.swift // Platzi // // Created by <NAME> on 25/09/21. // import SwiftUI import AVKit struct Player: View { var body: some View { NavigationView { VideoButton() } } } //TODO: Modularizar el código, con un fondo mejor y con mejor tamaño el reproductor struct VideoButton: View { @State var isPlayerActive:Bool = false var body: some View { VStack { Button(action: {isPlayerActive = true}, label: { ZStack { Image("cuphead").resizable().aspectRatio(contentMode: .fit) Image(systemName: "play.fill").foregroundColor(.white) } }) NavigationLink( destination: PlayerSection(), isActive: $isPlayerActive, label: { EmptyView() }) } } } struct PlayerSection: View { var body: some View { ZStack { Color.black VideoPlayer(player: AVPlayer( url: URL(string: "https://cdn.cloudflare.steamstatic.com/steam/apps/256705156/movie480.mp4")!)).frame(width: 420, height: 360, alignment: .center)// Hay que ponerle ! un wrap, dado que URL podría arrojar excepción. }.ignoresSafeArea() } } struct Player_Previews: PreviewProvider { static var previews: some View { Player() PlayerSection() } } <file_sep>/Platzi/Platzi/Buttons.swift // // Buttons.swift // Platzi // // Created by <NAME> on 16/09/21. // import SwiftUI struct Buttons: View { var body: some View { VStack { Button("Mi primer botón", action: { //Closures. Pedazos de código dentro de un elemento. print("Pulsé mi botón") }) Button("Mi segundo botón") { print("Mi segundo BOTÓN 2") } Button(action: {saludo()}, label: { // Se podrían poner imágenes aquí Text("Botón con LABEL como argumento") }) } } func saludo() { print("Método EXTERNO saludooo") } } struct Buttons_Previews: PreviewProvider { static var previews: some View { Buttons() } // TODO: Create git repo to this project } <file_sep>/Platzi/Platzi/Playgrounds/variablesConstantes.playground/Contents.swift import Foundation //pr - nombre - tipo - oa - valor var x:Int8 = 2 let y:Float16 = 9.8 var r = Float16(x) + y print(r) <file_sep>/Platzi/Platzi/Playgrounds/Funciones.playground/Contents.swift import UIKit var greeting = "Hello, playground" // La más utilizada print("Hola", "Mundo", separator: "..") // Argumentos // Estructura func suma() { print("El resultado es dos") } // Llamada de función suma() // Estructura con parámetros de entrada func sumaXY(x: Int8, y:Int8) { print(x + y) } sumaXY(x: 10, y: 8) // Con retorno func sumaXYRetorno(numero1:Int, numero2:Int) -> Int { return numero1 + numero2 } var resultado = sumaXYRetorno(numero1: 2, numero2: 3) print(resultado) // Arguments labels func saluda(_ destinatario:String, deParte remitente:String) { print("Mando saludos a \(destinatario) de parte de \(remitente)") } saluda("Juan", deParte: "Platzi") <file_sep>/Platzi/Platzi/Images.swift // // Images.swift // Platzi // // Created by <NAME> on 17/09/21. // import SwiftUI struct Images: View { var body: some View { VStack { Text("IMÁGENES") Image("platzi").resizable() .aspectRatio(contentMode: .fit) .frame(width: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, height: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) Image("platzi").resizable() .aspectRatio(contentMode: .fit) .frame(width: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, height: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) .blur(radius: 8.0) // Blur Image("platzi").resizable() .aspectRatio(contentMode: .fit) .frame(width: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, height: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/).opacity(0.7) // Opacity. For things in background Button(action: {print("Bienvenido a Platzi")}, label: { Image("platzi").resizable() .aspectRatio(contentMode: .fit) .frame(width: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, height: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) }) Image(systemName: "moon.fill") } } } struct Images_Previews: PreviewProvider { static var previews: some View { Images() } } <file_sep>/Platzi/Platzi/ZStackPadding.swift // // ZStackPadding.swift // Platzi // // Created by <NAME> on 22/09/21. // import SwiftUI struct ZStackPadding: View { var body: some View { ZStack { Color.yellow // Lo que está atrás //Text("Platzi!") Spacer() VStack // Todo lo que está al frente { Text("Bienvenidos al curso").padding(.bottom, 6.0) DatosEntradaUsuario() Imagenes() TextMod() } }.ignoresSafeArea() } } struct Imagenes: View { var body: some View { VStack { Image("platzi").resizable().aspectRatio(contentMode: .fit) .frame(width: 100, height: 100, alignment: .center) Image("platzi").resizable().aspectRatio(contentMode: .fit) .frame(width: 100, height: 100, alignment: .center) Image("platzi").resizable().aspectRatio(contentMode: .fit) .frame(width: 100, height: 100, alignment: .center) } } } struct DatosEntradaUsuario: View { @State var curso: String = "iOS" var body: some View { ZStack { if curso == "" { Text("Curso") .foregroundColor(Color.blue) } TextField("Curso", text: $curso).padding(.leading, 8.0) } } } struct Reto: View { var body: some View { VStack(alignment: .trailing) { Text("1").border(Color.black) Text("2").border(Color.black) Text("3").border(Color.black) HStack { Text("A").foregroundColor(.black) .frame(width: 100, height: 100, alignment: .center) .background(Color.red) .border(Color.black) HStack(alignment: .top) { Text("B").border(Color.black).background(Color.red) .frame(width: 20, height: 100, alignment: .top) Text("C").border(Color.black).background(Color.red) .frame(width: 20, height: 100, alignment: .top) } }.background(Color.red) }.background(Color.blue) } } struct ZStackPadding_Previews: PreviewProvider { static var previews: some View { ZStackPadding() Imagenes() } } <file_sep>/Platzi/Platzi/HStackVStack.swift // // HStackVStack.swift // Platzi // // Created by <NAME> on 20/09/21. // import SwiftUI struct HStackVStack: View { var body: some View { // TODO: Homework 1. Make the design of picture called "reto" // VStack(alignment: .trailing) { Text("1").border(Color.black) Text("2").border(Color.black) Text("3").border(Color.black) HStack { Text("A").foregroundColor(.black) .frame(width: 100, height: 100, alignment: .center) .background(Color.red) .border(Color.black) HStack(alignment: .top) { Text("B").border(Color.black).background(Color.red) .frame(width: 20, height: 100, alignment: .top) Text("C").border(Color.black).background(Color.red) .frame(width: 20, height: 100, alignment: .top) } }.background(Color.red) }.background(Color.blue) } } struct HStackVStack_Previews: PreviewProvider { static var previews: some View { Image("reto") HStackVStack() } }
a93cbcbd874ad1a3a9a47d0c9c3cbbbcb99c87f4
[ "Swift" ]
13
Swift
juansevargasc/SwiftUIIntro
9d4de098400f38ac9972174cc060b0fd5eb94e77
6ccb2494d2db0e967c36f1a68ac6ebb6b883dd88
refs/heads/master
<file_sep><?php require("mysql_DB.php"); // initialize database open_database(); header ('Content-type: text/html; charset=utf-8'); ?> <html> <head> <?php if ((!array_key_exists('date_von',$_REQUEST)) or (!array_key_exists('date_bis', $_REQUEST)) ) { $today=time(); $date_bis=date('d-m-Y', $today); $date_von=date('d-m-Y', strtotime('-1 year')); } else { $date_von=$_POST['date_von']; $date_bis=$_POST['date_bis']; } echo 'The date is: "'.$date_von.'"'; echo 'The date is: "'.$date_bis.'"'; list($tag_v,$monat_v,$jahr_v)=split('[/.-]',$date_von); list($tag_b,$monat_b,$jahr_b)=split('[/.-]',$date_bis); echo " tag $tag_v monat $monat_v jahr $jahr_v Test<br />"; file_put_contents("/tmp/roman.txt",$mystr); ?> </head> <body> <?php $from = sprintf("%s-%s-%s",$jahr_v,$monat_v,$tag_v); $to = sprintf("%s-%s-%s",$jahr_b,$monat_b,$tag_b); $tape=$_REQUEST['tape']; echo "<pre>".$tape."</pre>"; echo "<b><center>Read/Write Errors on Tape $tape</center></b><br><br>"; $params ="?sys=".$tape."&from=".$from."&to=".$to; $params .="&table=tapes"; $params .="&graphs=read_err,write_err"; $params .="&graphs_names=read_err,write_err"; print "<img src=\"gnuplot_graph.php".str_replace(array(" ","\"","+"),array("%20","%22","%2B"),$params)."\"><br>\n"; ?> </body> </html> <file_sep><?php require("conf.php"); // initialize database //open_database(); //$host = "192.168.0.90"; //$user = "postgres"; //$pass = "<PASSWORD>"; //$db = "sensors"; $con = pg_connect("host=$host dbname=$db user=$user password=$pass") or die ("Could not connect to server\n"); header ('Content-type: text/html; charset=utf-8'); ?> <html> <head> <?php if ((!array_key_exists('date_von',$_REQUEST)) or (!array_key_exists('date_bis', $_REQUEST)) ) { $today=time(); $date_bis=date('d-m-Y', $today); $date_von=date('d-m-Y', strtotime('-2 day')); } else { $date_von=$_POST['date_von']; $date_bis=$_POST['date_bis']; } echo 'From date is: "'.$date_von.'"'; echo 'To date is: "'.$date_bis.'"'; // echo 'The date is: <pre>"'.$_POST['comment'].'</pre>"'; // printf("len comment %d \n ",strlen($_POST['comment'])); $mystr=$_POST['comment']; for ($a=0;$a<strlen($_POST['comment']);$a++) printf(" %02x", ord( $mystr[$a])); list($tag_v,$monat_v,$jahr_v)=split('[/.-]',$date_von); list($tag_b,$monat_b,$jahr_b)=split('[/.-]',$date_bis); // echo " tag $tag_v monat $monat_v jahr $jahr_v Test<br />"; file_put_contents("/tmp/roman.txt",$mystr); ?> <!-- Jquery resources--> <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"> <script src="/jquery/jquery-1.9.1.js"></script> <script src="/jquery/jquery-ui.js"></script> <!-- end of Jquery resources--> <script> $(function() { $( "#datepicker" ).datepicker({ showOn: "button", buttonImage: "/jquery/calendar.gif", buttonImageOnly: true, dateFormat: "dd-mm-yy", showWeek: true, changeMonth: true, changeYear: true, setDate: "<?php echo $date_von ?>" }); }); $(function() { $( "#datepicker1" ).datepicker({ showOn: "button", buttonImage: "/jquery/calendar.gif", buttonImageOnly: true, dateFormat: "dd-mm-yy", setDate: "<?php echo $date_bis ?>" }); }); </script> </head> <body> <form action="<?php echo $_SERVER['REQUEST_URI'];?>" method="post"> Date From: <input type="text" name="date_von" id="datepicker" value="<?php echo $date_von?>" /> Date To: <input type="text" name="date_bis" id="datepicker1" value="<?php echo $date_bis?>" /> <br/> <input type="submit" value="Send date" /> </form> <?php $from = sprintf("%s-%s-%s 00:00:00",$jahr_v,$monat_v,$tag_v); $to = sprintf("%s-%s-%s 23:59:59",$jahr_b,$monat_b,$tag_b); $query="select sensor from sensors where datetime >= '".$from."' AND datetime <= '".$to."' group by 1 order by 1"; echo "<pre>".$query."</pre>"; $result=pg_query($con,$query); $num=pg_num_rows($result); printf("<pre>%d</pre>\n",$num); echo "<b><center>Sensor Data</center></b><br><br>"; ?> <table border="1" cellspacing="2" cellpadding="2"> <tr> <th><font face="Arial, Helvetica, sans-serif">Sensor</font></th> </tr> <?php $i=0; while ($i < $num) { $sensor=pg_fetch_row($result,$i); ?> <tr> <td><font face="Arial, Helvetica, sans-serif"><?php echo "$sensor[0]"; ?></font></td> </tr> <?php ++$i; } echo "</table>"; $i=0; while ($i < $num) { $sensor=pg_fetch_row($result,$i); $params ="?sys=".$sensor[0]."&from=".$from."&to=".$to; $params .="&table=sensors"; $params .="&title=Sensor Data ".$sensor[0]; $params .="&graphs=value"; $params .="&graphs_names=values"; print "<img src=\"pg_gnuplot_temp.php".str_replace(array(" ","\"","+"),array("%20","%22","%2B"),$params)."\"><br>\n"; ++$i; } $params ="?sys=".$sensor[0]."&from=".$from."&to=".$to; $params .="&table=in_out"; $params .="&title=Temperature Data "; $params .="&graphs=in1_v,in2_v,out_v"; $params .="&graphs_names=inside1,inside2,outside"; print "<img src=\"pg_gnuplot_multi.php".str_replace(array(" ","\"","+"),array("%20","%22","%2B"),$params)."\"><br>\n"; ?> </body> </html> <file_sep><?php require("mysql_DB.php"); //usage: gnuplot_graph.php // required options: // from=YYYY-mm-dd // to=YYYY-mm-dd // table=<Database data table> // graphs=<Column name of database data table, comma separated for more than one> // sys=<system ID> // optional: // title=<title of graph> // graphs_axes=<line descriptions, comma separated for more than one> // graphs_names=<line descriptions, comma separated for more than one> // data_file=<filename> // png_file=<filename> // pdf_file=<filename> // initialize database open_database(); if (!array_key_exists('from',$_REQUEST) or !array_key_exists('to',$_REQUEST) or !array_key_exists('table',$_REQUEST) or !array_key_exists('graphs',$_REQUEST) or !array_key_exists('sys',$_REQUEST)) crit_error("Not all required options are defined:<br><li>from<li>to<li>table<li>graphs<li>sys"); // open files if (array_key_exists('data_file',$_REQUEST)) { $tmpfilename = $_REQUEST['data_file']; } else { $tmpfilename = tempnam("/tmp","GNUPLOT_TMP_"); } $tmpfile = fopen( $tmpfilename,"w"); if (!$tmpfile) crit_error("Could not open temporary file ".$tmpfilename); if (array_key_exists('pdf_file',$_REQUEST)) { $pdffilename = $_REQUEST['pdf_file']; $pngfilename = tempnam("/tmp","GNUPLOT_PNG_").".png"; } if (array_key_exists('png_file',$_REQUEST)) $pngfilename = $_REQUEST['png_file']; if (array_key_exists('title',$_REQUEST)) $title = $_REQUEST['title']; $query = "select datetime,value from ".$_REQUEST['table']." "; $query .= "where datetime>='".$_REQUEST['from']."' and datetime<='".$_REQUEST['to']."'"; $query .= " and sensor='".$_REQUEST['sys']."' order by datetime"; //header of tmp file fwrite($tmpfile,"#\n# Automatically generated by gnuplot_graph.php\n#\n#Query: ".$query."\n#\n#"); $nodata = false; if (get_rows($query,$result) < 1) $nodata=true; // prints colum names in header file $fields = array(); if (!$nodata) { foreach ($result[0] as $fn => $r) { fwrite($tmpfile,$fn." "); array_push($fields,$fn); } fwrite($tmpfile,"\n#\n"); //print data in file foreach ($result as $r) { foreach ($r as $f) fwrite($tmpfile,$f." "); fwrite($tmpfile,"\n"); } } fclose($tmpfile); // initialize descriptors for comminication with gnuplot $desc = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", "/tmp/error-output.txt", "a") ); $proc = proc_open("/usr/bin/tee /tmp/tee.out | /usr/bin/gnuplot", $desc, $pipes); if (!is_resource($proc)) { crit_error("Error executing gnuplot\n"); } else { /* set terminal png {small | medium | large} */ /* {transparent|notransparent} */ /* {picsize <xsize> <ysize>} */ /* {monochrome | gray |color} */ /* {<color0> <color1> <color2> ...} */ fwrite($pipes[0], "set terminal png truecolor small size 640,480\n"); // set X axe fwrite($pipes[0], "set xdata time\n"); fwrite($pipes[0], "set timefmt \"%Y-%m-%d %H:%M:%S\"\n"); fwrite($pipes[0], "set grid\n"); if ((strtotime($_REQUEST['to'])-strtotime($_REQUEST['from']))>172800) fwrite($pipes[0], "set format x \" %d/%m/%Y \"\n"); else fwrite($pipes[0], "set format x \" %d/%m/%y \\n%H:%M\"\n"); fwrite($pipes[0], "set xrange [\"".$_REQUEST['from']."\":\"".$_REQUEST['to']."\"]\n"); if($title) fwrite($pipes[0], "set title \"".$title."\"\n"); // get other parameters from URL foreach ($_REQUEST as $param => $value) if (($param != 'PHPSESSID') && ($param != 'data_file') && ($param != 'png_file') && ($param != 'pdf_file') && ($param != 'from') && ($param != 'to') && ($param != 'sys') && ($param != 'table') && ($param != 'graphs') && ($param != 'graphs_axes') && ($param != 'graphs_names')) fwrite($pipes[0], "set ".$param." ".str_replace("\\\"","\"",$value)."\n"); if ($nodata) fwrite($pipes[0],"set label \"No data for the selected period\" at graph 0.5,0.5 center\n"); // plots $plot_query = "plot "; $graphs = split(",",$_REQUEST['graphs']); if (array_key_exists('graphs_axes',$_REQUEST)) $graphs_a = split(",",$_REQUEST['graphs_axes']); if (array_key_exists('graphs_names',$_REQUEST)) $graphs_n = split(",",$_REQUEST['graphs_names']); $range = array(); foreach ($fields as $k => $v) array_push ($range,"$".($k+2)); foreach($graphs as $k => $graph) { if ($k != 0) $plot_query .=" , "; $plot_query .= "'".$tmpfilename."' using 1:("; $plot_query .= str_replace($fields,$range,$graph); $plot_query .=") "; if (isset($graphs_a[$k])) $plot_query .= "axes ".$graphs_a[$k]." "; if (isset($graphs_n[$k])) $plot_query .= "title \"".$graphs_n[$k]."\" "; //$plot_query .="with linespoints"; } fwrite($pipes[0],$plot_query."\n"); // $field_set = split(",",$_REQUEST['fields']); // foreach ($result as $r) { // fwrite($pipes[0],$r['date']." "); // foreach ($field_set as $f) // fwrite($pipes[0],$r[$f]." "); // fwrite($pipes[0],"\n"); // } // fwrite($pipes[0],"e\n"); fwrite($pipes[0], "save '/tmp/gnu.plt'\n"); // if needed save png_file. if (isset($pngfilename)) { fwrite($pipes[0], "set output \"".$pngfilename."\"\n"); fwrite($pipes[0], "replot\n"); } fclose($pipes[0]); $image = ""; while(!feof($pipes[1])) { $image .= fgets($pipes[1], 1024); } fclose($pipes[1]); $return_value = proc_close($proc); if (0) { // for debug print "<pre>"; print "DB query: ".$query."\n\n"; print "Gnuplot query: ".$plot_query."\n\n"; print_r($graphs); print "</pre>"; }else { header("Content-type: image/png"); header("Content-length: ".strlen($image)); print $image; } } //if needed create pdf file if (isset($pdffilename)) { require ('./pdf/class.ezpdf.php'); /*initialize pdf and dimentions*/ $d = array(); # d = document $d['pdf'] = & new Cezpdf(); $d['pdf']->ezSetCmMargins(1.5, 2.5, 1.0, 1.0); $d['pdf']->selectFont('./pdf/fonts/Helvetica.afm'); /*page-width */ $d['w'] = $d['pdf']->ez['pageWidth']; /*page-height*/ $d['h'] = $d['pdf']->ez['pageHeight']; /*top -margin*/ $d['tm'] = $d['pdf']->ez['topMargin']; /*bottom-margin*/ $d['bm'] = $d['pdf']->ez['bottomMargin']; /*left -margin*/ $d['lm'] = $d['pdf']->ez['leftMargin']; /*right -margin*/ $d['rm'] = $d['pdf']->ez['rightMargin']; /*center-x*/ $d['cx'] = $d['lm'] + ($d['w'] - $d['lm'] - $d['rm'] )/2; /*header & footer*/ $hs = 10; $footer ="this is the footer"; $title = "this is the title"; $logow = $d['w'] - $d['lm']/2 - $d['rm']/2 - 2*$hs; $rect_b = $d['h']-3*$d['tm']/4; $rect_h = $d['tm']/2; $img_base = $d['h']-11*$d['tm']/16; $tit_base = $img_base - $d['pdf']->getFontDecender(16); $footer_hs = $d['pdf']->getTextWidth(12,$footer)/2; $footer_fh = $d['pdf']->getFontHeight(12); $all = $d['pdf']->openObject(); $d['pdf']->saveState(); $d['pdf']->setColor(1.0,1.0,0.0); // set_color($d,"sun_jellow"); $d['pdf']->filledRectangle($d['lm']/2 ,$rect_b, 0.55*$logow ,$rect_h); $d['pdf']->setColor(1.0,0.0,0.0); // set_color($d,"sun_red"); $d['pdf']->filledRectangle($d['lm']/2 + $hs + 0.55*$logow ,$rect_b, 0.25*$logow ,$rect_h); $d['pdf']->setColor(0.0,0.0,1.0); // set_color($d,"sun_blue"); $d['pdf']->filledRectangle($d['lm']/2 + 2*$hs + 0.80*$logow ,$rect_b, 0.20*$logow ,$rect_h); $d['pdf']->setColor(1.0,0.0,1.0); // set_color($d,"doc_title"); $d['pdf']->addText($hs+$d['lm']/2,$tit_base,16,$title); $d['pdf']->setColor(1.0,1.0,1.0); // set_color($d,"white"); $d['pdf']->addTextWrap($d['lm']/2 +0.55*$logow,$tit_base,0.25*$logow,12,date('F Y'),'right',0,0); $d['pdf']->addPngFromFile('./sunlogo.png',$d['lm']/2 + 2*$hs + 0.90*$logow,$img_base,0,3*$d['tm']/8); $d['pdf']->setStrokeColor(0.0,0.0,0.0,1); // set_stroke_color($d,"black"); $d['pdf']->line($d['lm']/2,$d['bm']*3/4,$d['w']-$d['rm']/2,$d['bm']*3/4); $d['pdf']->setColor(1.0,1.0,1.0); // set_color($d,"black"); $d['pdf']->addText($d['cx']-$footer_hs,$d['bm']/2-$footer_fh/2,12,$footer); $d['pdf']->restoreState(); $d['pdf']->closeObject(); // note that object can be told to appear on just odd or even pages by changing 'all' to 'odd' or 'even'. $d['pdf']->addObject($all,'all'); /*page numeration*/ $d['pdf']->ezStartPageNumbers($d['w']-$d['rm'],$d['bm']/4,12,'left','page {PAGENUM} of {TOTALPAGENUM}',''); $d['pdf']->addPngFromFile($pngfilename,$d['lm']/2 ,$d['tm']+200,$d['w'] - $d['lm'] - $d['rm']); $pdfcode = $d['pdf']->ezOutput(); $fp = fopen($pdffilename,'w'); fwrite($fp,$pdfcode); fclose($fp); } //delete png temporary file if not requested in url if (!array_key_exists('png_file',$_REQUEST) && array_key_exists('pdf_file',$_REQUEST)) unlink($pngfilename); //delete data temporary file if not requested in url if (!array_key_exists('data_file',$_REQUEST)) unlink($tmpfilename); // Close DB connection close_database(); ?> <file_sep>-- load driver local driver = require "luasql.postgres" -- create environment object env = assert (driver.postgres()) -- connect to data source con = assert (env:connect("dbname=sensor user=postgres password=<PASSWORD> hostaddr=127.0.0.1")) local mqttclient = require("luamqttc/client") function callbc(topic,data) print("t: "..topic.." d: "..data) str=string.format("insert into sensors values(now(),'%s','%s')",topic,data) print(str) print(con:execute(str)) end print(mqttclient) cl=mqttclient.new("DBSub") host="localhost" timeout=2 cl:connect(host,1883,{timeout=timeout}) --cl:subscribe("outTopic/sensor/wind",2,callbc) cl:subscribe("outTopic/#",2,callbc) while (1) do cl:message_loop(.5) end <file_sep>-- load driver local driver = require "luasql.postgres" -- create environment object env = assert (driver.postgres()) -- connect to data source con = assert (env:connect("user=postgres password=<PASSWORD> hostaddr=127.0.0.1")) -- retrieve a cursor cur = assert (con:execute"SELECT * from pg_catalog.pg_tables") -- print all rows, the rows will be indexed by field names row = cur:fetch ({}, "a") while row do print(string.format("Name: %s, %s", row.tablename, row.tableowner)) -- reusing the table of results row = cur:fetch (row, "a") end -- close everything cur:close() -- already closed because all the result set was consumed con:close() env:close() <file_sep> # Linux connection for the Vaisala WXT530 Weather station Weather station is connected via USB to Linux, this few Lua scripts receive the messages and convert those to more readable form. Then sends the messages to mqtt, where everybody can subscribe for the particalur values. # Description The "split.lua" opens the serial connection to the weather station (default /dev/ttyUSB0) and reads the Vaisala WXT530 messages. Messages are compared agains the "val" table, which is an associative array. When match is found, message is converted to the coresponding value in the "val" table. For example : val["Ta"]='outTopic/sensor/temp' the "Ta" message from the WXT530, is converted to "outTopic/sensor/temp". The "outTopic/sensor/temp" will be the Topic of the MQTT Message together with the physical value. The "sub.lua", subscribe to MQTT for all "outTopic" messages and received values are stored in the PostgreSQL. In the "www" directory, are php scripts, which are called via php to generate appropriate gnuplot graphics from the stored sensor data. In the "conf.php" are all configurations parameter for the DB connection. By calling "temp2.php" in browser, the webpage should get the stored db values and particular physical values and create the graphics. # Why doing it via MQTT ? Since such an Vaisala Sensor is not a cheap thing and very precise instrument, may be more the one User/Program may be interessted for the Physical Values. One thing is to show historical data via DB, but what about triggering events as they Weather values get critical? For example, a small wind turbine needs to be break to hold, when wind speed reaches curtain limits. In this case, programm subscribe to wind speed data via MQTT and when ever sensor send the Wind data, the subscribe programm will get those as well. # Prerequisites: * https://github.com/Yongke/luamqttc MQTT Lua Client * Postgresql * MQTT Server such as Mosquito * luasql postgress * apache2 + php + php postgress * Gnuplot <file_sep><?php require("mysql_DB.php"); // initialize database open_database(); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="refresh" content="30" /> <meta http-equiv="content-type" content="text/html; charset=UTF8"> </head> <body> <canvas id="myCanvas" width="800" height=600" style="solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var l=1*800; ctx.font = "13px Times"; //outline ctx.moveTo(0,0); ctx.lineTo(l,0); ctx.lineTo(l,l*.5357); ctx.lineTo(0,l*.5355); //kids ctx.lineTo(0,0); ctx.moveTo(l*.2035,0); ctx.lineTo(l*.2035,l*.1696); <?php $query="select datetime,value from sensors where sensor='OutTopic/sensor/temp/1' order by datetime desc limit 1"; $result=mysql_query($query); $num=mysql_numrows($result); $temp=mysql_result($result,$i,"value"); $query="select datetime,avg(value) as value from sensors where sensor ='outTopic/sensor/temp/1' and datetime > DATE_SUB(NOW(), interval 1 HOUR) group by sensor"; $result=mysql_query($query); $num=mysql_numrows($result); $temp_o=mysql_result($result,$i,"value"); if ($temp > $temp_o) $delta="\u2191" ; else $delta="\u2193"; ?> ctx.fillText("Kids 1",l*.05,l*.075); ctx.fillText("<?php echo $temp?> \xB0C <?php echo $delta?>",l*.05,l*.075+15); <?php $query="select datetime,value from sensors where sensor='OutTopic/sensor/temp/5' order by datetime desc limit 1"; $result=mysql_query($query); $num=mysql_numrows($result); $temp=mysql_result($result,$i,"value"); $query="select datetime,avg(value) as value from sensors where sensor ='outTopic/sensor/temp/5' and datetime > DATE_SUB(NOW(), interval 1 HOUR) group by sensor"; $result=mysql_query($query); $num=mysql_numrows($result); $temp_o=mysql_result($result,$i,"value"); if ($temp > $temp_o) $delta="^" ; else $delta="v"; ?> //schlaf ctx.moveTo(0,l*(.5357-.2142)); ctx.lineTo(l*(.2857+.1428),l*(.5357-.2142)); ctx.fillText("Spalna 5",l*.07,l*.4); ctx.fillText("<?php echo $temp?> \xB0C <?php echo $delta?>",l*.07,l*.4+15); ctx.fillText("Chodba 3",l*.32,l*.2); <?php $query="select datetime,value from sensors where sensor='OutTopic/sensor/temp/3' order by datetime desc limit 1"; $result=mysql_query($query); $num=mysql_numrows($result); $temp=mysql_result($result,$i,"value"); $query="select datetime,avg(value) as value from sensors where sensor ='outTopic/sensor/temp/3' and datetime > DATE_SUB(NOW(), interval 1 HOUR) group by sensor"; $result=mysql_query($query); $num=mysql_numrows($result); $temp_o=mysql_result($result,$i,"value"); if ($temp > $temp_o) $delta="^" ; else $delta="v"; ?> ctx.fillText("<?php echo $temp?> \xB0C <?php echo $delta?>",l*.32,l*.2+15); ctx.fillText("Obyvacka 0",l*.7,l*.2); <?php $query="select datetime,value from sensors where sensor='OutTopic/sensor/temp/0' order by datetime desc limit 1"; $result=mysql_query($query); $num=mysql_numrows($result); $temp=mysql_result($result,$i,"value"); $query="select datetime,avg(value) as value from sensors where sensor ='outTopic/sensor/temp/0' and datetime > DATE_SUB(NOW(), interval 1 HOUR) group by sensor"; $result=mysql_query($query); $num=mysql_numrows($result); $temp_o=mysql_result($result,$i,"value"); if ($temp > $temp_o) $delta="^" ; else $delta="v"; ?> ctx.fillText("<?php echo $temp?> \xB0C <?php echo $delta?>",l*.7,l*.2+15); <?php $query="select datetime,value from sensors where sensor='OutTopic/sensor/humi/0' order by datetime desc limit 1"; $result=mysql_query($query); $num=mysql_numrows($result); $temp=mysql_result($result,$i,"value"); $query="select datetime,avg(value) as value from sensors where sensor ='outTopic/sensor/humi/0' and datetime > DATE_SUB(NOW(), interval 1 HOUR) group by sensor"; $result=mysql_query($query); $num=mysql_numrows($result); $temp_o=mysql_result($result,$i,"value"); if ($temp > $temp_o) $delta="^" ; else $delta="v"; ?> ctx.fillText("<?php echo $temp?> % <?php echo $delta?>",l*.7,l*.2+30); ctx.fillText("Veranda 2",l*.32,l*.6); <?php $query="select datetime,value from sensors where sensor='OutTopic/sensor/temp/2' order by datetime desc limit 1"; $result=mysql_query($query); $num=mysql_numrows($result); $temp=mysql_result($result,$i,"value"); $query="select datetime,avg(value) as value from sensors where sensor ='outTopic/sensor/temp/2' and datetime > DATE_SUB(NOW(), interval 1 HOUR) group by sensor"; $result=mysql_query($query); $num=mysql_numrows($result); $temp_o=mysql_result($result,$i,"value"); if ($temp > $temp_o) $delta="^" ; else $delta="v"; ?> ctx.fillText("<?php echo $temp?> \xB0C <?php echo $delta?>",l*.32,l*.6+15); <?php $query="select datetime,value from sensors where sensor='OutTopic/sensor/humi/2' order by datetime desc limit 1"; $result=mysql_query($query); $num=mysql_numrows($result); $temp=mysql_result($result,$i,"value"); $query="select datetime,avg(value) as value from sensors where sensor ='outTopic/sensor/humi/2' and datetime > DATE_SUB(NOW(), interval 1 HOUR) group by sensor"; $result=mysql_query($query); $num=mysql_numrows($result); $temp_o=mysql_result($result,$i,"value"); if ($temp > $temp_o) $delta="^" ; else $delta="v"; ?> ctx.fillText("<?php echo $temp?> % <?php echo $delta?>",l*.32,l*.6+30); ctx.moveTo(l*.2857,l*.5357); ctx.lineTo(l*.2857,l*(.5357-.2142)); ctx.moveTo(l*(.2857+.1428),l*.5357); ctx.lineTo(l*(.2857+.1428),l*(.5357-.2142)); ctx.moveTo(l*(.2035+.1982),0); ctx.lineTo(l*(.2035+.1982),l*.1696); ctx.moveTo(l*(.2035+.1982+.1285),0); ctx.lineTo(l*(.2035+.1982+.1285),l*.1696); ctx.moveTo(l*(.2035+.1982+.1285+.0821),0); ctx.lineTo(l*(.2035+.1982+.1285+.0821),l*.1696); ctx.moveTo(l*(.1571),l*.1696); ctx.lineTo(l*(.2035+.1982+.1285+.0821),l*.1696); ctx.moveTo(l*(.1571),l*.1696); ctx.lineTo(l*(.1571),l*(.5357-.2142)); ctx.stroke(); </script> </body> </html> <file_sep>#!/bin/bash /usr/bin/lua /home/pi/wetter/roman/sub.lua >/tmp/wetter2db.log & <file_sep><?php //$host="localhost"; $host="192.168.0.90"; $user="postgres"; $pass = "<PASSWORD>"; $db ="sensors"; ?><file_sep><?php header ('Content-type: text/html; charset=utf-8'); ?> <html> <head> <?php echo 'The date is: "'.$_POST['date_von'].'"'; echo 'The date is: "'.$_POST['date_bis'].'"'; echo 'The date is: <pre>"'.$_POST['comment'].'</pre>"'; printf("len comment %d \n ",strlen($_POST['comment'])); $mystr=$_POST['comment']; for ($a=0;$a<strlen($_POST['comment']);$a++) printf(" %02x", ord( $mystr[$a])); list($tag_v,$monat_v,$jahr_v)=split('[/.-]',$_POST['date_von']); list($tag_b,$monat_b,$jahr_b)=split('[/.-]',$_POST['date_bis']); echo " tag $tag_v monat $monat_v jahr $jahr_v Test<br />"; file_put_contents("/tmp/roman.txt",$mystr); ?> <!-- Jquery resources--> <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.9.1.js"></script> <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- end of Jquery resources--> <script> $(function() { $( "#datepicker" ).datepicker({ showOn: "button", buttonImageOnly: false, dateFormat: "dd-mm-yy", showWeek: true, changeMonth: true, changeYear: true, setDate: "<?php echo $_POST['date_von'] ?>" }); }); $(function() { $( "#datepicker1" ).datepicker({ showOn: "button", buttonImage: "images/calendar.gif", buttonImageOnly: false, dateFormat: "dd-mm-yy", setDate: "<?php echo $_POST['date_bis'] ?>" }); }); </script> </head> <body> <form action="<?php echo $_SERVER['REQUEST_URI'];?>" method="post"> Date From: <input type="text" name="date_von" id="datepicker" value="<?php echo $_POST['date_von'] ?>" /> Date To: <input type="text" name="date_bis" id="datepicker1" value="<?php echo $_POST['date_bis'] ?>" /> <br/> <textarea maxlength="2048" name="comment" rows="5" cols="75"><?php echo $_POST['comment'] ?></textarea> <input type="submit" value="Send date" /> </form> <?php $image_file = "tmp/image.png"; //$image_file = tempnam("tmp/","gnuplotout"); echo $image_file; $data_file = tempnam("/tmp","gnuplotout"); $handle = fopen($data_file, "w"); fprintf($handle, "2014/01/01 123\n"); fprintf($handle, "2014/01/02 121\n"); fprintf($handle, "2014/01/03 122\n"); fprintf($handle, "2014/01/04 123\n"); fprintf($handle, "2014/01/05 125\n"); fprintf($handle, "2014/01/06 123\n"); fclose($handle); $gplot_start = sprintf("%s/%s/%s",$jahr_v,$monat_v,$tag_v); $gplot_finish = sprintf("%s/%s/%s",$jahr_b,$monat_b,$tag_b); //$gplot_start = date("y/m/d", $_POST['date_von']); //$gplot_finish = date("y/m/d", $_POST['date_bis']); $gnuplot_cmds = <<< GNUPLOTCMDS set term png truecolor small size 800,600 set output "$image_file" set size 1, 1 set title "Title" set xlabel "Date" set ylabel "EURO" set grid set xdata time set timefmt "%Y/%m/%d" set xrange ["$gplot_start":"$gplot_finish"] set yrange [0:*] set format x "%d/%m/%Y" #set nokey plot "$data_file" using 1:2 with lines t 'Kurs' GNUPLOTCMDS; $gnuplot_cmds .= "\n"; // Start gnuplot if(!($pgp = popen("/usr/bin/gnuplot", "w"))){ # TODO Handle error exit; } fputs($pgp, $gnuplot_cmds); pclose($pgp); //header("Content-Type: image/png"); //passthru("cat $image_file"); // Clean up and exit //unlink($data_file); //unlink($image_file); echo '<p><img src="'. htmlspecialchars($image_file) . "?" . filemtime($image_file) . '"/></p>'; ?> </body> </html> <file_sep>local mqttclient = require("luamqttc/client") --local test="Xd=200c,Xm=29c,Tu=180,Tx=120db,Vi=120,Vi=120.1V" val={} val["Ta"]='outTopic/sensor/temp' val["Dm"]='outTopic/sensor/winddir' val["Pa"]='outTopic/sensor/airpres' val["Sm"]='outTopic/sensor/windspeed' val["Ua"]='outTopic/sensor/humi' val["Ri"]='outTopic/sensor/rain' val["Sx"]='outTopic/sensor/windspeedMax' fd=io.open("/dev/ttyUSB0","r") --fd=io.open("/tmp/wetter.pipe","r") if fd == nil then print("Couldn't open file ") os.exit() end function split3(str, pattern) pattern = pattern or "[^%s]+" if pattern:len() == 0 then pattern = "[^%s]+" end local parts = {__index = insert} setmetatable(parts, parts) str:gsub(pattern, parts) print(parts) setmetatable(parts, nil) parts.__index = nil return parts end function split2(str, delimiter) if (delimiter=='') then return false end local pos,array = 0, {} -- for each divider found for st,sp in function() return string.find(str, delimiter, pos, true) end do table.insert(array, string.sub(str, pos, st - 1)) --print(string.sub(str,pos,st-1)) pos = sp + 1 end table.insert(array, string.sub(str, pos)) return array end function split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do print(cap) if s ~= 1 or cap ~= "" then table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) table.insert(t, cap) end return t end function dump(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. dump(v) .. ',' end return s .. '} ' else return tostring(o) end end srv=mqttclient.new("Sensors") timeout=5 host="localhost" srv:connect(host,1883,{timeout=timeout}) while true do test=fd:read("*line") if test==nil then break end k1=split2(test,",") --print(dump(k1)) --print(k1) nr= table.getn(k1) for i = 1,nr do --print("test "..type(k1[i])) for k,v in string.gmatch(k1[i], "(%w+)=([%w%.]+)&*") do print("test2: "..k.." "..v) mstr=string.match(v,"[0-9]+") --print(mstr) num=tonumber(string.match(v,"(%d[,.%d]*)")) --print(num) --num=tonumber(v) --print(num) if (val[k]) then print (val[k].. " val ".. num) print(srv:publish(val[k],num)) end end end end <file_sep><?php ########################################################################## # # # (c) Sun Microsystems, Inc. # # Proactive Services Switzerland # # # # Ver: 1.0 # # # # Author: <NAME> (<EMAIL>) # # # ########################################################################## # # # Description: This file contains all the function that handle the # # error messages and access to the MySQL Database # # # # ALL ERROR MESSAGES PASS THROUGH THOSE FUNCTIONS # # ALL THE DB REQUESTS PASS THROUGH THOSE FUNCTIONS # # # # Functions: error($text) # # message($text) # # crit_error($text) # # modify_table($query) return affected rows # # get_rows($query,&$result) return number of rows # # open_database() # # close_database() # # # ########################################################################## $config_data = array( 'db_hostname' =>"localhost", 'db_user' =>"root", 'db_name' =>"sensors", ); /*error handling*/ function error($text) { echo "<h2><font color=\"#ff0000\">ERROR: ".$text."</font></h2><br>"; } function message($text) { echo "<h2><font color=\"#ff0000\">".$text."</font></h2><br>"; } function crit_error($text) { die("<h2><font color=\"#ff0000\">CRITICAL ERROR: ".$text."</font></h2><br>"); } # function that executes the sql query (normally insert/update/alter ... but not selects) # and returns the numer of affected rows function modify_table($query) { /* The connetion to the DB should already be established */ $t = mysql_query($query) or $error = mysql_error(); if (isset($error)) { error("Wrong SQL query</h2><br>Error message:". $error."<br>Executing: ".$query); return -1;#exit; } return mysql_affected_rows(); } # function that executes the sql query (normally a select) # and returns the numer of selected lines function get_rows($query,&$result) { /* The connetion to the DB should already be established */ $t = mysql_query($query) or $error = mysql_error(); if (isset($error)) { error("Wrong SQL query</h2><br>Error message:". $error."<br>Executing: ".$query); return -1;#exit; } $result = array(); # clears $result while ($r = mysql_fetch_array($t, MYSQL_ASSOC)) array_push($result,$r); $lines = mysql_num_rows($t); mysql_free_result($t); return $lines; } #function to open the database link function open_database() { # initialize database global $database_link,$config_data; $database_link = mysql_connect($config_data['db_hostname'],$config_data['db_user'],'65536') or crit_error("Could not connect to host \"".$config_data['db_hostname']."\" as \"".$config_data['db_user']."\"<br> Error: ". mysql_error()); mysql_select_db($config_data['db_name']) or crit_error("Could not select database: ". mysql_error() ); } #function to close the database link function close_database() { global $database_link; mysql_close($database_link); } ?>
2e4c67b397f2142f4bbc9adf3839d3ead53adb47
[ "Markdown", "PHP", "Shell", "Lua" ]
12
PHP
roman65536/weather
45e0bc949b859c8cd9c6a3240640f5b48bebf9b2
6d51d9149e39cc474d604fe4c96a5058e846314b
refs/heads/master
<file_sep>using System; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using AzureResourceManagerDeployment = Microsoft.Azure.Management.ResourceManager.Models.Deployment; namespace Calamari.AzureResourceGroup { class DeployAzureResourceGroupBehaviour : IDeployBehaviour { readonly TemplateService templateService; readonly IResourceGroupTemplateNormalizer parameterNormalizer; readonly ILog log; public DeployAzureResourceGroupBehaviour(TemplateService templateService, IResourceGroupTemplateNormalizer parameterNormalizer, ILog log) { this.templateService = templateService; this.parameterNormalizer = parameterNormalizer; this.log = log; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment deployment) { var variables = deployment.Variables; var subscriptionId = variables[AzureAccountVariables.SubscriptionId]; var tenantId = variables[AzureAccountVariables.TenantId]; var clientId = variables[AzureAccountVariables.ClientId]; var password = variables[AzureAccountVariables.Password]; var templateFile = variables.Get(SpecialVariables.Action.Azure.Template, "template.json"); var templateParametersFile = variables.Get(SpecialVariables.Action.Azure.TemplateParameters, "parameters.json"); var filesInPackage = variables.Get(SpecialVariables.Action.Azure.TemplateSource, String.Empty) == "Package"; if (filesInPackage) { templateFile = variables.Get(SpecialVariables.Action.Azure.ResourceGroupTemplate); templateParametersFile = variables.Get(SpecialVariables.Action.Azure.ResourceGroupTemplateParameters); } var resourceManagementEndpoint = variables.Get(AzureAccountVariables.ResourceManagementEndPoint, DefaultVariables.ResourceManagementEndpoint); if (resourceManagementEndpoint != DefaultVariables.ResourceManagementEndpoint) log.InfoFormat("Using override for resource management endpoint - {0}", resourceManagementEndpoint); var activeDirectoryEndPoint = variables.Get(AzureAccountVariables.ActiveDirectoryEndPoint, DefaultVariables.ActiveDirectoryEndpoint); log.InfoFormat("Using override for Azure Active Directory endpoint - {0}", activeDirectoryEndPoint); var resourceGroupName = variables[SpecialVariables.Action.Azure.ResourceGroupName]; var deploymentName = !string.IsNullOrWhiteSpace(variables[SpecialVariables.Action.Azure.ResourceGroupDeploymentName]) ? variables[SpecialVariables.Action.Azure.ResourceGroupDeploymentName] : GenerateDeploymentNameFromStepName(variables[ActionVariables.Name]); var deploymentMode = (DeploymentMode) Enum.Parse(typeof (DeploymentMode), variables[SpecialVariables.Action.Azure.ResourceGroupDeploymentMode]); var template = templateService.GetSubstitutedTemplateContent(templateFile, filesInPackage, variables); var parameters = !string.IsNullOrWhiteSpace(templateParametersFile) ? parameterNormalizer.Normalize(templateService.GetSubstitutedTemplateContent(templateParametersFile, filesInPackage, variables)) : null; log.Info($"Deploying Resource Group {resourceGroupName} in subscription {subscriptionId}.\nDeployment name: {deploymentName}\nDeployment mode: {deploymentMode}"); // We re-create the client each time it is required in order to get a new authorization-token. Else, the token can expire during long-running deployments. Func<Task<IResourceManagementClient>> createArmClient = async () => { var token = new TokenCredentials(await ServicePrincipal.GetAuthorizationToken(tenantId, clientId, password, resourceManagementEndpoint, activeDirectoryEndPoint)); var resourcesClient = new ResourceManagementClient(token) { SubscriptionId = subscriptionId, BaseUri = new Uri(resourceManagementEndpoint), }; resourcesClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); resourcesClient.HttpClient.BaseAddress = new Uri(resourceManagementEndpoint); return resourcesClient; }; await CreateDeployment(createArmClient, resourceGroupName, deploymentName, deploymentMode, template, parameters); await PollForCompletion(createArmClient, resourceGroupName, deploymentName, variables); } internal static string GenerateDeploymentNameFromStepName(string stepName) { var deploymentName = stepName ?? string.Empty; deploymentName = deploymentName.ToLower(); deploymentName = Regex.Replace(deploymentName, "\\s", "-"); deploymentName = new string(deploymentName.Select(x => (char.IsLetterOrDigit(x) || x == '-') ? x : '-').ToArray()); deploymentName = Regex.Replace(deploymentName, "-+", "-"); deploymentName = deploymentName.Trim('-', '/'); // Azure Deployment Names can only be 64 characters == 31 chars + "-" (1) + Guid (32 chars) deploymentName = deploymentName.Length <= 31 ? deploymentName : deploymentName.Substring(0, 31); deploymentName = deploymentName + "-" + Guid.NewGuid().ToString("N"); return deploymentName; } async Task CreateDeployment(Func<Task<IResourceManagementClient>> createArmClient, string resourceGroupName, string deploymentName, DeploymentMode deploymentMode, string template, string parameters) { log.Verbose($"Template:\n{template}\n"); if (parameters != null) { log.Verbose($"Parameters:\n{parameters}\n"); } using (var armClient = await createArmClient()) { try { var createDeploymentResult = await armClient.Deployments.BeginCreateOrUpdateAsync(resourceGroupName, deploymentName, new AzureResourceManagerDeployment { Properties = new DeploymentProperties { Mode = deploymentMode, Template = template, Parameters = parameters } }); log.Info($"Deployment created: {createDeploymentResult.Id}"); } catch (Microsoft.Rest.Azure.CloudException ex) { log.Error("Error submitting deployment"); log.Error(ex.Message); LogCloudError(ex.Body, 0); throw; } } } async Task PollForCompletion(Func<Task<IResourceManagementClient>> createArmClient, string resourceGroupName, string deploymentName, IVariables variables) { // While the deployment is running, we poll to check its state. // We increase the poll interval according to the Fibonacci sequence, up to a maximum of 30 seconds. var currentPollWait = 1; var previousPollWait = 0; var continueToPoll = true; const int maxWaitSeconds = 30; while (continueToPoll) { await Task.Delay(TimeSpan.FromSeconds(Math.Min(currentPollWait, maxWaitSeconds))); log.Verbose("Polling for status of deployment..."); using (var armClient = await createArmClient()) { var deployment = await armClient.Deployments.GetAsync(resourceGroupName, deploymentName); if (deployment.Properties == null) { log.Verbose("Failed to find deployment.Properties"); return; } log.Verbose($"Provisioning state: {deployment.Properties.ProvisioningState}"); switch (deployment.Properties.ProvisioningState) { case "Succeeded": log.Info($"Deployment {deploymentName} complete."); log.Info(GetOperationResults(armClient, resourceGroupName, deploymentName)); CaptureOutputs(deployment.Properties.Outputs?.ToString(), variables); continueToPoll = false; break; case "Failed": throw new CommandException($"Azure Resource Group deployment {deploymentName} failed:\n" + GetOperationResults(armClient, resourceGroupName, deploymentName)); case "Canceled": throw new CommandException($"Azure Resource Group deployment {deploymentName} was canceled:\n" + GetOperationResults(armClient, resourceGroupName, deploymentName)); default: if (currentPollWait < maxWaitSeconds) { var temp = previousPollWait; previousPollWait = currentPollWait; currentPollWait = temp + currentPollWait; } break; } } } } static string GetOperationResults(IResourceManagementClient armClient, string resourceGroupName, string deploymentName) { var operations = armClient?.DeploymentOperations.List(resourceGroupName, deploymentName); if (operations == null) return null; var log = new StringBuilder("Operations details:\n"); foreach (var operation in operations) { if (operation?.Properties == null) continue; log.AppendLine($"Resource: {operation.Properties.TargetResource?.ResourceName}"); log.AppendLine($"Type: {operation.Properties.TargetResource?.ResourceType}"); log.AppendLine($"Timestamp: {operation.Properties.Timestamp?.ToLocalTime():s}"); log.AppendLine($"Deployment operation: {operation.Id}"); log.AppendLine($"Status: {operation.Properties.StatusCode}"); log.AppendLine($"Provisioning State: {operation.Properties.ProvisioningState}"); if (operation.Properties.StatusMessage != null) log.AppendLine($"Status Message: {JsonConvert.SerializeObject(operation.Properties.StatusMessage)}"); } return log.ToString(); } void CaptureOutputs(string outputsJson, IVariables variables) { if (string.IsNullOrWhiteSpace(outputsJson)) return; log.Verbose("Deployment Outputs:"); log.Verbose(outputsJson); var outputs = JObject.Parse(outputsJson); foreach (var output in outputs) { log.SetOutputVariable($"AzureRmOutputs[{output.Key}]", output.Value["value"].ToString(), variables); } } void LogCloudError(Microsoft.Rest.Azure.CloudError error, int count) { if (count > 5) { return; } if (error != null) { string indent = new string(' ', count * 4); if (!string.IsNullOrEmpty(error.Message)) { log.Error($"{indent}Message: {error.Message}"); } if (!string.IsNullOrEmpty(error.Code)) { log.Error($"{indent}Code: {error.Code}"); } if (!string.IsNullOrEmpty(error.Target)) { log.Error($"{indent}Target: {error.Target}"); } foreach (var errorDetail in error.Details) { LogCloudError(errorDetail, ++count); } } } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace Calamari.Testing.Requirements { public class RequiresBashDotExeIfOnWindowsAttribute : NUnitAttribute, IApplyToTest { public void ApplyToTest(Test test) { if (CalamariEnvironment.IsRunningOnWindows && !BashExeExists) { test.RunState = RunState.Skipped; test.Properties.Set(PropertyNames.SkipReason, "This test needs bash.exe (which comes with WSL) on windows"); } } bool BashExeExists { get { var bashPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "bash.exe"); return File.Exists(bashPath); } } } } <file_sep>using System; using System.IO; using Calamari.Common.Plumbing.FileSystem; using Calamari.Integration.Packages.Download; using Calamari.Testing; using Calamari.Testing.Helpers; using NUnit.Framework; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] #if NETFX [Ignore("GitHub tests are not run in .netcore to reduce throttling exceptions from GitHub itself.")] #endif public class GitHubPackageDownloadFixture { //See "GitHub Test Account" static readonly string AuthFeedUri = "https://api.github.com"; static readonly string FeedUsername = ExternalVariables.Get(ExternalVariable.GitHubUsername); static readonly string FeedPassword = ExternalVariables.Get(ExternalVariable.GitHubPassword); static readonly CalamariPhysicalFileSystem fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); static string home = Path.GetTempPath(); [OneTimeSetUp] public void TestFixtureSetUp() { Environment.SetEnvironmentVariable("TentacleHome", home); } [OneTimeTearDown] public void TestFixtureTearDown() { Environment.SetEnvironmentVariable("TentacleHome", null); } [SetUp] public void SetUp() { var rootDir = new PackageDownloaderUtils().RootDirectory; if (Directory.Exists(rootDir)) Directory.Delete(rootDir, true); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] //Keeps rate limit low public void DownloadsPackageFromGitHub() { var downloader = GetDownloader(); var file = downloader.DownloadPackage("OctopusDeploy/Octostache", new SemanticVersion("2.1.8"), "feed-github", new Uri(AuthFeedUri), FeedUsername, FeedPassword, true, 3, TimeSpan.FromSeconds(3)); Assert.Greater(file.Size, 0); Assert.IsFalse(String.IsNullOrWhiteSpace(file.Hash)); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] //Keeps rate limit low public void WillReUseFileIfItExists() { var downloader = GetDownloader(); var file1 = downloader.DownloadPackage("OctopusDeploy/Octostache", new SemanticVersion("2.1.7"), "feed-github", new Uri(AuthFeedUri), FeedUsername, FeedPassword, true, 3, TimeSpan.FromSeconds(3)); Assert.Greater(file1.Size, 0); var file2 = downloader.DownloadPackage("OctopusDeploy/Octostache", new SemanticVersion("2.1.7"), "feed-github", new Uri("https://WillFailIfInvoked"), null, null, false, 3, TimeSpan.FromSeconds(3)); Assert.AreEqual(file1.FullFilePath, file1.FullFilePath); Assert.AreEqual(file1.Hash, file2.Hash); Assert.AreEqual(file1.Size, file1.Size); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] //Keeps rate limit low public void DownloadsPackageFromGitHubWithDifferentVersionFormat() { var downloader = GetDownloader(); var file = downloader.DownloadPackage("octokit/octokit.net", new SemanticVersion("0.28.0"), "feed-github", new Uri(AuthFeedUri), FeedUsername, FeedPassword, true, 3, TimeSpan.FromSeconds(3)); Assert.Greater(file.Size, 0); Assert.IsFalse(String.IsNullOrWhiteSpace(file.Hash)); } static GitHubPackageDownloader GetDownloader() { return new GitHubPackageDownloader(new InMemoryLog(), fileSystem); } } } <file_sep>using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; namespace Calamari.Deployment.Conventions { public class RollbackScriptConvention : PackagedScriptRunner, IRollbackConvention { public RollbackScriptConvention(ILog log, string scriptFilePrefix, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(log, scriptFilePrefix, fileSystem, scriptEngine, commandLineRunner) { } public void Rollback(RunningDeployment deployment) { RunPreferredScript(deployment); } public void Cleanup(RunningDeployment deployment) { if (deployment.Variables.GetFlag(SpecialVariables.DeleteScriptsOnCleanup, true)) { DeleteScripts(deployment); } } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Variables; namespace Calamari.Commands { [Command("structured-config-variables")] public class StructuredConfigVariablesCommand : Command<StructuredConfigVariablesCommandInputs> { readonly IVariables variables; readonly IStructuredConfigVariablesService structuredConfigVariablesService; public StructuredConfigVariablesCommand(IVariables variables, IStructuredConfigVariablesService structuredConfigVariablesService) { this.variables = variables; this.structuredConfigVariablesService = structuredConfigVariablesService; } protected override void Execute(StructuredConfigVariablesCommandInputs inputs) { var targetPath = variables.GetRaw(inputs.TargetPathVariable); if (targetPath == null) { throw new CommandException($"Could not locate target path from variable {inputs.TargetPathVariable} for {nameof(StructuredConfigVariablesCommand)}"); } structuredConfigVariablesService.ReplaceVariables(targetPath); } } public class StructuredConfigVariablesCommandInputs { public string TargetPathVariable { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Proxies; using Calamari.Common.Plumbing.Variables; using Calamari.Terraform.Helpers; using Newtonsoft.Json; using NuGet.Versioning; namespace Calamari.Terraform { class TerraformCliExecutor : IDisposable { readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; readonly RunningDeployment deployment; readonly IVariables variables; readonly Dictionary<string, string> environmentVariables; readonly string templateDirectory; readonly string logPath; Dictionary<string, string> defaultEnvironmentVariables; readonly TemporaryDirectory disposableDirectory = TemporaryDirectory.Create(); bool haveLoggedUntestedVersionInfoMessage = false; readonly VersionRange supportedVersionRange = new VersionRange(NuGetVersion.Parse("0.11.15"), true, NuGetVersion.Parse("1.1"), false); public TerraformCliExecutor( ILog log, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner, RunningDeployment deployment, Dictionary<string, string> environmentVariables ) { this.log = log; this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; this.deployment = deployment; variables = deployment.Variables; this.environmentVariables = environmentVariables; logPath = Path.Combine(deployment.CurrentDirectory, "terraform.log"); /* * Terraform has an issue where it will not clean up temporary files created while downloading * providers: https://github.com/hashicorp/terraform/issues/28477 * * By overriding the temporary directory and cleaning it up when Calamari is done, * we can work around the the issue. * * https://golang.org/pkg/os/#TempDir * On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, * it uses GetTempPath, returning the first non-empty value from %TMP%, * %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp. */ this.environmentVariables["TMP"] = disposableDirectory.DirectoryPath; this.environmentVariables["TEMP"] = disposableDirectory.DirectoryPath; this.environmentVariables["TMPDIR"] = disposableDirectory.DirectoryPath; templateDirectory = variables.Get(TerraformSpecialVariables.Action.Terraform.TemplateDirectory, deployment.CurrentDirectory); if (!string.IsNullOrEmpty(templateDirectory)) { var templateDirectoryTemp = Path.Combine(deployment.CurrentDirectory, templateDirectory); if (!Directory.Exists(templateDirectoryTemp)) throw new Exception($"Directory {templateDirectory} does not exist."); templateDirectory = templateDirectoryTemp; } InitializeTerraformEnvironmentVariables(); Version = GetVersion(); InitializePlugins(); InitializeWorkspace(); } public Version Version { get; } public string ActionParams => variables.Get(TerraformSpecialVariables.Action.Terraform.AdditionalActionParams); /// <summary> /// Create a list of -var-file arguments from the newline separated list of variable files /// </summary> public string TerraformVariableFiles { get { var varFilesAsString = deployment.Variables.Get(TerraformSpecialVariables.Action.Terraform.VarFiles); if (varFilesAsString == null) return null; var varFiles = Regex.Split(varFilesAsString, "\r?\n") .Select(var => $"-var-file=\"{var}\"") .ToList(); return string.Join(" ", varFiles); } } public CommandResult ExecuteCommand(params string[] arguments) { return ExecuteCommandAndVerifySuccess(arguments, out var result, true); } public CommandResult ExecuteCommand(out string result, params string[] arguments) { return ExecuteCommand(out result, true, arguments); } public CommandResult ExecuteCommand(out string result, bool outputToCalamariConsole, params string[] arguments) { return ExecuteCommandInternal(arguments, out result, outputToCalamariConsole); } public void Dispose() { var attachLogFile = variables.GetFlag(TerraformSpecialVariables.Action.Terraform.AttachLogFile); if (attachLogFile) { var crashLogPath = Path.Combine(deployment.CurrentDirectory, "crash.log"); if (fileSystem.FileExists(logPath)) log.NewOctopusArtifact(fileSystem.GetFullPath(logPath), fileSystem.GetFileName(logPath), fileSystem.GetFileSize(logPath)); //When terraform crashes, the information would be contained in the crash.log file. We should attach this since //we don't want to blow that information away in case it provides something relevant https://www.terraform.io/docs/internals/debugging.html#interpreting-a-crash-log if (fileSystem.FileExists(crashLogPath)) log.NewOctopusArtifact(fileSystem.GetFullPath(crashLogPath), fileSystem.GetFileName(crashLogPath), fileSystem.GetFileSize(crashLogPath)); } disposableDirectory.Dispose(); } public void VerifySuccess(CommandResult commandResult, Predicate<CommandResult> isSuccess) { LogUntestedVersionMessageIfNeeded(commandResult, isSuccess); if (isSuccess == null || !isSuccess(commandResult)) commandResult.VerifySuccess(); } public void VerifySuccess(CommandResult commandResult) { VerifySuccess(commandResult, r => r.ExitCode == 0); } void LogUntestedVersionMessageIfNeeded(CommandResult commandResult, Predicate<CommandResult> isSuccess) { if (this.Version != null && !supportedVersionRange.Satisfies(new NuGetVersion(Version))) { var messageCode = "Terraform-Configuration-UntestedTerraformCLIVersion"; var message = $"{log.FormatLink($"https://g.octopushq.com/Terraform#{messageCode.ToLower()}", messageCode)}: Terraform steps are tested against versions {(supportedVersionRange.IsMinInclusive ? "" : ">")}{supportedVersionRange.MinVersion.ToNormalizedString()} to {(supportedVersionRange.IsMaxInclusive ? "" : "<")}{supportedVersionRange.MaxVersion.ToNormalizedString()} of the Terraform CLI. Version {Version} of Terraform CLI has not been tested, however Terraform commands may work successfully with this version. Click the error code link for more information."; if (isSuccess == null || !isSuccess(commandResult)) { log.Warn(message); } else if (!haveLoggedUntestedVersionInfoMessage) // Only want to log an info message once, not on every command { log.Info(message); haveLoggedUntestedVersionInfoMessage = true; } } } CommandResult ExecuteCommandAndVerifySuccess(string[] arguments, out string result, bool outputToCalamariConsole) { var commandResult = ExecuteCommandInternal(arguments, out result, outputToCalamariConsole); VerifySuccess(commandResult); return commandResult; } CommandResult ExecuteCommandInternal(string[] arguments, out string result, bool outputToCalamariConsole) { var environmentVar = defaultEnvironmentVariables; if (environmentVariables != null) environmentVar.AddRange(environmentVariables); var terraformExecutable = variables.Get(TerraformSpecialVariables.Action.Terraform.CustomTerraformExecutable) ?? $"terraform{(CalamariEnvironment.IsRunningOnWindows ? ".exe" : string.Empty)}"; var captureOutput = new CaptureInvocationOutputSink(); var commandLineInvocation = new CommandLineInvocation(terraformExecutable, arguments) { WorkingDirectory = templateDirectory, EnvironmentVars = environmentVar, OutputToLog = outputToCalamariConsole, AdditionalInvocationOutputSink = captureOutput }; log.Info(commandLineInvocation.ToString()); var commandResult = commandLineRunner.Execute(commandLineInvocation); result = string.Join("\n", captureOutput.Infos); return commandResult; } void InitializePlugins() { var initParams = variables.Get(TerraformSpecialVariables.Action.Terraform.AdditionalInitParams); var allowPluginDownloads = variables.GetFlag(TerraformSpecialVariables.Action.Terraform.AllowPluginDownloads, true); string initCommand = $"init -no-color"; if (Version?.IsLessThan("0.15.0") == true) initCommand += $" -get-plugins={allowPluginDownloads.ToString().ToLower()}"; initCommand += $" {initParams}"; ExecuteCommandAndVerifySuccess(new[] { initCommand }, out _, true); } class TerraformVersionCommandOutput { [JsonProperty("terraform_version")] public string Version { get; set; } } Version GetVersion() { ExecuteCommandAndVerifySuccess(new[] { "version --json" }, out string consoleOutput, true); Version parsedVersion = null; bool hasParsingFailed = false; var versionJsonOutput = JsonConvert.DeserializeObject<TerraformVersionCommandOutput>(consoleOutput, new JsonSerializerSettings { // this prevents NewtonsoftJson from throwing an exception Error = (sender, args) => { hasParsingFailed = true; args.ErrorContext.Handled = true; } }); if (hasParsingFailed || !Version.TryParse(versionJsonOutput.Version, out parsedVersion)) { // fallback to regex match for older versions var versionString = Regex.Match(consoleOutput, @"Terraform v([0-9\.]*)"); if (versionString.Success && versionString.Groups.Count > 1 && !Version.TryParse(versionString.Groups[1].Value, out parsedVersion)) { log.Warn($"Could not parse Terraform CLI version. This might indicate you are using a version that is not supported or that an unexpected output was received from Terraform CLI."); } } return parsedVersion; } void InitializeWorkspace() { var workspace = variables.Get(TerraformSpecialVariables.Action.Terraform.Workspace); if (!string.IsNullOrWhiteSpace(workspace)) { ExecuteCommandAndVerifySuccess(new[] { "workspace list" }, out var results, true); foreach (var line in results.Split('\n')) { var workspaceName = line.Trim('*', ' '); if (workspaceName.Equals(workspace)) { ExecuteCommandAndVerifySuccess(new[] { $"workspace select \"{workspace}\"" }, out _, true); return; } } ExecuteCommandAndVerifySuccess(new[] { $"workspace new \"{workspace}\"" }, out _, true); } } void InitializeTerraformEnvironmentVariables() { defaultEnvironmentVariables = ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables().ToDictionary(e => e.Key, e => e.Value); defaultEnvironmentVariables.Add("TF_IN_AUTOMATION", "1"); defaultEnvironmentVariables.Add("TF_LOG", "TRACE"); defaultEnvironmentVariables.Add("TF_LOG_PATH", logPath); defaultEnvironmentVariables.Add("TF_INPUT", "0"); var customPluginDir = deployment.Variables.Get(TerraformSpecialVariables.Action.Terraform.PluginsDirectory); var pluginsPath = Path.Combine(deployment.CurrentDirectory, "terraformplugins"); fileSystem.EnsureDirectoryExists(pluginsPath); if (!string.IsNullOrEmpty(customPluginDir)) fileSystem.CopyDirectory(customPluginDir, pluginsPath); defaultEnvironmentVariables.Add("TF_PLUGIN_CACHE_DIR", pluginsPath); } class CaptureInvocationOutputSink : ICommandInvocationOutputSink { public List<string> Infos { get; } = new List<string>(); public void WriteInfo(string line) { Infos.Add(line); } public void WriteError(string line) { } } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Integration.Certificates; namespace Calamari.Commands { [Command("import-certificate", Description = "Imports a X.509 certificate into a Windows certificate store")] public class ImportCertificateCommand : Command { readonly IVariables variables; public ImportCertificateCommand(IVariables variables) { this.variables = variables; } public override int Execute(string[] commandLineArguments) { ImportCertificate(); return 0; } void ImportCertificate() { var certificateVariable = GetMandatoryVariable(variables, SpecialVariables.Action.Certificate.CertificateVariable); var pfxBytes = Convert.FromBase64String(GetMandatoryVariable(variables, $"{certificateVariable}.{CertificateVariables.Properties.Pfx}")); var password = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Password}"); var thumbprint = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Thumbprint}"); var storeName = GetMandatoryVariable(variables, SpecialVariables.Action.Certificate.StoreName); var privateKeyExportable = variables.GetFlag(SpecialVariables.Action.Certificate.PrivateKeyExportable, false); // Either a store-location (LocalMachine or CurrentUser) or a user can be supplied StoreLocation storeLocation; var locationSpecified = Enum.TryParse(variables.Get(SpecialVariables.Action.Certificate.StoreLocation), out storeLocation); ValidateStore(locationSpecified ? (StoreLocation?)storeLocation : null, storeName); try { if (locationSpecified) { Log.Info( $"Importing certificate '{variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Subject}")}' with thumbprint '{thumbprint}' into store '{storeLocation}\\{storeName}'"); WindowsX509CertificateStore.ImportCertificateToStore(pfxBytes, password, storeLocation, storeName, privateKeyExportable); if (storeLocation == StoreLocation.LocalMachine) { // Set private-key access var privateKeyAccessRules = GetPrivateKeyAccessRules(variables); if (privateKeyAccessRules.Any()) WindowsX509CertificateStore.AddPrivateKeyAccessRules(thumbprint, storeLocation, storeName, privateKeyAccessRules); } } else // Import into a specific user's store { var storeUser = variables.Get(SpecialVariables.Action.Certificate.StoreUser); if (string.IsNullOrWhiteSpace(storeUser)) { throw new CommandException( $"Either '{SpecialVariables.Action.Certificate.StoreLocation}' or '{SpecialVariables.Action.Certificate.StoreUser}' must be supplied"); } Log.Info( $"Importing certificate '{variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Subject}")}' with thumbprint '{thumbprint}' into store '{storeName}' for user '{storeUser}'"); WindowsX509CertificateStore.ImportCertificateToStore(pfxBytes, password, storeUser, storeName, privateKeyExportable); } } catch (Exception) { Log.Error("There was an error importing the certificate into the store"); throw; } } internal static ICollection<PrivateKeyAccessRule> GetPrivateKeyAccessRules(IVariables variables) { // The private-key access-rules are stored as escaped JSON. However, they may contain nested // variables (for example the user-name may be an Octopus variable) which may not be escaped, // causing JSON parsing to fail. // So, we get the raw text var raw = variables.GetRaw(SpecialVariables.Certificate.PrivateKeyAccessRules); if (string.IsNullOrWhiteSpace(raw)) return new List<PrivateKeyAccessRule>(); // Unescape it (we only care about backslashes) var unescaped = raw.Replace(@"\\", @"\"); // Perform variable-substitution and re-escape var escapedAndSubstituted = variables.Evaluate(unescaped).Replace(@"\", @"\\"); return PrivateKeyAccessRule.FromJson(escapedAndSubstituted); } string GetMandatoryVariable(IVariables variables, string variableName) { var value = variables.Get(variableName); if (string.IsNullOrWhiteSpace(value)) { throw new CommandException($"Variable {variableName} was not supplied"); } return value; } static void ValidateStore(StoreLocation? storeLocation, string storeName) { // Windows wants to launch an interactive confirmation dialog when importing into the Root store for a user. // https://github.com/OctopusDeploy/Issues/issues/3347 if ((!storeLocation.HasValue || storeLocation.Value != StoreLocation.LocalMachine) && storeName == WindowsX509CertificateStore.RootAuthorityStoreName) { throw new CommandException($"When importing certificate into {WindowsX509CertificateStore.RootAuthorityStoreName} store, location must be '{StoreLocation.LocalMachine}'. " + $"Windows security restrictions prevent importing into the {WindowsX509CertificateStore.RootAuthorityStoreName} store for a user."); } } } } #endif<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Commands { public class RunningDeployment { public RunningDeployment(IVariables variables, Dictionary<string, string>? environmentVariables = null) : this( null, variables, environmentVariables) { } public RunningDeployment(string? packageFilePath, IVariables variables, Dictionary<string, string>? environmentVariables = null) { if (!string.IsNullOrEmpty(packageFilePath)) { PackageFilePath = new PathToPackage(packageFilePath); } Variables = variables; EnvironmentVariables = environmentVariables ?? new Dictionary<string, string>(); } public PathToPackage? PackageFilePath { get; } /// <summary> /// Gets the directory that Tentacle extracted the package to. /// </summary> public string? StagingDirectory { get => Variables.Get(KnownVariables.OriginalPackageDirectoryPath); set => Variables.Set(KnownVariables.OriginalPackageDirectoryPath, value); } /// <summary> /// Gets the custom installation directory for this package, as selected by the user. /// If the user didn't choose a custom directory, this will return <see cref="StagingDirectory" /> instead. /// </summary> public string? CustomDirectory { get { var custom = Variables.Get(PackageVariables.CustomInstallationDirectory); return string.IsNullOrWhiteSpace(custom) ? StagingDirectory : custom; } } public DeploymentWorkingDirectory CurrentDirectoryProvider { get; set; } public string CurrentDirectory => CurrentDirectoryProvider == DeploymentWorkingDirectory.StagingDirectory ? string.IsNullOrWhiteSpace(StagingDirectory) ? Environment.CurrentDirectory : StagingDirectory : CustomDirectory ?? throw new InvalidOperationException("Current directory is not set for the deployment"); public IVariables Variables { get; } public Dictionary<string, string> EnvironmentVariables { get; } public bool SkipJournal { get => Variables.GetFlag(KnownVariables.Action.SkipJournal); set => Variables.Set(KnownVariables.Action.SkipJournal, value.ToString().ToLower()); } public void Error(Exception ex) { ex = ex.GetBaseException(); Variables.Set("OctopusLastError", ex.ToString()); Variables.Set("OctopusLastErrorMessage", ex.Message); } } }<file_sep>using System; using System.Collections; using System.IO; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class ConfigurationTransformConventionFixture { ICalamariFileSystem fileSystem; IConfigurationTransformer configurationTransformer; ITransformFileLocator transformFileLocator; RunningDeployment deployment; IVariables variables; InMemoryLog logs; [SetUp] public void SetUp() { fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); configurationTransformer = Substitute.For<IConfigurationTransformer>(); logs = new InMemoryLog(); transformFileLocator = new TransformFileLocator(fileSystem, logs); var deployDirectory = BuildConfigPath(null); variables = new CalamariVariables(); variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationTransforms); variables.Set(KnownVariables.OriginalPackageDirectoryPath, deployDirectory); deployment = new RunningDeployment(deployDirectory, variables); } void AddConfigurationVariablesFlag() { variables.Set(KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles, true.ToString()); } [Test] public void ShouldApplyReleaseTransformIfAutomaticallyRunConfigurationTransformationFilesFlagIsSet() { AddConfigurationVariablesFlag(); CreateConvention(deployment.Variables).Install(deployment); AssertTransformRun("bar.config", "bar.Release.config"); } [Test] public void ShouldNotApplyReleaseTransformIfAutomaticallyRunConfigurationTransformationFilesFlagNotSet() { CreateConvention(deployment.Variables).Install(deployment); AssertTransformNotRun("bar.config", "bar.Release.config"); } [Test] public void ShouldApplyEnvironmentTransform() { const string environment = "Production"; AddConfigurationVariablesFlag(); variables.Set(DeploymentEnvironment.Name, environment); CreateConvention(deployment.Variables).Install(deployment); AssertTransformRun("bar.config", "bar.Release.config"); AssertTransformRun("bar.config", "bar.Production.config"); } [Test] public void ShouldApplyTenantTransform() { const string environment = "Production"; const string tenant = "Tenant-1"; AddConfigurationVariablesFlag(); variables.Set(DeploymentEnvironment.Name, environment); variables.Set(DeploymentVariables.Tenant.Name, tenant); CreateConvention(deployment.Variables).Install(deployment); AssertTransformRun("bar.config", "bar.Release.config"); AssertTransformRun("bar.config", "bar.Production.config"); AssertTransformRun("bar.config", "bar.Tenant-1.config"); } [Test] public void ShouldApplyNamingConventTransformsInTheRightOrder() { const string environment = "Production"; const string tenant = "Tenant-1"; AddConfigurationVariablesFlag(); variables.Set(DeploymentEnvironment.Name, environment); variables.Set(DeploymentVariables.Tenant.Name, tenant); CreateConvention(deployment.Variables).Install(deployment); Received.InOrder(() => { configurationTransformer.Received().PerformTransform( Arg.Any<string>(), Arg.Is<string>(s => s.Equals(BuildConfigPath("bar.Release.config"), StringComparison.OrdinalIgnoreCase)), Arg.Any<string>()); configurationTransformer.Received().PerformTransform( Arg.Any<string>(), Arg.Is<string>(s => s.Equals(BuildConfigPath("bar.Production.config"), StringComparison.OrdinalIgnoreCase)), Arg.Any<string>()); configurationTransformer.Received().PerformTransform( Arg.Any<string>(), Arg.Is<string>(s => s.Equals(BuildConfigPath("bar.Tenant-1.config"), StringComparison.OrdinalIgnoreCase)), Arg.Any<string>()); }); } [Test] public void ShouldApplySpecificCustomTransform() { variables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, "foo.bar.config => foo.config"); CreateConvention(deployment.Variables).Install(deployment); AssertTransformRun("foo.config", "foo.bar.config"); } [Test] [TestCase("foo.missing.config => foo.config")] [TestCase("config\\fizz.buzz.config => config\\fizz.config")] public void ShouldLogErrorIfUnableToFindFile(string transform) { variables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, transform); CreateConvention(deployment.Variables).Install(deployment); logs.StandardOut.Should().Contain($"The transform pattern \"{transform}\" was not performed as no matching files could be found."); } [Test] [TestCase("foo.bar.config => foo.config", "foo.bar.config => foo.config")] [TestCase("*.bar.config => foo.config", "foo.bar.config => foo.config")] [TestCase("foo.bar.config => foo.config", "*.bar.config => foo.config")] public void ShouldLogErrorIfDuplicateTransform(string transformA, string transformB) { variables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, transformA + Environment.NewLine + transformB); CreateConvention(deployment.Variables).Install(deployment); logs.StandardOut.Should().Contain($"The transform pattern \"{transformB}\" was not performed as it overlapped with another transform."); } [Test] [TestCaseSource(nameof(AdvancedTransformTestCases))] public void ShouldApplyAdvancedTransformations(string sourceFile, string transformDefinition, string expectedAppliedTransform) { variables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, transformDefinition.Replace('\\', Path.DirectorySeparatorChar)); CreateConvention(deployment.Variables).Install(deployment); AssertTransformRun(sourceFile, expectedAppliedTransform); configurationTransformer.ReceivedWithAnyArgs(1).PerformTransform("", "", ""); // Only Called Once } [Test] public void ShouldApplyMultipleWildcardsToSourceFile() { variables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, "*.bar.blah => bar.blah"); CreateConvention(deployment.Variables).Install(deployment); AssertTransformRun("bar.blah", "foo.bar.blah"); AssertTransformRun("bar.blah", "xyz.bar.blah"); configurationTransformer.ReceivedWithAnyArgs(2).PerformTransform("", "", ""); } [Test] public void ShouldApplyTransformToMulipleTargetFiles() { variables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, "bar.blah => *.bar.blah"); CreateConvention(deployment.Variables).Install(deployment); AssertTransformRun("foo.bar.blah", "bar.blah"); AssertTransformRun("xyz.bar.blah", "bar.blah"); configurationTransformer.ReceivedWithAnyArgs(2).PerformTransform("", "", ""); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] [TestCase("bar.blah => *.Bar.Blah", "xyz.bar.blah", "bar.blah")] [TestCase("*.Bar.Blah => bar.blah", "bar.blah", "xyz.bar.blah")] [TestCase("foo.bar.config => Foo.Config", "foo.config", "foo.bar.config")] public void CaseInsensitiveOnWindows(string pattern, string from, string to) { variables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, pattern); CreateConvention(deployment.Variables).Install(deployment); AssertTransformRun(from, to); } [Test] [Category(TestCategory.CompatibleOS.OnlyNix)] [TestCase("bar.blah => *.Bar.Blah", "xyz.bar.blah", "bar.blah")] [TestCase("*.Bar.Blah => bar.blah", "bar.blah", "xyz.bar.blah")] [TestCase("foo.bar.config => Foo.Config", "foo.config", "foo.bar.config")] public void CaseSensitiveOnNix(string pattern, string from, string to) { if (!CalamariEnvironment.IsRunningOnNix) Assert.Ignore("This test is designed to run on *nix"); variables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, pattern); CreateConvention(deployment.Variables).Install(deployment); AssertTransformNotRun(from, to); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldOutputDiagnosticsLoggingIfEnabled() { var calamariFileSystem = Substitute.For<ICalamariFileSystem>(); var deploymentVariables = new CalamariVariables(); deploymentVariables.Set(KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles, true.ToString()); deploymentVariables.Set(SpecialVariables.Action.Azure.CloudServicePackagePath, @"MyPackage.1.0.0.nupkg"); deploymentVariables.Set(SpecialVariables.Package.AdditionalXmlConfigurationTransforms, @"MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config => MyApplication.ProcessingServer.WorkerRole.dll.config"); deploymentVariables.Set(DeploymentEnvironment.Name, "my-test-env"); deploymentVariables.Set(SpecialVariables.Package.EnableDiagnosticsConfigTransformationLogging, "True"); deploymentVariables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationTransforms); var runningDeployment = new RunningDeployment(@"c:\temp\MyPackage.1.0.0.nupkg", deploymentVariables); //mock the world calamariFileSystem.DirectoryExists(@"c:\temp").Returns(true); calamariFileSystem.FileExists(@"c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config").Returns(true); calamariFileSystem.FileExists(@"c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.config").Returns(true); calamariFileSystem.EnumerateFilesRecursively(@"c:\temp", "*.config") .Returns(new[] { @"c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config", @"c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.config" }); calamariFileSystem.EnumerateFiles(@"c:\temp", "MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config", @"MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config") .Returns(new[] { @"c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config" }); calamariFileSystem.EnumerateFiles(@"c:\temp", "MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config", @"MyApplication.ProcessingServer.WorkerRole.dll.my-test-env") .Returns(new[] { @"c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config" }); //these variables would normally be set by ExtractPackageToStagingDirectoryConvention Log.SetOutputVariable(PackageVariables.Output.InstallationDirectoryPath, "c:\\temp", runningDeployment.Variables); Log.SetOutputVariable(KnownVariables.OriginalPackageDirectoryPath, "c:\\temp", runningDeployment.Variables); var log = new InMemoryLog(); var transformer = Substitute.For<IConfigurationTransformer>(); var fileLocator = new TransformFileLocator(calamariFileSystem, log); new ConfigurationTransformsConvention(new ConfigurationTransformsBehaviour(calamariFileSystem, deploymentVariables, transformer, fileLocator, log)).Install(runningDeployment); //not completely testing every scenario here, but this is a reasonable half way point to make sure it works without going overboard log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @"Recursively searching for transformation files that match *.config in folder 'c:\temp'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @"Found config file 'c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - checking against transform 'MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config => MyApplication.ProcessingServer.WorkerRole.dll.config'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - Skipping as file name 'MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config' does not match the target pattern 'MyApplication.ProcessingServer.WorkerRole.dll.config'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - checking against transform 'Release'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - skipping as neither transform 'MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.Release.config' nor transform 'MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.Release' could be found in 'c:\temp'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - checking against transform 'my-test-env'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - skipping as neither transform 'MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.my-test-env.config' nor transform 'MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.my-test-env' could be found in 'c:\temp'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @"Found config file 'c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.config'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - checking against transform 'MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config => MyApplication.ProcessingServer.WorkerRole.dll.config'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Info && m.FormattedMessage == @"Transforming 'c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.config' using 'c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config'."); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - checking against transform 'Release'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - skipping as neither transform 'MyApplication.ProcessingServer.WorkerRole.dll.Release.config' nor transform 'MyApplication.ProcessingServer.WorkerRole.dll.Release' could be found in 'c:\temp'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - checking against transform 'my-test-env'"); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == @" - Skipping as target 'c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.config' has already been transformed by transform 'c:\temp\MyApplication.ProcessingServer.WorkerRole.dll.my-test-env.config'"); } private static IEnumerable AdvancedTransformTestCases { get { //get absolute path and test against that too var directory = BuildConfigPath("") + Path.DirectorySeparatorChar; yield return new TestCaseData("bar.sitemap", "config\\fizz.sitemap.config=>bar.sitemap", "config\\fizz.sitemap.config"); yield return new TestCaseData("bar.config", "config\\fizz.buzz.config=>bar.config", "config\\fizz.buzz.config"); yield return new TestCaseData("bar.config", "foo.config=>bar.config", "foo.config"); yield return new TestCaseData("bar.blah", "foo.baz=>bar.blah", "foo.baz"); yield return new TestCaseData("bar.config", "foo.xml=>bar.config", "foo.xml"); yield return new TestCaseData("xyz.bar.blah", "*.foo.blah=>*.bar.blah", "xyz.foo.blah"); yield return new TestCaseData("foo.bar.config", "foo.config=>*.bar.config", "foo.config"); yield return new TestCaseData("bar.blah", "*.bar.config=>bar.blah", "foo.bar.config"); yield return new TestCaseData("foo.config", "foo.bar.additional.config=>foo.config", "foo.bar.additional.config"); yield return new TestCaseData("foo.config", "*.bar.config=>*.config", "foo.bar.config"); yield return new TestCaseData("foo.xml", "*.bar.xml=>*.xml", "foo.bar.xml"); yield return new TestCaseData("config\\fizz.xml", "foo.bar.xml=>config\\fizz.xml", "foo.bar.xml"); yield return new TestCaseData("config\\fizz.xml", "transform\\fizz.buzz.xml=>config\\fizz.xml", "transform\\fizz.buzz.xml"); yield return new TestCaseData("config\\fizz.xml", "transform\\*.xml=>config\\*.xml", "transform\\fizz.xml"); yield return new TestCaseData("foo.config", "transform\\*.config=>foo.config", "transform\\fizz.config"); yield return new TestCaseData("bar.sitemap", directory + "config\\fizz.sitemap.config=>bar.sitemap", "config\\fizz.sitemap.config"); yield return new TestCaseData("bar.config", directory + "config\\fizz.buzz.config=>bar.config", "config\\fizz.buzz.config"); yield return new TestCaseData("bar.config", directory + "foo.config=>bar.config", "foo.config"); yield return new TestCaseData("bar.blah", directory + "foo.baz=>bar.blah", "foo.baz"); yield return new TestCaseData("bar.config", directory + "foo.xml=>bar.config", "foo.xml"); yield return new TestCaseData("xyz.bar.blah", directory + "*.foo.blah=>*.bar.blah", "xyz.foo.blah"); yield return new TestCaseData("foo.bar.config", directory + "foo.config=>*.bar.config", "foo.config"); yield return new TestCaseData("bar.blah", directory + "*.bar.config=>bar.blah", "foo.bar.config"); yield return new TestCaseData("foo.config", directory + "foo.bar.additional.config=>foo.config", "foo.bar.additional.config"); yield return new TestCaseData("foo.config", directory + "*.bar.config=>*.config", "foo.bar.config"); yield return new TestCaseData("foo.xml", directory + "*.bar.xml=>*.xml", "foo.bar.xml"); yield return new TestCaseData("config\\fizz.xml", directory + "foo.bar.xml=>config\\fizz.xml", "foo.bar.xml"); yield return new TestCaseData("config\\fizz.xml", directory + "transform\\fizz.buzz.xml=>config\\fizz.xml", "transform\\fizz.buzz.xml"); yield return new TestCaseData("config\\fizz.xml", directory + "transform\\*.xml=>config\\*.xml", "transform\\fizz.xml"); yield return new TestCaseData("foo.config", directory + "transform\\*.config=>foo.config", "transform\\fizz.config"); } } private ConfigurationTransformsConvention CreateConvention(IVariables variables) { return new ConfigurationTransformsConvention(new ConfigurationTransformsBehaviour(fileSystem, variables, configurationTransformer, transformFileLocator, logs)); } private void AssertTransformRun(string configFile, string transformFile) { configurationTransformer.Received().PerformTransform( Arg.Is<string>(s => s.Equals(BuildConfigPath(configFile), StringComparison.OrdinalIgnoreCase)), Arg.Is<string>(s => s.Equals(BuildConfigPath(transformFile), StringComparison.OrdinalIgnoreCase)), Arg.Is<string>(s => s.Equals(BuildConfigPath(configFile), StringComparison.OrdinalIgnoreCase))); } private void AssertTransformNotRun(string configFile, string transformFile) { configurationTransformer.DidNotReceive().PerformTransform( Arg.Is<string>(s => s.Equals(BuildConfigPath(configFile), StringComparison.OrdinalIgnoreCase)), Arg.Is<string>(s => s.Equals(BuildConfigPath(transformFile), StringComparison.OrdinalIgnoreCase)), Arg.Is<string>(s => s.Equals(BuildConfigPath(configFile), StringComparison.OrdinalIgnoreCase))); } private static string BuildConfigPath(string filename) { var path = typeof(ConfigurationTransformConventionFixture).Namespace.Replace("Calamari.Tests.", string.Empty); path = path.Replace('.', Path.DirectorySeparatorChar); var workingDirectory = Path.Combine(TestEnvironment.CurrentWorkingDirectory, path, "ConfigTransforms"); if (string.IsNullOrEmpty(filename)) return workingDirectory; return Path.Combine(workingDirectory, filename.Replace('\\', Path.DirectorySeparatorChar)); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Calamari.Common.Commands; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json.Linq; using Octopus.Versioning; namespace Calamari.Integration.Packages.Download { // Note about moving this class: GetScript method uses the namespace of this class as part of the // get Embedded Resource to find the DockerLogin and DockerPull scripts. If you move this file, be sure look at that method // and make sure it can still find the scripts public class DockerImagePackageDownloader : IPackageDownloader { readonly IScriptEngine scriptEngine; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; readonly IVariables variables; readonly ILog log; const string DockerHubRegistry = "index.docker.io"; // Ensures that any credential details are only available for the duration of the acquisition readonly Dictionary<string, string> environmentVariables = new Dictionary<string, string>() { { "DOCKER_CONFIG", "./octo-docker-configs" } }; public DockerImagePackageDownloader(IScriptEngine scriptEngine, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner, IVariables variables, ILog log) { this.scriptEngine = scriptEngine; this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; this.variables = variables; this.log = log; } public PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, string? username, string? password, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { //Always try re-pull image, docker engine can take care of the rest var fullImageName = GetFullImageName(packageId, version, feedUri); var feedHost = GetFeedHost(feedUri); PerformLogin(username, password, feedHost); const string cachedWorkerToolsShortLink = "https://g.octopushq.com/CachedWorkerToolsImages"; var imageNotCachedMessage = "The docker image '{0}' may not be cached." + " Please note images that have not been cached may take longer to be acquired than expected." + " Your deployment will begin as soon as all images have been pulled." + $" Please see {cachedWorkerToolsShortLink} for more information on cached worker-tools image versions."; if (!IsImageCached(fullImageName)) { log.InfoFormat(imageNotCachedMessage, fullImageName); } PerformPull(fullImageName); var (hash, size) = GetImageDetails(fullImageName); return new PackagePhysicalFileMetadata(new PackageFileNameMetadata(packageId, version, version, ""), string.Empty, hash, size); } static string GetFullImageName(string packageId, IVersion version, Uri feedUri) { return feedUri.Host.Equals(DockerHubRegistry) ? $"{packageId}:{version}" : $"{feedUri.Authority}{feedUri.AbsolutePath.TrimEnd('/')}/{packageId}:{version}"; } static string GetFeedHost(Uri feedUri) { if (feedUri.Host.Equals(DockerHubRegistry)) { return string.Empty; } if (feedUri.Port == 443) { return feedUri.Host; } return $"{feedUri.Host}:{feedUri.Port}"; } void PerformLogin(string? username, string? password, string feed) { var result = ExecuteScript("DockerLogin", new Dictionary<string, string?> { ["DockerUsername"] = username, ["DockerPassword"] = <PASSWORD>, ["FeedUri"] = feed }); if (result == null) throw new CommandException("Null result attempting to log in Docker registry"); if (result.ExitCode != 0) throw new CommandException("Unable to log in Docker registry"); } bool IsImageCached(string fullImageName) { var cachedDigests = GetCachedImageDigests(); var selectedDigests = GetImageDigests(fullImageName); // If there are errors in the above steps, we treat the image as being cached and do not log image-not-cached if (cachedDigests == null || selectedDigests == null) { return true; } return cachedDigests.Intersect(selectedDigests).Any(); } void PerformPull(string fullImageName) { var result = ExecuteScript("DockerPull", new Dictionary<string, string?> { ["Image"] = fullImageName }); if (result == null) throw new CommandException("Null result attempting to pull Docker image"); if (result.ExitCode != 0) throw new CommandException("Unable to pull Docker image"); } CommandResult ExecuteScript(string scriptName, Dictionary<string, string?> envVars) { var file = GetScript(scriptName); using (new TemporaryFile(file)) { var clone = variables.Clone(); foreach (var keyValuePair in envVars) { clone[keyValuePair.Key] = keyValuePair.Value; } return scriptEngine.Execute(new Script(file), clone, commandLineRunner, environmentVariables); } } (string hash, long size) GetImageDetails(string fullImageName) { var details = ""; var result2 = SilentProcessRunner.ExecuteCommand("docker", "inspect --format=\"{{.Id}} {{.Size}}\" " + fullImageName, ".", environmentVariables, (stdout) => { details = stdout; }, log.Error); if (result2.ExitCode != 0) { throw new CommandException("Unable to determine acquired docker image hash"); } var parts = details.Split(' '); var hash = parts[0]; // Be more defensive trying to parse the image size. // We dont tend to use this property for docker atm anyway so it seems reasonable to ignore if it cant be loaded. if (!long.TryParse(parts[1], out var size)) { size = 0; log.Verbose($"Unable to parse image size. ({parts[0]})"); } return (hash, size); } IEnumerable<string>? GetCachedImageDigests() { var output = ""; var result = SilentProcessRunner.ExecuteCommand("docker", "image ls --format=\"{{.ID}}\" --no-trunc", ".", environmentVariables, (stdout) => { output += stdout + " "; }, (error) => { }); return result.ExitCode == 0 ? output.Split(' ').Select(digest => digest.Trim()) : null; } IEnumerable<string>? GetImageDigests(string fullImageName) { var output = ""; var result = SilentProcessRunner.ExecuteCommand("docker", $"manifest inspect --verbose {fullImageName}", ".", environmentVariables, (stdout) => { output += stdout; }, (error) => { }); if (result.ExitCode != 0) { return null; } if (!output.TrimStart().StartsWith("[")) { output = $"[{output}]"; } try { return JArray.Parse(output.ToLowerInvariant()) .Select(token => (string)token.SelectToken("schemav2manifest.config.digest")) .ToList(); } catch { return null; } } string GetScript(string scriptName) { var syntax = ScriptSyntaxHelper.GetPreferredScriptSyntaxForEnvironment(); string contextFile; switch (syntax) { case ScriptSyntax.Bash: contextFile = $"{scriptName}.sh"; break; case ScriptSyntax.PowerShell: contextFile = $"{scriptName}.ps1"; break; default: throw new InvalidOperationException("No kubernetes context wrapper exists for " + syntax); } var scriptFile = Path.Combine(".", $"Octopus.{contextFile}"); var contextScript = new AssemblyEmbeddedResources().GetEmbeddedResourceText(Assembly.GetExecutingAssembly(), $"{typeof (DockerImagePackageDownloader).Namespace}.Scripts.{contextFile}"); fileSystem.OverwriteFile(scriptFile, contextScript); return scriptFile; } } } <file_sep>using System; using System.Collections.Generic; namespace Calamari.Deployment.PackageRetention.Model { public class PackageLocks : List<UsageDetails> { } }<file_sep>using Calamari.Common.Plumbing.Extensions; using NUnit.Framework; using NUnit.Framework.Interfaces; namespace Calamari.Testing.Requirements { public class RequiresDotNet45Attribute : TestAttribute, ITestAction { public void BeforeTest(ITest testDetails) { if (!ScriptingEnvironment.IsNet45OrNewer()) { Assert.Ignore("Requires .NET 4.5"); } } public void AfterTest(ITest testDetails) { } public ActionTargets Targets { get; set; } } }<file_sep>using System; using System.Fabric; using System.Fabric.Security; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Microsoft.Identity.Client; namespace Calamari.AzureServiceFabric { class HealthCheckBehaviour: IDeployBehaviour { readonly IVariables variables; readonly ILog log; public HealthCheckBehaviour(IVariables variables, ILog log) { this.variables = variables; this.log = log; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment context) { if (!ServiceFabricHelper.IsServiceFabricSdkKeyInRegistry()) { throw new Exception("Could not find the Azure Service Fabric SDK on this server. This SDK is required before running health checks on Service Fabric targets."); } var connectionEndpoint = variables.Get(SpecialVariables.Action.ServiceFabric.ConnectionEndpoint); var securityMode = (AzureServiceFabricSecurityMode)Enum.Parse(typeof(AzureServiceFabricSecurityMode), variables.Get(SpecialVariables.Action.ServiceFabric.SecurityMode)); var serverCertThumbprint = variables.Get(SpecialVariables.Action.ServiceFabric.ServerCertThumbprint); var clientCertVariable = variables.Get(SpecialVariables.Action.ServiceFabric.ClientCertVariable); var certificateStoreLocation = variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreLocation); if (string.IsNullOrWhiteSpace(certificateStoreLocation)) certificateStoreLocation = StoreLocation.LocalMachine.ToString(); var certificateStoreName = variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreName); if (string.IsNullOrWhiteSpace(certificateStoreName)) certificateStoreName = "My"; var aadUserCredentialUsername = variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialUsername); var aadUserCredentialPassword = variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialPassword); log.Verbose($"Checking connectivity to Service Fabric cluster '{connectionEndpoint}' with security-mode '{securityMode}'"); FabricClient fabricClient; switch (securityMode) { case AzureServiceFabricSecurityMode.SecureClientCertificate: { log.Info("Connecting with Secure Client Certificate"); var clientCertThumbprint = variables.Get(clientCertVariable + ".Thumbprint"); var commonName = variables.Get(clientCertVariable + ".SubjectCommonName"); CalamariCertificateStore.EnsureCertificateIsInstalled(variables, clientCertVariable, certificateStoreName, certificateStoreLocation); var xc = GetCredentials(clientCertThumbprint, certificateStoreLocation, certificateStoreName, serverCertThumbprint, commonName); try { fabricClient = new FabricClient(xc, connectionEndpoint); } catch (Exception ex) { // SF throw weird exception messages if you don't have the certificate installed. if (ex.InnerException != null && ex.InnerException.Message.Contains("0x80071C57")) throw new Exception($"Service Fabric was unable to to find certificate with thumbprint '{clientCertThumbprint}' in Cert:\\{certificateStoreLocation}\\{certificateStoreName}. Please make sure you have installed the certificate on the Octopus Server before attempting to use/reference it in a Service Fabric Cluster target."); throw; } break; } case AzureServiceFabricSecurityMode.SecureAzureAD: { log.Info("Connecting with Secure Azure Active Directory"); var claimsCredentials = new ClaimsCredentials(); claimsCredentials.ServerThumbprints.Add(serverCertThumbprint); fabricClient = new FabricClient(claimsCredentials, connectionEndpoint); fabricClient.ClaimsRetrieval += (o, e) => { try { return GetAccessToken(e.AzureActiveDirectoryMetadata, aadUserCredentialUsername, aadUserCredentialPassword); } catch (Exception ex) { log.Error($"Connect failed: {ex.PrettyPrint()}"); return "BAD_TOKEN"; //TODO: mark.siedle - You cannot return null or an empty value here or the Azure lib spazzes out trying to call a lib that doesn't exist "System.Fabric.AzureActiveDirectory.Client" :( } }; break; } case AzureServiceFabricSecurityMode.SecureAD: { log.Info("Connecting with Secure Azure Active Directory"); log.Verbose("Using the service account of the octopus service as windows credentials"); var windowsCredentials = new WindowsCredentials(); fabricClient = new FabricClient(windowsCredentials, connectionEndpoint); break; } default: { log.Info("Connecting insecurely"); fabricClient = new FabricClient(connectionEndpoint); break; } } if (fabricClient == null) { throw new Exception("Unable to create Service Fabric client."); } try { await fabricClient.ClusterManager.GetClusterManifestAsync(); log.Verbose("Successfully received a response from the Service Fabric client"); } finally { fabricClient.Dispose(); } } #region Auth helpers static string GetAccessToken(AzureActiveDirectoryMetadata aad, string aadUsername, string aadPassword) { var app = PublicClientApplicationBuilder .Create(aad.ClientApplication) .WithAuthority(aad.Authority) .Build(); var authResult = app.AcquireTokenByUsernamePassword(new[] { $"{aad.ClusterApplication}/.default" }, aadUsername, aadPassword) .ExecuteAsync() .GetAwaiter() .GetResult(); return authResult.AccessToken; } static X509Credentials GetCredentials(string clientCertThumbprint, string clientCertStoreLocation, string clientCertStoreName, string serverCertThumb, string commonName) { var xc = new X509Credentials { StoreLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), clientCertStoreLocation), StoreName = clientCertStoreName, FindType = X509FindType.FindByThumbprint, FindValue = clientCertThumbprint }; xc.RemoteCommonNames.Add(commonName); xc.RemoteCertThumbprints.Add(serverCertThumb); xc.ProtectionLevel = ProtectionLevel.EncryptAndSign; return xc; } #endregion } }<file_sep>#if !NET40 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Aws.Integration; using Calamari.Commands; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Common.Features.ConfigurationVariables; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Kubernetes.Conventions; using Calamari.Kubernetes.Integration; namespace Calamari.Kubernetes.Commands { public abstract class KubernetesDeploymentCommandBase : Command { public const string PackageDirectoryName = "package"; private const string InlineYamlFileName = "customresource.yml"; private readonly ILog log; private readonly IDeploymentJournalWriter deploymentJournalWriter; private readonly IVariables variables; private readonly ICalamariFileSystem fileSystem; private readonly IExtractPackage extractPackage; private readonly ISubstituteInFiles substituteInFiles; private readonly IStructuredConfigVariablesService structuredConfigVariablesService; private readonly Kubectl kubectl; private PathToPackage pathToPackage; protected KubernetesDeploymentCommandBase( ILog log, IDeploymentJournalWriter deploymentJournalWriter, IVariables variables, ICalamariFileSystem fileSystem, IExtractPackage extractPackage, ISubstituteInFiles substituteInFiles, IStructuredConfigVariablesService structuredConfigVariablesService, Kubectl kubectl) { this.log = log; this.deploymentJournalWriter = deploymentJournalWriter; this.variables = variables; this.fileSystem = fileSystem; this.extractPackage = extractPackage; this.substituteInFiles = substituteInFiles; this.structuredConfigVariablesService = structuredConfigVariablesService; this.kubectl = kubectl; Options.Add("package=", "Path to the NuGet package to install.", v => pathToPackage = new PathToPackage(Path.GetFullPath(v))); } protected virtual IEnumerable<IInstallConvention> CommandSpecificInstallConventions() => Enumerable.Empty<IInstallConvention>(); /// <remarks> /// This empty implementation uses Task.FromResult(new object()); instead of /// Task.CompletedTask because Task.CompletedTask was only added in .NET 4.6.1 /// so it is not compatible with Calamari. /// </remarks> protected virtual async Task<bool> ExecuteCommand(RunningDeployment runningDeployment) => await Task.FromResult(true); public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); var conventions = new List<IConvention> { new DelegateInstallConvention(d => { var workingDirectory = d.CurrentDirectory; var stagingDirectory = Path.Combine(workingDirectory, ExtractPackage.StagingDirectoryName); var packageDirectory = Path.Combine(stagingDirectory, PackageDirectoryName); fileSystem.EnsureDirectoryExists(packageDirectory); if (pathToPackage != null) { extractPackage.ExtractToCustomDirectory(pathToPackage, packageDirectory); } else { //If using the inline yaml, copy it to the staging directory. var inlineFile = Path.Combine(workingDirectory, InlineYamlFileName); if (fileSystem.FileExists(inlineFile)) { fileSystem.MoveFile(inlineFile, Path.Combine(packageDirectory, InlineYamlFileName)); } } d.StagingDirectory = stagingDirectory; d.CurrentDirectoryProvider = DeploymentWorkingDirectory.StagingDirectory; kubectl.SetWorkingDirectory(stagingDirectory); kubectl.SetEnvironmentVariables(d.EnvironmentVariables); }), new SubstituteInFilesConvention(new SubstituteInFilesBehaviour(substituteInFiles, PackageDirectoryName)), new ConfigurationTransformsConvention(new ConfigurationTransformsBehaviour(fileSystem, variables, ConfigurationTransformer.FromVariables(variables, log), new TransformFileLocator(fileSystem, log), log, PackageDirectoryName)), new ConfigurationVariablesConvention(new ConfigurationVariablesBehaviour(fileSystem, variables, new ConfigurationVariablesReplacer(variables, log), log, PackageDirectoryName)), new StructuredConfigurationVariablesConvention( new StructuredConfigurationVariablesBehaviour(structuredConfigVariablesService, PackageDirectoryName)) }; if (variables.Get(Deployment.SpecialVariables.Account.AccountType) == "AmazonWebServicesAccount") { conventions.Add(new AwsAuthConvention(log, variables)); } conventions.Add(new KubernetesAuthContextConvention(log, new CommandLineRunner(log, variables), kubectl)); conventions.AddRange(CommandSpecificInstallConventions()); var runningDeployment = new RunningDeployment(pathToPackage, variables); var conventionRunner = new ConventionProcessor(runningDeployment, conventions, log); try { conventionRunner.RunConventions(logExceptions: false); var result = ExecuteCommand(runningDeployment).GetAwaiter().GetResult(); deploymentJournalWriter.AddJournalEntry(runningDeployment, result, pathToPackage); return result ? 0 : -1; } catch (Exception) { deploymentJournalWriter.AddJournalEntry(runningDeployment, false, pathToPackage); throw; } } } } #endif<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.WindowsPowerShell { public class WindowsPowerShellBootstrapper : PowerShellBootstrapper { const string EnvPowerShellPath = "PowerShell.exe"; static string? powerShellPath; public override bool AllowImpersonation() { return true; } public override string PathToPowerShellExecutable(IVariables variables) { if (powerShellPath != null) return powerShellPath; try { var systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System); powerShellPath = Path.Combine(systemFolder, @"WindowsPowershell\v1.0\", EnvPowerShellPath); if (!File.Exists(powerShellPath)) powerShellPath = EnvPowerShellPath; } catch (Exception) { powerShellPath = EnvPowerShellPath; } return powerShellPath; } protected override IEnumerable<string> ContributeCommandArguments(IVariables variables) { var customPowerShellVersion = variables[PowerShellVariables.CustomPowerShellVersion]; if (!string.IsNullOrEmpty(customPowerShellVersion)) yield return $"-Version {customPowerShellVersion} "; } } public class UnixLikePowerShellCoreBootstrapper : PowerShellCoreBootstrapper { public override bool AllowImpersonation() { return false; } public override string PathToPowerShellExecutable(IVariables variables) { return "pwsh"; } } public class WindowsPowerShellCoreBootstrapper : PowerShellCoreBootstrapper { const string EnvPowerShellPath = "pwsh.exe"; readonly ICalamariFileSystem fileSystem; public WindowsPowerShellCoreBootstrapper(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } public override bool AllowImpersonation() { return true; } public override string PathToPowerShellExecutable(IVariables variables) { var customVersion = variables[PowerShellVariables.CustomPowerShellVersion]; try { var availablePowerShellVersions = new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) } .Where(p => p != null) .Distinct() .Select(pf => Path.Combine(pf, "PowerShell")) .Where(fileSystem.DirectoryExists) .SelectMany(fileSystem.EnumerateDirectories) .Select<string, (string path, string versionId, int? majorVersion, string remaining)>(d => { var directoryName = fileSystem.GetDirectoryName(d); // Directories are typically versions like "6" or they might also have a prerelease component like "7-preview" var splitString = directoryName.Split(new[] { '-' }, 2); var majorVersionPart = splitString[0]; var preRelease = splitString.Length < 2 ? string.Empty : splitString[1]; // typically a prerelease tag, like "preview" if (int.TryParse(majorVersionPart, out var majorVersion)) return (d, directoryName, majorVersion, preRelease); return (d, directoryName, null, preRelease); }) .ToList(); var latestPowerShellVersionDirectory = availablePowerShellVersions .Where(p => string.IsNullOrEmpty(customVersion) || p.versionId == customVersion) .OrderByDescending(p => p.majorVersion) .ThenBy(p => p.remaining) .Select(p => p.path) .FirstOrDefault(); if (!string.IsNullOrEmpty(customVersion) && latestPowerShellVersionDirectory == null) throw new PowerShellVersionNotFoundException(customVersion, availablePowerShellVersions.Select(v => v.versionId)); if (latestPowerShellVersionDirectory == null) return EnvPowerShellPath; var pathToPwsh = Path.Combine(latestPowerShellVersionDirectory, EnvPowerShellPath); return fileSystem.FileExists(pathToPwsh) ? pathToPwsh : EnvPowerShellPath; } catch (PowerShellVersionNotFoundException) { throw; } catch (Exception) { return EnvPowerShellPath; } } } public abstract class PowerShellCoreBootstrapper : PowerShellBootstrapper { protected override IEnumerable<string> ContributeCommandArguments(IVariables variables) { yield break; } } public class PowerShellVersionNotFoundException : CommandException { public PowerShellVersionNotFoundException(string customVersion, IEnumerable<string> availableVersions) : base($"Attempted to use version '{customVersion}' of PowerShell Core, but this version could not be found. Available versions: {string.Join(", ", availableVersions)}") { } } public abstract class PowerShellBootstrapper { static readonly string BootstrapScriptTemplate; static readonly string DebugBootstrapScriptTemplate; static readonly string SensitiveVariablePassword = AesEncryption.RandomString(16); static readonly AesEncryption VariableEncryptor = new AesEncryption(SensitiveVariablePassword); static readonly ICalamariFileSystem CalamariFileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); static PowerShellBootstrapper() { BootstrapScriptTemplate = EmbeddedResource.ReadEmbeddedText(typeof(PowerShellBootstrapper).Namespace + ".Bootstrap.ps1"); DebugBootstrapScriptTemplate = EmbeddedResource.ReadEmbeddedText(typeof(PowerShellBootstrapper).Namespace + ".DebugBootstrap.ps1"); } public abstract bool AllowImpersonation(); public abstract string PathToPowerShellExecutable(IVariables variables); public string FormatCommandArguments(string bootstrapFile, string debuggingBootstrapFile, IVariables variables) { var encryptionKey = Convert.ToBase64String(AesEncryption.GetEncryptionKey(SensitiveVariablePassword)); var commandArguments = new StringBuilder(); var executeWithoutProfile = variables[PowerShellVariables.ExecuteWithoutProfile]; var traceCommand = GetPsDebugCommand(variables); foreach (var argument in ContributeCommandArguments(variables)) commandArguments.Append(argument); bool noProfile; if (bool.TryParse(executeWithoutProfile, out noProfile) && noProfile) commandArguments.Append("-NoProfile "); commandArguments.Append("-NoLogo "); commandArguments.Append("-NonInteractive "); commandArguments.Append("-ExecutionPolicy Unrestricted "); var fileToExecute = IsDebuggingEnabled(variables) ? debuggingBootstrapFile.EscapeSingleQuotedString() : bootstrapFile.EscapeSingleQuotedString(); commandArguments.AppendFormat("-Command \"{0}Try {{. {{. '{1}' -OctopusKey '{2}'; if ((test-path variable:global:lastexitcode)) {{ exit $LastExitCode }}}};}} catch {{ throw }}\"", traceCommand, fileToExecute, encryptionKey); return commandArguments.ToString(); } static string GetPsDebugCommand(IVariables variables) { //https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-psdebug?view=powershell-6 var traceArg = variables[PowerShellVariables.PSDebug.Trace]; var traceCommand = "-Trace 0"; int.TryParse(traceArg, out var traceArgAsInt); bool.TryParse(traceArg, out var traceArgAsBool); if (traceArgAsInt > 0 || traceArgAsBool) { var powerShellVersion = ScriptingEnvironment.SafelyGetPowerShellVersion(); if (powerShellVersion.Major < 5 && powerShellVersion.Major > 0) { Log.Warn($"{PowerShellVariables.PSDebug.Trace} is enabled, but PowerShell tracing is only supported with PowerShell versions 5 and above. This server is currently running PowerShell version {powerShellVersion}."); } else { Log.Warn($"{PowerShellVariables.PSDebug.Trace} is enabled. This should only be used for debugging, and then disabled again for normal deployments."); if (traceArgAsInt > 0) traceCommand = $"-Trace {traceArgAsInt}"; if (traceArgAsBool) traceCommand = "-Trace 2"; } } var strictArg = variables[PowerShellVariables.PSDebug.Strict]; var strictCommand = ""; if (bool.TryParse(strictArg, out var strictArgAsBool) && strictArgAsBool) { Log.Info($"{PowerShellVariables.PSDebug.Strict} is enabled, putting PowerShell into strict mode where variables must be assigned a value before being referenced in a script. If a variable is referenced before a value is assigned, an exception will be thrown. This feature is experimental."); strictCommand = " -Strict"; } return $"Set-PSDebug {traceCommand}{strictCommand};"; } protected abstract IEnumerable<string> ContributeCommandArguments(IVariables variables); static bool IsDebuggingEnabled(IVariables variables) { var powershellDebugMode = variables[PowerShellVariables.DebugMode]; if (string.IsNullOrEmpty(powershellDebugMode)) return false; if (powershellDebugMode.Equals("False", StringComparison.OrdinalIgnoreCase) || powershellDebugMode.Equals("None", StringComparison.OrdinalIgnoreCase)) return false; return true; } public (string bootstrapFile, string[] temporaryFiles) PrepareBootstrapFile(Script script, IVariables variables) { var parent = Path.GetDirectoryName(Path.GetFullPath(script.File)); var name = Path.GetFileName(script.File); var bootstrapFile = Path.Combine(parent, "Bootstrap." + name); var variableString = GetEncryptedVariablesString(variables); var (scriptModulePaths, scriptModuleDeclarations) = DeclareScriptModules(variables, parent); var builder = new StringBuilder(BootstrapScriptTemplate); builder.Replace("{{TargetScriptFile}}", script.File.EscapeSingleQuotedString()) .Replace("{{ScriptParameters}}", script.Parameters) .Replace("{{EncryptedVariablesString}}", variableString.encrypted) .Replace("{{VariablesIV}}", variableString.iv) .Replace("{{LocalVariableDeclarations}}", DeclareLocalVariables(variables)) .Replace("{{ScriptModules}}", scriptModuleDeclarations); builder = SetupDebugBreakpoints(builder, variables); CalamariFileSystem.OverwriteFile(bootstrapFile, builder.ToString(), new UTF8Encoding(true)); File.SetAttributes(bootstrapFile, FileAttributes.Hidden); return (bootstrapFile, scriptModulePaths); } static StringBuilder SetupDebugBreakpoints(StringBuilder builder, IVariables variables) { const string powershellWaitForDebuggerCommand = "Wait-Debugger"; var startOfBootstrapScriptDebugLocation = string.Empty; var beforeVariablesDebugLocation = string.Empty; var beforeScriptModulesDebugLocation = string.Empty; var beforeLaunchingUserScriptDebugLocation = string.Empty; var powershellDebugMode = variables[PowerShellVariables.DebugMode]; if (!string.IsNullOrEmpty(powershellDebugMode)) switch (powershellDebugMode.ToLower()) { case "breakatstartofbootstrapscript": startOfBootstrapScriptDebugLocation = powershellWaitForDebuggerCommand; break; case "breakbeforesettingvariables": beforeVariablesDebugLocation = powershellWaitForDebuggerCommand; break; case "breakbeforeimportingscriptmodules": beforeScriptModulesDebugLocation = powershellWaitForDebuggerCommand; break; case "breakbeforelaunchinguserscript": case "true": beforeLaunchingUserScriptDebugLocation = powershellWaitForDebuggerCommand; break; } builder.Replace("{{StartOfBootstrapScriptDebugLocation}}", startOfBootstrapScriptDebugLocation) .Replace("{{BeforeVariablesDebugLocation}}", beforeVariablesDebugLocation) .Replace("{{BeforeScriptModulesDebugLocation}}", beforeScriptModulesDebugLocation) .Replace("{{BeforeLaunchingUserScriptDebugLocation}}", beforeLaunchingUserScriptDebugLocation); return builder; } public string PrepareDebuggingBootstrapFile(Script script) { var parent = Path.GetDirectoryName(Path.GetFullPath(script.File)); var name = Path.GetFileName(script.File); var debugBootstrapFile = Path.Combine(parent, "DebugBootstrap." + name); var bootstrapFile = Path.Combine(parent, "Bootstrap." + name); var escapedBootstrapFile = bootstrapFile.EscapeSingleQuotedString(); var builder = new StringBuilder(DebugBootstrapScriptTemplate); builder.Replace("{{BootstrapFile}}", escapedBootstrapFile); CalamariFileSystem.OverwriteFile(debugBootstrapFile, builder.ToString(), new UTF8Encoding(true)); File.SetAttributes(debugBootstrapFile, FileAttributes.Hidden); return debugBootstrapFile; } static (string[] scriptModulePaths, string scriptModuleDeclarations) DeclareScriptModules(IVariables variables, string parentDirectory) { var output = new StringBuilder(); var scriptModules = WriteScriptModules(variables, parentDirectory, output); return (scriptModules, output.ToString()); } static string[] WriteScriptModules(IVariables variables, string parentDirectory, StringBuilder output) { var scriptModules = new List<string>(); foreach (var variableName in variables.GetNames().Where(ScriptVariables.IsLibraryScriptModule)) if (ScriptVariables.GetLibraryScriptModuleLanguage(variables, variableName) == ScriptSyntax.PowerShell) { var libraryScriptModuleName = ScriptVariables.GetLibraryScriptModuleName(variableName); var name = "Library_" + new string(libraryScriptModuleName.Where(char.IsLetterOrDigit).ToArray()) + "_" + DateTime.Now.Ticks; var moduleFileName = $"{name}.psm1"; var moduleFilePath = Path.Combine(parentDirectory, moduleFileName); Log.VerboseFormat("Writing script module '{0}' as PowerShell module {1}. This module will be automatically imported - functions will automatically be in scope.", libraryScriptModuleName, moduleFileName, name); var contents = variables.Get(variableName); if (contents == null) throw new InvalidOperationException($"Value for variable {variableName} could not be found."); CalamariFileSystem.OverwriteFile(moduleFilePath, contents, Encoding.UTF8); output.AppendLine($"Import-ScriptModule '{libraryScriptModuleName.EscapeSingleQuotedString()}' '{moduleFilePath.EscapeSingleQuotedString()}'"); output.AppendLine(); scriptModules.Add(moduleFilePath); } return scriptModules.ToArray(); } static (string encrypted, string iv) GetEncryptedVariablesString(IVariables variables) { var sb = new StringBuilder(); foreach (var variableName in variables.GetNames().Where(name => !ScriptVariables.IsLibraryScriptModule(name))) { var value = variables.Get(variableName); var encryptedValue = value == null ? "nul" : EncodeAsBase64(value); // "nul" is not a valid Base64 string sb.Append(EncodeAsBase64(variableName)).Append("$").AppendLine(encryptedValue); } var encrypted = VariableEncryptor.Encrypt(sb.ToString()); var rawEncrypted = AesEncryption.ExtractIV(encrypted, out var iv); return ( Convert.ToBase64String(rawEncrypted, Base64FormattingOptions.InsertLineBreaks), Convert.ToBase64String(iv) ); } static string DeclareLocalVariables(IVariables variables) { var output = new StringBuilder(); foreach (var variableName in variables.GetNames().Where(name => !ScriptVariables.IsLibraryScriptModule(name))) { if (ScriptVariables.IsExcludedFromLocalVariables(variableName)) continue; // This is the way we used to fix up the identifiers - people might still rely on this behavior var legacyKey = new string(variableName.Where(char.IsLetterOrDigit).ToArray()); // This is the way we should have done it var smartKey = new string(variableName.Where(IsValidPowerShellIdentifierChar).ToArray()); if (legacyKey != smartKey) WriteVariableAssignment(output, legacyKey, variableName); WriteVariableAssignment(output, smartKey, variableName); } return output.ToString(); } static void WriteVariableAssignment(StringBuilder writer, string key, string variableName) { if (string.IsNullOrWhiteSpace(key)) // we can end up with an empty key if everything was stripped by the IsValidPowerShellIdentifierChar check in WriteLocalVariables return; writer.Append("if (-Not (test-path variable:global:").Append(key).AppendLine(")) {"); writer.Append(" ${").Append(key).Append("} = $OctopusParameters[").Append(EncodeValue(variableName)).AppendLine("]"); writer.AppendLine("}"); } static string EncodeValue(string value) { if (value == null) return "$null"; var bytes = Encoding.UTF8.GetBytes(value); return string.Format("[System.Text.Encoding]::UTF8.GetString(" + "[Convert]::FromBase64String(\"{0}\")" + ")", Convert.ToBase64String(bytes)); } static string EncodeAsBase64(string value) { var bytes = Encoding.UTF8.GetBytes(value); return Convert.ToBase64String(bytes); } static bool IsValidPowerShellIdentifierChar(char c) { return c == '_' || char.IsLetterOrDigit(c); } } }<file_sep>using System; using System.IO; using System.Security.Cryptography; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Integration.FileSystem; using Calamari.Integration.Packages; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; using Octopus.Versioning; namespace Calamari.Tests.Fixtures.FindPackage { [TestFixture] public class FindPackageFixture : CalamariFixture { readonly static string tentacleHome = TestEnvironment.GetTestPath("temp", "FindPackage"); readonly static string downloadPath = Path.Combine(tentacleHome, "Files"); readonly string packageId = "Acme.Web"; readonly string mavenPackageId = "com.acme:web"; readonly string packageVersion = "1.0.0"; readonly string newpackageVersion = "1.0.1"; private readonly string mavenPackage = TestEnvironment.GetTestPath("Java", "Fixtures", "Deployment", "Packages", "HelloWorld.0.0.1.jar"); private string mavenPackageHash; [OneTimeSetUp] public void TestFixtureSetUp() { Environment.SetEnvironmentVariable("TentacleHome", tentacleHome); using (var file = File.OpenRead(mavenPackage)) { mavenPackageHash = BitConverter.ToString(SHA1.Create().ComputeHash(file)).Replace("-", "").ToLowerInvariant(); } } [OneTimeTearDown] public void TestFixtureTearDown() { Environment.SetEnvironmentVariable("TentacleHome", null); } [SetUp] public void SetUp() { if (!Directory.Exists(downloadPath)) Directory.CreateDirectory(downloadPath); } [TearDown] public void TearDown() { if (Directory.Exists(downloadPath)) Directory.Delete(downloadPath, true); } CalamariResult FindPackages(string id, string version, string hash, VersionFormat versionFormat = VersionFormat.Semver) { return Invoke(Calamari() .Action("find-package") .Argument("packageId", id) .Argument("packageVersion", version) .Argument("packageVersionFormat", versionFormat) .Argument("packageHash", hash)); } CalamariResult FindPackagesExact(string id, string version, string hash, bool exactMatch) { return Invoke(Calamari() .Action("find-package") .Argument("packageId", id) .Argument("packageVersion", version) .Argument("packageHash", hash) .Argument("exactMatch", exactMatch)); } [Test] public void ShouldFindNoEarlierPackageVersions() { using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion))) { var result = FindPackages(packageId, packageVersion, acmeWeb.Hash); result.AssertSuccess(); result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", packageId, packageVersion, acmeWeb.Hash); result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle"); result.AssertOutput("No earlier packages for {0} has been uploaded", packageId); } } [Test] public void ShouldFindNoEarlierMavenPackageVersions() { var result = FindPackages(mavenPackageId, packageVersion, mavenPackageHash); result.AssertSuccess(); result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", mavenPackageId, packageVersion, mavenPackageHash); result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle"); result.AssertOutput("No earlier packages for {0} has been uploaded", mavenPackageId); } [Test] public void ShouldFindOneEarlierPackageVersion() { using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion))) { var destinationFilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(packageId, VersionFactory.CreateSemanticVersion(packageVersion), ".nupkg")); File.Copy(acmeWeb.FilePath, destinationFilePath); using (var newAcmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, newpackageVersion))) { var result = FindPackages(packageId, newpackageVersion, newAcmeWeb.Hash); result.AssertSuccess(); result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", packageId, newpackageVersion, newAcmeWeb.Hash); result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle"); result.AssertOutput("Found 1 earlier version of {0} on this Tentacle", packageId); result.AssertOutput(" - {0}: {1}", packageVersion, destinationFilePath); result.AssertServiceMessage(ServiceMessageNames.FoundPackage.Name, Is.True); var foundPackage = result.CapturedOutput.FoundPackage; Assert.AreEqual(VersionFactory.CreateSemanticVersion(packageVersion), foundPackage.Version); Assert.AreEqual(acmeWeb.Hash, foundPackage.Hash); Assert.AreEqual(destinationFilePath, foundPackage.RemotePath); Assert.AreEqual(".nupkg", foundPackage.FileExtension); Assert.AreEqual(packageId, foundPackage.PackageId); } } } [Test] public void ShouldNotFindEarlierPackageVersionWhenExactMatchRequested() { using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion))) { var destinationFilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(packageId, VersionFactory.CreateSemanticVersion(packageVersion), ".nupkg")); File.Copy(acmeWeb.FilePath, destinationFilePath); using (var newAcmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, newpackageVersion))) { var result = FindPackagesExact(packageId, newpackageVersion, newAcmeWeb.Hash, true); result.AssertSuccess(); result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", packageId, newpackageVersion, newAcmeWeb.Hash); result.AssertNoOutput("Finding earlier packages that have been uploaded to this Tentacle"); } } } [Test] public void ShouldFindOneEarlierMavenPackageVersion() { var destinationFilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(mavenPackageId, VersionFactory.CreateMavenVersion(packageVersion), ".jar")); File.Copy(mavenPackage, destinationFilePath); var result = FindPackages(mavenPackageId, newpackageVersion, mavenPackageHash, VersionFormat.Maven); result.AssertSuccess(); result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", mavenPackageId, newpackageVersion, mavenPackageHash); result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle"); result.AssertOutput("Found 1 earlier version of {0} on this Tentacle", mavenPackageId); result.AssertOutput(" - {0}: {1}", packageVersion, destinationFilePath); var foundPackage = result.CapturedOutput.FoundPackage; Assert.AreEqual(VersionFactory.CreateMavenVersion(packageVersion), foundPackage.Version); Assert.AreEqual(mavenPackageHash, foundPackage.Hash); Assert.AreEqual(destinationFilePath, foundPackage.RemotePath); Assert.AreEqual(".jar", foundPackage.FileExtension); Assert.AreEqual(mavenPackageId, foundPackage.PackageId); } [Test] public void ShouldFindTheCorrectPackageWhenSimilarPackageExist() { using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion))) using (var acmeWebTest = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId + ".Tests", packageVersion))) { var destinationFilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(packageId, VersionFactory.CreateVersion(packageVersion, VersionFormat.Semver), ".nupkg")); File.Copy(acmeWeb.FilePath, destinationFilePath); var destinationFilePathTest = Path.Combine(downloadPath, PackageName.ToCachedFileName(packageId + ".Tests", VersionFactory.CreateVersion(packageVersion, VersionFormat.Semver), ".nupkg")); File.Copy(acmeWebTest.FilePath, destinationFilePathTest); using (var newAcmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, newpackageVersion))) { var result = FindPackages(packageId, newpackageVersion, newAcmeWeb.Hash); result.AssertSuccess(); result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", packageId, newpackageVersion, newAcmeWeb.Hash); result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle"); result.AssertOutput("Found 1 earlier version of {0} on this Tentacle", packageId); result.AssertOutput(" - {0}: {1}", packageVersion, destinationFilePath); result.AssertServiceMessage(ServiceMessageNames.FoundPackage.Name, Is.True); var foundPackage = result.CapturedOutput.FoundPackage; Assert.AreEqual(VersionFactory.CreateSemanticVersion(packageVersion), foundPackage.Version); Assert.AreEqual(acmeWeb.Hash, foundPackage.Hash); Assert.AreEqual(destinationFilePath, foundPackage.RemotePath); Assert.AreEqual(".nupkg", foundPackage.FileExtension); Assert.AreEqual(packageId, foundPackage.PackageId); } } } [Test] public void ShouldFindTheCorrectMavenPackageWhenSimilarPackageExist() { var destinationFilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(mavenPackageId, VersionFactory.CreateMavenVersion(packageVersion), ".jar")); File.Copy(mavenPackage, destinationFilePath); var destination2FilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(mavenPackageId + ".Test", VersionFactory.CreateMavenVersion(packageVersion), ".jar")); File.Copy(mavenPackage, destination2FilePath); var result = FindPackages(mavenPackageId, newpackageVersion, mavenPackageHash, VersionFormat.Maven); result.AssertSuccess(); result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", mavenPackageId, newpackageVersion, mavenPackageHash); result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle"); result.AssertOutput("Found 1 earlier version of {0} on this Tentacle", mavenPackageId); result.AssertOutput(" - {0}: {1}", packageVersion, destinationFilePath); result.AssertServiceMessage(ServiceMessageNames.FoundPackage.Name, Is.True); var foundPackage = result.CapturedOutput.FoundPackage; Assert.AreEqual(VersionFactory.CreateMavenVersion(packageVersion), foundPackage.Version); Assert.AreEqual(mavenPackageHash, foundPackage.Hash); Assert.AreEqual(destinationFilePath, foundPackage.RemotePath); Assert.AreEqual(".jar", foundPackage.FileExtension); Assert.AreEqual(mavenPackageId, foundPackage.PackageId); } [Test] public void ShouldFindPackageAlreadyUploaded() { using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion))) { var destinationFilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(packageId, VersionFactory.CreateSemanticVersion(packageVersion), ".nupkg")); File.Copy(acmeWeb.FilePath, destinationFilePath); var result = FindPackages(packageId, packageVersion, acmeWeb.Hash); result.AssertSuccess(); result.AssertServiceMessage( ServiceMessageNames.CalamariFoundPackage.Name, Is.True, message: "Expected service message '{0}' to be True", args: ServiceMessageNames.CalamariFoundPackage.Name); result.AssertOutput("Package {0} {1} hash {2} has already been uploaded", packageId, packageVersion, acmeWeb.Hash); result.AssertServiceMessage(ServiceMessageNames.FoundPackage.Name, Is.True); var foundPackage = result.CapturedOutput.FoundPackage; Assert.AreEqual(VersionFactory.CreateSemanticVersion(packageVersion), foundPackage.Version); Assert.AreEqual(acmeWeb.Hash, foundPackage.Hash); Assert.AreEqual(destinationFilePath, foundPackage.RemotePath); Assert.AreEqual(".nupkg", foundPackage.FileExtension); Assert.AreEqual(packageId, foundPackage.PackageId); } } [Test] public void ShouldFindMavenPackageAlreadyUploaded() { var destinationFilePath = Path.Combine(downloadPath, PackageName.ToCachedFileName(mavenPackageId, VersionFactory.CreateMavenVersion(packageVersion), ".jar")); File.Copy(mavenPackage, destinationFilePath); var result = FindPackages(mavenPackageId, packageVersion, mavenPackageHash, VersionFormat.Maven); result.AssertSuccess(); result.AssertServiceMessage( ServiceMessageNames.CalamariFoundPackage.Name, Is.True, message: "Expected service message '{0}' to be True", args: ServiceMessageNames.CalamariFoundPackage.Name); result.AssertOutput( "Package {0} {1} hash {2} has already been uploaded", mavenPackageId, packageVersion, mavenPackageHash); var foundPackage = result.CapturedOutput.FoundPackage; Assert.AreEqual(VersionFactory.CreateMavenVersion(packageVersion), foundPackage.Version); Assert.AreEqual(mavenPackageHash, foundPackage.Hash); Assert.AreEqual(destinationFilePath, foundPackage.RemotePath); Assert.AreEqual(".jar", foundPackage.FileExtension); Assert.AreEqual(mavenPackageId, foundPackage.PackageId); } [Test] public void ShouldFailWhenNoPackageIdIsSpecified() { var result = FindPackages("", "1.0.0", "Hash"); result.AssertFailure(); result.AssertErrorOutput("No package ID was specified. Please pass --packageId YourPackage"); } [Test] public void ShouldFailWhenNoPackageVersionIsSpecified() { var result = FindPackages("Calamari", "", "Hash"); result.AssertFailure(); result.AssertErrorOutput("No package version was specified. Please pass --packageVersion 1.0.0.0"); } [Test] public void ShouldFailWhenInvalidPackageVersionIsSpecified() { var result = FindPackages("Calamari", "1.0.*", "Hash"); result.AssertFailure(); result.AssertErrorOutput("Package version '1.0.*' is not a valid Semver version string. Please pass --packageVersionFormat with a different version type."); } [Test] public void ShouldFailWhenNoPackageHashIsSpecified() { var result = FindPackages("Calamari", "1.0.0", ""); result.AssertFailure(); result.AssertErrorOutput("No package hash was specified. Please pass --packageHash YourPackageHash"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.Logging; using Microsoft.Rest.Azure; namespace Calamari.Azure.Kubernetes.Discovery { using AzureTargetDiscoveryContext = TargetDiscoveryContext<AccountAuthenticationDetails<ServicePrincipalAccount>>; public class AzureKubernetesDiscoverer : KubernetesDiscovererBase { public AzureKubernetesDiscoverer(ILog log) : base(log) { } /// <remarks> /// This type value here must be the same as in Octopus.Server.Orchestration.ServerTasks.Deploy.TargetDiscovery.TargetDiscoveryAuthenticationDetailsFactory.AzureAuthenticationDetailsFactory /// This value is hardcoded because: /// a) There is currently no existing project to place code shared between server and Calamari, and /// b) We expect a bunch of stuff in the Sashimi/Calamari space to be refactored back into the OctopusDeploy solution soon. /// </remarks> public override string Type => "Azure"; public override IEnumerable<KubernetesCluster> DiscoverClusters(string contextJson) { if (!TryGetDiscoveryContext<AccountAuthenticationDetails<ServicePrincipalAccount>>(contextJson, out var authenticationDetails, out _)) return Enumerable.Empty<KubernetesCluster>(); var account = authenticationDetails.AccountDetails; Log.Verbose("Looking for Kubernetes clusters in Azure using:"); Log.Verbose($" Subscription ID: {account.SubscriptionNumber}"); Log.Verbose($" Tenant ID: {account.TenantId}"); Log.Verbose($" Client ID: {account.ClientId}"); var azureClient = account.CreateAzureClient(); var discoveredClusters = new List<KubernetesCluster>(); // There appears to be an issue where the azure client returns stale data // We need to upgrade this to use the newer SDK, but we need to upgrade to .NET 4.6.2 to support that. var resourceGroups = azureClient.ResourceGroups.List(); //we don't care about resource groups that are being deleted foreach (var resourceGroup in resourceGroups.Where(rg => rg.ProvisioningState != "Deleting")) { try { // There appears to be an issue where the azure client returns stale data // to mitigate this, specifically for scenario's where the resource group doesn't exist anymore // we specifically list the clusters in each resource group var clusters = azureClient.KubernetesClusters.ListByResourceGroup(resourceGroup.Name); discoveredClusters.AddRange( clusters .Select(c => KubernetesCluster.CreateForAks( $"aks/{account.SubscriptionNumber}/{c.ResourceGroupName}/{c.Name}", c.Name, c.ResourceGroupName, authenticationDetails.AccountId, c.Tags.ToTargetTags()))); } catch (CloudException ex) { Log.Verbose($"Failed to list kubernetes clusters for resource group {resourceGroup.Name}. Response message: {ex.Message}, Status code: {ex.Response.StatusCode}"); // if the resource group was not found, we don't care and move on if (ex.Response.StatusCode == HttpStatusCode.NotFound && ex.Message.StartsWith("Resource group")) continue; //throw in all other scenario's throw; } } return discoveredClusters; } } }<file_sep>using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Features.Java { public class TomcatFeature : IFeature { readonly JavaRunner javaRunner; public TomcatFeature(JavaRunner javaRunner) { this.javaRunner = javaRunner; } public string Name => SpecialVariables.Action.Java.Tomcat.Feature; public string DeploymentStage => DeploymentStages.BeforeDeploy; public void Execute(RunningDeployment deployment) { var variables = deployment.Variables; // Octopus.Features.TomcatDeployManager was set to True previously, // but now we rely on the feature being enabled if (!(variables.GetFlag(SpecialVariables.Action.Java.Tomcat.Feature) || (variables.Get(KnownVariables.Package.EnabledFeatures) ?? "").Contains(SpecialVariables.Action.Java.Tomcat.Feature))) return; // Environment variables are used to pass parameters to the Java library Log.Verbose("Invoking java to perform Tomcat integration"); javaRunner.Run("com.octopus.calamari.tomcat.TomcatDeploy", new Dictionary<string, string>() { {"OctopusEnvironment_Octopus_Tentacle_CurrentDeployment_PackageFilePath", deployment.Variables.Get(PackageVariables.Output.InstallationPackagePath, deployment.PackageFilePath)}, {"OctopusEnvironment_Tomcat_Deploy_Name", variables.Get(SpecialVariables.Action.Java.Tomcat.DeployName)}, {"OctopusEnvironment_Tomcat_Deploy_Controller", variables.Get(SpecialVariables.Action.Java.Tomcat.Controller)}, {"OctopusEnvironment_Tomcat_Deploy_User", variables.Get(SpecialVariables.Action.Java.Tomcat.User)}, {"OctopusEnvironment_Tomcat_Deploy_Password", variables.Get(SpecialVariables.Action.Java.Tomcat.Password)}, {"OctopusEnvironment_Tomcat_Deploy_Enabled", variables.Get(SpecialVariables.Action.Java.Tomcat.Enabled)}, {"OctopusEnvironment_Tomcat_Deploy_Version", variables.Get(SpecialVariables.Action.Java.Tomcat.Version)}, }); } } }<file_sep>namespace Calamari.Aws.Integration.CloudFormation.Templates { public class StackFormationNamedOutput { public string Name { get; } public StackFormationNamedOutput(string name) { Name = name; } } }<file_sep>using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Calamari.CloudAccounts; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; namespace Calamari.Terraform.Behaviours { public abstract class TerraformDeployBehaviour : IDeployBehaviour { protected readonly ILog log; protected TerraformDeployBehaviour(ILog log) { this.log = log; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment context) { var variables = context.Variables; var environmentVariables = new Dictionary<string, string>(); var useAWSAccount = variables.Get(TerraformSpecialVariables.Action.Terraform.AWSManagedAccount, "None") == "AWS"; var useAzureAccount = variables.GetFlag(TerraformSpecialVariables.Action.Terraform.AzureManagedAccount); var useGoogleCloudAccount = variables.GetFlag(TerraformSpecialVariables.Action.Terraform.GoogleCloudAccount); if (useAWSAccount) { var awsEnvironmentGeneration = await AwsEnvironmentGeneration.Create(log, variables).ConfigureAwait(false); environmentVariables.AddRange(awsEnvironmentGeneration.EnvironmentVars); } if (useAzureAccount) { environmentVariables.AddRange(AzureEnvironmentVariables(variables)); } if (useGoogleCloudAccount) { environmentVariables.AddRange(GoogleCloudEnvironmentVariables(variables)); } environmentVariables.AddRange(GetEnvironmentVariableArgs(variables)); await Execute(context, environmentVariables); } static Dictionary<string, string> GetEnvironmentVariableArgs(IVariables variables) { var rawJson = variables.Get(TerraformSpecialVariables.Action.Terraform.EnvironmentVariables); if (string.IsNullOrEmpty(rawJson)) return new Dictionary<string, string>(); return JsonConvert.DeserializeObject<Dictionary<string, string>>(rawJson); } protected abstract Task Execute(RunningDeployment deployment, Dictionary<string, string> environmentVariables); static Dictionary<string, string> GoogleCloudEnvironmentVariables(IVariables variables) { // See https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#full-reference var googleCloudEnvironmentVariables = new Dictionary<string, string>(); var useVmServiceAccount = variables.GetFlag("Octopus.Action.GoogleCloud.UseVMServiceAccount"); var account = variables.Get("Octopus.Action.GoogleCloudAccount.Variable")?.Trim(); var keyFile = variables.Get($"{account}.JsonKey")?.Trim() ?? variables.Get("Octopus.Action.GoogleCloudAccount.JsonKey")?.Trim(); if (!useVmServiceAccount && !string.IsNullOrEmpty(keyFile)) { var bytes = Convert.FromBase64String(keyFile); var json = Encoding.UTF8.GetString(bytes); googleCloudEnvironmentVariables.Add("GOOGLE_CLOUD_KEYFILE_JSON", json); Log.Verbose($"A JSON key has been set to GOOGLE_CLOUD_KEYFILE_JSON environment variable"); } var impersonateServiceAccount = variables.GetFlag("Octopus.Action.GoogleCloud.ImpersonateServiceAccount"); if (impersonateServiceAccount) { var serviceAccountEmails = variables.Get("Octopus.Action.GoogleCloud.ServiceAccountEmails") ?? string.Empty; googleCloudEnvironmentVariables.Add("GOOGLE_IMPERSONATE_SERVICE_ACCOUNT", serviceAccountEmails); Log.Verbose($"{serviceAccountEmails} has been set to GOOGLE_IMPERSONATE_SERVICE_ACCOUNT environment variable"); } var project = variables.Get("Octopus.Action.GoogleCloud.Project")?.Trim(); var region = variables.Get("Octopus.Action.GoogleCloud.Region")?.Trim(); var zone = variables.Get("Octopus.Action.GoogleCloud.Zone")?.Trim(); if (!string.IsNullOrEmpty(project)) { googleCloudEnvironmentVariables.Add("GOOGLE_PROJECT", project); Log.Verbose($"{project} has been set to GOOGLE_PROJECT environment variable"); } if (!string.IsNullOrEmpty(region)) { googleCloudEnvironmentVariables.Add("GOOGLE_REGION", region); Log.Verbose($"{region} has been set to GOOGLE_REGION environment variable"); } if (!string.IsNullOrEmpty(zone)) { googleCloudEnvironmentVariables.Add("GOOGLE_ZONE", zone); Log.Verbose($"{zone} has been set to GOOGLE_ZONE environment variable"); } return googleCloudEnvironmentVariables; } static Dictionary<string, string> AzureEnvironmentVariables(IVariables variables) { string AzureEnvironment(string s) { switch (s) { case "AzureChinaCloud": return "china"; case "AzureGermanCloud": return "german"; case "AzureUSGovernment": return "usgovernment"; default: return "public"; } } var environmentName = AzureEnvironment(variables.Get(AzureAccountVariables.Environment)); var account = variables.Get(AzureAccountVariables.AccountVariable)?.Trim(); var subscriptionId = variables.Get($"{account}.SubscriptionNumber")?.Trim() ?? variables.Get(AzureAccountVariables.SubscriptionId)?.Trim(); var clientId = variables.Get($"{account}.Client")?.Trim() ?? variables.Get(AzureAccountVariables.ClientId)?.Trim(); var clientSecret = variables.Get($"{account}.Password")?.Trim() ?? variables.Get(AzureAccountVariables.Password)?.Trim(); var tenantId = variables.Get($"{account}.TenantId")?.Trim() ?? variables.Get(AzureAccountVariables.TenantId)?.Trim(); var env = new Dictionary<string, string> { { "ARM_SUBSCRIPTION_ID", subscriptionId }, { "ARM_CLIENT_ID", clientId }, { "ARM_CLIENT_SECRET", clientSecret }, { "ARM_TENANT_ID", tenantId }, { "ARM_ENVIRONMENT", environmentName } }; return env; } } }<file_sep>#if IIS_SUPPORT using System; namespace Calamari.Integration.Iis { public abstract class WebServerSupport { public abstract void CreateWebSiteOrVirtualDirectory(string webSiteName, string virtualDirectoryPath, string webRootPath, int port); public abstract string GetHomeDirectory(string webSiteName, string virtualDirectoryPath); public abstract void DeleteWebSite(string webSiteName); public abstract bool ChangeHomeDirectory(string webSiteName, string virtualDirectoryPath, string newWebRootPath); public static WebServerSupport Legacy() { return new WebServerSixSupport(); } public static WebServerSupport AutoDetect() { // Sources: // http://support.microsoft.com/kb/224609 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx #pragma warning disable DE0009 // API is deprecated if (Environment.OSVersion.Version.Major < 6) #pragma warning restore DE0009 // API is deprecated { return new WebServerSixSupport(); } return new WebServerSevenSupport(); } } } #endif<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.Python { public class PythonScriptExecutor : ScriptExecutor { protected override IEnumerable<ScriptExecution> PrepareExecution(Script script, IVariables variables, Dictionary<string, string>? environmentVars = null) { var executable = PythonBootstrapper.FindPythonExecutable(); var workingDirectory = Path.GetDirectoryName(script.File); var dependencyInstallerFile = PythonBootstrapper.PrepareDependencyInstaller(workingDirectory); var dependencyInstallerArguments = PythonBootstrapper.FormatCommandArguments(dependencyInstallerFile, string.Empty); yield return new ScriptExecution( new CommandLineInvocation(executable, dependencyInstallerArguments) { WorkingDirectory = workingDirectory, EnvironmentVars = environmentVars, Isolate = true }, new[] { dependencyInstallerFile }); var configurationFile = PythonBootstrapper.PrepareConfigurationFile(workingDirectory, variables); var (bootstrapFile, otherTemporaryFiles) = PythonBootstrapper.PrepareBootstrapFile(script, workingDirectory, configurationFile, variables); var arguments = PythonBootstrapper.FormatCommandArguments(bootstrapFile, script.Parameters); yield return new ScriptExecution( new CommandLineInvocation(executable, arguments) { WorkingDirectory = workingDirectory, EnvironmentVars = environmentVars }, otherTemporaryFiles.Concat(new[] { bootstrapFile, configurationFile })); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; using Calamari.Terraform.Behaviours; namespace Calamari.Terraform.Commands { [Command("destroy-terraform", Description = "Destroys Terraform resources")] public class DestroyCommand : TerraformCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<DestroyBehaviour>(); } } }<file_sep>using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using Calamari.Aws.Integration.S3; using Calamari.Common.Features.Packages; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Deployment.Conventions { public interface IBucketKeyProvider { string GetBucketKey(string defaultKey, IHaveBucketKeyBehaviour behaviour, string packageFilePath = ""); string EncodeBucketKeyForUrl(string bucketKey); } public class BucketKeyProvider : IBucketKeyProvider { public string GetBucketKey(string defaultKey, IHaveBucketKeyBehaviour behaviour, string packageFilePath = "") { var packageContentHash = string.Empty; if (!packageFilePath.IsNullOrEmpty()) { packageContentHash = CalculateContentHash(packageFilePath); } switch (behaviour.BucketKeyBehaviour) { case BucketKeyBehaviourType.Custom: return SubstitutePackageHashVariable(behaviour.BucketKey, packageContentHash); case BucketKeyBehaviourType.Filename: return $"{SubstitutePackageHashVariable(behaviour.BucketKeyPrefix, packageContentHash)}{defaultKey}"; case BucketKeyBehaviourType.FilenameWithContentHash: var (fileName, extension) = GetFileNameParts(defaultKey); var bucketKey = new StringBuilder(); bucketKey.Append(SubstitutePackageHashVariable(behaviour.BucketKeyPrefix, packageContentHash)); bucketKey.Append(fileName); if (!packageContentHash.IsNullOrEmpty()) bucketKey.Append($"@{packageContentHash}"); bucketKey.Append(extension); return bucketKey.ToString(); default: throw new ArgumentOutOfRangeException(nameof(behaviour), "The provided bucket key behavior was not valid."); } } string CalculateContentHash(string packageFilePath) { var packageContent = File.ReadAllBytes(packageFilePath); using (SHA256 sha256Hash = SHA256.Create()) { var computedHashByte = sha256Hash.ComputeHash(packageContent); var computedHash = new StringBuilder(); foreach (var c in computedHashByte) { computedHash.Append(c.ToString("X2")); } return computedHash.ToString(); } } string SubstitutePackageHashVariable(string input, string contentHash) { return input.Replace($"#{{Octopus.Action.Package.PackageContentHash}}", contentHash); } public string EncodeBucketKeyForUrl(string bucketKey) { var prefix = Path.GetDirectoryName(bucketKey)?.Replace('\\','/') ?? string.Empty; var (fileName, extension) = GetFileNameParts(Path.GetFileName(bucketKey)); var encodedBucketKey = new StringBuilder(); if (!prefix.IsNullOrEmpty()) encodedBucketKey.Append($"{prefix}/"); encodedBucketKey.Append(Uri.EscapeDataString(fileName)); encodedBucketKey.Append(extension); return encodedBucketKey.ToString(); } (string filename, string extension) GetFileNameParts(string fileNameWithExtensions) { return PackageName.TryMatchTarExtensions(fileNameWithExtensions, out var fileName, out var extension) ? (fileName, extension) : (Path.GetFileNameWithoutExtension(fileNameWithExtensions), Path.GetExtension(fileNameWithExtensions)); } } }<file_sep>#if IIS_SUPPORT using System; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Iis; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers.Certificates; using Microsoft.Web.Administration; using NUnit.Framework; using Polly; using FluentAssertions; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] public class DeployWebPackageToIISFixture : DeployPackageFixture { TemporaryFile packageV1; TemporaryFile packageV2; private string uniqueValue; private WebServerSevenSupport iis; [OneTimeSetUp] public void Init() { packageV1 = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0")); packageV2 = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "2.0.0")); } [OneTimeTearDown] public void Dispose() { packageV1.Dispose(); packageV2.Dispose(); } [SetUp] public override void SetUp() { iis = new WebServerSevenSupport(); uniqueValue = "Test_" + Guid.NewGuid().ToString("N"); #if WINDOWS_CERTIFICATE_STORE_SUPPORT SampleCertificate.CapiWithPrivateKey.EnsureCertificateNotInStore(StoreName.My, StoreLocation.LocalMachine); #endif base.SetUp(); } [TearDown] public override void CleanUp() { if (iis.WebSiteExists(uniqueValue)) iis.DeleteWebSite(uniqueValue); if (iis.ApplicationPoolExists(uniqueValue)) iis.DeleteApplicationPool(uniqueValue); #if WINDOWS_CERTIFICATE_STORE_SUPPORT SampleCertificate.CapiWithPrivateKey.EnsureCertificateNotInStore(StoreName.My, StoreLocation.LocalMachine); #endif base.CleanUp(); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldDeployAsWebSite() { Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webSite"; Variables["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] = "True"; Variables["Octopus.Action.IISWebSite.Bindings"] = "[{\"protocol\":\"http\",\"port\":1082,\"host\":\"\",\"thumbprint\":\"\",\"requireSni\":false,\"enabled\":true}]"; Variables["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] = "True"; Variables["Octopus.Action.IISWebSite.EnableBasicAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var website = GetWebSite(uniqueValue); Assert.AreEqual(uniqueValue, website.Name); Assert.AreEqual(ObjectState.Started, website.State); Assert.AreEqual(1082, website.Bindings.Single().EndPoint.Port); var application = website.Applications.First(); Assert.AreEqual(uniqueValue, application.ApplicationPoolName); Assert.IsTrue(application.VirtualDirectories.Single().PhysicalPath.Contains("1.0.0")); var applicationPool = GetApplicationPool(uniqueValue); Assert.AreEqual(uniqueValue, applicationPool.Name); Assert.AreEqual(ObjectState.Started, applicationPool.State); Assert.AreEqual("v4.0", applicationPool.ManagedRuntimeVersion); Assert.AreEqual(ProcessModelIdentityType.ApplicationPoolIdentity, applicationPool.ProcessModel.IdentityType); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldDeployAsVirtualDirectory() { iis.CreateWebSiteOrVirtualDirectory(uniqueValue, null, ".", 1083); Variables["Octopus.Action.IISWebSite.DeploymentType"] = "virtualDirectory"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.CreateOrUpdate"] = "True"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.VirtualDirectory.VirtualPath"] = ToFirstLevelPath(uniqueValue); Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var applicationPoolExists = ApplicationPoolExists(uniqueValue); Assert.IsFalse(applicationPoolExists); var virtualDirectory = FindVirtualDirectory(uniqueValue, ToFirstLevelPath(uniqueValue)); Assert.AreEqual(ToFirstLevelPath(uniqueValue), virtualDirectory.Path); Assert.IsTrue(virtualDirectory.PhysicalPath.Contains("1.0.0")); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldKeepExistingBindingsWhenExistingBindingsIsMerge() { // The variable we are testing Variables["Octopus.Action.IISWebSite.ExistingBindings"] = "merge"; const int existingBindingPort = 1083; iis.CreateWebSiteOrVirtualDirectory(uniqueValue, null, ".", existingBindingPort); Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webSite"; Variables["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] = "True"; Variables["Octopus.Action.IISWebSite.Bindings"] = @"[{""protocol"":""http"",""port"":1082,""host"":"""",""thumbprint"":"""",""requireSni"":false,""enabled"":true}]"; Variables["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] = "True"; Variables["Octopus.Action.IISWebSite.EnableBasicAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var website = GetWebSite(uniqueValue); website.Bindings.Should().Contain(b => b.EndPoint.Port == existingBindingPort, "Existing binding should remain"); website.Bindings.Should().Contain(b => b.EndPoint.Port == 1082, "New binding should be added"); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldExcludeTempBindingWhenExistingBindingsIsMerge() { // The variable we are testing Variables["Octopus.Action.IISWebSite.ExistingBindings"] = "merge"; Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webSite"; Variables["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] = "True"; Variables["Octopus.Action.IISWebSite.Bindings"] = @"[{""protocol"":""http"",""port"":1082,""host"":"""",""thumbprint"":"""",""requireSni"":false,""enabled"":true}]"; Variables["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] = "True"; Variables["Octopus.Action.IISWebSite.EnableBasicAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var website = GetWebSite(uniqueValue); website.Bindings.Count().Should().Be(1); website.Bindings.Should().Contain(b => b.EndPoint.Port == 1082, "New binding should be added"); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldRemoveExistingBindingsByDefault() { const int existingBindingPort = 1083; iis.CreateWebSiteOrVirtualDirectory(uniqueValue, null, ".", existingBindingPort); Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webSite"; Variables["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] = "True"; Variables["Octopus.Action.IISWebSite.Bindings"] = @"[{""protocol"":""http"",""port"":1082,""host"":"""",""thumbprint"":"""",""requireSni"":false,""enabled"":true}]"; Variables["Octopus.Action.IISWebSite.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] = "True"; Variables["Octopus.Action.IISWebSite.EnableBasicAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var website = GetWebSite(uniqueValue); website.Bindings.Should().NotContain(b => b.EndPoint.Port == existingBindingPort); website.Bindings.Should().Contain(b => b.EndPoint.Port == 1082); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldDeployNewVersion() { iis.CreateWebSiteOrVirtualDirectory(uniqueValue, null, ".", 1083); Variables["Octopus.Action.IISWebSite.DeploymentType"] = "virtualDirectory"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.CreateOrUpdate"] = "True"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.VirtualDirectory.VirtualPath"] = ToFirstLevelPath(uniqueValue); Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); result = DeployPackage(packageV2.FilePath); result.AssertSuccess(); var virtualDirectory = FindVirtualDirectory(uniqueValue, ToFirstLevelPath(uniqueValue)); Assert.IsTrue(virtualDirectory.PhysicalPath.Contains("2.0.0")); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldNotAllowMissingParentSegments() { iis.CreateWebSiteOrVirtualDirectory(uniqueValue, null, ".", 1084); Variables["Octopus.Action.IISWebSite.DeploymentType"] = "virtualDirectory"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.CreateOrUpdate"] = "True"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.VirtualDirectory.VirtualPath"] = ToFirstLevelPath(uniqueValue) + "/" + uniqueValue; Variables["Octopus.Action.IISWebSite.VirtualDirectory.VirtualDirectory.CreateAsWebApplication"] = "False"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertFailure(); result.AssertErrorOutput($"Virtual path \"IIS:\\Sites\\{uniqueValue}\\{uniqueValue}\" does not exist.", true); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldNotAllowMissingWebSiteForVirtualFolders() { Variables["Octopus.Action.IISWebSite.DeploymentType"] = "virtualDirectory"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.CreateOrUpdate"] = "True"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.VirtualDirectory.VirtualPath"] = ToFirstLevelPath(uniqueValue); Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertFailure(); result.AssertErrorOutput($"The Web Site \"{uniqueValue}\" does not exist", true); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldDeployAsWebApplication() { iis.CreateWebSiteOrVirtualDirectory(uniqueValue, null, ".", 1085); Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webApplication"; Variables["Octopus.Action.IISWebSite.WebApplication.CreateOrUpdate"] = "True"; Variables["Octopus.Action.IISWebSite.WebApplication.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.WebApplication.VirtualPath"] = ToFirstLevelPath(uniqueValue); Variables["Octopus.Action.IISWebSite.WebApplication.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.WebApplication.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.WebApplication.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var applicationPool = GetApplicationPool(uniqueValue); Assert.AreEqual(uniqueValue, applicationPool.Name); Assert.AreEqual(ObjectState.Started, applicationPool.State); Assert.AreEqual("v4.0", applicationPool.ManagedRuntimeVersion); Assert.AreEqual(ProcessModelIdentityType.ApplicationPoolIdentity, applicationPool.ProcessModel.IdentityType); var webApplication = FindWebApplication(uniqueValue, ToFirstLevelPath(uniqueValue)); Assert.AreEqual(ToFirstLevelPath(uniqueValue), webApplication.Path); Assert.AreEqual(uniqueValue, webApplication.ApplicationPoolName); Assert.IsTrue(webApplication.VirtualDirectories.Single().PhysicalPath.Contains("1.0.0")); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldDetectAttemptedConversionFromVirtualDirectoryToWebApplication() { iis.CreateWebSiteOrVirtualDirectory(uniqueValue, $"/{uniqueValue}", ".", 1086); Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webApplication"; Variables["Octopus.Action.IISWebSite.WebApplication.CreateOrUpdate"] = "True"; Variables["Octopus.Action.IISWebSite.WebApplication.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.WebApplication.VirtualPath"] = ToFirstLevelPath(uniqueValue); Variables["Octopus.Action.IISWebSite.WebApplication.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.WebApplication.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.WebApplication.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertFailure(); result.AssertErrorOutput("Please delete", true); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldDeployWhenVirtualPathAlreadyExistsAndPointsToPhysicalDirectory() { var webSitePhysicalPath = Path.Combine(Path.GetTempPath(), uniqueValue); Directory.CreateDirectory(webSitePhysicalPath); using (new TemporaryDirectory(webSitePhysicalPath)) { iis.CreateWebSiteOrVirtualDirectory(uniqueValue, null, webSitePhysicalPath, 1087); Variables["Octopus.Action.IISWebSite.DeploymentType"] = "virtualDirectory"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.CreateOrUpdate"] = "True"; Variables["Octopus.Action.IISWebSite.VirtualDirectory.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.VirtualDirectory.VirtualPath"] = ToFirstLevelPath(uniqueValue); Variables["Octopus.Action.Package.CustomInstallationDirectory"] = Path.Combine(webSitePhysicalPath, uniqueValue); Variables["Octopus.Action.Package.CustomInstallationDirectoryShouldBePurgedBeforeDeployment"] = "True"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); } } #if WINDOWS_CERTIFICATE_STORE_SUPPORT [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldCreateHttpsBindingUsingCertificatePassedAsVariable() { Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webSite"; Variables["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] = "True"; Variables["Octopus.Action.IISWebSite.Bindings"] = "[{\"protocol\":\"https\",\"port\":1083,\"host\":\"\",\"certificateVariable\":\"AcmeSelfSigned\",\"requireSni\":false,\"enabled\":true}]"; Variables["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] = "True"; Variables["Octopus.Action.IISWebSite.EnableBasicAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables["AcmeSelfSigned"] = "Certificates-1"; Variables["AcmeSelfSigned.Type"] = "Certificate"; Variables["AcmeSelfSigned.Thumbprint"] = SampleCertificate.CapiWithPrivateKey.Thumbprint; Variables["AcmeSelfSigned.Pfx"] = SampleCertificate.CapiWithPrivateKey.Base64Bytes(); Variables["AcmeSelfSigned.Password"] = <PASSWORD>Certificate.CapiWithPrivateKey.Password; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var website = GetWebSite(uniqueValue); var binding = website.Bindings.Single(); Assert.AreEqual(1083, binding.EndPoint.Port); Assert.AreEqual("https", binding.Protocol); Assert.AreEqual(SampleCertificate.CapiWithPrivateKey.Thumbprint, BitConverter.ToString(binding.CertificateHash).Replace("-", "")); Assert.IsTrue(binding.CertificateStoreName.Equals("My", StringComparison.OrdinalIgnoreCase), $"Expected: 'My'. Received: '{binding.CertificateStoreName}'"); // Assert the application-pool account was granted access to the certificate private-key var certificate = SampleCertificate.CapiWithPrivateKey.GetCertificateFromStore("MY", StoreLocation.LocalMachine); SampleCertificate.AssertIdentityHasPrivateKeyAccess(certificate, new NTAccount("IIS AppPool\\" + uniqueValue), CryptoKeyRights.GenericAll); Assert.AreEqual(ObjectState.Started, website.State); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldFindAndUseExistingCertificateInStoreIfPresent() { Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webSite"; Variables["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] = "True"; Variables["Octopus.Action.IISWebSite.Bindings"] = "[{\"protocol\":\"https\",\"port\":1084,\"host\":\"\",\"certificateVariable\":\"AcmeSelfSigned\",\"requireSni\":false,\"enabled\":true}]"; Variables["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] = "True"; Variables["Octopus.Action.IISWebSite.EnableBasicAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables["AcmeSelfSigned"] = "Certificates-1"; Variables["AcmeSelfSigned.Type"] = "Certificate"; Variables["AcmeSelfSigned.Thumbprint"] = SampleCertificate.CapiWithPrivateKey.Thumbprint; Variables["AcmeSelfSigned.Pfx"] = SampleCertificate.CapiWithPrivateKey.Base64Bytes(); Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; SampleCertificate.CapiWithPrivateKey.EnsureCertificateIsInStore(StoreName.My, StoreLocation.LocalMachine); var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var website = GetWebSite(uniqueValue); var binding = website.Bindings.Single(); Assert.AreEqual(1084, binding.EndPoint.Port); Assert.AreEqual("https", binding.Protocol); Assert.AreEqual(SampleCertificate.CapiWithPrivateKey.Thumbprint, BitConverter.ToString(binding.CertificateHash).Replace("-", "")); Assert.AreEqual(StoreName.My.ToString(), binding.CertificateStoreName); Assert.AreEqual(ObjectState.Started, website.State); SampleCertificate.CapiWithPrivateKey.EnsureCertificateNotInStore(StoreName.My, StoreLocation.LocalMachine); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldCreateHttpsBindingUsingCertificatePassedAsThumbprint() { Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webSite"; Variables["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] = "True"; Variables["Octopus.Action.IISWebSite.Bindings"] = $"[{{\"protocol\":\"https\",\"port\":1083,\"host\":\"\",\"thumbprint\":\"{SampleCertificate.CapiWithPrivateKey.Thumbprint}\",\"requireSni\":false,\"enabled\":true}}]"; Variables["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] = "True"; Variables["Octopus.Action.IISWebSite.EnableBasicAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; SampleCertificate.CapiWithPrivateKey.EnsureCertificateIsInStore(StoreName.My, StoreLocation.LocalMachine); var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); var website = GetWebSite(uniqueValue); var binding = website.Bindings.Single(); Assert.AreEqual(1083, binding.EndPoint.Port); Assert.AreEqual("https", binding.Protocol); Assert.AreEqual(SampleCertificate.CapiWithPrivateKey.Thumbprint, BitConverter.ToString(binding.CertificateHash).Replace("-", "")); Assert.IsTrue(binding.CertificateStoreName.Equals("My", StringComparison.OrdinalIgnoreCase), $"Expected: 'My'. Received: '{binding.CertificateStoreName}'"); Assert.AreEqual(ObjectState.Started, website.State); } [Test] // https://github.com/OctopusDeploy/Issues/issues/3378 [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldNotFailIfDisabledBindingUsesUnavailableCertificateVariable() { Variables["Octopus.Action.IISWebSite.DeploymentType"] = "webSite"; Variables["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] = "True"; Variables["Octopus.Action.IISWebSite.Bindings"] = "[{\"protocol\":\"http\",\"port\":1082,\"host\":\"\",\"thumbprint\":\"\",\"requireSni\":false,\"enabled\":true},{\"protocol\":\"https\",\"port\":1084,\"host\":\"\",\"certificateVariable\":\"AcmeSelfSigned\",\"requireSni\":false,\"enabled\":#{HTTPS Binding Enabled}}]"; Variables["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] = "True"; Variables["Octopus.Action.IISWebSite.EnableBasicAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] = "False"; Variables["Octopus.Action.IISWebSite.WebSiteName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolName"] = uniqueValue; Variables["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] = "v4.0"; Variables["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] = "ApplicationPoolIdentity"; Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.IISWebSite"; Variables["HTTPS Binding Enabled"] = "false"; var result = DeployPackage(packageV1.FilePath); result.AssertSuccess(); } #endif private string ToFirstLevelPath(string value) { return $"/{value}"; } private Site GetWebSite(string webSiteName) { return Retry(() => iis.GetWebSite(webSiteName)); } private ApplicationPool GetApplicationPool(string applicationPoolNae) { return Retry(() => iis.GetApplicationPool(applicationPoolNae)); } private VirtualDirectory FindVirtualDirectory(string webSiteName, string path) { return Retry(() => iis.FindVirtualDirectory(webSiteName, path)); } private bool ApplicationPoolExists(string applicationPoolName) { return Retry(() => iis.ApplicationPoolExists(applicationPoolName)); } private TResult Retry<TResult>(Func<TResult> func) { return Policy.Handle<Exception>() .WaitAndRetry(5, retry => TimeSpan.FromSeconds(retry), (e, _) => { Console.WriteLine("Retry failed."); }) .Execute(func); } private Application FindWebApplication(string websiteName, string virtualPath) { return GetWebSite(websiteName).Applications.Single(ap => ap.Path == virtualPath); } } } #endif <file_sep>using System; using Calamari.AzureWebApp.Integration.Websites.Publishing; namespace Calamari.AzureWebApp.Util { static class AzureWebAppHelper { public static AzureTargetSite GetAzureTargetSite(string siteAndMaybeSlotName, string slotName) { var targetSite = new AzureTargetSite {RawSite = siteAndMaybeSlotName}; if (siteAndMaybeSlotName.Contains("(")) { // legacy site and slot "site(slot)" var parenthesesIndex = siteAndMaybeSlotName.IndexOf("(", StringComparison.Ordinal); targetSite.Site = siteAndMaybeSlotName.Substring(0, parenthesesIndex).Trim(); targetSite.Slot = siteAndMaybeSlotName.Substring(parenthesesIndex + 1).Replace(")", string.Empty).Trim(); return targetSite; } if (siteAndMaybeSlotName.Contains("/")) { // "site/slot" var slashIndex = siteAndMaybeSlotName.IndexOf("/", StringComparison.Ordinal); targetSite.Site = siteAndMaybeSlotName.Substring(0, slashIndex).Trim(); targetSite.Slot = siteAndMaybeSlotName.Substring(slashIndex + 1).Trim(); return targetSite; } targetSite.Site = siteAndMaybeSlotName; targetSite.Slot = slotName; return targetSite; } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; namespace Calamari.Testing.Helpers { public class TestCommandLineRunner : CommandLineRunner { private readonly ILog log; readonly IVariables variables; public TestCommandLineRunner(ILog log, IVariables variables) : base(log, variables) { this.log = log; this.variables = variables; Output = new CaptureCommandInvocationOutputSink(); } public CaptureCommandInvocationOutputSink Output { get; } protected override List<ICommandInvocationOutputSink> GetCommandOutputs(CommandLineInvocation invocation) { var outputSinks = new List<ICommandInvocationOutputSink>() { Output, new ServiceMessageCommandInvocationOutputSink(variables) }; if (invocation.OutputToLog) { outputSinks.Add(new CalamariInvocationToLogOutputSink(log)); } return outputSinks; } } }<file_sep>using System; using Calamari.Common.Commands; namespace Calamari.Common.Plumbing.Deployment.Journal { public interface IDeploymentJournalWriter { void AddJournalEntry(RunningDeployment deployment, bool wasSuccessful, string? packageFile = null); } }<file_sep>using System; namespace Calamari.Testing.LogParser { public class DeltaPackage { public DeltaPackage(string fullPathOnRemoteMachine, string hash, long size) { FullPathOnRemoteMachine = fullPathOnRemoteMachine; Hash = hash; Size = size; } public string FullPathOnRemoteMachine { get; } public string Hash { get; } public long Size { get; } } }<file_sep>using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Autofac; using Calamari.AzureScripting; using Calamari.Common; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Scripting; namespace Calamari.AzureCloudService { public class Program : CalamariFlavourProgramAsync { public Program(ILog log) : base(log) { } public static Task<int> Main(string[] args) { return new Program(ConsoleLog.Instance).Run(args); } protected override void ConfigureContainer(ContainerBuilder builder, CommonOptions options) { base.ConfigureContainer(builder, options); builder.RegisterType<AzurePackageUploader>().AsSelf(); builder.RegisterType<AzureAccount>().AsSelf(); } protected override IEnumerable<Assembly> GetProgramAssembliesToRegister() { yield return typeof(AzureContextScriptWrapper).Assembly; yield return typeof(RunScriptCommand).Assembly; yield return typeof(Program).Assembly; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Tests.Helpers { public static class TextExtensions { static readonly byte BytePeriod = Encoding.ASCII.GetBytes(".")[0]; static readonly byte ByteCaret = Encoding.ASCII.GetBytes("^")[0]; static readonly byte ByteQuestionMark = Encoding.ASCII.GetBytes("?")[0]; public static string ToReadableHexDump(this IEnumerable<byte> byteSequence) { const int blockLength = 8; return byteSequence .Select((byt, index) => (byt, index)) .GroupBy(pair => pair.index / blockLength, pair => pair.byt, (key, bytes) => bytes.ToArray()) .Select(bytes => BitConverter.ToString(bytes).Replace('-', ' ').PadRight(blockLength * 3 + 2) + bytes.ToPrintableAsciiString()) .Join(Environment.NewLine); } public static string ToPrintableAsciiString(this IEnumerable<byte> bytes) { return Encoding.ASCII.GetString(bytes.Select(byt => byt >= 0x20 && byt <= 0x7E ? byt : byt == 0x00 ? BytePeriod : byt == 0x0D || byt == 0x0A ? ByteCaret : ByteQuestionMark) .ToArray()); } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Logging; using SharpCompress.Compressors; using SharpCompress.Compressors.BZip2; namespace Calamari.Common.Features.Packages { public class TarBzipPackageExtractor : TarPackageExtractor { public TarBzipPackageExtractor(ILog log) : base(log) { } public override string[] Extensions => new[] { ".tar.bz2", ".tar.bz", ".tbz" }; protected override Stream GetCompressionStream(Stream stream) { return new BZip2Stream(stream, CompressionMode.Decompress, false); } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Deployment { public class PathToPackage { readonly string path; public PathToPackage(string path) { this.path = path; } public static implicit operator string?(PathToPackage? pathToPackage) { return pathToPackage?.path; } } }<file_sep>using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { /// <summary> /// Represents a kubernetes resource in a cluster, including its status /// </summary> public class Resource : IResourceIdentity { [JsonIgnore] protected JObject data; [JsonIgnore] public IEnumerable<string> OwnerUids { get; } [JsonIgnore] public string Uid { get; set; } [JsonIgnore] public string Kind { get; set; } [JsonIgnore] public string Name { get; } [JsonIgnore] public string Namespace { get; } [JsonIgnore] public virtual ResourceStatus ResourceStatus { get; set; } = ResourceStatus.Successful; [JsonIgnore] public virtual string ChildKind => ""; [JsonIgnore] public IEnumerable<Resource> Children { get; internal set; } internal Resource() { } public Resource(JObject json, Options options) { data = json; OwnerUids = data.SelectTokens("$.metadata.ownerReferences[*].uid").Values<string>(); Uid = Field("$.metadata.uid"); Kind = Field("$.kind"); Name = Field("$.metadata.name"); Namespace = Field("$.metadata.namespace"); } public virtual bool HasUpdate(Resource lastStatus) => false; public virtual void UpdateChildren(IEnumerable<Resource> children) => Children = children; protected string Field(string jsonPath) => FieldOrDefault(jsonPath, ""); protected T FieldOrDefault<T>(string jsonPath, T defaultValue) { var result = data.SelectToken(jsonPath); if (result == null) { return defaultValue; } try { return result.Value<T>(); } catch { return defaultValue; } } protected static T CastOrThrow<T>(Resource resource) where T: Resource { if (resource is T subType) { return subType; } throw new Exception($"Cannot cast resource to subtype {nameof(T)}"); } } }<file_sep>wget https://packages.microsoft.com/config/debian/10/packages-microsoft-prod.deb -O packages-microsoft-prod.deb sudo dpkg -i packages-microsoft-prod.deb sudo apt-get update sudo apt-get install -y apt-transport-https unzip sudo apt-get update sudo apt-get install -y dotnet-sdk-6.0 export AWS_CLUSTER_URL=${endpoint} export AWS_CLUSTER_NAME=${cluster_name} export AWS_REGION=${region} export AWS_IAM_ROLE_ARN=${iam_role_arn} export AWS_CLUSTER_ARN=${cluster_arn} mkdir tools cd tools || exit curl -L -o kubectl "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" curl -L -o aws-iam-authenticator "https://github.com/kubernetes-sigs/aws-iam-authenticator/releases/download/v0.5.3/aws-iam-authenticator_0.5.3_linux_amd64" curl -L -o awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" unzip -u awscliv2.zip mv aws awscli cp -a awscli/dist/* . chmod u+x aws-iam-authenticator chmod u+x kubectl chmod u+x aws export PATH="$PATH:$(pwd)" cd .. mkdir tests cd tests || exit unzip /tmp/data.zip dotnet test Calamari.Tests.dll --Tests AuthoriseWithAmazonEC2Role --logger "console;verbosity=detailed" dotnet test Calamari.Tests.dll --Tests DiscoverKubernetesClusterWithEc2InstanceCredentialsAndIamRole --logger "console;verbosity=detailed" dotnet test Calamari.Tests.dll --Tests DiscoverKubernetesClusterWithEc2InstanceCredentialsAndNoIamRole --logger "console;verbosity=detailed" <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Calamari.Common.Commands; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class FeatureScriptConventionFixture { ICalamariFileSystem fileSystem; ICalamariEmbeddedResources embeddedResources; IScriptEngine scriptEngine; ICommandLineRunner commandLineRunner; RunningDeployment deployment; IVariables variables; const string stagingDirectory = "c:\\applications\\acme\\1.0.0"; const string scriptContents = "blah blah blah"; [SetUp] public void SetUp() { fileSystem = Substitute.For<ICalamariFileSystem>(); embeddedResources = Substitute.For<ICalamariEmbeddedResources>(); scriptEngine = Substitute.For<IScriptEngine>(); commandLineRunner = Substitute.For<ICommandLineRunner>(); scriptEngine.GetSupportedTypes().Returns(new[] { ScriptSyntax.PowerShell }); variables = new CalamariVariables(); variables.Set(KnownVariables.Package.EnabledFeatures, "Octopus.Features.blah"); deployment = new RunningDeployment("C:\\packages", variables) { StagingDirectory = stagingDirectory }; } [Test] public void ShouldRunMatchingScripts() { const string suffix = "AfterPreDeploy"; var features = new string[] {"feature1", "feature2"}; Arrange(features, suffix); var convention = CreateConvention(suffix); convention.Install(deployment); foreach (var feature in features) { var scriptPath = Path.Combine(stagingDirectory, FeatureConvention.GetScriptName(feature, suffix, "ps1")); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == scriptPath), variables, commandLineRunner); } } [Test] public void ShouldCreateScriptFileIfNotExists() { const string deployStage = "BeforePostDeploy"; const string feature = "doTheThing"; var scriptPath = Path.Combine(stagingDirectory, FeatureConvention.GetScriptName(feature, deployStage, "ps1")); variables.Set(KnownVariables.Package.EnabledFeatures, feature); Arrange(new List<string>{ feature }, deployStage); fileSystem.FileExists(scriptPath).Returns(false); var convention = CreateConvention(deployStage); scriptEngine.Execute(Arg.Is<Script>(s => s.File == scriptPath), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.Received().OverwriteFile(scriptPath, scriptContents ); } [Test] public void ShouldNotOverwriteScriptFileIfItExists() { const string deployStage = "BeforeDeploy"; const string feature = "doTheThing"; var scriptPath = Path.Combine(stagingDirectory, FeatureConvention.GetScriptName(feature, deployStage, "ps1")); Arrange(new List<string>{ feature }, deployStage); fileSystem.FileExists(scriptPath).Returns(true); var convention = CreateConvention(deployStage); scriptEngine.Execute(Arg.Is<Script>(s => s.File == scriptPath), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.DidNotReceive().OverwriteFile(scriptPath, Arg.Any<string>() ); } [Test] public void ShouldDeleteScriptFile() { const string deployStage = "BeforeDeploy"; const string feature = "doTheThing"; var scriptPath = Path.Combine(stagingDirectory, FeatureConvention.GetScriptName(feature, deployStage, "ps1")); Arrange(new List<string>{ feature }, deployStage); var convention = CreateConvention(deployStage); scriptEngine.Execute(Arg.Is<Script>(s => s.File == scriptPath), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.Received().DeleteFile(scriptPath, Arg.Any<FailureOptions>()); } private void Arrange(ICollection<string> features, string suffix) { variables.Set(KnownVariables.Package.EnabledFeatures, string.Join(",", features)); var embeddedResourceNames = new List<string>(); foreach (var feature in features) { var scriptName = FeatureConvention.GetScriptName(feature, suffix, "ps1"); var embeddedResourceName = FeatureConvention.GetEmbeddedResourceName(scriptName); embeddedResources.GetEmbeddedResourceText(Arg.Any<Assembly>(), embeddedResourceName).Returns(scriptContents); embeddedResourceNames.Add(embeddedResourceName); var scriptPath = Path.Combine(stagingDirectory, scriptName); scriptEngine.Execute(Arg.Is<Script>(s => s.File == scriptPath), variables, commandLineRunner) .Returns(new CommandResult("", 0)); } embeddedResources.GetEmbeddedResourceNames(Arg.Any<Assembly>()).Returns(embeddedResourceNames.ToArray()); } private FeatureConvention CreateConvention(string deployStage) { return new FeatureConvention(deployStage, null, fileSystem, scriptEngine, commandLineRunner, embeddedResources); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Proxies; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting { public abstract class ScriptExecutor : IScriptExecutor { static readonly string CopyWorkingDirectoryVariable = "Octopus.Calamari.CopyWorkingDirectoryIncludingKeyTo"; public CommandResult Execute(Script script, IVariables variables, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars = null) { var environmentVariablesIncludingProxy = environmentVars ?? new Dictionary<string, string>(); foreach (var proxyVariable in ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables()) environmentVariablesIncludingProxy[proxyVariable.Key] = proxyVariable.Value; var prepared = PrepareExecution(script, variables, environmentVariablesIncludingProxy); CommandResult? result = null; foreach (var execution in prepared) { if (variables.IsSet(CopyWorkingDirectoryVariable)) CopyWorkingDirectory(variables, execution.CommandLineInvocation.WorkingDirectory, execution.CommandLineInvocation.Arguments); try { if (execution.CommandLineInvocation.Isolate) using (SemaphoreFactory.Get() .Acquire("CalamariSynchronizeProcess", "Waiting for other process to finish executing script")) { result = commandLineRunner.Execute(execution.CommandLineInvocation); } else result = commandLineRunner.Execute(execution.CommandLineInvocation); if (result.ExitCode != 0) return result; } finally { foreach (var temporaryFile in execution.TemporaryFiles) { var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); fileSystem.DeleteFile(temporaryFile, FailureOptions.IgnoreFailure); } } } return result!; } protected abstract IEnumerable<ScriptExecution> PrepareExecution(Script script, IVariables variables, Dictionary<string, string>? environmentVars = null); static void CopyWorkingDirectory(IVariables variables, string workingDirectory, string arguments) { var fs = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); var copyToParent = Path.Combine( variables.Get(CopyWorkingDirectoryVariable), fs.RemoveInvalidFileNameChars(variables.Get(ProjectVariables.Name, "Non-Project")), variables.Get(DeploymentVariables.Id, "Non-Deployment"), fs.RemoveInvalidFileNameChars(variables.Get(ActionVariables.Name, "Non-Action")) ); string copyTo; var n = 1; do { copyTo = Path.Combine(copyToParent, $"{n++}"); } while (Directory.Exists(copyTo)); Log.Verbose($"Copying working directory '{workingDirectory}' to '{copyTo}'"); fs.CopyDirectory(workingDirectory, copyTo); File.WriteAllText(Path.Combine(copyTo, "Arguments.txt"), arguments); File.WriteAllText(Path.Combine(copyTo, "CopiedFromDirectory.txt"), workingDirectory); } protected class ScriptExecution { public ScriptExecution(CommandLineInvocation commandLineInvocation, IEnumerable<string> temporaryFiles) { CommandLineInvocation = commandLineInvocation; TemporaryFiles = temporaryFiles; } public CommandLineInvocation CommandLineInvocation { get; } public IEnumerable<string> TemporaryFiles { get; } } } }<file_sep>using System; using System.Diagnostics; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.Runtime; using Calamari.Aws.Exceptions; using Calamari.Aws.Integration.CloudFormation; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Integration.Processes; using Newtonsoft.Json; namespace Calamari.Aws.Deployment.Conventions { public class DescribeCloudFormationChangeSetConvention : CloudFormationInstallationConventionBase { private readonly Func<IAmazonCloudFormation> clientFactory; private readonly Func<RunningDeployment, StackArn> stackProvider; private readonly Func<RunningDeployment, ChangeSetArn> changeSetProvider; public DescribeCloudFormationChangeSetConvention(Func<IAmazonCloudFormation> clientFactory, StackEventLogger logger, Func<RunningDeployment, StackArn> stackProvider, Func<RunningDeployment, ChangeSetArn> changeSetProvider) : base(logger) { this.clientFactory = clientFactory; this.stackProvider = stackProvider; this.changeSetProvider = changeSetProvider; } public override void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private Task InstallAsync(RunningDeployment deployment) { var stack = stackProvider(deployment); var changeSet = changeSetProvider(deployment); return WithAmazonServiceExceptionHandling(async () => await DescribeChangeset(stack, changeSet, deployment.Variables) ); } public async Task DescribeChangeset(StackArn stack, ChangeSetArn changeSet, IVariables variables) { Guard.NotNull(stack, "The provided stack identifer or name may not be null"); Guard.NotNull(changeSet, "The provided change set identifier or name may not be null"); Guard.NotNull(variables, "The variable dictionary may not be null"); try { var response = await clientFactory.DescribeChangeSetAsync(stack, changeSet); SetOutputVariable(variables, "ChangeCount", response.Changes.Count.ToString()); SetOutputVariable(variables, "Changes", JsonConvert.SerializeObject(response.Changes, Formatting.Indented)); } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "AccessDenied") { throw new PermissionException( "The AWS account used to perform the operation does not have the required permissions to describe the change set.\n" + "Please ensure the current account has permission to perfrom action 'cloudformation:DescribeChangeSet'." + ex.Message + "\n"); } catch (AmazonCloudFormationException ex) { throw new UnknownException("An unrecognized exception was thrown while describing the CloudFormation change set.", ex); } } } }<file_sep>using System.Linq; using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class DeploymentTests { [Test] public void ShouldCollectCorrectProperties() { var input = new DeploymentResponseBuilder() .WithDesiredReplicas(3) .WithTotalReplicas(4) .WithAvailableReplicas(3) .WithReadyReplicas(3) .WithUpdatedReplicas(1) .Build(); var deployment = ResourceFactory.FromJson(input, new Options()); deployment.Should().BeEquivalentTo(new { Kind = "Deployment", Name = "nginx", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", UpToDate = 1, Ready = "3/3", Available = 3, ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress }); } [Test] public void ShouldNotBeSuccessfulIfSomeChildrenPodsAreStillRunning() { var input = new DeploymentResponseBuilder() .WithDesiredReplicas(3) .WithTotalReplicas(3) .WithAvailableReplicas(3) .WithReadyReplicas(3) .WithUpdatedReplicas(3) .Build(); var deployment = ResourceFactory.FromJson(input, new Options()); var pod = new PodResponseBuilder().Build(); // More pods remaining than desired var children = Enumerable.Range(0, 4) .Select(_ => ResourceFactory.FromJson(pod, new Options())); var replicaSet = ResourceFactory.FromJson("{}", new Options()); replicaSet.UpdateChildren(children); deployment.UpdateChildren(new Resource[] { replicaSet }); deployment.ResourceStatus.Should().Be(Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress); } [Test] public void ShouldBeSuccessfulIfOnlyDesiredPodsAreRunning() { var input = new DeploymentResponseBuilder() .WithDesiredReplicas(3) .WithTotalReplicas(3) .WithAvailableReplicas(3) .WithReadyReplicas(3) .WithUpdatedReplicas(3) .Build(); var deployment = ResourceFactory.FromJson(input, new Options()); var pod = new PodResponseBuilder().Build(); var children = Enumerable.Range(0, 3) .Select(_ => ResourceFactory.FromJson(pod, new Options())); var replicaSet = ResourceFactory.FromJson("{}", new Options()); replicaSet.UpdateChildren(children); deployment.UpdateChildren(new Resource[] { replicaSet }); deployment.ResourceStatus.Should().Be(Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful); } } internal class DeploymentResponseBuilder { private const string Template = @"{{ ""kind"": ""Deployment"", ""metadata"": {{ ""name"": ""nginx"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }}, ""spec"": {{ ""replicas"": {0} }}, ""status"": {{ ""replicas"": {1}, ""availableReplicas"": {2}, ""readyReplicas"": {3}, ""updatedReplicas"": {4} }} }}"; private int DesiredReplicas { get; set; } private int TotalReplicas { get; set; } private int AvailableReplicas { get; set; } private int ReadyReplicas { get; set; } private int UpdatedReplicas { get; set; } public DeploymentResponseBuilder WithDesiredReplicas(int replicas) { DesiredReplicas = replicas; return this; } public DeploymentResponseBuilder WithTotalReplicas(int replicas) { TotalReplicas = replicas; return this; } public DeploymentResponseBuilder WithAvailableReplicas(int replicas) { AvailableReplicas = replicas; return this; } public DeploymentResponseBuilder WithReadyReplicas(int replicas) { ReadyReplicas = replicas; return this; } public DeploymentResponseBuilder WithUpdatedReplicas(int replicas) { UpdatedReplicas = replicas; return this; } public string Build() { return string.Format( Template, DesiredReplicas, TotalReplicas, AvailableReplicas, ReadyReplicas, UpdatedReplicas); } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; namespace Calamari.Deployment.Conventions { public class ConfigurationTransformsConvention : IInstallConvention { readonly ConfigurationTransformsBehaviour configurationTransformsBehaviour; public ConfigurationTransformsConvention(ConfigurationTransformsBehaviour configurationTransformsBehaviour) { this.configurationTransformsBehaviour = configurationTransformsBehaviour; } public void Install(RunningDeployment deployment) { if (configurationTransformsBehaviour.IsEnabled(deployment)) { configurationTransformsBehaviour.Execute(deployment).Wait(); } } } } <file_sep>using System; namespace Calamari.AzureAppService.Azure { static class SpecialVariables { public static class Action { public static class Azure { /// <summary> /// Expected Values: /// Package, /// Container, /// </summary> public static readonly string DeploymentType = "Octopus.Action.Azure.DeploymentType"; public static readonly string ResourceGroupName = "Octopus.Action.Azure.ResourceGroupName"; public static readonly string WebAppName = "Octopus.Action.Azure.WebAppName"; public static readonly string WebAppSlot = "Octopus.Action.Azure.DeploymentSlot"; public static readonly string AppSettings = "Octopus.Action.Azure.AppSettings"; public static readonly string ConnectionStrings = "Octopus.Action.Azure.ConnectionStrings"; } public static class Package { public static readonly string FeedId = "Octopus.Action.Package.FeedId"; public static readonly string PackageId = "Octopus.Action.Package.PackageId"; public static readonly string PackageVersion = "Octopus.Action.Package.PackageVersion"; // This will only be set for container registry feeds public static readonly string Image = "Octopus.Action.Package[].Image"; public static readonly string Registry = "Octopus.Action.Package[].Registry"; public static class Feed { public static readonly string Username = "Octopus.Action.Package[].Feed.Username"; public static readonly string Password = "Octopus.Action.Package[].Feed.Password"; } } } } } <file_sep>using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.ConfigurationVariables; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Octopus.CoreUtilities.Extensions; namespace Calamari.Common.Features.Behaviours { public class ConfigurationVariablesBehaviour : IBehaviour { readonly ICalamariFileSystem fileSystem; readonly IVariables variables; readonly IConfigurationVariablesReplacer replacer; readonly ILog log; private readonly string subdirectory; public ConfigurationVariablesBehaviour( ICalamariFileSystem fileSystem, IVariables variables, IConfigurationVariablesReplacer replacer, ILog log, string subdirectory = "") { this.fileSystem = fileSystem; this.variables = variables; this.replacer = replacer; this.log = log; this.subdirectory = subdirectory; } public bool IsEnabled(RunningDeployment context) { return context.Variables.IsFeatureEnabled(KnownVariables.Features.ConfigurationVariables) && context.Variables.GetFlag(KnownVariables.Package.AutomaticallyUpdateAppSettingsAndConnectionStrings); } public Task Execute(RunningDeployment context) { DoTransforms(Path.Combine(context.CurrentDirectory, subdirectory)); return this.CompletedTask(); } public void DoTransforms(string currentDirectory) { var appliedAsTransforms = variables.GetStrings(KnownVariables.AppliedXmlConfigTransforms, '|'); log.Verbose("Looking for appSettings, applicationSettings, and connectionStrings in any .config files"); if (variables.GetFlag(KnownVariables.Package.IgnoreVariableReplacementErrors)) log.Info("Variable replacement errors are suppressed because the variable Octopus.Action.Package.IgnoreVariableReplacementErrors has been set."); foreach (var configurationFile in MatchingFiles(currentDirectory)) { if (appliedAsTransforms.Contains(configurationFile)) { log.VerboseFormat("File '{0}' was interpreted as an XML configuration transform; variable substitution won't be attempted.", configurationFile); continue; } replacer.ModifyConfigurationFile(configurationFile, variables); } } string[] MatchingFiles(string currentDirectory) { var files = fileSystem.EnumerateFilesRecursively(currentDirectory, "*.config"); var additional = variables.GetStrings(ActionVariables.AdditionalPaths) .Where(s => !string.IsNullOrWhiteSpace(s)) .SelectMany(p => fileSystem.EnumerateFilesRecursively(p, "*.config")); return files.Concat(additional).Distinct().ToArray(); } } }<file_sep>using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class Service : Resource { public override string ChildKind => "EndpointSlice"; public string Type { get; } public string ClusterIp { get; } public string ExternalIp { get; } public IEnumerable<string> Ports { get; } public Service(JObject json, Options options) : base(json, options) { Type = Field("$.spec.type"); ClusterIp = Field("$.spec.clusterIP"); var ports = data.SelectToken("$.spec.ports") ?.ToObject<ServicePort[]>() ?? new ServicePort[] { }; Ports = FormatPorts(ports); var loadBalancerIngresses = data.SelectToken("$.status.loadBalancer.ingress") ?.ToObject<LoadBalancerIngress[]>() ?? new LoadBalancerIngress[] { }; ExternalIp = FormatExternalIp(loadBalancerIngresses); } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<Service>(lastStatus); return last.ClusterIp != ClusterIp || last.ExternalIp != ExternalIp || last.Type != Type || last.Ports.SequenceEqual(Ports); } private static IEnumerable<string> FormatPorts(IEnumerable<ServicePort> ports) { return ports.Select(port => port.NodePort == null ? $"{port.Port}/{port.Protocol}" : $"{port.Port}:{port.NodePort}/{port.Protocol}"); } private static string FormatExternalIp(LoadBalancerIngress[] loadBalancerIngresses) { return !loadBalancerIngresses.Any() ? "<none>" : string.Join(",", loadBalancerIngresses.Select(ingress => ingress.Ip)); } } }<file_sep>using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.LaunchTools; using Calamari.Testing.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; using System; using System.IO; namespace Calamari.Tests.LaunchTools { [TestFixture] public class NodeExecutorFixture { [Test] [TestCase("execute")] [TestCase("Execute")] [TestCase("eXeCuTe")] public void Execute_UsesCorrectCommandLineInvocation_ForValidExecutionCommands(string executionCommand) { // Arrange var instructions = BuildInstructions(executionCommand); var variables = BuildVariables(); var options = BuildOptions(); var commandLineRunner = Substitute.For<ICommandLineRunner>(); var sut = new NodeExecutor(options, variables, commandLineRunner, new InMemoryLog()); CommandLineInvocation capturedInvocation = null; var fakeResult = new CommandResult("fakeCommand", 0); commandLineRunner.Execute(Arg.Do<CommandLineInvocation>(arg => capturedInvocation = arg)).Returns(fakeResult); // Act sut.Execute(instructions); // Assert var arguments = capturedInvocation.Arguments.Split(' '); arguments.Should().HaveCount(8) .And.HaveElementAt(0, $"\"{Path.Combine("expectedBootstrapperPath","bootstrapper.js")}\"") .And.HaveElementAt(1, $"\"{executionCommand}\"") .And.HaveElementAt(2, "\"expectedTargetPath\"") .And.HaveElementAt(4, "\"encryptionPassword\"") .And.HaveElementAt(5, "\"Octopuss\"") .And.HaveElementAt(6, "\"inputsKey\"") .And.HaveElementAt(7, "\"targetInputsKey\""); } [TestCase("discover")] [TestCase("Discover")] [TestCase("dIsCoVeR")] public void Execute_UsesCorrectCommandLineInvocation_ForValidTargetDiscoveryCommands(string discoveryCommand) { // Arrange var instructions = BuildInstructions(discoveryCommand); var variables = BuildVariables(); var options = BuildOptions(); var commandLineRunner = Substitute.For<ICommandLineRunner>(); var sut = new NodeExecutor(options, variables, commandLineRunner, new InMemoryLog()); CommandLineInvocation capturedInvocation = null; var fakeResult = new CommandResult("fakeCommand", 0); commandLineRunner.Execute(Arg.Do<CommandLineInvocation>(arg => capturedInvocation = arg)).Returns(fakeResult); // Act sut.Execute(instructions); // Assert var arguments = capturedInvocation.Arguments.Split(' '); arguments.Should().HaveCount(7) .And.HaveElementAt(0, $"\"{Path.Combine("expectedBootstrapperPath","bootstrapper.js")}\"") .And.HaveElementAt(1, $"\"{discoveryCommand}\"") .And.HaveElementAt(2, "\"expectedTargetPath\"") .And.HaveElementAt(4, "\"encryptionPassword\"") .And.HaveElementAt(5, "\"<PASSWORD>\"") .And.HaveElementAt(6, "\"discoveryContextKey\""); } [Test] public void Execute_ThrowsCommandException_ForUnknownBootstrapperInvocationCommand() { // Arrange var instructions = BuildInstructions("wrongCommand"); var variables = BuildVariables(); var options = BuildOptions(); var commandLineRunner = Substitute.For<ICommandLineRunner>(); var sut = new NodeExecutor(options, variables, commandLineRunner, new InMemoryLog()); // Act Action action = () => sut.Execute(instructions); // Assert action.Should().Throw<CommandException>().WithMessage("Unknown bootstrapper invocation command: 'wrongCommand'"); } private string BuildInstructions(string command) => $@"{{ ""nodePathVariable"": ""nodePathKey"", ""targetPathVariable"": ""targetPathKey"", ""bootstrapperPathVariable"": ""bootstrapperVarKey"", ""bootstrapperInvocationCommand"": ""{command}"", ""inputsVariable"": ""inputsKey"", ""deploymentTargetInputsVariable"": ""targetInputsKey"", ""targetDiscoveryContextVariable"": ""discoveryContextKey"" }}"; private CommonOptions BuildOptions() => CommonOptions.Parse(new[] { "Test", "--variables", "firstInsensitiveVariablesFileName", "--sensitiveVariables", "firstSensitiveVariablesFileName", "--sensitiveVariables", "secondSensitiveVariablesFileName", "--sensitiveVariablesPassword", "encryptionPassword" }); private CalamariVariables BuildVariables() { var variables = new CalamariVariables(); variables.Set("nodePathKey", "expectedNodePath"); variables.Set("targetPathKey", "expectedTargetPath"); variables.Set("bootstrapperVarKey", "expectedBootstrapperPath"); variables.Set("inputsKey", @"{ input: ""foo"" }"); variables.Set("targetInputsKey", @"{ targetInput: ""bar"" }"); variables.Set("foo", "AwsAccount"); variables.Set("discoveryContextKey", @"{ ""blah"": ""baz"" }"); return variables; } } } <file_sep>using System; using System.Diagnostics; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Calamari.AzureWebApp.Integration.Websites.Publishing; using Calamari.AzureWebApp.Util; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Microsoft.Web.Deployment; namespace Calamari.AzureWebApp { class AzureWebAppBehaviour : IDeployBehaviour { readonly ILog log; readonly ResourceManagerPublishProfileProvider resourceManagerPublishProfileProvider; public AzureWebAppBehaviour(ILog log, ResourceManagerPublishProfileProvider resourceManagerPublishProfileProvider) { this.log = log; this.resourceManagerPublishProfileProvider = resourceManagerPublishProfileProvider; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment deployment) { var variables = deployment.Variables; var subscriptionId = variables.Get(SpecialVariables.Action.Azure.SubscriptionId); var resourceGroupName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName, string.Empty); var siteAndSlotName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); var targetSite = AzureWebAppHelper.GetAzureTargetSite(siteAndSlotName, slotName); var resourceGroupText = string.IsNullOrEmpty(resourceGroupName) ? string.Empty : $" in Resource Group '{resourceGroupName}'"; var slotText = targetSite.HasSlot ? $", deployment slot '{targetSite.Slot}'" : string.Empty; log.Info($"Deploying to Azure WebApp '{targetSite.Site}'{slotText}{resourceGroupText}, using subscription-id '{subscriptionId}'"); var publishSettings = await GetPublishProfile(variables); RemoteCertificateValidationCallback originalServerCertificateValidationCallback = null; try { originalServerCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback; ServicePointManager.ServerCertificateValidationCallback = WrapperForServerCertificateValidationCallback; await DeployToAzure(deployment, targetSite, variables, publishSettings); } finally { ServicePointManager.ServerCertificateValidationCallback = originalServerCertificateValidationCallback; } } async Task DeployToAzure(RunningDeployment deployment, AzureTargetSite targetSite, IVariables variables, WebDeployPublishSettings publishSettings) { var retry = AzureRetryTracker.GetDefaultRetryTracker(); while (retry.Try()) { try { log.Verbose($"Using site '{targetSite.Site}'"); log.Verbose($"Using slot '{targetSite.Slot}'"); var changeSummary = DeploymentManager .CreateObject("contentPath", deployment.CurrentDirectory) .SyncTo( "contentPath", BuildPath(targetSite, variables), DeploymentOptions(publishSettings), DeploymentSyncOptions(variables) ); log.InfoFormat( "Successfully deployed to Azure. {0} objects added. {1} objects updated. {2} objects deleted.", changeSummary.ObjectsAdded, changeSummary.ObjectsUpdated, changeSummary.ObjectsDeleted); break; } catch (DeploymentDetailedException ex) { if (retry.CanRetry()) { if (retry.ShouldLogWarning()) { Log.VerboseFormat("Retry #{0} on Azure deploy. Exception: {1}", retry.CurrentTry, ex.Message); } await Task.Delay(retry.Sleep()); } else { throw; } } } } bool WrapperForServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { switch (sslPolicyErrors) { case SslPolicyErrors.None: return true; case SslPolicyErrors.RemoteCertificateNameMismatch: log.Error( $"A certificate mismatch occurred. We have had reports previously of Azure using incorrect certificates for some Web App SCM sites, which seem to related to a known issue, a possible fix is documented in {log.FormatLink("https://g.octopushq.com/CertificateMismatch")}."); break; } return false; } Task<WebDeployPublishSettings> GetPublishProfile(IVariables variables) { var account = new AzureServicePrincipalAccount(variables); var siteAndSlotName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); var targetSite = AzureWebAppHelper.GetAzureTargetSite(siteAndSlotName, slotName); return resourceManagerPublishProfileProvider.GetPublishProperties(account, variables.Get(SpecialVariables.Action.Azure.ResourceGroupName, string.Empty), targetSite); } string BuildPath(AzureTargetSite site, IVariables variables) { var relativePath = variables.Get(SpecialVariables.Action.Azure.PhysicalPath, String.Empty).TrimStart('\\'); return relativePath != String.Empty ? site.Site + "\\" + relativePath : site.Site; } DeploymentBaseOptions DeploymentOptions(WebDeployPublishSettings settings) { var publishProfile = settings.PublishProfile; var deploySite = settings.DeploymentSite; var options = new DeploymentBaseOptions { AuthenticationType = "Basic", RetryAttempts = 3, RetryInterval = 1000, TraceLevel = TraceLevel.Verbose, UserName = publishProfile.UserName, Password = <PASSWORD>, UserAgent = "OctopusDeploy/1.0", ComputerName = new Uri(publishProfile.Uri, $"/msdeploy.axd?site={deploySite}").ToString() }; options.Trace += (sender, eventArgs) => LogDeploymentEvent(eventArgs); return options; } DeploymentSyncOptions DeploymentSyncOptions(IVariables variables) { var syncOptions = new DeploymentSyncOptions { WhatIf = false, UseChecksum = variables.GetFlag(SpecialVariables.Action.Azure.UseChecksum), DoNotDelete = !variables.GetFlag(SpecialVariables.Action.Azure.RemoveAdditionalFiles) }; ApplyAppOfflineDeploymentRule(syncOptions, variables); ApplyPreserveAppDataDeploymentRule(syncOptions, variables); ApplyPreservePathsDeploymentRule(syncOptions, variables); return syncOptions; } void ApplyPreserveAppDataDeploymentRule(DeploymentSyncOptions syncOptions, IVariables variables) { // If PreserveAppData variable set, then create SkipDelete rules for App_Data directory // ReSharper disable once InvertIf if (variables.GetFlag(SpecialVariables.Action.Azure.PreserveAppData)) { syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataFiles", "Delete", "filePath", "\\\\App_Data\\\\.*", null)); syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataDir", "Delete", "dirPath", "\\\\App_Data(\\\\.*|$)", null)); } } void ApplyPreservePathsDeploymentRule(DeploymentSyncOptions syncOptions, IVariables variables) { // If PreservePaths variable set, then create SkipDelete rules for each path regex var preservePaths = variables.GetStrings(SpecialVariables.Action.Azure.PreservePaths, ';'); for (var i = 0; i < preservePaths.Count; i++) { var path = preservePaths[i]; syncOptions.Rules.Add(new DeploymentSkipRule($"SkipDeleteFiles_{i}", "Delete", "filePath", path, null)); syncOptions.Rules.Add(new DeploymentSkipRule($"SkipDeleteDir_{i}", "Delete", "dirPath", path, null)); } } void ApplyAppOfflineDeploymentRule(DeploymentSyncOptions syncOptions, IVariables variables) { // ReSharper disable once InvertIf if (variables.GetFlag(SpecialVariables.Action.Azure.AppOffline)) { var rules = Microsoft.Web.Deployment.DeploymentSyncOptions.GetAvailableRules(); if (rules.TryGetValue("AppOffline", out var rule)) syncOptions.Rules.Add(rule); else log.Verbose("Azure Deployment API does not support `AppOffline` deployment rule."); } } void LogDeploymentEvent(DeploymentTraceEventArgs args) { switch (args.EventLevel) { case TraceLevel.Verbose: log.Verbose(args.Message); break; case TraceLevel.Info: // The deploy-log is noisy; we'll log info as verbose log.Verbose(args.Message); break; case TraceLevel.Warning: log.Warn(args.Message); break; case TraceLevel.Error: log.Error(args.Message); break; } } } }<file_sep>namespace Calamari.Util { public enum HelmVersion { V2, V3 } }<file_sep>using System; using System.Collections.Generic; using System.Text; using Calamari.Common.Features.Scripts; namespace Calamari.Common.Features.FunctionScriptContributions { class PowerShellLanguage : ICodeGenFunctions { public ScriptSyntax Syntax { get; } = ScriptSyntax.PowerShell; public string Generate(IEnumerable<ScriptFunctionRegistration> registrations) { var sb = new StringBuilder(); var tabsCount = 0; void TabIndentedAppendLine(string value) { switch (value) { case "{": sb.AppendLine($"{new string('\t', tabsCount)}{value}"); tabsCount++; break; case "}": tabsCount--; sb.AppendLine($"{new string('\t', tabsCount)}{value}"); break; default: sb.AppendLine($"{new string('\t', tabsCount)}{value}"); break; } } foreach (var registration in registrations) { sb.Append($"function New-{registration.Name}("); var count = 0; foreach (var pair in registration.Parameters) { if (count > 0) { sb.Append(", "); } sb.Append($"[{ConvertType(pair.Value.Type)}] ${pair.Key}"); count++; } TabIndentedAppendLine(")"); TabIndentedAppendLine("{"); TabIndentedAppendLine("$parameters = \"\""); foreach (var pair in registration.Parameters) { if (!String.IsNullOrEmpty(pair.Value.DependsOn)) { if (registration.Parameters.TryGetValue(pair.Value.DependsOn, out var dependsOnProperty)) { switch (dependsOnProperty.Type) { case ParameterType.String: TabIndentedAppendLine($"if (![string]::IsNullOrEmpty(${pair.Value.DependsOn}))"); break; case ParameterType.Bool: TabIndentedAppendLine($"if (${pair.Value.DependsOn} -eq $true)"); break; case ParameterType.Int: TabIndentedAppendLine($"if (${pair.Value.DependsOn} -gt 0)"); break; } } TabIndentedAppendLine("{"); } TabIndentedAppendLine($"$tempParameter = Convert-ToServiceMessageParameter -name \"{pair.Key}\" -value ${pair.Key}"); TabIndentedAppendLine("$parameters = $parameters, $tempParameter -join ' '"); if (!String.IsNullOrEmpty(pair.Value.DependsOn)) { TabIndentedAppendLine("}"); } } TabIndentedAppendLine($"Write-Host \"##octopus[{registration.ServiceMessageName} $($parameters)]\""); TabIndentedAppendLine("}"); TabIndentedAppendLine(""); } sb.AppendLine("Write-Verbose \"Invoking target script $OctopusFunctionAppenderTargetScript with $OctopusFunctionAppenderTargetScriptParameters parameters.\""); sb.AppendLine("Invoke-Expression \". `\"$OctopusFunctionAppenderTargetScript`\" $OctopusFunctionAppenderTargetScriptParameters\""); return sb.ToString(); } string ConvertType(ParameterType type) { return type switch { ParameterType.String => "string", ParameterType.Bool => "switch", ParameterType.Int => "int", _ => throw new ArgumentOutOfRangeException(nameof(type), type, null) }; } } }<file_sep>#!/bin/bash echo $(get_octopusvariable "PreDeployGreeting") "from PostDeploy.sh"<file_sep>using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; namespace Calamari.Tests.Helpers { public static class VariablesExtensions { public static void Save(this IVariables variables, string filename) { var dictionary = variables.ToDictionary(x => x.Key, x => x.Value); File.WriteAllText(filename, JsonConvert.SerializeObject(dictionary)); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Calamari.Common.Plumbing.FileSystem { public interface IFile { void Copy(string temporaryReplacement, string originalFile, bool overwrite); void Delete(string path); bool Exists(string? path); byte[] ReadAllBytes(string path); void WriteAllBytes(string filePath, byte[] data); void Move(string sourceFile, string destination); void SetAttributes(string path, FileAttributes normal); DateTime GetCreationTime(string filePath); Stream Open(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare none); } public interface IDirectory { void CreateDirectory(string path); void Delete(string path, bool recursive); bool Exists(string? path); string[] GetFileSystemEntries(string path); IEnumerable<string> EnumerateDirectories(string path); IEnumerable<string> EnumerateDirectoriesRecursively(string path); IEnumerable<string> EnumerateFiles(string parentDirectoryPath, params string[] searchPatterns); IEnumerable<string> EnumerateFilesRecursively( string parentDirectoryPath, params string[] searchPatterns); IEnumerable<string> GetFiles(string sourceDirectory, string s); IEnumerable<string> GetDirectories(string path); string GetCurrentDirectory(); } public class StandardFile : IFile { public void Delete(string path) { File.Delete(path); } public bool Exists(string? path) { return File.Exists(path); } public byte[] ReadAllBytes(string path) { return File.ReadAllBytes(path); } public void WriteAllBytes(string path, byte[] bytes) { File.WriteAllBytes(path, bytes); } public void Move(string source, string destination) { File.Move(source, destination); } public void SetAttributes(string path, FileAttributes fileAttributes) { File.SetAttributes(path, fileAttributes); } public DateTime GetCreationTime(string path) { return File.GetCreationTime(path); } public Stream Open(string path, FileMode mode, FileAccess access, FileShare share) { return File.Open(path, mode, access, share); } public void Copy(string source, string destination, bool overwrite) { File.Copy(source, destination, overwrite); } } public class StandardDirectory : IDirectory { public void CreateDirectory(string path) { Directory.CreateDirectory(path); } public void Delete(string path, bool recursive) { Directory.Delete(path, recursive); } public bool Exists(string? path) { return Directory.Exists(path); } public string[] GetFileSystemEntries(string path) { return Directory.GetFileSystemEntries(path); } public IEnumerable<string> EnumerateDirectories(string path) { return Directory.EnumerateDirectories(path); } public IEnumerable<string> EnumerateDirectoriesRecursively(string path) { return Directory.EnumerateDirectories(path, "*", SearchOption.AllDirectories); } public virtual IEnumerable<string> EnumerateFiles( string parentDirectoryPath, params string[] searchPatterns) { return EnumerateFiles(parentDirectoryPath, SearchOption.TopDirectoryOnly, searchPatterns); } public virtual IEnumerable<string> EnumerateFilesRecursively( string parentDirectoryPath, params string[] searchPatterns) { return EnumerateFiles(parentDirectoryPath, SearchOption.AllDirectories, searchPatterns); } private IEnumerable<string> EnumerateFiles( string parentDirectoryPath, SearchOption searchOption, string[] searchPatterns) { return searchPatterns.Length == 0 ? Directory.EnumerateFiles(parentDirectoryPath, "*", searchOption) : searchPatterns.SelectMany(pattern => Directory.EnumerateFiles(parentDirectoryPath, pattern, searchOption)); } public IEnumerable<string> GetFiles(string path, string searchPattern) { return Directory.GetFiles(path, searchPattern); } public IEnumerable<string> GetDirectories(string path) { return Directory.GetDirectories(path); } public string GetCurrentDirectory() { return Directory.GetCurrentDirectory(); } } #if USE_ALPHAFS_FOR_LONG_FILE_PATH_SUPPORT public class LongPathsFile : IFile { public void Delete(string path) { Alphaleonis.Win32.Filesystem.File.Delete(path); } public bool Exists(string? path) { return Alphaleonis.Win32.Filesystem.File.Exists(path); } public byte[] ReadAllBytes(string path) { return Alphaleonis.Win32.Filesystem.File.ReadAllBytes(path); } public void WriteAllBytes(string path, byte[] bytes) { Alphaleonis.Win32.Filesystem.File.WriteAllBytes(path, bytes); } public void Move(string source, string destination) { Alphaleonis.Win32.Filesystem.File.Move(source, destination); } public void SetAttributes(string path, FileAttributes fileAttributes) { Alphaleonis.Win32.Filesystem.File.SetAttributes(path, fileAttributes); } public DateTime GetCreationTime(string path) { return Alphaleonis.Win32.Filesystem.File.GetCreationTime(path); } public Stream Open(string path, FileMode mode, FileAccess access, FileShare share) { return Alphaleonis.Win32.Filesystem.File.Open(path, mode, access, share); } public void Copy(string source, string destination, bool overwrite) { Alphaleonis.Win32.Filesystem.File.Copy(source, destination, overwrite); } } public class LongPathsDirectory : IDirectory { public void CreateDirectory(string path) { Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(path); } public void Delete(string path, bool recursive) { Alphaleonis.Win32.Filesystem.Directory.Delete(path, recursive); } public bool Exists(string? path) { return Alphaleonis.Win32.Filesystem.Directory.Exists(path); } public string[] GetFileSystemEntries(string path) { return Alphaleonis.Win32.Filesystem.Directory.GetFileSystemEntries(path); } public IEnumerable<string> EnumerateDirectories(string path) { return Alphaleonis.Win32.Filesystem.Directory.EnumerateDirectories(path); } public IEnumerable<string> EnumerateDirectoriesRecursively(string path) { return Alphaleonis.Win32.Filesystem.Directory.EnumerateDirectories(path, "*", SearchOption.AllDirectories); } public IEnumerable<string> EnumerateFiles(string parentDirectoryPath, params string[] searchPatterns) { return EnumerateFiles(parentDirectoryPath, SearchOption.TopDirectoryOnly, searchPatterns); } public IEnumerable<string> EnumerateFilesRecursively(string parentDirectoryPath, params string[] searchPatterns) { return EnumerateFiles(parentDirectoryPath, SearchOption.AllDirectories, searchPatterns); } private IEnumerable<string> EnumerateFiles( string parentDirectoryPath, SearchOption searchOption, string[] searchPatterns) { return searchPatterns.Length == 0 ? Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(parentDirectoryPath, "*", searchOption) : searchPatterns.SelectMany(pattern => Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(parentDirectoryPath, pattern, searchOption)); } public IEnumerable<string> GetFiles(string path, string searchPattern) { return Alphaleonis.Win32.Filesystem.Directory.GetFiles(path, searchPattern); } public IEnumerable<string> GetDirectories(string path) { return Alphaleonis.Win32.Filesystem.Directory.GetDirectories(path); } public string GetCurrentDirectory() { return Alphaleonis.Win32.Filesystem.Directory.GetCurrentDirectory(); } } #endif }<file_sep>using System.Collections.Generic; using System.IO; using Calamari.Deployment; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; using Octostache; namespace Calamari.Tests.Fixtures.FSharp { [TestFixture] [Category(TestCategory.ScriptingSupport.FSharp)] public class FSharpFixture : CalamariFixture { [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldPrintEncodedVariable() { var (output, _) = RunScript("OutputVariable.fsx"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='RG9ua2V5' value='S29uZw==']"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldPrintSensitiveVariable() { var (output, _) = RunScript("SensitiveOutputVariable.fsx", new Dictionary<string, string>()); output.AssertSuccess(); output.AssertOutput( "##octopus[setVariable name='UGFzc3dvcmQ=' value='Y29ycmVjdCBob3JzZSBiYXR0ZXJ5IHN0YXBsZQ==' sensitive='VHJ1ZQ==']"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldCreateArtifact() { var (output, _) = RunScript("CreateArtifact.fsx", new Dictionary<string, string>()); output.AssertOutput("##octopus[createArtifact"); output.AssertOutput("name='bXlGaWxlLnR4dA==' length='MTAw']"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldUpdateProgress() { var (output, _) = RunScript("UpdateProgress.fsx", new Dictionary<string, string>()); output.AssertOutput("##octopus[progress percentage='NTA=' message='SGFsZiBXYXk=']"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldCallHello() { var (output, _) = RunScript("Hello.fsx", new Dictionary<string, string>() { ["Name"] = "Paul", ["Variable2"] = "DEF", ["Variable3"] = "GHI", ["Foo_bar"] = "Hello", ["Host"] = "Never", }); output.AssertSuccess(); output.AssertOutput("Hello Paul"); output.AssertProcessNameAndId("fsi"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldCallHelloWithSensitiveVariable() { var (output, _) = RunScript("Hello.fsx", new Dictionary<string, string>() {["Name"] = "NameToEncrypt"}, sensitiveVariablesPassword: "<PASSWORD>=="); output.AssertSuccess(); output.AssertOutput("Hello NameToEncrypt"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldCallHelloWithVariableSubstitution() { var (output, _) = RunScript("HelloVariableSubstitution.fsx", new Dictionary<string, string>() {["Name"] = "SubstitutedValue"}); output.AssertSuccess(); output.AssertOutput("Hello SubstitutedValue"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldCallHelloDirectValue() { var (output, _) = RunScript("Hello.fsx", new Dictionary<string, string>() {["Name"] = "direct value"}); output.AssertSuccess(); output.AssertOutput("Hello direct value"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldCallHelloDefaultValue() { var (output, _) = RunScript("HelloDefaultValue.fsx", new Dictionary<string, string>() {["Name"] = "direct value"}); output.AssertSuccess(); output.AssertOutput("Hello default value"); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldCallHelloWithNullVariable() { var (output, _) = RunScript("Hello.fsx", new Dictionary<string, string>()); output.AssertSuccess(); output.AssertOutput("Hello "); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldCallHelloWithNullSensitiveVariable() { var (output, _) = RunScript("Hello.fsx", new Dictionary<string, string>(), sensitiveVariablesPassword: "<PASSWORD>=="); output.AssertSuccess(); output.AssertOutput("Hello "); } [Test, RequiresDotNet45, RequiresMonoVersion400OrAbove] public void ShouldConsumeParametersWithQuotes() { var (output, _) = RunScript("Parameters.fsx", new Dictionary<string, string>() { [SpecialVariables.Action.Script.ScriptParameters] = "\"Para meter0\" Parameter1" }); output.AssertSuccess(); output.AssertOutput("Parameters Para meter0-Parameter1"); } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Commands.Options; namespace Calamari.Commands.Support { public abstract class Command : ICommandWithArgs { protected Command() { Options = new OptionSet(); } protected OptionSet Options { get; private set; } public abstract int Execute(string[] commandLineArguments); } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Octopus.Diagnostics; namespace Calamari.Testing { public class CalamariInMemoryTaskLog { readonly StringBuilder log = new StringBuilder(); public void Dispose() { } public bool IsVerboseEnabled { get; } public bool IsErrorEnabled { get; } public bool IsFatalEnabled { get; } public bool IsInfoEnabled { get; } public bool IsTraceEnabled { get; } public bool IsWarnEnabled { get; } public override string ToString() { return log.ToString(); } public List<(string?, Exception?)> ErrorLog { get; } = new List<(string?, Exception?)>(); public List<(string?, Exception?)> WarnLog { get; } = new List<(string?, Exception?)>(); public List<(string?, Exception?)> InfoLog { get; } = new List<(string?, Exception?)>(); public List<(string?, Exception?)> FatalLog { get; } = new List<(string?, Exception?)>(); public List<(string?, Exception?)> TraceLog { get; } = new List<(string?, Exception?)>(); public List<(string?, Exception?)> VerboseLog { get; } = new List<(string?, Exception?)>(); public void WithSensitiveValues(string[] sensitiveValues) { } public void WithSensitiveValue(string sensitiveValue) { } public void Trace(string messageText) { Trace(null, messageText); } public void Trace(Exception error) { Trace(error, null); } public void Trace(Exception? error, string? messageText) { Write(TraceLog, messageText, error); } public void Verbose(string messageText) { Verbose(null, messageText); } public void Verbose(Exception error) { Verbose(error, null); } public void Verbose(Exception? error, string? messageText) { Write(VerboseLog, messageText, error); } public void Info(string messageText) { Info(null, messageText); } public void Info(Exception error) { Info(error, null); } public void Info(Exception? error, string? messageText) { Write(InfoLog, messageText, error); } public void Warn(string messageText) { Warn(null, messageText); } public void Warn(Exception error) { Warn(error, null); } public void Warn(Exception? error, string? messageText) { Write(WarnLog, messageText, error); } public void Error(string messageText) { Error(null, messageText); } public void Error(Exception error) { Error(error, null); } public void Error(Exception? error, string? messageText) { Write(ErrorLog, messageText, error); } public void Fatal(string messageText) { Fatal(null, messageText); } public void Fatal(Exception error) { Fatal(error, null); } public void Fatal(Exception? error, string? messageText) { Write(FatalLog, messageText, error); } public void Write(LogCategory category, string messageText) { Write(category, null, messageText); } public void Write(LogCategory category, Exception error) { Write(category, error, null); } public void Write(LogCategory category, Exception? error, string? messageText) { switch (category) { case LogCategory.Trace: Trace(error, messageText); break; case LogCategory.Verbose: Verbose(error, messageText); break; case LogCategory.Info: Info(error, messageText); break; case LogCategory.Planned: break; case LogCategory.Highlight: break; case LogCategory.Abandoned: break; case LogCategory.Wait: break; case LogCategory.Progress: break; case LogCategory.Finished: break; case LogCategory.Warning: Warn(error, messageText); break; case LogCategory.Error: Error(error, messageText); break; case LogCategory.Fatal: Fatal(error, messageText); break; default: throw new ArgumentOutOfRangeException(nameof(category), category, null); } } public void WriteFormat(LogCategory category, string messageFormat, params object[] args) { WriteFormat(category, null, messageFormat, args); } public void WriteFormat(LogCategory category, Exception? error, string messageFormat, params object[] args) { Write(category, error, String.Format(messageFormat, args)); } public void TraceFormat(string messageFormat, params object[] args) { TraceFormat(null, messageFormat, args); } public void TraceFormat(Exception? error, string format, params object[] args) { Trace(error, String.Format(format, args)); } public void VerboseFormat(string messageFormat, params object[] args) { VerboseFormat(null, messageFormat, args); } public void VerboseFormat(Exception? error, string format, params object[] args) { Verbose(error, String.Format(format, args)); } public void InfoFormat(string messageFormat, params object[] args) { InfoFormat(null, messageFormat, args); } public void InfoFormat(Exception? error, string format, params object[] args) { Info(error, String.Format(format, args)); } public void WarnFormat(string messageFormat, params object[] args) { WarnFormat(null, messageFormat, args); } public void WarnFormat(Exception? error, string format, params object[] args) { Warn(error, String.Format(format, args)); } public void ErrorFormat(string messageFormat, params object[] args) { ErrorFormat(null, messageFormat, args); } public void ErrorFormat(Exception? error, string format, params object[] args) { Error(error, String.Format(format, args)); } public void FatalFormat(string messageFormat, params object[] args) { FatalFormat(null, messageFormat, args); } public void FatalFormat(Exception? error, string format, params object[] args) { Fatal(error, String.Format(format, args)); } public void Flush() { } public CalamariInMemoryTaskLog CreateBlock(string messageText) { return new CalamariInMemoryTaskLog(); } public CalamariInMemoryTaskLog CreateBlock(string messageFormat, params object[] args) { return new CalamariInMemoryTaskLog(); } public CalamariInMemoryTaskLog ChildContext(string[] sensitiveValues) { return new CalamariInMemoryTaskLog(); } public CalamariInMemoryTaskLog PlanGroupedBlock(string messageText) { return new CalamariInMemoryTaskLog(); } public CalamariInMemoryTaskLog PlanFutureBlock(string messageText) { return new CalamariInMemoryTaskLog(); } public CalamariInMemoryTaskLog PlanFutureBlock(string messageFormat, params object[] args) { return new CalamariInMemoryTaskLog(); } public void Abandon() { } public void Reinstate() { } public void Finish() { } public bool IsEnabled(LogCategory category) { return true; } public void UpdateProgress(int progressPercentage, string messageText) { } public void UpdateProgressFormat(int progressPercentage, string messageFormat, params object[] args) { } void Write(ICollection<(string?, Exception?)> list, string? message, Exception? error) { log.AppendLine(message); list.Add((message, error)); } } }<file_sep>using System; using Autofac; namespace Calamari.Common.Plumbing.Pipeline { public class PackageExtractionResolver: Resolver<IPackageExtractionBehaviour> { public PackageExtractionResolver(ILifetimeScope lifetimeScope) : base(lifetimeScope) { } } }<file_sep>using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; namespace Calamari.Deployment.Conventions { public class StructuredConfigurationVariablesConvention : IInstallConvention { readonly StructuredConfigurationVariablesBehaviour structuredConfigurationVariablesBehaviour; public StructuredConfigurationVariablesConvention(StructuredConfigurationVariablesBehaviour structuredConfigurationVariablesBehaviour) { this.structuredConfigurationVariablesBehaviour = structuredConfigurationVariablesBehaviour; } public void Install(RunningDeployment deployment) { if (structuredConfigurationVariablesBehaviour.IsEnabled(deployment)) { structuredConfigurationVariablesBehaviour.Execute(deployment).Wait(); } } } }<file_sep>using System; using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Scripts; namespace Calamari.Common.Plumbing.Extensions { public static class ScriptTypeExtensions { public static string FileExtension(this ScriptSyntax scriptSyntax) { return typeof(ScriptSyntax).GetField(scriptSyntax.ToString()) .GetCustomAttributes(typeof(FileExtensionAttribute), false) .Select(attr => ((FileExtensionAttribute)attr).Extension) .FirstOrDefault(); } public static ScriptSyntax ToScriptType(this string filename) { var extension = Path.GetExtension(filename)?.TrimStart('.'); var scriptTypeField = typeof(ScriptSyntax).GetFields() .SingleOrDefault( field => field.GetCustomAttributes(typeof(FileExtensionAttribute), false) .Any(attr => ((FileExtensionAttribute)attr).Extension == extension?.ToLower())); if (scriptTypeField != null) return (ScriptSyntax)scriptTypeField.GetValue(null); throw new CommandException("Unknown script-extension: " + extension); } } }<file_sep>using System; using System.IO; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Octopus.CoreUtilities; namespace Calamari.Common.Util { public class TemplateResolver : ITemplateResolver { readonly ICalamariFileSystem filesystem; public TemplateResolver(ICalamariFileSystem filesystem) { this.filesystem = filesystem; } public ResolvedTemplatePath Resolve(string relativeFilePath, bool inPackage, IVariables variables) { var result = MaybeResolve(relativeFilePath, inPackage, variables); if (result.Some()) return result.Value; var packageId = variables.Get("Octopus.Action.Package.PackageId"); var packageVersion = variables.Get("Octopus.Action.Package.PackageVersion"); var packageMessage = inPackage ? $" in the package {packageId} {packageVersion}" : string.Empty; throw new CommandException($"Could not find '{relativeFilePath}'{packageMessage}"); } public Maybe<ResolvedTemplatePath> MaybeResolve(string relativeFilePath, bool inPackage, IVariables variables) { var absolutePath = relativeFilePath.ToMaybe() .Select(path => inPackage ? Path.Combine(variables.Get(KnownVariables.OriginalPackageDirectoryPath), variables.Evaluate(path)) : Path.Combine(Environment.CurrentDirectory, path)); return absolutePath.SelectValueOr(x => !filesystem.FileExists(x) ? Maybe<ResolvedTemplatePath>.None : new ResolvedTemplatePath(x).AsSome(), Maybe<ResolvedTemplatePath>.None ); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureServiceFabric { [Command("health-check", Description = "Run a health check on a DeploymentTargetType")] public class HealthCheckCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<HealthCheckBehaviour>(); } } }<file_sep>using System; using System.IO; using System.Linq; using System.Net; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.NuGet; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Packages.NuGet; using Octopus.Versioning; using PackageName = Calamari.Common.Features.Packages.PackageName; #if USE_NUGET_V2_LIBS using NuGet; #else using NuGet.Packaging; #endif namespace Calamari.Integration.Packages.Download { public class NuGetPackageDownloader : IPackageDownloader { const string WhyAmINotAllowedToUseDependencies = "http://octopusdeploy.com/documentation/packaging"; static readonly IPackageDownloaderUtils PackageDownloaderUtils = new PackageDownloaderUtils(); public static readonly string DownloadingExtension = ".downloading"; readonly ICalamariFileSystem fileSystem; readonly IVariables variables; public NuGetPackageDownloader(ICalamariFileSystem fileSystem, IVariables variables) { this.fileSystem = fileSystem; this.variables = variables; } public PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, string? feedUsername, string? feedPassword, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { var cacheDirectory = PackageDownloaderUtils.GetPackageRoot(feedId); fileSystem.EnsureDirectoryExists(cacheDirectory); if (!forcePackageDownload) { var downloaded = AttemptToGetPackageFromCache(packageId, version, cacheDirectory); if (downloaded != null) { Log.VerboseFormat("Package was found in cache. No need to download. Using file: '{0}'", downloaded.FullFilePath); return downloaded; } } return DownloadPackage(packageId, version, feedUri, GetFeedCredentials(feedUsername, feedPassword), cacheDirectory, maxDownloadAttempts, downloadAttemptBackoff); } PackagePhysicalFileMetadata? AttemptToGetPackageFromCache(string packageId, IVersion version, string cacheDirectory) { Log.VerboseFormat("Checking package cache for package {0} v{1}", packageId, version.ToString()); var files = fileSystem.EnumerateFilesRecursively(cacheDirectory, PackageName.ToSearchPatterns(packageId, version, new[] { ".nupkg" })); foreach (var file in files) { var package = PackageName.FromFile(file); if (package == null) continue; var idMatches = string.Equals(package.PackageId, packageId, StringComparison.OrdinalIgnoreCase); var versionExactMatch = string.Equals(package.Version.ToString(), version.ToString(), StringComparison.OrdinalIgnoreCase); var nugetVerMatches = package.Version.Equals(version); if (idMatches && (nugetVerMatches || versionExactMatch)) return PackagePhysicalFileMetadata.Build(file, package); } return null; } PackagePhysicalFileMetadata DownloadPackage( string packageId, IVersion version, Uri feedUri, ICredentials feedCredentials, string cacheDirectory, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { Log.Info("Downloading NuGet package {0} v{1} from feed: '{2}'", packageId, version, feedUri); Log.VerboseFormat("Downloaded package will be stored in: '{0}'", cacheDirectory); var fullPathToDownloadTo = Path.Combine(cacheDirectory, PackageName.ToCachedFileName(packageId, version, ".nupkg")); var downloader = new InternalNuGetPackageDownloader(fileSystem, variables); downloader.DownloadPackage(packageId, version, feedUri, feedCredentials, fullPathToDownloadTo, maxDownloadAttempts, downloadAttemptBackoff); var pkg = PackagePhysicalFileMetadata.Build(fullPathToDownloadTo); if (pkg == null) throw new CommandException($"Package metadata for {packageId}, version {version}, could not be determined"); CheckWhetherThePackageHasDependencies(pkg); return pkg; } void CheckWhetherThePackageHasDependencies(PackagePhysicalFileMetadata pkg) { var nuGetMetadata = new LocalNuGetPackage(pkg.FullFilePath).Metadata; #if USE_NUGET_V3_LIBS var dependencies = nuGetMetadata.DependencyGroups.SelectMany(ds => ds.Packages).ToArray(); #else var dependencies = nuGetMetadata.DependencySets.SelectMany(ds => ds.Dependencies).ToArray(); #endif if (dependencies.Any()) Log.Info( "NuGet packages with dependencies are not currently supported, and dependencies won't be installed on the Tentacle. The package '{0} {1}' appears to have the following dependencies: {2}. For more information please see {3}", pkg.PackageId, pkg.Version, string.Join(", ", dependencies.Select(dependency => $"{dependency.Id}")), WhyAmINotAllowedToUseDependencies); } static ICredentials GetFeedCredentials(string? feedUsername, string? feedPassword) { ICredentials credentials = CredentialCache.DefaultNetworkCredentials; if (!String.IsNullOrWhiteSpace(feedUsername)) { credentials = new NetworkCredential(feedUsername, feedPassword); } return credentials; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json.Linq; namespace Calamari.Common.Features.StructuredVariables { public class JsonUpdateMap { readonly ILog log; readonly IDictionary<string, Action<string?>> map = new SortedDictionary<string, Action<string?>>(StringComparer.OrdinalIgnoreCase); readonly Stack<string> path = new Stack<string>(); string? key; public JsonUpdateMap(ILog log) { this.log = log; } public void Load(JToken json) { if (json.Type == JTokenType.Array) MapArray(json.Value<JArray>(), true); else MapObject(json, true); } void MapObject(JToken j, bool first = false) { if (!first) { if (key == null) throw new InvalidOperationException("Path has not been pushed"); map[key] = t => j.Replace(JToken.Parse(t)); } foreach (var property in j.Children<JProperty>()) MapProperty(property); } void MapToken(JToken token) { switch (token.Type) { case JTokenType.Object: MapObject(token.Value<JObject>()); break; case JTokenType.Array: MapArray(token.Value<JArray>()); break; case JTokenType.Integer: case JTokenType.Float: MapNumber(token); break; case JTokenType.Boolean: MapBool(token); break; default: MapDefault(token); break; } } void MapProperty(JProperty property) { PushPath(property.Name); MapToken(property.Value); PopPath(); } void MapDefault(JToken value) { if (key == null) throw new InvalidOperationException("Path has not been pushed"); map[key] = t => value.Replace(t == null ? null : JToken.FromObject(t)); } void MapNumber(JToken value) { if (key == null) throw new InvalidOperationException("Path has not been pushed"); map[key] = t => { long longvalue; if (long.TryParse(t, out longvalue)) { value.Replace(JToken.FromObject(longvalue)); return; } double doublevalue; if (double.TryParse(t, out doublevalue)) { value.Replace(JToken.FromObject(doublevalue)); return; } value.Replace(JToken.FromObject(t)); }; } void MapBool(JToken value) { if (key == null) throw new InvalidOperationException("Path has not been pushed"); map[key] = t => { bool boolvalue; if (bool.TryParse(t, out boolvalue)) { value.Replace(JToken.FromObject(boolvalue)); return; } value.Replace(JToken.FromObject(t)); }; } void MapArray(JContainer array, bool first = false) { if (!first) { if (key == null) throw new InvalidOperationException("Path has not been pushed"); map[key] = t => array.Replace(JToken.Parse(t)); } for (var index = 0; index < array.Count; index++) { PushPath(index.ToString()); MapToken(array[index]); PopPath(); } } void PushPath(string p) { path.Push(p); key = string.Join(":", path.Reverse()); } void PopPath() { path.Pop(); key = string.Join(":", path.Reverse()); } public void Update(IVariables variables) { bool VariableNameIsMappedPath(string v) { if (v.StartsWith("Octopus", StringComparison.OrdinalIgnoreCase) && !v.StartsWith("Octopus:", StringComparison.OrdinalIgnoreCase)) // Only include variables starting with 'Octopus' // if it also has a colon (:) return false; return map.ContainsKey(v); } var replaced = 0; foreach (var name in variables.GetNames().Where(VariableNameIsMappedPath)) try { log.Verbose(StructuredConfigMessages.StructureFound(name)); replaced++; map[name](variables.Get(name)); } catch (Exception e) { log.WarnFormat("Unable to set value for {0}. The following error occurred: {1}", name, e.Message); } if (replaced == 0) log.Info(StructuredConfigMessages.NoStructuresFound); } } }<file_sep>using System; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.Logging { public interface ILog { void AddValueToRedact(string value, string replacement); void Verbose(string message); void VerboseFormat(string messageFormat, params object[] args); void Info(string message); void InfoFormat(string messageFormat, params object[] args); void Warn(string message); void WarnFormat(string messageFormat, params object[] args); void Error(string message); void ErrorFormat(string messageFormat, params object[] args); void SetOutputVariableButDoNotAddToVariables(string name, string value, bool isSensitive = false); void SetOutputVariable(string name, string value, IVariables variables, bool isSensitive = false); void NewOctopusArtifact(string fullPath, string name, long fileLength); void Progress(int percentage, string message); void DeltaVerification(string remotePath, string hash, long size); void DeltaVerificationError(string error); string FormatLink(string uri, string? description = null); void WriteServiceMessage(ServiceMessage serviceMessage); } }<file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.Scripting { public class ExecuteScriptBehaviour : IDeployBehaviour { readonly IScriptEngine scriptEngine; readonly ICommandLineRunner commandLineRunner; public ExecuteScriptBehaviour(IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) { this.scriptEngine = scriptEngine; this.commandLineRunner = commandLineRunner; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var variables = context.Variables; var scriptFileName = variables.Get(ScriptVariables.ScriptFileName); if (scriptFileName == null) throw new InvalidOperationException($"{ScriptVariables.ScriptFileName} variable value could not be found."); var scriptFile = Path.Combine(context.CurrentDirectory, scriptFileName); var scriptParameters = variables.Get(SpecialVariables.Action.Script.ScriptParameters); Log.VerboseFormat("Executing '{0}'", scriptFile); var result = scriptEngine.Execute(new Script(scriptFile, scriptParameters), variables, commandLineRunner); var exitCode = result.ExitCode == 0 && result.HasErrors && variables.GetFlag(SpecialVariables.Action.FailScriptOnErrorOutput) ? -1 : result.ExitCode; Log.SetOutputVariable(SpecialVariables.Action.Script.ExitCode, exitCode.ToString(), variables); return this.CompletedTask(); } } }<file_sep>using System.Collections.Generic; namespace Calamari.Aws.Integration.S3 { public interface IHaveMetadata { List<KeyValuePair<string, string>> Metadata { get; } } public interface IHaveTags { List<KeyValuePair<string, string>> Tags { get; } } public abstract class S3TargetPropertiesBase: IHaveMetadata, IHaveTags { public List<KeyValuePair<string, string>> Tags { get; set; } = new List<KeyValuePair<string, string>>(); public List<KeyValuePair<string, string>> Metadata { get; set; } = new List<KeyValuePair<string, string>>(); public string CannedAcl { get; set; } public string StorageClass { get; set; } } }<file_sep>#if IIS_SUPPORT using System.Linq; namespace Calamari.Integration.Iis { /// <summary> /// Tools for working with IIS. /// </summary> public class InternetInformationServer : IInternetInformationServer { /// <summary> /// Sets the home directory (web root) of the given IIS website to the given path. /// </summary> /// <param name="iisWebSiteNameAndVirtualDirectory">The name of the web site under IIS.</param> /// <param name="path">The path to point the site to.</param> /// <param name="legacySupport">If true, forces using the IIS6 compatible IIS support. Otherwise, try to auto-detect.</param> /// <returns> /// True if the IIS site was found and updated. False if it could not be found. /// </returns> public bool OverwriteHomeDirectory(string iisWebSiteNameAndVirtualDirectory, string path, bool legacySupport) { var parts = iisWebSiteNameAndVirtualDirectory.Split('/'); var iisSiteName = parts.First(); var remainder = parts.Skip(1).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); var virtualDirectory = remainder.Length > 0 ? string.Join("/", remainder) : null; var server = legacySupport ? WebServerSupport.Legacy() : WebServerSupport.AutoDetect(); return server.ChangeHomeDirectory(iisSiteName, virtualDirectory, path); } } } #endif<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class StructuredConfigurationVariablesConventionFixture { RunningDeployment deployment; IStructuredConfigVariablesService service; [SetUp] public void SetUp() { var variables = new CalamariVariables(); service = Substitute.For<IStructuredConfigVariablesService>(); deployment = new RunningDeployment(TestEnvironment.ConstructRootedPath("Packages"), variables); } [Test] public void ShouldNotRunIfVariableNotSet() { var convention = new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(service)); convention.Install(deployment); service.DidNotReceiveWithAnyArgs().ReplaceVariables(deployment.CurrentDirectory); } [Test] public void ShouldNotRunIfVariableIsFalse() { var convention = new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(service)); convention.Install(deployment); service.DidNotReceiveWithAnyArgs().ReplaceVariables(deployment.CurrentDirectory); } [Test] public void ShouldRunIfVariableIsTrue() { var convention = new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(service)); deployment.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); convention.Install(deployment); service.Received().ReplaceVariables(deployment.CurrentDirectory); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using YamlDotNet.Core.Events; namespace Calamari.Common.Features.StructuredVariables { public class YamlIndentDetector { readonly List<int> indents = new List<int>(); int lastNestingChangeColumn = 1; public void Process(ParsingEvent ev) { if (ev.NestingIncrease > 0 && (ev is MappingStart ms && ms.Style != MappingStyle.Flow || ev is SequenceStart ss && ss.Style != SequenceStyle.Flow)) { var startColumnChange = ev.Start.Column - lastNestingChangeColumn; if (IndentDoesNotCrashYamlDotNetEmitter(startColumnChange)) indents.Add(startColumnChange); lastNestingChangeColumn = ev.Start.Column; } if (ev.NestingIncrease < 1 && ev.Start.Column < lastNestingChangeColumn) lastNestingChangeColumn = ev.Start.Column; } static bool IndentDoesNotCrashYamlDotNetEmitter(int indent) { return indent >= 2 && indent <= 9; } public int GetMostCommonIndent() { return indents.GroupBy(indent => indent) .OrderByDescending(group => group.Count()) .FirstOrDefault() ?.Key ?? 2; } } }<file_sep>Calamari is the command-line tool invoked by Tentacle during a deployment. It knows how to extract and install NuGet packages, run the Deploy.ps1 etc. conventions, modify configuration files, and all the other things that happen during a deployment. ## Building You will need the .NET SDK `5.0`, downloadable from https://dotnet.microsoft.com/download Run `Build-Local.ps1` or `Build-Local.sh` to build the solution locally. When the solution is built, several new Calamari nuget packages are created in the `artifacts` directory. > **For Octopus Developers:** > >The `Build-Local` scripts will also copy the nuget packages to the LocalPackages folder which can be found in the same parent folder as the Calamari repo. If the Octopus Server repo exists in the same parent folder, `Build-Local` will also update the Octopus.Server.csproj to reference the Calamari version produced by the build. This means that you can simply rebuild Server locally to test the new version of Calamari. > >folder structure example: >``` >dev\ > Calamari\ > LocalPackages\ > OctopusDeploy\ >``` ## Usage > **Octopus Server 2020.3+: Using a custom version of Calamari may not work** > > Calamari is currently being filleted into [Sashimi](https://github.com/OctopusDeploy/Sashimi). Due to the architectural changes involved in this transformation, using a custom version of Calamari with Octopus Server version 2020.3+ may not work. Please get in touch with <EMAIL> if this affects you, to help us make decisions about how we can support custom implementations of deployment steps. To use your own Calamari package with an Octopus 3.0 server, run the following commands ``` Octopus.Server.exe service --instance <instance> --stop --nologo --console Octopus.Server.exe configure --instance <instance> --customBundledPackageDirectory=<directory> --nologo --console Octopus.Server.exe service --instance <instance> --start --nologo --console ``` where `<directory>` is the directory containing the `Calamari.*.nupkg` files. If your server is setup as the default instance, you may ommit the `--instance <instance>` parameter. This will add the following setting to your Octopus Server configuration file: ``` <set key="Octopus.Deployment.CustomBundledPackageDirectory">C:\GitHub\Calamari\built-packages</set> ``` The exe and configuration file can normally be found at: ``` C:\Octopus\OctopusServer\OctopusServer.config ``` If you want to revert to the bundled package, run the following commands ``` Octopus.Server.exe service --instance <instance> --stop --nologo --console Octopus.Server.exe configure --instance <instance> --customBundledPackageDirectory= --nologo --console Octopus.Server.exe service --instance <instance> --start --nologo --console ``` ** Ensure you update your build to the latest Calamari or revert to the bundled package when you upgrade Octopus Server ** ## Releasing After you finish merging to master to tag the Calamari NuGet package: Firstly, find out what the latest tag is. There are two ways to do this: * On your terminal, checkout `master` and `git pull` for good measure * Run `git tag` and scroll to the bottom of the list to get the last known tag Alternatively, * Check the last build on master as it will be pre-release version of the next `<Major>.<Minor>.<Patch>` version Finally, tag and push the new release * Patch, Minor or Major Version the tag according to `<Major>.<Minor>.<Patch>` * `git push --tag` This will trigger our build server to build and publish a new version to feedz.io which can be seen here https://feedz.io/org/octopus-deploy/repository/dependencies/packages/Calamari. <file_sep>using System; using System.IO; namespace Calamari.Common.Features.ConfigurationTransforms { public class XmlConfigTransformDefinition { readonly string definition; public XmlConfigTransformDefinition(string definition) { this.definition = definition; if (definition.Contains("=>")) { Advanced = true; var separators = new[] {"=>"}; var parts = definition.Split(separators, StringSplitOptions.RemoveEmptyEntries); TransformPattern = parts[0].Trim(); SourcePattern = parts[1].Trim(); if (Path.GetFileName(TransformPattern).StartsWith("*.")) { IsTransformWildcard = true; TransformPattern = TrimWildcardPattern(TransformPattern); } if (Path.GetFileName(SourcePattern).StartsWith("*.")) { IsSourceWildcard = true; SourcePattern = TrimWildcardPattern(SourcePattern); } } else { TransformPattern = definition; } } static string TrimWildcardPattern(string pattern) { var wildcardIndex = pattern.IndexOf('*'); return (pattern.LastIndexOf('.') > wildcardIndex + 1) ? pattern.Remove(wildcardIndex, 2) : pattern.Remove(wildcardIndex, 1); } public string TransformPattern { get; private set; } public string? SourcePattern { get; private set; } public bool IsTransformWildcard { get; private set; } public bool IsSourceWildcard { get; private set; } public bool Advanced { get; private set; } public override string ToString() { return definition; } } }<file_sep>namespace Calamari.Deployment.Conventions { public interface IConvention { } }<file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Microsoft.WindowsAzure.Management.Compute; using Hyak.Common; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Calamari.AzureCloudService { public class DeployAzureCloudServicePackageBehaviour : IDeployBehaviour { readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly IScriptEngine scriptEngine; readonly ICommandLineRunner commandLineRunner; public DeployAzureCloudServicePackageBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) { this.log = log; this.fileSystem = fileSystem; this.scriptEngine = scriptEngine; this.commandLineRunner = commandLineRunner; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment context) { static async Task<bool> Exists(IComputeManagementClient azureClient, string serviceName, DeploymentSlot deploymentSlot) { try { var deployment = await azureClient.Deployments.GetBySlotAsync(serviceName, deploymentSlot); if (deployment == null) { return false; } } catch (CloudException e) { if (e.Error.Code == "ResourceNotFound") { return false; } throw; } return true; } var configurationFile = context.Variables.Get(SpecialVariables.Action.Azure.Output.ConfigurationFile); var cloudServiceName = context.Variables.Get(SpecialVariables.Action.Azure.CloudServiceName); var slot = context.Variables.Get(SpecialVariables.Action.Azure.Slot, DeploymentSlot.Staging.ToString()); var packageUri = context.Variables.Get(SpecialVariables.Action.Azure.UploadedPackageUri); var deploymentLabel = context.Variables.Get(SpecialVariables.Action.Azure.DeploymentLabel, $"{context.Variables.Get(ActionVariables.Name)} v{context.Variables.Get(KnownVariables.Release.Number)}"); log.Info($"Config file: {configurationFile}"); log.SetOutputVariable("OctopusAzureServiceName", cloudServiceName, context.Variables); log.SetOutputVariable("OctopusAzureStorageAccountName", context.Variables.Get(SpecialVariables.Action.Azure.StorageAccountName), context.Variables); log.SetOutputVariable("OctopusAzureSlot", slot, context.Variables); log.SetOutputVariable("OctopusAzurePackageUri", packageUri, context.Variables); log.SetOutputVariable("OctopusAzureDeploymentLabel", deploymentLabel, context.Variables); log.SetOutputVariable("OctopusAzureSwapIfPossible", context.Variables.Get(SpecialVariables.Action.Azure.SwapIfPossible, bool.FalseString), context.Variables); log.SetOutputVariable("OctopusAzureUseCurrentInstanceCount", context.Variables.Get(SpecialVariables.Action.Azure.UseCurrentInstanceCount), context.Variables); // The script name 'DeployToAzure.ps1' is used for backwards-compatibility var scriptFile = Path.Combine(context.CurrentDirectory, "DeployToAzure.ps1"); // The user may supply the script, to override behaviour if (fileSystem.FileExists(scriptFile)) { var result = scriptEngine.Execute(new Script(scriptFile), context.Variables, commandLineRunner); fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure); if (result.ExitCode != 0) { throw new CommandException($"Script '{scriptFile}' returned non-zero exit code: {result.ExitCode}"); } return; } var account = new AzureAccount(context.Variables); var certificate = CalamariCertificateStore.GetOrAdd(account.CertificateThumbprint, account.CertificateBytes); var deploymentSlot = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), slot); using var azureClient = account.CreateComputeManagementClient(certificate); var exists = await Exists(azureClient, cloudServiceName, deploymentSlot); if (!exists) { log.Verbose("Creating a new deployment..."); await azureClient.Deployments.CreateAsync(cloudServiceName, deploymentSlot, new DeploymentCreateParameters { Label = deploymentLabel, Configuration = File.ReadAllText(configurationFile), PackageUri = new Uri(packageUri), Name = Guid.NewGuid().ToString("N"), StartDeployment = true }); } else { log.Verbose($"A deployment already exists in {cloudServiceName} for slot {slot}. Upgrading deployment..."); await azureClient.Deployments.UpgradeBySlotAsync(cloudServiceName, deploymentSlot, new DeploymentUpgradeParameters { Label = deploymentLabel, Configuration = File.ReadAllText(configurationFile), PackageUri = new Uri(packageUri), Mode = DeploymentUpgradeMode.Auto, Force = true }); } var deployment = await azureClient.Deployments.GetBySlotAsync(cloudServiceName, deploymentSlot); log.SetOutputVariable("OctopusAzureCloudServiceDeploymentID", deployment.PrivateId, context.Variables); log.SetOutputVariable("OctopusAzureCloudServiceDeploymentUrl", deployment.Uri.ToString(), context.Variables); log.Info($"Deployment complete; Deployment ID: {deployment.PrivateId}"); } } }<file_sep>using System; namespace Calamari.Common.Features.Processes.Semaphores { public class UnableToDeserialiseLockFile : IFileLock { public UnableToDeserialiseLockFile(DateTime creationTime) { CreationTime = creationTime; } public DateTime CreationTime { get; } } }<file_sep>using System.Collections.Generic; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Model; namespace Calamari.Deployment.PackageRetention.Caching { public interface IRetentionAlgorithm { IEnumerable<PackageIdentity> GetPackagesToRemove(IEnumerable<JournalEntry> journalEntries); } }<file_sep>using System.Collections.Generic; using Calamari.Deployment; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Bash { [TestFixture] public class BashFixture : CalamariFixture { [Test] [RequiresBashDotExeIfOnWindows] public void ShouldPrintEncodedVariable() { var (output, _) = RunScript("print-encoded-variable.sh"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='U3VwZXI=' value='TWFyaW8gQnJvcw==']"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldPrintSensitiveVariable() { var (output, _) = RunScript("print-sensitive-variable.sh"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='UGFzc3dvcmQ=' value='Y29ycmVjdCBob3JzZSBiYXR0ZXJ5IHN0YXBsZQ==' sensitive='VHJ1ZQ==']"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldCreateArtifact() { var (output, _) = RunScript("create-artifact.sh"); output.AssertSuccess(); output.AssertOutput("##octopus[createArtifact path='Li9zdWJkaXIvYW5vdGhlcmRpci9teWZpbGU=' name='bXlmaWxl' length='MA==']"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldUpdateProgress() { var (output, _) = RunScript("update-progress.sh"); output.AssertSuccess(); output.AssertOutput("##octopus[progress percentage='NTA=' message='SGFsZiBXYXk=']"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldConsumeParametersWithQuotes() { var (output, _) = RunScript("parameters.sh", new Dictionary<string, string>() { [SpecialVariables.Action.Script.ScriptParameters] = "\"Para meter0\" 'Para meter1'" }); output.AssertSuccess(); output.AssertOutput("Parameters ($1='Para meter0' $2='Para meter1'"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldNotReceiveParametersIfNoneProvided() { var (output, _) = RunScript("parameters.sh", sensitiveVariablesPassword: "<PASSWORD>=="); output.AssertSuccess(); output.AssertOutput("Parameters ($1='' $2='')"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldCallHello() { var (output, _) = RunScript("hello.sh", new Dictionary<string, string>() { ["Name"] = "Paul", ["Variable2"] = "DEF", ["Variable3"] = "GHI", ["Foo_bar"] = "Hello", ["Host"] = "Never", }); output.AssertSuccess(); output.AssertOutput("Hello Paul"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldCallHelloWithSensitiveVariable() { var (output, _) = RunScript("hello.sh", new Dictionary<string, string>() { ["Name"] = "NameToEncrypt" }, sensitiveVariablesPassword: "<PASSWORD>=="); output.AssertSuccess(); output.AssertOutput("Hello NameToEncrypt"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldCallHelloWithNullVariable() { var (output, _) = RunScript("hello.sh", new Dictionary<string, string>() {["Name"] = null}); output.AssertSuccess(); output.AssertOutput("Hello"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldCallHelloWithNullSensitiveVariable() { var (output, _) = RunScript("hello.sh", new Dictionary<string, string>() { ["Name"] = null }, sensitiveVariablesPassword: "<PASSWORD>=="); output.AssertSuccess(); output.AssertOutput("Hello"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldNotFailOnStdErr() { var (output, _) = RunScript("stderr.sh"); output.AssertSuccess(); output.AssertErrorOutput("hello"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldFailOnStdErrWithTreatScriptWarningsAsErrors() { var (output, _) = RunScript("stderr.sh", new Dictionary<string, string>() {[SpecialVariables.Action.FailScriptOnErrorOutput] = "True"}); output.AssertFailure(); output.AssertErrorOutput("hello"); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldNotFailOnStdErrFromServiceMessagesWithTreatScriptWarningsAsErrors() { var (output, _) = RunScript("hello.sh", new Dictionary<string, string>() {[SpecialVariables.Action.FailScriptOnErrorOutput] = "True"}); output.AssertSuccess(); } [Test] [RequiresBashDotExeIfOnWindows] public void ShouldSupportStrictVariableUnset() { var (output, _) = RunScript("strict-mode.sh"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='UGFzc3dvcmQ=' value='Y29ycmVjdCBob3JzZSBiYXR0ZXJ5IHN0YXBsZQ==']"); } } }<file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Commands; namespace Calamari.Kubernetes.Integration { public interface ICommandOutput { Message[] Messages { get; } IEnumerable<string> InfoLogs { get; } } public class CaptureCommandOutput : ICommandInvocationOutputSink, ICommandOutput { private readonly List<Message> messages = new List<Message>(); public Message[] Messages => messages.ToArray(); public IEnumerable<string> InfoLogs => Messages.Where(m => m.Level == Level.Info).Select(m => m.Text); public void WriteInfo(string line) { messages.Add(new Message(Level.Info, line)); } public void WriteError(string line) { messages.Add(new Message(Level.Error, line)); } } public class Message { public Level Level { get; } public string Text { get; } public Message(Level level, string text) { Level = level; Text = text; } } public enum Level { Info, Error } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Calamari.Common.Plumbing.Logging; using Newtonsoft.Json; namespace Calamari.Common.Features.Discovery { public abstract class KubernetesDiscovererBase : IKubernetesDiscoverer { protected readonly ILog Log; protected KubernetesDiscovererBase(ILog log) { this.Log = log; } protected bool TryGetDiscoveryContext<TAuthenticationDetails>(string json, [NotNullWhen(returnValue: true)] out TAuthenticationDetails? authenticationDetails, out string? workerPoolId) where TAuthenticationDetails : class, ITargetDiscoveryAuthenticationDetails { authenticationDetails = null; workerPoolId = null; try { var discoveryContext = JsonConvert.DeserializeObject<TargetDiscoveryContext<TAuthenticationDetails>>(json); if (discoveryContext == null) { LogDeserialisationError(); return false; } if (discoveryContext.Authentication == null) { LogDeserialisationError("authentication details"); return false; } if (discoveryContext.Scope == null) { LogDeserialisationError("scope"); return false; } authenticationDetails = discoveryContext.Authentication; workerPoolId = discoveryContext.Scope.WorkerPoolId; return true; } catch (Exception ex) { LogDeserialisationError(exception: ex); return false; } } void LogDeserialisationError(string? detail = null, Exception? exception = null) { Log.Warn("Target discovery context is in the wrong format, please contact Octopus Support."); Log.Verbose($"Unable to deserialise {(detail == null ? $"{detail} in " : "")} Target Discovery Context" + $"{(exception == null ? " but no exception was thrown" : "")}, aborting discovery" + $"{(exception == null ? "." : $":{exception}")}."); } public abstract string Type { get; } public abstract IEnumerable<KubernetesCluster> DiscoverClusters(string contextJson); } }<file_sep>namespace Calamari.Kubernetes { public static class SpecialVariables { public const string ActionId = "Octopus.Action.Id"; public const string ClusterUrl = "Octopus.Action.Kubernetes.ClusterUrl"; public const string AksClusterName = "Octopus.Action.Kubernetes.AksClusterName"; public const string EksClusterName = "Octopus.Action.Kubernetes.EksClusterName"; public const string GkeClusterName = "Octopus.Action.Kubernetes.GkeClusterName"; public const string GkeUseClusterInternalIp = "Octopus.Action.Kubernetes.GkeUseClusterInternalIp"; public const string Namespace = "Octopus.Action.Kubernetes.Namespace"; public const string SkipTlsVerification = "Octopus.Action.Kubernetes.SkipTlsVerification"; public const string OutputKubeConfig = "Octopus.Action.Kubernetes.OutputKubeConfig"; public const string CustomKubectlExecutable = "Octopus.Action.Kubernetes.CustomKubectlExecutable"; public const string ResourceStatusCheck = "Octopus.Action.Kubernetes.ResourceStatusCheck"; public const string DeploymentStyle = "Octopus.Action.KubernetesContainers.DeploymentStyle"; public const string DeploymentWait = "Octopus.Action.KubernetesContainers.DeploymentWait"; public const string CustomResourceYamlFileName = "Octopus.Action.KubernetesContainers.CustomResourceYamlFileName"; public const string GroupedYamlDirectories = "Octopus.Action.KubernetesContainers.YamlDirectories"; public const string Timeout = "Octopus.Action.Kubernetes.DeploymentTimeout"; public const string WaitForJobs = "Octopus.Action.Kubernetes.WaitForJobs"; public const string KubeConfig = "Octopus.KubeConfig.Path"; public const string KustomizeManifest = "Octopus.Kustomize.Manifest.Path"; public const string KubernetesResourceStatusServiceMessageName = "k8s-status"; public static class Helm { public const string ReleaseName = "Octopus.Action.Helm.ReleaseName"; public const string Namespace = "Octopus.Action.Helm.Namespace"; public const string KeyValues = "Octopus.Action.Helm.KeyValues"; public const string YamlValues = "Octopus.Action.Helm.YamlValues"; public const string ResetValues = "Octopus.Action.Helm.ResetValues"; public const string AdditionalArguments = "Octopus.Action.Helm.AdditionalArgs"; public const string CustomHelmExecutable = "Octopus.Action.Helm.CustomHelmExecutable"; public const string ClientVersion = "Octopus.Action.Helm.ClientVersion"; public const string Timeout = "Octopus.Action.Helm.Timeout"; public const string TillerNamespace = "Octopus.Action.Helm.TillerNamespace"; public const string TillerTimeout = "Octopus.Action.Helm.TillerTimeout"; public static class Packages { public const string CustomHelmExePackageKey = "HelmExe"; public static string ValuesFilePath(string key) { return $"Octopus.Action.Package[{key}].ValuesFilePath"; } } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Caching; using Calamari.Deployment.PackageRetention.Model; using FluentAssertions; using NUnit.Framework; using Octopus.Versioning; namespace Calamari.Tests.Fixtures.PackageRetention { [TestFixture] public class LeastFrequentlyUsedWithAgingSortFixture { [Test] public void WhenPackageIsLocked_ThenDoNotConsiderItForRemoval() { var lfu = new LeastFrequentlyUsedWithAgingSort(); //If this entry wasn't locked, we would expect it to be removed var lockedEntry = CreateEntry("package-locked", "1.0", 20, ("task-1", 1)); lockedEntry.AddLock(new ServerTaskId("task-0"), new CacheAge(1)); //This entry would not be removed if the locked entry wasn't locked, because it has multiple, more recent usages. var unlockedEntry = CreateEntry("package-unlocked", "1.0", 20, ("task-2", 12), ("task-3", 15)); var entries = new List<JournalEntry>(new[] { lockedEntry, unlockedEntry }); var packagesToRemove = lfu.Sort(entries); packagesToRemove.Select(p => p.Package).Should().Equal(CreatePackageIdentity("package-unlocked", "1.0")); } [Test] public void WhenUsingAllThreeFactors_ThenReturnThePackageWithTheLowestValue() { var entries = new[] { CreateEntry("package-1", "1.0", 10, ("task-1", 2), ("task-2", 3)), CreateEntry("package-2", "1.1", 10, ("task-3", 1)), CreateEntry("package-3", "1.0", 10, ("task-4", 2)), //Lower value - has a newer version, and is only used once. CreateEntry("package-3", "1.1", 10, ("task-5", 3)) }; var packagesToRemove = new LeastFrequentlyUsedWithAgingSort(0.5M, 1, 1) .Sort(entries) .ToList(); packagesToRemove .Select(p => p.Package) .Should() .Equal(new object[] { CreatePackageIdentity("package-3", "1.0"), CreatePackageIdentity("package-2", "1.1"), CreatePackageIdentity("package-3", "1.1"), CreatePackageIdentity("package-1", "1.0") }); } [TestCaseSource(nameof(ExpectMultiplePackageIdsTestCaseSource))] public void ExpectingMultiplePackages(JournalEntry[] entries, PackageIdentity[] expectedPackageIdVersionPairs) { var packagesToRemove = new LeastFrequentlyUsedWithAgingSort() .Sort(entries); packagesToRemove.Select(p => p.Package).Should().Equal(expectedPackageIdVersionPairs); } public static IEnumerable ExpectMultiplePackageIdsTestCaseSource() { yield return SetUpTestCase("WhenOnlyRelyingOnAge_OrdersByAge", new[] { CreateEntry("package-1", "1.0", 5, ("task-1", 1)), CreateEntry("package-2", "1.0", 5, ("task-2", 3)), CreateEntry("package-3", "1.0", 5, ("task-3", 2)) }, CreatePackageIdentity("package-1", "1.0"), CreatePackageIdentity("package-3", "1.0"), CreatePackageIdentity("package-2", "1.0")); yield return SetUpTestCase("WhenOnlyRelyingOnHitCount_OrderByFewestHits", new[] { CreateEntry("package-1", "1.0", 10, ("task-1", 1), ("task-3", 1)), CreateEntry("package-2", "1.0", 10, ("task-2", 1)) }, CreatePackageIdentity("package-2", "1.0"), CreatePackageIdentity("package-1", "1.0")); yield return SetUpTestCase("WhenOnlyRelyingOnVersions_ThenReturnPackagesWithMostNewVersions", new[] { CreateEntry("package-1", "1.0", 10), CreateEntry("package-1", "1.1", 10), CreateEntry("package-1", "1.2", 10), CreateEntry("package-1", "1.3", 10), CreateEntry("package-2", "1.0", 10), CreateEntry("package-2", "1.1", 10), CreateEntry("package-2", "1.2", 10) }, CreatePackageIdentity("package-1", "1.0"), CreatePackageIdentity("package-1", "1.1"), CreatePackageIdentity("package-2", "1.0"), CreatePackageIdentity("package-1", "1.2"), CreatePackageIdentity("package-2", "1.1"), CreatePackageIdentity("package-1", "1.3"), CreatePackageIdentity("package-2", "1.2")); } static TestCaseData SetUpTestCase(string testName, JournalEntry[] testJournalEntries, params PackageIdentity[] expectedPackageIdentities) { return new TestCaseData(testJournalEntries, expectedPackageIdentities).SetName(testName); } static JournalEntry CreateEntry(string packageId, string version, ulong packageSize, params (string serverTaskId, int cacheAgeAtUsage)[] usages) { if (usages.Length == 0) usages = new[] { ("Task-1", 1) }; var packageUsages = new PackageUsages(); packageUsages.AddRange(usages.Select(details => new UsageDetails(new ServerTaskId(details.serverTaskId), new CacheAge(details.cacheAgeAtUsage)))); var packageIdentity = CreatePackageIdentity(packageId, version); return new JournalEntry(packageIdentity, packageSize, null, packageUsages); } static PackageIdentity CreatePackageIdentity(string packageId, string packageVersion) { var version = VersionFactory.CreateSemanticVersion(packageVersion); return new PackageIdentity(new PackageId(packageId), version, new PackagePath($"C:\\{packageId}.{packageVersion}.zip")); } } }<file_sep>using Calamari.AzureServiceFabric.Integration; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using FluentAssertions; using NUnit.Framework; namespace Calamari.AzureServiceFabric.Tests { [TestFixture] public class AzureServiceFabricPowerShellContextFixture { [Test] [TestCase("Endpoint", ScriptSyntax.PowerShell, true)] [TestCase("", ScriptSyntax.PowerShell, false)] [TestCase("Endpoint", ScriptSyntax.FSharp, false)] public void ShouldBeEnabled(string connectionEndpoint, ScriptSyntax syntax, bool expected) { var variables = new CalamariVariables { { SpecialVariables.Action.ServiceFabric.ConnectionEndpoint, connectionEndpoint } }; var target = new AzureServiceFabricPowerShellContext(variables, ConsoleLog.Instance); var actual = target.IsEnabled(syntax); actual.Should().Be(expected); } } }<file_sep>using Calamari.Common.Plumbing.ServiceMessages; using FluentAssertions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calamari.Tests.Fixtures.ServiceMessages { [TestFixture] public class ServiceMessageFixture { [Test] public void ToString_FormatsMessageCorrectly() { // Arrange var sut = ServiceMessage.Create("my-message-name", ("foo", "my-parameter-value")); // Act var text = sut.ToString(); // Assert // Base65 encoding "my-parameter-value" gives "bXktcGFyYW1ldGVyLXZhbHVl" text.Should().Be("##octopus[my-message-name foo=\"bXktcGFyYW1ldGVyLXZhbHVl\"]"); } [Test] public void ToString_IgnoresNullParameters() { // Arrange var sut = ServiceMessage.Create("my-message-name", ("foo", "1"), ("bar", null)); // Act var text = sut.ToString(); // Assert // Base64 encoding "1" gives "MQ==" text.Should().Be("##octopus[my-message-name foo=\"MQ==\"]"); } } } <file_sep>#nullable disable using System; using System.Net; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Calamari.Common.Plumbing.Proxies; using Calamari.Testing; using FluentAssertions; using Microsoft.Azure.Management.AppService.Fluent; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using NUnit.Framework; using OperatingSystem = Microsoft.Azure.Management.AppService.Fluent.OperatingSystem; namespace Calamari.AzureAppService.Tests { [TestFixture] [NonParallelizable] class LegacyAzureWebAppHealthCheckActionHandlerFixtures { const string NonExistentProxyHostname = "non-existent-proxy.local"; const int NonExistentProxyPort = 3128; readonly IWebProxy originalProxy = WebRequest.DefaultWebProxy; readonly string originalProxyHost = Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost); readonly string originalProxyPort = Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort); [Test] [NonParallelizable] public async Task WebAppIsFound_WithAndWithoutProxy() { IAzure azure = null; IResourceGroup resourceGroup = null; IWebApp webApp; try { (azure, resourceGroup, webApp) = await SetUpAzureWebApp(); azure.Should().NotBeNull(); resourceGroup.Should().NotBeNull(); webApp.Should().NotBeNull(); await CommandTestBuilder.CreateAsync<HealthCheckCommand, Program>() .WithArrange(context => SetUpVariables(context, resourceGroup.Name, webApp.Name)) .WithAssert(result => result.WasSuccessful.Should().BeTrue()) .Execute(); // Here we verify whether the proxy is correctly picked up // Since the proxy we use here is non-existent, health check to the same Web App should fail due this this proxy setting SetLocalEnvironmentProxySettings(NonExistentProxyHostname, NonExistentProxyPort); SetCiEnvironmentProxySettings(NonExistentProxyHostname, NonExistentProxyPort); await CommandTestBuilder.CreateAsync<HealthCheckCommand, Program>() .WithArrange(context => SetUpVariables(context, resourceGroup.Name, webApp.Name)) .WithAssert(result => result.WasSuccessful.Should().BeFalse()) .Execute(false); } finally { RestoreLocalEnvironmentProxySettings(); RestoreCiEnvironmentProxySettings(); await CleanResources(azure, resourceGroup); } } [Test] [NonParallelizable] public async Task WebAppIsNotFound() { var randomName = SdkContext.RandomResourceName(nameof(LegacyAzureWebAppHealthCheckActionHandlerFixtures), 60); await CommandTestBuilder.CreateAsync<HealthCheckCommand, Program>() .WithArrange(context => SetUpVariables(context, randomName, randomName)) .WithAssert(result => result.WasSuccessful.Should().BeFalse()) .Execute(false); } static void SetLocalEnvironmentProxySettings(string hostname, int port) { var proxySettings = new UseCustomProxySettings(hostname, port, null!, null!).CreateProxy().Value; WebRequest.DefaultWebProxy = proxySettings; } static void SetCiEnvironmentProxySettings(string hostname, int port) { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, hostname); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, $"{port}"); } void RestoreLocalEnvironmentProxySettings() { WebRequest.DefaultWebProxy = originalProxy; } void RestoreCiEnvironmentProxySettings() { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, originalProxyHost); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, originalProxyPort); } static async Task<(IAzure azure, IResourceGroup resourceGroup, IWebApp webApp)> SetUpAzureWebApp() { var resourceGroupName = SdkContext.RandomResourceName(nameof(LegacyAzureWebAppHealthCheckActionHandlerFixtures), 60); var clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); var clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); var tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); var subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud); var azure = Microsoft.Azure.Management.Fluent.Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithSubscription(subscriptionId); IResourceGroup resourceGroup = null; IWebApp webApp = null; try { resourceGroup = await azure.ResourceGroups .Define(resourceGroupName) .WithRegion(Region.USWest) .CreateAsync(); var appServicePlan = await azure.AppServices.AppServicePlans .Define(SdkContext.RandomResourceName(nameof(LegacyAzureWebAppHealthCheckActionHandlerFixtures), 60)) .WithRegion(resourceGroup.Region) .WithExistingResourceGroup(resourceGroup) .WithPricingTier(PricingTier.BasicB1) .WithOperatingSystem(OperatingSystem.Windows) .CreateAsync(); var webAppName = SdkContext.RandomResourceName(nameof(LegacyAzureWebAppHealthCheckActionHandlerFixtures), 60); webApp = await azure.WebApps .Define(webAppName) .WithExistingWindowsPlan(appServicePlan) .WithExistingResourceGroup(resourceGroup) .WithRuntimeStack(WebAppRuntimeStack.NETCore) .CreateAsync(); return (azure, resourceGroup, webApp); } catch { // When errors encountered in set up, we return the resources that have been set up so far anyway // We will clean the resources from the caller return (azure, resourceGroup, webApp); } } static void SetUpVariables(CommandTestBuilderContext context, string resourceGroupName, string webAppName) { var clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); var clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); var tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); var subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); context.Variables.Add(AccountVariables.SubscriptionId, subscriptionId); context.Variables.Add(AccountVariables.TenantId, tenantId); context.Variables.Add(AccountVariables.ClientId, clientId); context.Variables.Add(AccountVariables.Password, clientSecret); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupName, resourceGroupName); context.Variables.Add(SpecialVariables.Action.Azure.WebAppName, webAppName); context.Variables.Add("Octopus.Account.AccountType", "AzureServicePrincipal"); } static async Task CleanResources(IAzure azure, IResourceGroup resourceGroup) { if (azure != null && resourceGroup != null) { await azure.ResourceGroups.DeleteByNameAsync(resourceGroup.Name); } } } }<file_sep>using System; using Autofac; namespace Calamari.Common.Plumbing.Pipeline { public class PreDeployResolver: Resolver<IPreDeployBehaviour> { public PreDeployResolver(ILifetimeScope lifetimeScope) : base(lifetimeScope) { } } }<file_sep>using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; namespace Calamari.Deployment.Features.Java.Actions { public class WildflyDeployCertificateAction: JavaAction { public WildflyDeployCertificateAction(JavaRunner runner): base(runner) { } public override void Execute(RunningDeployment deployment) { var variables = deployment.Variables; Log.Info("Deploying certificate to WildFly"); var envVariables = new Dictionary<string, string>(){ {"OctopusEnvironment_Java_Certificate_Variable", variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable)}, {"OctopusEnvironment_Java_Certificate_Password", variables.Get(SpecialVariables.Action.Java.JavaKeystore.Password)}, {"OctopusEnvironment_Java_Certificate_KeystoreFilename", variables.Get(SpecialVariables.Action.Java.JavaKeystore.KeystoreFilename)}, {"OctopusEnvironment_Java_Certificate_KeystoreAlias", variables.Get(SpecialVariables.Action.Java.JavaKeystore.KeystoreAlias)}, {"OctopusEnvironment_WildFly_Deploy_ServerType", variables.Get(SpecialVariables.Action.Java.WildFly.ServerType)}, {"OctopusEnvironment_WildFly_Deploy_Controller", variables.Get(SpecialVariables.Action.Java.WildFly.Controller)}, {"OctopusEnvironment_WildFly_Deploy_Port", variables.Get(SpecialVariables.Action.Java.WildFly.Port)}, {"OctopusEnvironment_WildFly_Deploy_Protocol", variables.Get(SpecialVariables.Action.Java.WildFly.Protocol)}, {"OctopusEnvironment_WildFly_Deploy_User", variables.Get(SpecialVariables.Action.Java.WildFly.User)}, {"OctopusEnvironment_WildFly_Deploy_Password", variables.Get(SpecialVariables.Action.Java.WildFly.Password)}, {"OctopusEnvironment_WildFly_Deploy_CertificateProfiles", variables.Get(SpecialVariables.Action.Java.WildFly.CertificateProfiles)}, {"OctopusEnvironment_WildFly_Deploy_DeployCertificate", variables.Get(SpecialVariables.Action.Java.WildFly.DeployCertificate)}, {"OctopusEnvironment_WildFly_Deploy_CertificateRelativeTo", variables.Get(SpecialVariables.Action.Java.WildFly.CertificateRelativeTo)}, {"OctopusEnvironment_WildFly_Deploy_HTTPSPortBindingName", variables.Get(SpecialVariables.Action.Java.WildFly.HTTPSPortBindingName)}, {"OctopusEnvironment_WildFly_Deploy_SecurityRealmName", variables.Get(SpecialVariables.Action.Java.WildFly.SecurityRealmName)}, {"OctopusEnvironment_WildFly_Deploy_ElytronKeystoreName", variables.Get(SpecialVariables.Action.Java.WildFly.ElytronKeystoreName)}, {"OctopusEnvironment_WildFly_Deploy_ElytronKeymanagerName", variables.Get(SpecialVariables.Action.Java.WildFly.ElytronKeymanagerName)}, {"OctopusEnvironment_WildFly_Deploy_ElytronSSLContextName", variables.Get(SpecialVariables.Action.Java.WildFly.ElytronSSLContextName)} }; if (variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable) != null) { envVariables.Add("OctopusEnvironment_Java_Certificate_Private_Key", variables.Get(variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable) + ".PrivateKeyPem")); envVariables.Add("OctopusEnvironment_Java_Certificate_Public_Key", variables.Get(variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable) + ".CertificatePem")); envVariables.Add("OctopusEnvironment_Java_Certificate_Public_Key_Subject", variables.Get(variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable) + ".Subject")); } runner.Run("com.octopus.calamari.wildflyhttps.WildflyHttpsStandaloneConfig", envVariables); } } }<file_sep>using System; using Calamari.AzureWebApp.Util; using FluentAssertions; using NUnit.Framework; namespace Calamari.AzureWebApp.Tests { [TestFixture] public class AzureWebAppHelperFixture { string site; string slot; [SetUp] public void Setup() { site = $"site-{Guid.NewGuid().ToString()}"; slot = $"slot-{Guid.NewGuid().ToString()}"; } [Test] public void LegacySiteWithSlot() { var siteAndMaybeSlotName = $"{site}({slot})"; var targetSite = AzureWebAppHelper.GetAzureTargetSite(siteAndMaybeSlotName, string.Empty); targetSite.HasSlot.Should().BeTrue(); targetSite.Site.Should().Be(site); targetSite.RawSite.Should().Be(siteAndMaybeSlotName); targetSite.Slot.Should().Be(slot); } [Test] public void SiteWithSlotSlashFormat() { var siteAndMaybeSlotName = $"{site}/{slot}"; var targetSite = AzureWebAppHelper.GetAzureTargetSite(siteAndMaybeSlotName, string.Empty); targetSite.HasSlot.Should().BeTrue(); targetSite.Site.Should().Be(site); targetSite.RawSite.Should().Be(siteAndMaybeSlotName); targetSite.Slot.Should().Be(slot); } [Test] public void SiteWithNoSlot() { var targetSite = AzureWebAppHelper.GetAzureTargetSite($"{site}", string.Empty); targetSite.HasSlot.Should().BeFalse(); targetSite.Site.Should().Be(site); targetSite.RawSite.Should().Be(site); targetSite.Slot.Should().BeNullOrEmpty(); } [Test] public void LegacySiteWithSlotInSiteNameAndSlotInProperty() { var overrideSlot = Guid.NewGuid().ToString(); var siteAndMaybeSlotName = $"{site}({slot})"; var targetSite = AzureWebAppHelper.GetAzureTargetSite(siteAndMaybeSlotName, overrideSlot); targetSite.HasSlot.Should().BeTrue(); targetSite.Site.Should().Be(site); targetSite.RawSite.Should().Be(siteAndMaybeSlotName); targetSite.Slot.Should().Be(slot); } [Test] public void SiteWithSlotInSiteNameAndSlotInProperty() { var overrideSlot = Guid.NewGuid().ToString(); var siteAndMaybeSlotName = $"{site}/{slot}"; var targetSite = AzureWebAppHelper.GetAzureTargetSite(siteAndMaybeSlotName, overrideSlot); targetSite.HasSlot.Should().BeTrue(); targetSite.Site.Should().Be(site); targetSite.RawSite.Should().Be(siteAndMaybeSlotName); targetSite.Slot.Should().Be(slot); } [Test] public void SiteAndSlotInProperty() { var targetSite = AzureWebAppHelper.GetAzureTargetSite(site, slot); targetSite.HasSlot.Should().BeTrue(); targetSite.Site.Should().Be(site); targetSite.RawSite.Should().Be(site); targetSite.Slot.Should().Be(slot); targetSite.SiteAndSlot.Should().Be($"{site}/{slot}"); } [Test] public void PoorlyFormedLegacySite() { var targetSite = AzureWebAppHelper.GetAzureTargetSite($"{site}({slot}", string.Empty); targetSite.HasSlot.Should().BeTrue(); targetSite.Site.Should().Be(site); targetSite.Slot.Should().Be(slot); } } }<file_sep>#!/bin/bash set_octopusvariable "Password" "<PASSWORD>" -sensitive <file_sep>using System; namespace Calamari.Integration.Time { public class SystemClock : IClock { public DateTimeOffset GetUtcTime() { return DateTimeOffset.UtcNow; } public DateTimeOffset GetLocalTime() { return DateTimeOffset.Now; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Packages.NuGet; using Calamari.Common.Plumbing.Logging; using Octopus.Versioning; namespace Calamari.Integration.Packages.NuGet { public class NuGetFileSystemDownloader { private static string NuGetFileExtension = ".nupkg"; public static void DownloadPackage(string packageId, IVersion version, Uri feedUri, string targetFilePath) { if (!Directory.Exists(feedUri.LocalPath)) throw new Exception($"Path does not exist: '{feedUri}'"); // Lookup files which start with the name "<Id>." and attempt to match it with all possible version string combinations (e.g. 1.2.0, 1.2.0.0) // before opening the package. To avoid creating file name strings, we attempt to specifically match everything after the last path separator // which would be the file name and extension. var package = (from path in GetPackageLookupPaths(packageId, version, feedUri) let pkg = new LocalNuGetPackage(path) where pkg.Metadata.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase) && VersionFactory.CreateSemanticVersion(pkg.Metadata.Version.ToString()).Equals(version) select path ).FirstOrDefault(); if (package == null) throw new Exception($"Could not find package {packageId} v{version} in feed: '{feedUri}'"); Log.VerboseFormat("Found package {0} v{1}", packageId, version); Log.Verbose("Downloading to: " + targetFilePath); using (var targetFile = File.Open(targetFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { using (var fileStream = File.OpenRead(package)) { fileStream.CopyTo(targetFile); } } } static IEnumerable<string> GetPackageLookupPaths(string packageId, IVersion version, Uri feedUri) { // Files created by the path resolver. This would take into account the non-side-by-side scenario // and we do not need to match this for id and version. var packageFileName = GetPackageFileName(packageId, version); var filesMatchingFullName = GetPackageFiles(feedUri, packageFileName); if (version != null && version.Revision < 1) { // If the build or revision number is not set, we need to look for combinations of the format // * Foo.1.2.nupkg // * Foo.1.2.3.nupkg // * Foo.1.2.0.nupkg // * Foo.1.2.0.0.nupkg // To achieve this, we would look for files named 1.2*.nupkg if both build and revision are 0 and // 1.2.3*.nupkg if only the revision is set to 0. string partialName = version.Patch < 1 ? String.Join(".", packageId, version.Major, version.Minor) : String.Join(".", packageId, version.Major, version.Minor, version.Patch); partialName += "*" + NuGetFileExtension; // Partial names would result is gathering package with matching major and minor but different build and revision. // Attempt to match the version in the path to the version we're interested in. var partialNameMatches = GetPackageFiles(feedUri, partialName).Where(path => FileNameMatchesPattern(packageId, version, path)); return Enumerable.Concat(filesMatchingFullName, partialNameMatches); } return filesMatchingFullName; } static bool FileNameMatchesPattern(string packageId, IVersion version, string path) { var name = Path.GetFileNameWithoutExtension(path); // When matching by pattern, we will always have a version token. Packages without versions would be matched early on by the version-less path resolver // when doing an exact match. return name.Length > packageId.Length && (VersionFactory.TryCreateSemanticVersion(name.Substring(packageId.Length + 1))?.Equals(version) ?? false); } static IEnumerable<string> GetPackageFiles(Uri feedUri, string filter) { var feedPath = feedUri.LocalPath; // Check for package files one level deep. We use this at package install time // to determine the set of installed packages. Installed packages are copied to // {id}.{version}\{packagefile}.{extension}. foreach (var dir in Directory.EnumerateDirectories(feedPath)) { foreach (var path in GetFiles(dir, filter)) { yield return path; } } // Check top level directory foreach (var path in GetFiles(feedPath, filter)) { yield return path; } } static IEnumerable<string> GetFiles(string path, string filter) { try { return Directory.EnumerateFiles(path, filter, SearchOption.TopDirectoryOnly); } catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } return Enumerable.Empty<string>(); } static string GetPackageFileName(string packageId, IVersion version) { return packageId + "." + version + NuGetFileExtension; } } }<file_sep>using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Iis; namespace Calamari.Deployment.Conventions { public class LegacyIisWebSiteConvention : IInstallConvention { readonly ICalamariFileSystem fileSystem; readonly IInternetInformationServer iis; public LegacyIisWebSiteConvention(ICalamariFileSystem fileSystem, IInternetInformationServer iis) { this.fileSystem = fileSystem; this.iis = iis; } public void Install(RunningDeployment deployment) { if (!deployment.Variables.GetFlag(SpecialVariables.Package.UpdateIisWebsite)) return; var iisSiteName = deployment.Variables.Get(SpecialVariables.Package.UpdateIisWebsiteName); if (string.IsNullOrWhiteSpace(iisSiteName)) { iisSiteName = deployment.Variables.Get(PackageVariables.PackageId); } var webRoot = GetRootMostDirectoryContainingWebConfig(deployment); if (webRoot == null) throw new CommandException("A web.config file was not found, so no IIS configuration will be performed. To turn off this feature, use the 'Configure features' link in the deployment step configuration to disable IIS updates."); // In situations where the IIS version cannot be correctly determined automatically, // this variable can be set to force IIS6 compatibility. var legacySupport = deployment.Variables.GetFlag(SpecialVariables.UseLegacyIisSupport); var updated = iis.OverwriteHomeDirectory(iisSiteName, webRoot, legacySupport); if (!updated) throw new CommandException( string.Format( "Could not find an IIS website or virtual directory named '{0}' on the local machine. You need to create the site and/or virtual directory manually. To turn off this feature, use the 'Configure features' link in the deployment step configuration to disable IIS updates.", iisSiteName)); Log.Info("The IIS website named '{0}' has had its path updated to: '{1}'", iisSiteName, webRoot); } string GetRootMostDirectoryContainingWebConfig(RunningDeployment deployment) { // Optimize for most common case. if (fileSystem.FileExists(Path.Combine(deployment.CurrentDirectory, "Web.config"))) { return deployment.CurrentDirectory; } // Find all folders under package root and sort them by depth var dirs = fileSystem.EnumerateDirectoriesRecursively(deployment.CurrentDirectory).ToList(); return dirs.OrderBy(x => x.Count(c => c == '\\')).FirstOrDefault(dir => fileSystem.FileExists(Path.Combine(dir, "Web.config"))); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.Scripting { public class SubstituteScriptSourceBehaviour : IPreDeployBehaviour { readonly ISubstituteInFiles substituteInFiles; public SubstituteScriptSourceBehaviour(ISubstituteInFiles substituteInFiles) { this.substituteInFiles = substituteInFiles; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { substituteInFiles.Substitute(context.CurrentDirectory, ScriptFileTargetFactory(context).ToList()); return this.CompletedTask(); } IEnumerable<string> ScriptFileTargetFactory(RunningDeployment context) { var scriptFile = context.Variables.Get(ScriptVariables.ScriptFileName); if (scriptFile == null) throw new InvalidOperationException($"{ScriptVariables.ScriptFileName} variable value could not be found."); yield return Path.Combine(context.CurrentDirectory, scriptFile); } bool WasProvided(string value) { return !string.IsNullOrEmpty(value); } } }<file_sep>using System; #if WINDOWS_USER_ACCOUNT_SUPPORT using System.DirectoryServices.AccountManagement; #endif using System.Linq; using System.Net; using System.Security.Principal; using Microsoft.Win32; using Polly; namespace Calamari.Tests.Fixtures.Util { public class TestUserPrincipal { public TestUserPrincipal(string username, string password = null) { #if WINDOWS_USER_ACCOUNT_SUPPORT var usernameToUse = username; if (usernameToUse.Length > 20) { var shortenedUsername = new string(usernameToUse.Take(20).ToArray()); Console.WriteLine($"The requested username '{usernameToUse}' will fail because it is longer than 20 characters. Shortening it to '{shortenedUsername}' instead. You should always use the resulting Username property of this class when trying to use the user account."); usernameToUse = shortenedUsername; } try { var usingRandomlyGeneratedPassword = password == null; if (usingRandomlyGeneratedPassword) { // There is a slight chance the password won't meet complexity requirements, try a few times string passwordToUse = null; Policy.Handle<PasswordException>().Retry( retryCount: 10, onRetry: (exception, i) => { Console.WriteLine($"The password '{passwordToUse}' was not acceptable: {exception.Message}. Trying another random password!"); }) .Execute(() => { passwordToUse = PasswordGenerator.Generate(16, 4); CreateOrUpdateUser(usernameToUse, passwordToUse); }); } else { CreateOrUpdateUser(usernameToUse, password); } } catch (Exception ex) { Console.WriteLine($"Failed to create the Windows User Account called '{username}': {ex.Message}"); throw; } #endif } void CreateOrUpdateUser(string username, string password) { #if WINDOWS_USER_ACCOUNT_SUPPORT using (var principalContext = new PrincipalContext(ContextType.Machine)) { UserPrincipal principal = null; try { principal = UserPrincipal.FindByIdentity(principalContext, IdentityType.Name, username); if (principal != null) { Console.WriteLine($"The Windows User Account named '{username}' already exists, making sure the password is set correctly..."); principal.SetPassword(<PASSWORD>); principal.Save(); } else { Console.WriteLine($"Trying to create a Windows User Account on the local machine called '{username}'..."); principal = new UserPrincipal(principalContext) { Name = username }; principal.SetPassword(<PASSWORD>); principal.Save(); } HideUserAccountFromLogonScreen(username); SamAccountName = principal.SamAccountName; Sid = principal.Sid; Password = <PASSWORD>; } finally { principal?.Dispose(); } } #endif } static void HideUserAccountFromLogonScreen(string username) { #if WINDOWS_REGISTRY_SUPPORT using (var winLogonSubKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CUrrentVersion\\WinLogon", RegistryKeyPermissionCheck.ReadWriteSubTree)) { using (var specialAccountsSubKey = winLogonSubKey.GetSubKeyNames().Contains("SpecialAccounts") ? winLogonSubKey.OpenSubKey("SpecialAccounts", RegistryKeyPermissionCheck.ReadWriteSubTree) : winLogonSubKey.CreateSubKey("SpecialAccounts")) { using (var userListSubKey = specialAccountsSubKey.GetSubKeyNames().Contains("UserList") ? specialAccountsSubKey.OpenSubKey("UserList", RegistryKeyPermissionCheck.ReadWriteSubTree) : specialAccountsSubKey.CreateSubKey("UserList")) { userListSubKey.SetValue(username, 0, RegistryValueKind.DWord); } } } #endif } public TestUserPrincipal EnsureIsMemberOfGroup(string groupName) { #if WINDOWS_REGISTRY_SUPPORT Console.WriteLine($"Ensuring the Windows User Account called '{UserName}' is a member of the '{groupName}' group..."); using (var principalContext = new PrincipalContext(ContextType.Machine)) using (var principal = UserPrincipal.FindByIdentity(principalContext, IdentityType.Sid, Sid.Value)) { if (principal == null) throw new Exception($"Couldn't find a user account for {UserName} by the SID {Sid.Value}"); using (var group = GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupName)) { if (group == null) throw new Exception($"Couldn't find a group with the name {groupName}"); if (!group.Members.Contains(principal)) { group.Members.Add(principal); group.Save(); } } return this; } #else return null; #endif } public TestUserPrincipal GrantLogonAsAServiceRight() { var privilegeName = "SeServiceLogonRight"; Console.WriteLine($"Granting the '{privilegeName}' privilege to the '{NTAccountName}' user account."); LsaUtility.SetRight(NTAccountName, privilegeName); return this; } public SecurityIdentifier Sid { get; private set; } #pragma warning disable CA1416 // API not supported on all platforms public string NTAccountName => Sid.Translate(typeof(NTAccount)).ToString(); #pragma warning restore CA1416 // API not supported on all platforms public string DomainName => NTAccountName.Split(new[] {'\\'}, 2)[0]; public string UserName => NTAccountName.Split(new[] {'\\'}, 2)[1]; public string SamAccountName { get; private set; } public string Password { get; private set; } public NetworkCredential GetCredential() => new NetworkCredential(UserName, Password, DomainName); public override string ToString() { return NTAccountName; } public void Delete() { #if WINDOWS_USER_ACCOUNT_SUPPORT using (var principalContext = new PrincipalContext(ContextType.Machine)) { UserPrincipal principal = null; try { principal = UserPrincipal.FindByIdentity(principalContext, IdentityType.Name, UserName); if (principal == null) { Console.WriteLine($"The Windows User Account named {UserName} doesn't exist, nothing to do..."); return; } Console.WriteLine($"The Windows User Account named {UserName} exists, deleting..."); principal.Delete(); } finally { principal?.Dispose(); } } #endif } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using Assent; using Calamari.Common.Commands; using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NSubstitute; using NSubstitute.Core; using NUnit.Framework; namespace Calamari.Tests.Fixtures.ConfigurationTransforms { internal class ConfigurationTransformTestCaseBuilder { private readonly ICalamariFileSystem fileSystem; private string transformDefinition; private readonly List<string> files = new List<string>(); private string[] mostRecentResult; private readonly Dictionary<string, string[]> allResults = new Dictionary<string, string[]>() ; private readonly string scenarioDescription; private string extractionDirectory; private ConfigurationTransformTestCaseBuilder(string description) { scenarioDescription = description; fileSystem = Substitute.For<ICalamariFileSystem>(); } public static ConfigurationTransformTestCaseBuilder ForTheScenario(string description) { return new ConfigurationTransformTestCaseBuilder(description); } public ConfigurationTransformTestCaseBuilder Given => this; public ConfigurationTransformTestCaseBuilder And => this; public ConfigurationTransformTestCaseBuilder When => this; public ConfigurationTransformTestCaseBuilder Then => this; public ConfigurationTransformTestCaseBuilder Should => this; public ConfigurationTransformTestCaseBuilder FileExists(string fileName) { fileSystem.FileExists(fileName).Returns(true); var directory = Path.GetDirectoryName(fileName); fileSystem.DirectoryExists(directory).Returns(true); files.Add(fileName); return this; } public ConfigurationTransformTestCaseBuilder ExtractionDirectoryIs(string path) { extractionDirectory = path; return this; } public ConfigurationTransformTestCaseBuilder UsingTransform(string transform) { transformDefinition = transform; return this; } public ConfigurationTransformTestCaseBuilder SourceFile(string sourceFile) { Assert.IsTrue(fileSystem.FileExists(sourceFile), $"The sourceFile {sourceFile} should exist for this test"); mostRecentResult = PerformTransform(sourceFile); allResults.Add(sourceFile, mostRecentResult); return this; } public ConfigurationTransformTestCaseBuilder FailToBeTransformed() { CollectionAssert.IsEmpty(mostRecentResult); return this; } public ConfigurationTransformTestCaseBuilder BeTransFormedBy(params string[] transformFiles) { CollectionAssert.AreEquivalent(transformFiles, mostRecentResult); return this; } private bool FilesMatch(CallInfo callInfo, string file) { var filePatterns = callInfo.ArgAt<string[]>(1); return filePatterns.Any(pattern => { //bit of a naive regex, but it works enough for our tests //"foo.*.config" becomes "foo\..*\.config" var regex = new Regex(pattern.Replace(".", @"\.").Replace("*", ".*")); return regex.IsMatch(file); }); } private string GetRelativePath(CallInfo callInfo, CalamariPhysicalFileSystem realFileSystem) { //nsubstitute calls the first return when you setup a second one. odd. if (callInfo.ArgAt<string>(0) == null) return null; return realFileSystem.GetRelativePath(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)); } private string[] PerformTransform(string sourceFile) { fileSystem.EnumerateFiles(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()) .Returns(callInfo => files.Where(file => FilesMatch(callInfo, file))); var realFileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); fileSystem.GetRelativePath(Arg.Any<string>(), Arg.Any<string>()) .Returns(x => GetRelativePath(x, realFileSystem)); var transformFileLocator = new TransformFileLocator(fileSystem, new InMemoryLog()); var transform = new XmlConfigTransformDefinition(transformDefinition); var deploymentVariables = new CalamariVariables(); deploymentVariables[KnownVariables.OriginalPackageDirectoryPath] = extractionDirectory; var deployment = new RunningDeployment(null, deploymentVariables); const bool diagnosticLoggingEnabled = false; var result = transformFileLocator.DetermineTransformFileNames(sourceFile, transform, diagnosticLoggingEnabled, deployment.CurrentDirectory).ToArray(); return result; } private class FolderOrFile { public readonly List<FolderOrFile> Children = new List<FolderOrFile>(); public FolderOrFile(string name = "") { Name = name; } public string Name { get; } public void Print(StringBuilder results) { PrintPretty("", true, false, results); } private void PrintPretty(string indent, bool first, bool last, StringBuilder results) { results.Append(indent); if (last) { results.Append("└─"); indent += " "; } else if (!first) { results.Append("├─"); indent += "| "; } results.AppendLine(Name); for (var i = 0; i < Children.Count; i++) Children[i].PrintPretty(indent, false, i == Children.Count - 1, results); } } private void PrintPackageStructure(StringBuilder results) { var rootFolder = ConvertToHierachy("Acme.Core.1.0.0.nupkg", @"c:\temp\", x => x.StartsWith(@"c:\temp")); results.AppendLine("Given a package which has the structure:"); rootFolder.Print(results); } private void PrintFilesNotInPackage(StringBuilder results) { if (files.All(x => x.StartsWith(@"c:\temp"))) return; var rootFolder = ConvertToHierachy(@"c:\", @"c:\", x => !x.StartsWith(@"c:\temp")); results.AppendLine("And the following files exist:"); rootFolder.Print(results); } private FolderOrFile ConvertToHierachy(string rootName, string prefixToRemove, Func<string, bool> predicate) { var rootFolder = new FolderOrFile(rootName); files.Sort(); foreach (var file in files.Where(predicate)) { var relativeFileName = file.Replace(prefixToRemove, ""); if (relativeFileName.Contains(@"\")) { FolderOrFile folder; var directory = GetDirectory(relativeFileName); if (rootFolder.Children.Any(x => x.Name == directory)) { folder = rootFolder.Children.First(x => x.Name == directory); } else { folder = new FolderOrFile(directory); rootFolder.Children.Add(folder); } folder.Children.Add(new FolderOrFile(GetFile(relativeFileName))); } else { rootFolder.Children.Add(new FolderOrFile(relativeFileName)); } } return rootFolder; } private string GetDirectory(string relativePath) { return relativePath.Split('\\')[0]; } private string GetFile(string relativePath) { return relativePath.Split('\\')[1]; } public void Verify(object testFixture, [CallerMemberName] string testName = null, [CallerFilePath] string filePath = null) { var results = new StringBuilder(); results.AppendLine(scenarioDescription); PrintPackageStructure(results); PrintFilesNotInPackage(results); if (allResults.Count(x => x.Value.Length > 0) == 0) { results.AppendLine("Then the transform " + transformDefinition + " will do nothing."); } else { results.AppendLine("Then the transform " + transformDefinition + " will:"); foreach (var result in allResults) { foreach (var transform in result.Value) { results.AppendLine(" - Apply the transform " + transform.Replace(@"c:\temp\", "") + " to file " + result.Key.Replace(@"c:\temp\", "")); } } } testFixture.Assent(results.ToString(), AssentConfiguration.Default, testName, filePath); } } }<file_sep>using System; using System.IO; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; namespace Calamari.Tests.Fixtures.StructuredVariables { public abstract class VariableReplacerFixture : CalamariFixture { readonly ICalamariFileSystem fileSystem; readonly Func<ICalamariFileSystem, ILog, IFileFormatVariableReplacer> replacerFactory; protected VariableReplacerFixture(Func<ICalamariFileSystem, ILog, IFileFormatVariableReplacer> replacerFactory) { this.replacerFactory = replacerFactory; fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); } string Replace(IVariables variables, string existingFile, Func<string, string> outputFileReader) { var temp = Path.GetTempFileName(); File.Copy(GetFixtureResource("Samples", existingFile), temp, true); using (new TemporaryFile(temp)) { replacerFactory(fileSystem, Log).ModifyFile(temp, variables); return outputFileReader(temp); } } protected string Replace(IVariables variables, string existingFile) { return Replace(variables, existingFile, File.ReadAllText); } protected string ReplaceToHex(IVariables variables, string existingFile) { return Replace(variables, existingFile, path => File.ReadAllBytes(path).ToReadableHexDump()); } } }<file_sep>using System; using System.IO; using System.Net.Http; using System.Threading; using Calamari.Common.Plumbing.Extensions; using YamlDotNet.RepresentationModel; namespace Calamari.Integration.Packages.Download.Helm { public interface IHelmEndpointProxy { YamlStream Get(Uri chartRepositoryRootUrl, string username, string password, CancellationToken cancellationToken); } public class HelmEndpointProxy: IHelmEndpointProxy { static readonly string[] AcceptedContentType = {"application/x-yaml", "application/yaml"}; static string httpAccept = string.Join( ", ", AcceptedContentType); readonly HttpClient client; public HelmEndpointProxy(HttpClient client) { this.client = client; } public YamlStream Get(Uri chartRepositoryRootUrl, string username, string password, CancellationToken cancellationToken) { using (var response = GetIndexYaml(chartRepositoryRootUrl, username, password, cancellationToken)) { var stream = response.Content.ReadAsStreamAsync().Result; using (var sr = new StreamReader(stream)) { var yaml = new YamlStream(); yaml.Load(sr); return yaml; } } } HttpResponseMessage GetIndexYaml(Uri chartRepositoryRootUrl, string username, string password, CancellationToken cancellationToken) { HttpResponseMessage response; var endpoint = new Uri(chartRepositoryRootUrl, "index.yaml"); using (var msg = new HttpRequestMessage(HttpMethod.Get, endpoint)) { ApplyAuthorization(username, password, msg); ApplyAccept(msg); response = client.SendAsync(msg, cancellationToken).Result; } if (!response.IsSuccessStatusCode) { throw new Exception($"Unable to read Helm index file at {endpoint}.\r\n\tStatus Code: {response.StatusCode}\r\n\tResponse: {response.Content.ReadAsStringAsync().Result}"); } return response; } void ApplyAuthorization(string username, string password, HttpRequestMessage msg) { msg.Headers.AddAuthenticationHeader(username, password); } void ApplyAccept(HttpRequestMessage msg) { msg.Headers.Add("Accept", httpAccept); } } }<file_sep>using System; using Newtonsoft.Json; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public class CacheAge : IComparable<CacheAge>, IEquatable<CacheAge> { public int Value { get; private set; } [JsonConstructor] public CacheAge(int value) { Value = value; } public void IncrementAge() { Value++; } public bool Equals(CacheAge? other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Value == other.Value; } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((CacheAge)obj); } public override int GetHashCode() { return Value; } public int CompareTo(CacheAge? other) { if (ReferenceEquals(this, other)) return 0; if (ReferenceEquals(null, other)) return 1; return Value.CompareTo(other.Value); } public static bool operator > (CacheAge first, CacheAge second) { return first.Value > second.Value; } public static bool operator < (CacheAge first, CacheAge second) { return first.Value < second.Value; } public static bool operator == (CacheAge first, CacheAge second) { return first.Value == second.Value; } public static bool operator !=(CacheAge first, CacheAge second) { return first.Value != second.Value; } } }<file_sep>using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.FeatureToggles { public static class FeatureToggleExtensions { public static bool IsEnabled(this FeatureToggle featureToggle, IVariables variables) { var toggleName = featureToggle.ToString(); return variables.GetStrings(KnownVariables.EnabledFeatureToggles).Contains(toggleName); } } }<file_sep>echo "hello from PreDeploy.sh" <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Commands; //Required when NETFX is defined using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Processes; using Calamari.Testing.Helpers; using NUnit.Framework; namespace Calamari.Tests.Helpers { public abstract class CalamariFixture { protected InMemoryLog Log; [SetUp] public void SetUpCalamariFixture() { Log = new InMemoryLog(); } protected CommandLine Calamari() { #if NETFX var calamariFullPath = typeof(DeployPackageCommand).Assembly.FullLocalPath(); return new CommandLine(calamariFullPath); #else var folder = Path.GetDirectoryName(typeof(Program).Assembly.FullLocalPath()); var calamariFullPath = Path.Combine(folder, "Calamari.Tests.dll"); if (!File.Exists(calamariFullPath)) throw new Exception($"Could not find Calamari test wrapper at {calamariFullPath}"); return new CommandLine(calamariFullPath).UseDotnet().OutputToLog(false); #endif } protected CommandLine OctoDiff() { var octoDiffExe = OctoDiffCommandLineRunner.FindOctoDiffExecutable(); return new CommandLine(octoDiffExe); } protected CalamariResult InvokeInProcess(CommandLine command, IVariables variables = null) { var args = command.GetRawArgs(); var program = new TestProgram(Log); int exitCode; try { exitCode = program.RunWithArgs(args); } catch (Exception ex) { exitCode = ConsoleFormatter.PrintError(Log, ex); } variables = variables ?? new CalamariVariables(); var capture = new CaptureCommandInvocationOutputSink(); var sco = new SplitCommandInvocationOutputSink(new ServiceMessageCommandInvocationOutputSink(variables), capture); foreach(var line in Log.StandardOut) sco.WriteInfo(line); foreach(var line in Log.StandardError) sco.WriteError(line); return new CalamariResult(exitCode, capture); } protected CalamariResult Invoke(CommandLine command, IVariables variables = null, ILog log = null) { var runner = new TestCommandLineRunner(log ?? ConsoleLog.Instance, variables ?? new CalamariVariables()); var result = runner.Execute(command.Build()); return new CalamariResult(result.ExitCode, runner.Output); } protected string GetFixtureResource(params string[] paths) { var type = GetType(); return GetFixtureResource(type, paths); } public static string GetFixtureResource(Type type, params string[] paths) { var path = type.Namespace.Replace("Calamari.Tests.", String.Empty); path = path.Replace('.', Path.DirectorySeparatorChar); return Path.Combine(TestEnvironment.CurrentWorkingDirectory, path, Path.Combine(paths)); } protected (CalamariResult result, IVariables variables) RunScript(string scriptName, Dictionary<string, string> additionalVariables = null, Dictionary<string, string> additionalParameters = null, string sensitiveVariablesPassword = null, IEnumerable<string> extensions = null) { var variablesFile = Path.GetTempFileName(); var variables = new CalamariVariables(); variables.Set(ScriptVariables.ScriptFileName, scriptName); variables.Set(ScriptVariables.ScriptBody, File.ReadAllText(GetFixtureResource("Scripts", scriptName))); variables.Set(ScriptVariables.Syntax, scriptName.ToScriptType().ToString()); additionalVariables?.ToList().ForEach(v => variables[v.Key] = v.Value); using (new TemporaryFile(variablesFile)) { var cmdBase = Calamari() .Action("run-script"); if (sensitiveVariablesPassword == null) { variables.Save(variablesFile); cmdBase = cmdBase.Argument("variables", variablesFile); } else { variables.SaveEncrypted(sensitiveVariablesPassword, variablesFile); cmdBase = cmdBase.Argument("sensitiveVariables", variablesFile) .Argument("sensitiveVariablesPassword", sensitiveVariablesPassword); } if (extensions != null) { cmdBase.Argument("extensions", string.Join(",", extensions)); } cmdBase = (additionalParameters ?? new Dictionary<string, string>()).Aggregate(cmdBase, (cmd, param) => cmd.Argument(param.Key, param.Value)); var output = Invoke(cmdBase, variables); return (output, variables); } } } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class StatefulSetTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""StatefulSet"", ""metadata"": { ""name"": ""my-sts"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""status"": { ""readyReplicas"": 2, ""replicas"": 3 } }"; var statefulSet = ResourceFactory.FromJson(input, new Options()); statefulSet.Should().BeEquivalentTo(new { Kind = "StatefulSet", Name = "my-sts", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Ready = "2/3", ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress }); } } } <file_sep>#if !NET40 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Autofac; using Autofac.Core; using Autofac.Core.Registration; using Calamari.Common.Commands; using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Common.Features.ConfigurationVariables; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.FunctionScriptContributions; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Proxies; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common { public abstract class CalamariFlavourProgramAsync { readonly ILog log; protected CalamariFlavourProgramAsync(ILog log) { this.log = log; } protected virtual void ConfigureContainer(ContainerBuilder builder, CommonOptions options) { var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); builder.RegisterInstance(fileSystem).As<ICalamariFileSystem>(); builder.RegisterType<VariablesFactory>().AsSelf(); builder.Register(c => c.Resolve<VariablesFactory>().Create(options)).As<IVariables>().SingleInstance(); builder.RegisterType<ScriptEngine>().As<IScriptEngine>(); builder.RegisterType<VariableLogger>().AsSelf(); builder.RegisterInstance(log).As<ILog>().SingleInstance(); builder.RegisterType<FreeSpaceChecker>().As<IFreeSpaceChecker>().SingleInstance(); builder.RegisterType<CommandLineRunner>().As<ICommandLineRunner>().SingleInstance(); builder.RegisterType<FileSubstituter>().As<IFileSubstituter>(); builder.RegisterType<SubstituteInFiles>().As<ISubstituteInFiles>(); builder.RegisterType<CombinedPackageExtractor>().As<ICombinedPackageExtractor>(); builder.RegisterType<ExtractPackage>().As<IExtractPackage>(); builder.RegisterType<AssemblyEmbeddedResources>().As<ICalamariEmbeddedResources>(); builder.RegisterType<ConfigurationVariablesReplacer>().As<IConfigurationVariablesReplacer>(); builder.RegisterType<TransformFileLocator>().As<ITransformFileLocator>(); builder.Register(context => ConfigurationTransformer.FromVariables(context.Resolve<IVariables>(), context.Resolve<ILog>())).As<IConfigurationTransformer>(); builder.RegisterType<DeploymentJournalWriter>().As<IDeploymentJournalWriter>().SingleInstance(); builder.RegisterType<CodeGenFunctionsRegistry>().SingleInstance(); var assemblies = GetAllAssembliesToRegister().ToArray(); builder.RegisterAssemblyTypes(assemblies).AssignableTo<ICodeGenFunctions>().As<ICodeGenFunctions>().SingleInstance(); builder.RegisterAssemblyTypes(assemblies) .AssignableTo<IScriptWrapper>() .Except<TerminalScriptWrapper>() .As<IScriptWrapper>() .SingleInstance(); builder.RegisterAssemblyTypes(assemblies) .Where(t => t.IsAssignableTo<IBehaviour>() && !t.IsAbstract) .AsSelf() .InstancePerDependency(); builder.RegisterAssemblyTypes(assemblies) .AssignableTo<ICommandAsync>() .Where(t => t.GetCustomAttribute<CommandAttribute>().Name .Equals(options.Command, StringComparison.OrdinalIgnoreCase)) .Named<ICommandAsync>(t => t.GetCustomAttribute<CommandAttribute>().Name); builder.RegisterAssemblyTypes(assemblies) .AssignableTo<PipelineCommand>() .Where(t => t.GetCustomAttribute<CommandAttribute>().Name .Equals(options.Command, StringComparison.OrdinalIgnoreCase)) .Named<PipelineCommand>(t => t.GetCustomAttribute<CommandAttribute>().Name); builder.RegisterModule<StructuredConfigVariablesModule>(); } protected virtual IEnumerable<Assembly> GetProgramAssembliesToRegister() { yield return GetType().Assembly; } protected async Task<int> Run(string[] args) { try { AppDomainConfiguration.SetDefaultRegexMatchTimeout(); SecurityProtocols.EnableAllSecurityProtocols(); var options = CommonOptions.Parse(args); log.Verbose($"Calamari Version: {GetType().Assembly.GetInformationalVersion()}"); if (options.Command.Equals("version", StringComparison.OrdinalIgnoreCase)) { return 0; } var envInfo = string.Join($"{Environment.NewLine} ", EnvironmentHelper.SafelyGetEnvironmentInformation()); log.Verbose($"Environment Information: {Environment.NewLine} {envInfo}"); EnvironmentHelper.SetEnvironmentVariable("OctopusCalamariWorkingDirectory", Environment.CurrentDirectory); ProxyInitializer.InitializeDefaultProxy(); var builder = new ContainerBuilder(); ConfigureContainer(builder, options); using var container = builder.Build(); container.Resolve<VariableLogger>().LogVariables(); #if DEBUG var waitForDebugger = container.Resolve<IVariables>().Get(KnownVariables.Calamari.WaitForDebugger); if (string.Equals(waitForDebugger, "true", StringComparison.OrdinalIgnoreCase)) { using var proc = Process.GetCurrentProcess(); Log.Info($"Waiting for debugger to attach... (PID: {proc.Id})"); while (!Debugger.IsAttached) { await Task.Delay(1000); } } #endif await ResolveAndExecuteCommand(container, options); return 0; } catch (Exception ex) { return ConsoleFormatter.PrintError(ConsoleLog.Instance, ex); } } IEnumerable<Assembly> GetAllAssembliesToRegister() { var programAssemblies = GetProgramAssembliesToRegister(); foreach (var assembly in programAssemblies) yield return assembly; // Calamari Flavour & dependencies yield return typeof(CalamariFlavourProgramAsync).Assembly; // Calamari.Common } Task ResolveAndExecuteCommand(ILifetimeScope container, CommonOptions options) { try { if (container.IsRegisteredWithName<PipelineCommand>(options.Command)) { var pipeline = container.ResolveNamed<PipelineCommand>(options.Command); var variables = container.Resolve<IVariables>(); return pipeline.Execute(container, variables); } var command = container.ResolveNamed<ICommandAsync>(options.Command); return command.Execute(); } catch (Exception e) when (e is ComponentNotRegisteredException || e is DependencyResolutionException) { throw new CommandException($"Could not find the command {options.Command}"); } } } } #endif<file_sep>using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Calamari.AzureCloudService.CloudServicePackage.ManifestSchema { public class PackageDefinition { public static readonly XNamespace AzureNamespace = "http://schemas.microsoft.com/windowsazure"; public static readonly XName ElementName = AzureNamespace + "PackageDefinition"; static readonly XName PackageContentsElementName = AzureNamespace + "PackageContents"; static readonly XName PackageLayoutsElementName = AzureNamespace + "PackageLayouts"; public PackageDefinition() { MetaData = new AzurePackageMetadata(); Layouts = new List<LayoutDefinition>(); Contents = new List<ContentDefinition>(); } public PackageDefinition(XElement element) { MetaData = new AzurePackageMetadata(element.Element(AzurePackageMetadata.ElementName)); Contents = element .Element(PackageContentsElementName) .Elements(ContentDefinition.ElementName) .Select(x => new ContentDefinition(x)) .ToList(); Layouts = element .Element(PackageLayoutsElementName) .Elements(LayoutDefinition.ElementName) .Select(x => new LayoutDefinition(x)) .ToList(); } public AzurePackageMetadata MetaData { get; private set; } public ICollection<ContentDefinition> Contents { get; private set; } public ICollection<LayoutDefinition> Layouts { get; private set; } public ContentDefinition GetContentDefinition(string name) { return Contents.Single(x => x.Name == name); } public XElement ToXml() { return new XElement(ElementName, MetaData.ToXml(), new XElement(PackageContentsElementName, Contents.Select(x => x.ToXml())), new XElement(PackageLayoutsElementName, Layouts.Select(x => x.ToXml())) ); } } }<file_sep>using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Amazon; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.Packages.Download; using Calamari.Testing; using Calamari.Testing.Requirements; using Calamari.Tests.AWS; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; using Octopus.Versioning; using TestEnvironment = Calamari.Testing.Helpers.TestEnvironment; namespace Calamari.Tests.Fixtures.Integration.Packages { [RequiresNonMono] [TestFixture] public class S3PackageDownloaderFixture : CalamariFixture { string rootDir; static readonly string TentacleHome = TestEnvironment.GetTestPath("Fixtures", "PackageDownload"); readonly string region; readonly string bucketName; public S3PackageDownloaderFixture() { region = RegionRandomiser.GetARegion(); bucketName = $"calamari-e2e-{Guid.NewGuid():N}"; } [OneTimeSetUp] public async Task TestFixtureSetUp() { rootDir = GetFixtureResource(this.GetType().Name); if (Directory.Exists(rootDir)) { Directory.Delete(rootDir, true); } Environment.SetEnvironmentVariable("TentacleHome", TentacleHome); await Validate(async client => await client.PutBucketAsync(bucketName)); Directory.CreateDirectory(GetFixtureResource(rootDir)); } [OneTimeTearDown] public async Task TestFixtureTearDown() { if (Directory.Exists(rootDir)) { Directory.Delete(rootDir, true); } Environment.SetEnvironmentVariable("TentacleHome", null); await Validate(async client => { var response = await client.ListObjectsAsync(bucketName); foreach (var s3Object in response.S3Objects) { await client.DeleteObjectAsync(bucketName, s3Object.Key); } await client.DeleteBucketAsync(bucketName); }); } static S3PackageDownloader GetDownloader() { return new S3PackageDownloader(ConsoleLog.Instance, CalamariPhysicalFileSystem.GetPhysicalFileSystem()); } [Test] public async Task CanDownloadPackage() { string filename = "Acme.Core.1.0.0.0-bugfix.zip"; string packageId = $"{bucketName}/Acme.Core"; var version = VersionFactory.CreateVersion("1.0.0.0-bugfix", VersionFormat.Semver); File.Copy(GetFixtureResource("Samples", filename), Path.Combine(rootDir, filename)); await Validate(async client => await client.PutObjectAsync(new PutObjectRequest { BucketName = bucketName, Key = filename, InputStream = File.OpenRead(Path.Combine(rootDir, filename)) }, CancellationToken.None)); var downloader = GetDownloader(); var package = downloader.DownloadPackage(packageId, version, "s3-feed", new Uri("http://please-ignore.com"), ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey), ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey), true, 3, TimeSpan.FromSeconds(3)); package.PackageId.Should().Be(packageId); package.Size.Should().Be(new FileInfo(Path.Combine(rootDir, filename)).Length); } protected async Task Validate(Func<AmazonS3Client, Task> execute) { var credentials = new BasicAWSCredentials( ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey), ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); var config = new AmazonS3Config {AllowAutoRedirect = true, RegionEndpoint = RegionEndpoint.GetBySystemName(region)}; using (var client = new AmazonS3Client(credentials, config)) { await execute(client); } } } } <file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class IngressTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""Ingress"", ""metadata"": { ""name"": ""my-ingress"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""spec"": { ""ingressClassName"": ""nginx"", ""rules"": [ { ""host"": ""host"", ""http"": { ""paths"": [ { ""path"": ""/"", ""pathType"": ""Exact"", ""backend"": { ""name"": ""my-svc"", ""port"": { ""number"": 80 } } } ] } } ] }, ""status"": { ""loadBalancer"": { ""ingress"": [ { ""ip"": ""192.168.49.2"" } ] } } }"; var ingress = ResourceFactory.FromJson(input, new Options()); ingress.Should().BeEquivalentTo(new { Kind = "Ingress", Name = "my-ingress", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Hosts = new string[] { "host" }, Address = "192.168.49.2", ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful }); } } }<file_sep>using Newtonsoft.Json; namespace Calamari.Kubernetes.ResourceStatus.Resources { // Subset of: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.22/#containerstatus-v1-core public class ContainerStatus { [JsonProperty("state")] public ContainerState State { get; set; } [JsonProperty("ready")] public bool Ready { get; set; } [JsonProperty("restartCount")] public int RestartCount { get; set; } } // Subset of: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.22/#containerstate-v1-core public class ContainerState { [JsonProperty("running")] public ContainerStateRunning Running { get; set; } [JsonProperty("waiting")] public ContainerStateWaiting Waiting { get; set; } [JsonProperty("terminated")] public ContainerStateTerminated Terminated { get; set; } } public class ContainerStateRunning {} public class ContainerStateWaiting { [JsonProperty("reason")] public string Reason { get; set; } } public class ContainerStateTerminated { [JsonProperty("reason")] public string Reason { get; set; } } }<file_sep>using System.Linq; using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; using KubernetesResources = Calamari.Kubernetes.ResourceStatus.Resources; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class PodTests { [Test] public void ShouldCollectCorrectProperties() { var podResponse = new PodResponseBuilder() .WithPhase("Pending") .WithContainerStatuses(new ContainerStatus[] { new ContainerStatus() { State = new ContainerState { Running = new ContainerStateRunning() }, Ready = true }, new ContainerStatus() { State = new ContainerState { Waiting = new ContainerStateWaiting { Reason = "CrashLoopBackOff" } }, Ready = false, RestartCount = 3 } }) .Build(); var pod = ResourceFactory.FromJson(podResponse, new Options()); pod.Should().BeEquivalentTo(new { Kind = "Pod", Name = "Test", Namespace = "test", Ready = "1/2", Restarts = 3, ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress }); } [Test] public void WhenThePodCannotBeScheduled_TheStatusShouldBePending() { var podResponse = new PodResponseBuilder() .WithPhase("Pending") .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("Pending"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.InProgress); } [Test] public void WhenInitContainerIsBeingCreatedWithoutErrors_TheStatusShouldShowNumberOfInitContainersReady() { var podResponse = new PodResponseBuilder() .WithPhase("Pending") .WithInitContainerStates(new ContainerState[] { new ContainerState { Waiting = new ContainerStateWaiting { Reason = "PodInitializing" } }, new ContainerState { Terminated = new ContainerStateTerminated { Reason = "Completed" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("Init:1/2"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.InProgress); } [Test] public void WhenInitContainerCouldNotPullImages_TheStatusShouldShowInitImagePullBackOff() { var podResponse = new PodResponseBuilder() .WithPhase("Pending") .WithInitContainerStates(new ContainerState[] { new ContainerState { Waiting = new ContainerStateWaiting { Reason = "ImagePullBackOff" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("Init:ImagePullBackOff"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.InProgress); } [Test] public void WhenInitContainerCouldNotExecuteSuccessfully_TheStatusShouldShowCrashLoopBackOff() { var podResponse = new PodResponseBuilder() .WithPhase("Pending") .WithInitContainerStates(new ContainerState[] { new ContainerState { Waiting = new ContainerStateWaiting { Reason = "CrashLoopBackOff" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("Init:CrashLoopBackOff"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.InProgress); } [Test] public void WhenContainerIsBeingCreated_TheStatusShouldShowContainerCreating() { var podResponse = new PodResponseBuilder() .WithPhase("Pending") .WithContainerStates(new ContainerState[] { new ContainerState { Waiting = new ContainerStateWaiting { Reason = "ContainerCreating" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("ContainerCreating"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.InProgress); } [Test] public void WhenContainerCannotPullImage_TheStatusShouldShowImagePullBackOff() { var podResponse = new PodResponseBuilder() .WithPhase("Pending") .WithContainerStates(new ContainerState[] { new ContainerState { Waiting = new ContainerStateWaiting { Reason = "ImagePullBackOff" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("ImagePullBackOff"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.InProgress); } [Test] public void WhenContainerFailsExecutionAndRestarting_TheStatusShouldShowCrashLoopBackOff() { var podResponse = new PodResponseBuilder() .WithPhase("Running") .WithContainerStates(new ContainerState[] { new ContainerState { Waiting = new ContainerStateWaiting { Reason = "CrashLoopBackOff" } } }) .WithReady(false) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("CrashLoopBackOff"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.InProgress); } [Test] public void WhenContainerCannotStartExecutionAndWillNotRestart_TheStatusShouldShowContainerCannotRun() { var podResponse = new PodResponseBuilder() .WithPhase("Failed") .WithContainerStates(new ContainerState[] { new ContainerState { Terminated = new ContainerStateTerminated { Reason = "ContainerCannotRun" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("ContainerCannotRun"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.Failed); } [Test] public void WhenContainerFailsExecutionAndWillNotRestart_TheStatusShouldShowError() { var podResponse = new PodResponseBuilder() .WithPhase("Failed") .WithContainerStates(new ContainerState[] { new ContainerState { Terminated = new ContainerStateTerminated { Reason = "Error" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("Error"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.Failed); } [Test] public void WhenContainerHasCompletedSuccessfully_TheStatusShouldShowCompleted() { var podResponse = new PodResponseBuilder() .WithPhase("Succeeded") .WithContainerStates(new ContainerState[] { new ContainerState { Terminated = new ContainerStateTerminated { Reason = "Completed" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("Completed"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.Successful); } [Test] public void WhenContainerIsRunningWithoutErrors_TheStatusShouldShowRunning() { var podResponse = new PodResponseBuilder() .WithPhase("Running") .WithContainerStates(new ContainerState[] { new ContainerState { Running = new ContainerStateRunning() } }) .WithReady(true) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("Running"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.Successful); } [Test] public void WhenMoreThanOneContainerHasErrors_TheStatusShouldShowTheFirstError() { var podResponse = new PodResponseBuilder() .WithPhase("Pending") .WithContainerStates(new ContainerState[] { new ContainerState { Waiting = new ContainerStateWaiting { Reason = "ImagePullBackOff" } }, new ContainerState { Waiting = new ContainerStateWaiting { Reason = "CrashLoopBackOff" } } }) .Build(); var pod = (Pod)ResourceFactory.FromJson(podResponse, new Options()); pod.Status.Should().Be("ImagePullBackOff"); pod.ResourceStatus.Should().Be(KubernetesResources.ResourceStatus.InProgress); } } public class PodResponseBuilder { private const string Template = @" {{ ""kind"": ""Pod"", ""metadata"": {{ ""name"": ""Test"", ""namespace"": ""test"", ""uid"": ""123"" }}, ""status"": {{ ""phase"": ""{0}"", ""initContainerStatuses"": {1}, ""containerStatuses"": {2}, ""conditions"": [ {{ ""status"": ""{3}"", ""type"": ""Ready"" }} ] }} }}"; private string Phase { get; set; } = "Running"; private string InitContainerStatuses { get; set; } = "[]"; private string ContainerStatuses { get; set; } = "[]"; private string Ready { get; set; } = "False"; public string Build() { return string.Format(Template, Phase, InitContainerStatuses, ContainerStatuses, Ready); } public PodResponseBuilder WithPhase(string phase) { Phase = phase; return this; } public PodResponseBuilder WithInitContainerStates(params ContainerState[] initContainerStates) { var statuses = initContainerStates.Select(state => new ContainerStatus { State = state }); InitContainerStatuses = JsonConvert.SerializeObject(statuses); return this; } public PodResponseBuilder WithContainerStates(params ContainerState[] containerStates) { var statuses = containerStates.Select(state => new ContainerStatus { State = state }); ContainerStatuses = JsonConvert.SerializeObject(statuses); return this; } public PodResponseBuilder WithContainerStatuses(params ContainerStatus[] containerStatuses) { ContainerStatuses = JsonConvert.SerializeObject(containerStatuses); return this; } public PodResponseBuilder WithReady(bool ready) { Ready = ready ? "True" : "False"; return this; } } }<file_sep>using System; using System.Linq; using Calamari.Common.Plumbing.Logging; using NUnit.Framework; namespace Calamari.Testing { public enum ExternalVariable { [EnvironmentVariable("Azure_OctopusAPITester_SubscriptionId", "Azure - OctopusAPITester")] AzureSubscriptionId, [EnvironmentVariable("Azure_OctopusAPITester_TenantId", "Azure - OctopusAPITester")] AzureSubscriptionTenantId, [EnvironmentVariable("Azure_OctopusAPITester_Password", "Azure - OctopusAPITester")] AzureSubscriptionPassword, [EnvironmentVariable("Azure_OctopusAPITester_ClientId", "Azure - OctopusAPITester")] AzureSubscriptionClientId, [EnvironmentVariable("Azure_OctopusAPITester_Certificate", "Azure - OctopusAPITester")] AzureSubscriptionCertificate, [EnvironmentVariable("GitHub_OctopusAPITester_Username", "GitHub Test Account")] GitHubUsername, [EnvironmentVariable("GitHub_OctopusAPITester_Password", "GitHub Test Account")] GitHubPassword, [EnvironmentVariable("K8S_OctopusAPITester_Token", "GKS Kubernetes API Test Cluster Token")] KubernetesClusterToken, [EnvironmentVariable("K8S_OctopusAPITester_Server", "GKS Kubernetes API Test Cluster Url")] KubernetesClusterUrl, [EnvironmentVariable("Helm_OctopusAPITester_Password", "Artifactory Test Account")] HelmPassword, [EnvironmentVariable("DockerHub_TestReaderAccount_Password", "DockerHub Test Reader Account")] DockerReaderPassword, [EnvironmentVariable("AWS_E2E_AccessKeyId", "AWS E2E Test User Keys")] AwsCloudFormationAndS3AccessKey, [EnvironmentVariable("AWS_E2E_SecretKeyId", "AWS E2E Test User Keys")] AwsCloudFormationAndS3SecretKey, [EnvironmentVariable("CALAMARI_FEEDZV2URI", "Not LastPass; Calamari TC Config Variables")] FeedzNuGetV2FeedUrl, [EnvironmentVariable("CALAMARI_FEEDZV3URI", "Not LastPass; Calamari TC Config Variables")] FeedzNuGetV3FeedUrl, [EnvironmentVariable("CALAMARI_ARTIFACTORYV2URI", "Not LastPass; Calamari TC Config Variables")] ArtifactoryNuGetV2FeedUrl, [EnvironmentVariable("CALAMARI_ARTIFACTORYV3URI", "Not LastPass; Calamari TC Config Variables")] ArtifactoryNuGetV3FeedUrl, [EnvironmentVariable("CALAMARI_AUTHURI", "OctopusMyGetTester")] MyGetFeedUrl, [EnvironmentVariable("CALAMARI_AUTHUSERNAME", "OctopusMyGetTester")] MyGetFeedUsername, [EnvironmentVariable("CALAMARI_AUTHPASSWORD", "<PASSWORD>")] MyGetFeedPassword, [EnvironmentVariable("GOOGLECLOUD_OCTOPUSAPITESTER_JSONKEY", "GoogleCloud - OctopusAPITester")] GoogleCloudJsonKeyfile, [EnvironmentVariable("GitHub_RateLimitingPersonalAccessToken", "GitHub test account PAT")] GitHubRateLimitingPersonalAccessToken, } public static class ExternalVariables { public static void LogMissingVariables() { var missingVariables = Enum.GetValues(typeof(ExternalVariable)).Cast<ExternalVariable>() .Select(prop => EnvironmentVariableAttribute.Get(prop)) .Where(attr => Environment.GetEnvironmentVariable(attr.Name) == null) .ToList(); if (!missingVariables.Any()) return; Log.Warn($"The following environment variables could not be found: " + $"\n{string.Join("\n", missingVariables.Select(var => $" - {var.Name}\t\tSource: {var.LastPassName}"))}" + $"\n\nTests that rely on these variables are likely to fail."); } public static string Get(ExternalVariable property) { var attr = EnvironmentVariableAttribute.Get(property); if (attr == null) { throw new Exception($"`{property}` does not include a {nameof(EnvironmentVariableAttribute)}."); } var valueFromEnv = Environment.GetEnvironmentVariable(attr.Name); if (valueFromEnv == null) { throw new Exception($"Environment Variable `{attr.Name}` could not be found. The value can be found in the password store under `{attr.LastPassName}`"); } return valueFromEnv; } } [AttributeUsage(AttributeTargets.Field)] class EnvironmentVariableAttribute : Attribute { public string Name { get; } public string LastPassName { get; } public EnvironmentVariableAttribute(string name, string lastPassName) { Name = name; LastPassName = lastPassName; } public static EnvironmentVariableAttribute? Get(object enm) { var mi = enm?.GetType().GetMember(enm.ToString()); if (mi == null || mi.Length <= 0) { return null; } return GetCustomAttribute(mi[0], typeof(EnvironmentVariableAttribute)) as EnvironmentVariableAttribute; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting { public class PackagedScriptRunner { readonly ILog log; readonly string scriptFilePrefix; readonly ICalamariFileSystem fileSystem; readonly IScriptEngine scriptEngine; readonly ICommandLineRunner commandLineRunner; protected PackagedScriptRunner(ILog log, string scriptFilePrefix, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) { this.log = log; this.scriptFilePrefix = scriptFilePrefix; this.fileSystem = fileSystem; this.scriptEngine = scriptEngine; this.commandLineRunner = commandLineRunner; } protected void RunPreferredScript(RunningDeployment deployment) { var script = FindPreferredScript(deployment); if (!string.IsNullOrEmpty(script)) { log.VerboseFormat("Executing '{0}'", script); var result = scriptEngine.Execute(new Script(script), deployment.Variables, commandLineRunner); if (result.ExitCode != 0) { throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}. Deployment terminated.", script, result.ExitCode)); } if (result.HasErrors && deployment.Variables.GetFlag(KnownVariables.Action.FailScriptOnErrorOutput, false)) { throw new CommandException($"Script '{script}' returned zero exit code but had error output. Deployment terminated."); } } } protected void DeleteScripts(RunningDeployment deployment) { var scripts = FindScripts(deployment); foreach (var script in scripts) { fileSystem.DeleteFile(script, FailureOptions.IgnoreFailure); } } string FindPreferredScript(RunningDeployment deployment) { var supportedScriptExtensions = scriptEngine.GetSupportedTypes(); var files = (from file in FindScripts(deployment) let preferenceOrdinal = Array.IndexOf(supportedScriptExtensions, file.ToScriptType()) orderby preferenceOrdinal select file).ToArray(); var numFiles = files.Count(); var selectedFile = files.FirstOrDefault(); if (numFiles > 1) { var preferenceOrderDisplay = string.Join(", ", supportedScriptExtensions); log.Verbose($"Found {numFiles} {scriptFilePrefix} scripts. Selected {selectedFile} based on OS preferential ordering: {preferenceOrderDisplay}"); } return selectedFile; } IEnumerable<string> FindScripts(RunningDeployment deployment) { var supportedScriptExtensions = scriptEngine.GetSupportedTypes(); var searchPatterns = supportedScriptExtensions.Select(e => "*." + e.FileExtension()).ToArray(); return from file in fileSystem.EnumerateFiles(deployment.CurrentDirectory, searchPatterns) let nameWithoutExtension = Path.GetFileNameWithoutExtension(file) where nameWithoutExtension.Equals(scriptFilePrefix, StringComparison.OrdinalIgnoreCase) select file; } } }<file_sep>#if NETSTANDARD using NuGet.Packaging; using NuGet.Versioning; #else #endif using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Calamari.Common; using Calamari.Common.Commands; using Calamari.Common.Features.Packages.NuGet; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Testing.LogParser; using FluentAssertions; using NuGet; using Octopus.CoreUtilities; using KnownVariables = Calamari.Common.Plumbing.Variables.KnownVariables; using OSPlatform = System.Runtime.InteropServices.OSPlatform; namespace Calamari.Testing { public static class CommandTestBuilder { public static CommandTestBuilder<TCalamari> CreateAsync<TCalamari>(string command) where TCalamari : CalamariFlavourProgramAsync { return new CommandTestBuilder<TCalamari>(command); } public static CommandTestBuilder<TCalamari> CreateAsync<TCommand, TCalamari>() where TCalamari : CalamariFlavourProgramAsync where TCommand : PipelineCommand { return new CommandTestBuilder<TCalamari>(typeof(TCommand).GetCustomAttribute<CommandAttribute>().Name); } public static CommandTestBuilder<TCalamari> Create<TCalamari>(string command) where TCalamari : CalamariFlavourProgram { return new CommandTestBuilder<TCalamari>(command); } public static CommandTestBuilder<TCalamari> Create<TCommand, TCalamari>() where TCalamari : CalamariFlavourProgram where TCommand : ICommand { return new CommandTestBuilder<TCalamari>(typeof(TCommand).GetCustomAttribute<CommandAttribute>().Name); } public static CommandTestBuilderContext WithFilesToCopy(this CommandTestBuilderContext context, string path) { if (File.Exists(path)) { context.Variables.Add(KnownVariables.OriginalPackageDirectoryPath, Path.GetDirectoryName(path)); } else { context.Variables.Add(KnownVariables.OriginalPackageDirectoryPath, path); } context.Variables.Add("Octopus.Test.PackagePath", path); context.Variables.Add("Octopus.Action.Package.FeedId", "FeedId"); return context; } public static CommandTestBuilderContext WithPackage(this CommandTestBuilderContext context, string packagePath, string packageId, string packageVersion) { context.Variables.Add(KnownVariables.OriginalPackageDirectoryPath, Path.GetDirectoryName(packagePath)); context.Variables.Add(TentacleVariables.CurrentDeployment.PackageFilePath, packagePath); context.Variables.Add("Octopus.Action.Package.PackageId", packageId); context.Variables.Add("Octopus.Action.Package.PackageVersion", packageVersion); context.Variables.Add("Octopus.Action.Package.FeedId", "FeedId"); return context; } public static CommandTestBuilderContext WithNewNugetPackage(this CommandTestBuilderContext context, string packageRootPath, string packageId, string packageVersion) { var pathToPackage = Path.Combine(packageRootPath, CreateNugetPackage(packageId, packageVersion, packageRootPath)); return context.WithPackage(pathToPackage, packageId, packageVersion); } static string CreateNugetPackage(string packageId, string packageVersion, string filePath) { var metadata = new ManifestMetadata { #if NETSTANDARD Authors = new [] {"octopus@e2eTests"}, Version = new NuGetVersion(packageVersion), #else Authors = "octopus@e2eTests", Version = packageVersion, #endif Id = packageId, Description = nameof(CommandTestBuilder) }; var packageFileName = $"{packageId}.{metadata.Version}.nupkg"; var builder = new PackageBuilder(); builder.PopulateFiles(filePath, new[] { new ManifestFile { Source = "**" } }); builder.Populate(metadata); using var stream = File.Open(Path.Combine(filePath, packageFileName), FileMode.OpenOrCreate); builder.Save(stream); return packageFileName; } } public class CommandTestBuilder<TCalamariProgram> { readonly string command; readonly List<Action<CommandTestBuilderContext>> arrangeActions; Action<TestCalamariCommandResult>? assertAction; internal CommandTestBuilder(string command) { this.command = command; arrangeActions = new List<Action<CommandTestBuilderContext>>(); } public CommandTestBuilder<TCalamariProgram> WithArrange(Action<CommandTestBuilderContext> arrange) { arrangeActions.Add(arrange); return this; } public CommandTestBuilder<TCalamariProgram> WithAssert(Action<TestCalamariCommandResult> assert) { assertAction = assert; return this; } public async Task<TestCalamariCommandResult> Execute(bool assertWasSuccess = true) { var context = new CommandTestBuilderContext(); List<string> GetArgs(string workingPath) { var args = new List<string> {command}; var varPath = Path.Combine(workingPath, "variables.json"); context.Variables.Save(varPath); args.Add($"--variables={varPath}"); return args; } List<string> InstallTools(string toolsPath) { var extractor = new NupkgExtractor(new InMemoryLog()); var modulePaths = new List<string>(); var addToPath = new List<string>(); var platform = "win-x64"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) platform = "linux-x64"; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) platform = "osx-x64"; foreach (var tool in context.Tools) { var toolPath = Path.Combine(toolsPath, tool.Id); modulePaths.AddRange(tool.GetCompatiblePackage(platform) .SelectValueOr(package => package.BootstrapperModulePaths, Enumerable.Empty<string>()) .Select(s => Path.Combine(toolPath, s))); var toolPackagePath = Path.Combine(Path.GetDirectoryName(AssemblyExtensions.FullLocalPath(Assembly.GetExecutingAssembly())) ?? string.Empty, $"{tool.Id}.nupkg"); if (!File.Exists(toolPackagePath)) throw new Exception($"{tool.Id}.nupkg missing."); extractor.Extract(toolPackagePath, toolPath); var fullPathToTool = tool.SubFolder.None() ? toolPath : Path.Combine(toolPath, tool.SubFolder.Value); if (tool.ToolPathVariableToSet.Some()) context.Variables[tool.ToolPathVariableToSet.Value] = fullPathToTool .Replace("$HOME", "#{env:HOME}") .Replace("$TentacleHome", "#{env:TentacleHome}"); if (tool.AddToPath) addToPath.Add(fullPathToTool); } var modules = string.Join(";", modulePaths); context.Variables["Octopus.Calamari.Bootstrapper.ModulePaths"] = modules; return addToPath; } void Copy(string sourcePath, string destinationPath) { foreach (var dirPath in Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath)); } foreach (var newPath in Directory.EnumerateFiles(sourcePath, "*.*", SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true); } } void CopyFilesToWorkingFolder(string workingPath) { foreach (var (filename, contents) in context.Files) { using var fileStream = File.Create(Path.Combine(workingPath, filename!)); contents.Seek(0, SeekOrigin.Begin); contents.CopyTo(fileStream); } if (!context.withStagedPackageArgument) { var packageId = context.Variables.GetRaw("Octopus.Test.PackagePath"); if (File.Exists(packageId)) { var fileName = new FileInfo(packageId).Name; File.Copy(packageId, Path.Combine(workingPath, fileName)); } else if (Directory.Exists(packageId)) { Copy(packageId, workingPath); } } } async Task<TestCalamariCommandResult> ExecuteActionHandler(List<string> args, string workingFolder, List<string> paths) { var inMemoryLog = new InMemoryLog(); var constructor = typeof(TCalamariProgram).GetConstructor( BindingFlags.Public | BindingFlags.Instance, null, new[] {typeof(ILog)}, new ParameterModifier[0]); if (constructor == null) { throw new Exception( $"{typeof(TCalamariProgram).Name} doesn't seem to have a `public {typeof(TCalamariProgram)}({nameof(ILog)})` constructor."); } var instance = (TCalamariProgram) constructor.Invoke(new object?[] { inMemoryLog }); var methodInfo = typeof(TCalamariProgram).GetMethod("Run", BindingFlags.Instance | BindingFlags.NonPublic); if (methodInfo == null) { throw new Exception($"{typeof(TCalamariProgram).Name}.Run method was not found."); } var exitCode = await ExecuteWrapped(paths, async () => { if (methodInfo.ReturnType.IsGenericType) return await (Task<int>)methodInfo.Invoke(instance, new object?[] { args.ToArray() })!; return (int)methodInfo.Invoke(instance, new object?[] { args.ToArray() })!; }); var serverInMemoryLog = new CalamariInMemoryTaskLog(); var outputFilter = new ScriptOutputFilter(serverInMemoryLog); foreach (var text in inMemoryLog.StandardError) { outputFilter.Write(ProcessOutputSource.StdErr, text); } foreach (var text in inMemoryLog.StandardOut) { outputFilter.Write(ProcessOutputSource.StdOut, text); } return new TestCalamariCommandResult(exitCode, outputFilter.TestOutputVariables, outputFilter.Actions, outputFilter.ServiceMessages, outputFilter.ResultMessage, outputFilter.Artifacts, serverInMemoryLog.ToString(), workingFolder); } foreach (var arrangeAction in arrangeActions) { arrangeAction.Invoke(context); } TestCalamariCommandResult result; using (var working = TemporaryDirectory.Create()) { var workingPath = working.DirectoryPath; //HACK: set the working directory, we will need to modify Calamari to not depend on this var originalWorkingDirectory = Environment.CurrentDirectory; try { Environment.CurrentDirectory = workingPath; using var toolsBasePath = TemporaryDirectory.Create(); var paths = InstallTools(toolsBasePath.DirectoryPath); var args = GetArgs(workingPath); CopyFilesToWorkingFolder(workingPath); result = await ExecuteActionHandler(args, workingPath, paths); if (assertWasSuccess) { result.WasSuccessful.Should().BeTrue($"{command} execute result was unsuccessful"); } assertAction?.Invoke(result); } finally { Environment.CurrentDirectory = originalWorkingDirectory; } } return result; } Task<int> ExecuteWrapped(IReadOnlyCollection<string> paths, Func<Task<int>> func) { if (paths.Count > 0) { var originalPath = Environment.GetEnvironmentVariable("PATH"); try { Environment.SetEnvironmentVariable("PATH", $"{originalPath};{string.Join(";", paths)}", EnvironmentVariableTarget.Process); return func(); } finally { Environment.SetEnvironmentVariable("PATH", originalPath, EnvironmentVariableTarget.Process); } } return func(); } } }<file_sep>using System.Collections.Generic; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; using FluentAssertions; namespace Calamari.Tests.Fixtures.Integration.Scripting { [TestFixture] public class ScriptEngineFixture { private static readonly ScriptSyntax[] ScriptPreferencesNonWindows = new[] { ScriptSyntax.Bash, ScriptSyntax.Python, ScriptSyntax.CSharp, ScriptSyntax.FSharp, ScriptSyntax.PowerShell }; private static readonly ScriptSyntax[] ScriptPreferencesWindows = new[] { ScriptSyntax.PowerShell, ScriptSyntax.Python, ScriptSyntax.CSharp, ScriptSyntax.FSharp, ScriptSyntax.Bash }; [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void DeterminesCorrectScriptTypePreferenceOrderWindows() => DeterminesCorrectScriptTypePreferenceOrder(ScriptPreferencesWindows); [Test] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void DeterminesCorrectScriptTypePreferencesOrderNonWindows() => DeterminesCorrectScriptTypePreferenceOrder(ScriptPreferencesNonWindows); private void DeterminesCorrectScriptTypePreferenceOrder(IEnumerable<ScriptSyntax> expected) { var engine = new ScriptEngine(null); var supportedTypes = engine.GetSupportedTypes(); supportedTypes.Should().Equal(expected); } } }<file_sep>using System; using System.Net; using Calamari.Common.Plumbing.Proxies; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Proxies { [TestFixture] public class ProxySettingsInitializerFixture { const string ProxyUserName = "someuser"; const string ProxyPassword = "<PASSWORD>"; string proxyHost = "proxy-initializer-fixture-good-proxy"; int proxyPort = 1234; [TearDown] public void TearDown() { ResetProxyEnvironmentVariables(); } [Test] public void Initialize_BypassProxy() { SetEnvironmentVariables(false, "", 80, "", ""); AssertBypassProxy(ProxySettingsInitializer.GetProxySettingsFromEnvironment()); } [Test] public void Initialize_UseSystemProxy() { SetEnvironmentVariables(true, "", 80, "", ""); AssertSystemProxySettings(ProxySettingsInitializer.GetProxySettingsFromEnvironment(), false); } [Test] public void Initialize_UseSystemProxyWithCredentials() { SetEnvironmentVariables(true, "", 80, ProxyUserName, ProxyPassword); AssertSystemProxySettings(ProxySettingsInitializer.GetProxySettingsFromEnvironment(), true); } [Test] public void Initialize_CustomProxy() { SetEnvironmentVariables(false, proxyHost, proxyPort, "", ""); AssertCustomProxy(ProxySettingsInitializer.GetProxySettingsFromEnvironment(), false); } [Test] public void Initialize_CustomProxyWithCredentials() { SetEnvironmentVariables(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword); AssertCustomProxy(ProxySettingsInitializer.GetProxySettingsFromEnvironment(), true); } void SetEnvironmentVariables( bool useDefaultProxy, string proxyhost, int proxyPort, string proxyUsername, string proxyPassword) { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy, useDefaultProxy.ToString()); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, proxyhost); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, proxyPort.ToString()); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername, proxyUsername); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword, proxyPassword); } void ResetProxyEnvironmentVariables() { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword, string.Empty); } void AssertCustomProxy(IProxySettings proxySettings, bool hasCredentials) { var proxy = proxySettings.Should().BeOfType<UseCustomProxySettings>() .Subject; proxy.Host.Should().Be(proxyHost); proxy.Port.Should().Be(proxyPort); if (hasCredentials) { proxy.Username.Should().Be(ProxyUserName); proxy.Password.Should().Be(<PASSWORD>); } else { proxy.Username.Should().BeNull(); proxy.Password.Should().BeNull(); } } static void AssertSystemProxySettings(IProxySettings proxySettings, bool hasCredentials) { var proxy = proxySettings.Should().BeOfType<UseSystemProxySettings>() .Subject; if (hasCredentials) { proxy.Username.Should().Be(ProxyUserName); proxy.Password.Should().Be(<PASSWORD>); } else { proxy.Username.Should().BeNull(); proxy.Password.Should().BeNull(); } } void AssertBypassProxy(IProxySettings proxySettings) { proxySettings.Should().BeOfType<BypassProxySettings>(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Proxies; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; using NUnit.Framework.Constraints; namespace Calamari.Tests.Fixtures.Integration.Proxies { [TestFixture] public class ProxyEnvironmentVariablesGeneratorFixture { const string BadproxyUrl = "http://proxy-initializer-fixture-bad-proxy:1234"; const string ProxyUserName = "some@:/user"; const string ProxyPassword = "some@:/password"; const string UrlEncodedProxyUserName = "some%40%3A%2Fuser"; const string UrlEncodedProxyPassword = "<PASSWORD>"; const string proxyHost = "proxy-initializer-fixture-good-proxy"; const int proxyPort = 8888; string proxyUrl = $"http://{proxyHost}:{proxyPort}"; string authentiatedProxyUrl = $"http://{UrlEncodedProxyUserName}:{UrlEncodedProxyPassword}@{proxyHost}:{proxyPort}"; [TearDown] public void TearDown() { ResetProxyEnvironmentVariables(); ResetSystemProxy(); } static void ResetSystemProxy() { if (CalamariEnvironment.IsRunningOnWindows) ProxyRoutines.SetProxy(false).Should().BeTrue(); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void Initialize_HasSystemProxy_NoProxy() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); var result = RunWith(false, "", 80, "", ""); AssertProxyBypassed(result); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void Initialize_HasSystemProxy_UseSystemProxy() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); var result = RunWith(true, "", 80, "", ""); AssertUnauthenticatedSystemProxyUsed(result); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void Initialize_HasSystemProxy_UseSystemProxyWithCredentials() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); var result = RunWith(true, "", 80, ProxyUserName, ProxyPassword); AssertAuthenticatedSystemProxyUsed(result); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void Initialize_HasSystemProxy_CustomProxy() { ProxyRoutines.SetProxy(BadproxyUrl).Should().BeTrue(); var result = RunWith(false, proxyHost, proxyPort, "", ""); AssertUnauthenticatedProxyUsed(result); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void Initialize_HasSystemProxy_CustomProxyWithCredentials() { ProxyRoutines.SetProxy(BadproxyUrl).Should().BeTrue(); var result = RunWith(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword); AssertAuthenticatedProxyUsed(result); } [Test] public void Initialize_NoSystemProxy_NoProxy() { var result = RunWith(false, "", 80, "", ""); AssertProxyBypassed(result); } [Test] public void Initialize_NoSystemProxy_UseSystemProxy() { var result = RunWith(true, "", 80, "", ""); AssertNoProxyChanges(result); } [Test] public void Initialize_NoSystemProxy_UseSystemProxyWithCredentials() { var result = RunWith(true, "", 80, ProxyUserName, ProxyPassword); AssertNoProxyChanges(result); } [Test] public void Initialize_NoSystemProxy_CustomProxy() { var result = RunWith(false, proxyHost, proxyPort, "", ""); AssertUnauthenticatedProxyUsed(result); } [Test] public void Initialize_NoSystemProxy_CustomProxyWithCredentials() { var result = RunWith(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword); AssertAuthenticatedProxyUsed(result); } [TestCase("http_proxy")] [TestCase("https_proxy")] [TestCase("no_proxy")] public void Initialize_OneLowerCaseEnvironmentVariableExists_UpperCaseVariantReturned(string existingVariableName) { var existingValue = "blahblahblah"; Environment.SetEnvironmentVariable(existingVariableName, existingValue); var result = RunWith(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword).ToList(); result.Should().ContainSingle("The existing variable should be duplicated as an upper case variable"); var variable = result.Single(); variable.Key.Should().Be(existingVariableName.ToUpperInvariant()); variable.Value.Should().Be(existingValue); } [TestCase("HTTP_PROXY")] [TestCase("HTTPS_PROXY")] [TestCase("NO_PROXY")] public void Initialize_OneUpperCaseEnvironmentVariableExists_LowerCaseVariantReturned(string existingVariableName) { var existingValue = "blahblahblah"; Environment.SetEnvironmentVariable(existingVariableName, existingValue); var result = RunWith(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword).ToList(); result.Should().ContainSingle("The existing variable should be duplicated as a lower case variable"); var variable = result.Single(); variable.Key.Should().Be(existingVariableName.ToLowerInvariant()); variable.Value.Should().Be(existingValue); } IEnumerable<EnvironmentVariable> RunWith( bool useDefaultProxy, string proxyhost, int proxyPort, string proxyUsername, string proxyPassword) { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy, useDefaultProxy.ToString()); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, proxyhost); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, proxyPort.ToString()); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername, proxyUsername); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword, <PASSWORD>); return ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables(); } void ResetProxyEnvironmentVariables() { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword, string.Empty); Environment.SetEnvironmentVariable("HTTP_PROXY", string.Empty); Environment.SetEnvironmentVariable("http_proxy", string.Empty); Environment.SetEnvironmentVariable("HTTPS_PROXY", string.Empty); Environment.SetEnvironmentVariable("https_proxy", string.Empty); Environment.SetEnvironmentVariable("NO_PROXY", string.Empty); Environment.SetEnvironmentVariable("no_proxy", string.Empty); } void AssertAuthenticatedProxyUsed(IEnumerable<EnvironmentVariable> result) { var httpProxy = result.Should().ContainSingle(kv => kv.Key == "HTTP_PROXY").Subject; var httpsProxy = result.Should().ContainSingle(kv => kv.Key == "HTTPS_PROXY").Subject; var noProxy = result.Should().ContainSingle(kv => kv.Key == "NO_PROXY").Subject; httpProxy.Value.Should().Be(authentiatedProxyUrl, "should use the proxy"); httpsProxy.Value.Should().Be(authentiatedProxyUrl, "should use the proxy"); noProxy.Value.Should().Be("127.0.0.1,localhost,169.254.169.254", "should use the proxy"); } void AssertUnauthenticatedProxyUsed(IEnumerable<EnvironmentVariable> result) { var httpProxy = result.Should().ContainSingle(kv => kv.Key == "HTTP_PROXY").Subject; var httpsProxy = result.Should().ContainSingle(kv => kv.Key == "HTTPS_PROXY").Subject; var noProxy = result.Should().ContainSingle(kv => kv.Key == "NO_PROXY").Subject; httpProxy.Value.Should().Be(proxyUrl, "should use the proxy"); httpsProxy.Value.Should().Be(proxyUrl, "should use the proxy"); noProxy.Value.Should().Be("127.0.0.1,localhost,169.254.169.254", "should use the proxy"); } void AssertNoProxyChanges(IEnumerable<EnvironmentVariable> result) { result.Should().NotContain(kv => kv.Key == "HTTP_PROXY"); result.Should().NotContain(kv => kv.Key == "HTTPS_PROXY"); result.Should().NotContain(kv => kv.Key == "NO_PROXY"); } void AssertProxyBypassed(IEnumerable<EnvironmentVariable> result) { result.Should().NotContain(kv => kv.Key == "HTTP_PROXY"); result.Should().NotContain(kv => kv.Key == "HTTPS_PROXY"); var noProxy = result.Should().ContainSingle(kv => kv.Key == "NO_PROXY").Subject; noProxy.Value.Should().Be("*", "should bypass the proxy"); } void AssertUnauthenticatedSystemProxyUsed(IEnumerable<EnvironmentVariable> output) { #if !NETCORE AssertUnauthenticatedProxyUsed(output); #else AssertNoProxyChanges(output); #endif } void AssertAuthenticatedSystemProxyUsed(IEnumerable<EnvironmentVariable> output) { #if !NETCORE AssertAuthenticatedProxyUsed(output); #else AssertNoProxyChanges(output); #endif } } } <file_sep>using System; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Runtime; using Calamari.Aws.Exceptions; using Calamari.Aws.Integration; using Calamari.Aws.Integration.CloudFormation; using Calamari.CloudAccounts; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Octopus.CoreUtilities; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Deployment.Conventions { public class DeleteCloudFormationStackConvention : CloudFormationInstallationConventionBase { private readonly Func<IAmazonCloudFormation> clientFactory; private readonly Func<RunningDeployment, StackArn> stackProvider; private readonly AwsEnvironmentGeneration environment; private readonly bool waitForComplete; public DeleteCloudFormationStackConvention( AwsEnvironmentGeneration environment, StackEventLogger logger, Func<IAmazonCloudFormation> clientFactory, Func<RunningDeployment, StackArn> stackProvider, bool waitForComplete ): base(logger) { Guard.NotNull(clientFactory, "Client must not be null"); Guard.NotNull(stackProvider, "Stack provider must not be null"); Guard.NotNull(environment, "Aws environment generation may not be null"); this.clientFactory = clientFactory; this.stackProvider = stackProvider; this.waitForComplete = waitForComplete; this.environment = environment; } public override void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private async Task InstallAsync(RunningDeployment deployment) { Guard.NotNull(deployment, "deployment can not be null"); var deploymentStartTime = DateTime.Now; var stack = stackProvider(deployment); if (await clientFactory.StackExistsAsync(stack, StackStatus.Completed) != StackStatus.DoesNotExist) { await DeleteCloudFormation(stack); Log.Info($"Deleted stack called {stack.Value} in region {environment.AwsRegion.SystemName}"); } else { Log.Info($"No stack called {stack.Value} exists in region {environment.AwsRegion.SystemName}"); return; } if (waitForComplete) { await WithAmazonServiceExceptionHandling(async () => { await clientFactory.WaitForStackToComplete(CloudFormationDefaults.StatusWaitPeriod, stack, LogAndThrowRollbacks(clientFactory, stack, true, false, FilterStackEventsSince(deploymentStartTime))); }); } } private Task DeleteCloudFormation(StackArn stack) { Guard.NotNull(stack, "Stack must not be null"); return WithAmazonServiceExceptionHandling(async () => { await clientFactory.DeleteStackAsync(stack); }); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Deployment.PackageRetention; namespace Calamari.Commands { [Command("transfer-package", Description = "Copies a deployment package to a specific directory")] public class TransferPackageCommand : Command { readonly ILog log; private readonly IDeploymentJournalWriter deploymentJournalWriter; readonly IVariables variables; readonly ICalamariFileSystem fileSystem; public TransferPackageCommand(ILog log, IDeploymentJournalWriter deploymentJournalWriter, IVariables variables, ICalamariFileSystem fileSystem) { this.log = log; this.deploymentJournalWriter = deploymentJournalWriter; this.variables = variables; this.fileSystem = fileSystem; } public override int Execute(string[] commandLineArguments) { var packageFile = variables.GetPathToPrimaryPackage(fileSystem, true); if (packageFile == null) // required: true in the above call means it will throw rather than return null, but there's no way to tell the compiler that. And ! doesn't work in older frameworks throw new CommandException("Package File path could not be determined"); var journal = new DeploymentJournal(fileSystem, SemaphoreFactory.Get(), variables); var conventions = new List<IConvention> { new AlreadyInstalledConvention(log, journal), new TransferPackageConvention(log, fileSystem), }; var deployment = new RunningDeployment(packageFile, variables); var conventionRunner = new ConventionProcessor(deployment, conventions, log); try { conventionRunner.RunConventions(); deploymentJournalWriter.AddJournalEntry(deployment, true); } catch (Exception) { deploymentJournalWriter.AddJournalEntry(deployment, false); throw; } return 0; } } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class SecretTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""Secret"", ""metadata"": { ""name"": ""my-secret"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""type"": ""Opaque"", ""data"": { ""x"": ""y"", ""a"": ""b"" } }"; var secret = ResourceFactory.FromJson(input, new Options()); secret.Should().BeEquivalentTo(new { Kind = "Secret", Name = "my-secret", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Data = 2, Type = "Opaque", ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful }); } } } <file_sep>#!/bin/bash dockerUsername=$(get_octopusvariable "DockerUsername") dockerPassword=$(get_octopusvariable "DockerPassword") feedUri=$(get_octopusvariable "FeedUri") echo "##octopus[stdout-verbose]" docker -v echo "##octopus[stdout-default]" if [ ! -z $dockerUsername ]; then # docker 17.07 throws a warning to stderr if you use the --password param dockerVersion=`docker version --format '{{.Client.Version}}'` parsedVersion=(${dockerVersion//./ }) if (( parsedVersion[0] > 17 || (parsedVersion[0] == 17 && parsedVersion[1] > 6) )); then echo $dockerPassword | docker login --username $dockerUsername --password-stdin $feedUri 2>&1 else docker login --username $dockerUsername --password $<PASSWORD>Password $feedUri 2>&1 fi rc=$?; if [[ $rc != 0 ]]; then echo "Login Failed" exit $rc; fi fi<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Autofac; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; namespace Calamari.Tests.Helpers { class TestProgram : Program { private bool registerTestAssembly = true; public TestProgram(ILog log = null) : base(log = log ?? new InMemoryLog()) { TestLog = log as InMemoryLog; } internal InMemoryLog TestLog { get; } ICommandWithArgs CommandOverride { get; set; } public bool StubWasCalled { get; set; } public IVariables VariablesOverride { get; set; } public int RunWithArgs(string[] args) { return Run(args); } public int RunStubCommand() { registerTestAssembly = false; CommandOverride = new StubCommand(() => StubWasCalled = true); return Run(new [] {"stub"}); } protected override Assembly GetProgramAssemblyToRegister() { return typeof(Program).Assembly; } protected override IEnumerable<Assembly> GetAllAssembliesToRegister() { var allAssemblies = base.GetAllAssembliesToRegister(); if (registerTestAssembly) { allAssemblies = allAssemblies.Concat(new[] { typeof(TestProgram).Assembly }); } return allAssemblies; } protected override void ConfigureContainer(ContainerBuilder builder, CommonOptions options) { // Register CommandOverride so it shows up first in IEnumerable if (CommandOverride != null) builder.RegisterInstance(CommandOverride).WithMetadata("Name", "stub").As<ICommandWithArgs>(); base.ConfigureContainer(builder, options); // Register after base so Singleton gets overridden if (VariablesOverride != null) builder.RegisterInstance(VariablesOverride).As<IVariables>(); } } [Command("stub")] class StubCommand : ICommandWithArgs { readonly Action callback; public StubCommand(Action callback) { this.callback = callback; } public void GetHelp(TextWriter writer) { throw new NotImplementedException(); } public int Execute(string[] commandLineArguments) { callback(); return 0; } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting { public interface IScriptExecutor { CommandResult Execute( Script script, IVariables variables, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars = null); } }<file_sep>using System; using System.Globalization; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Packages.Download; using Octopus.Versioning; namespace Calamari.Commands { [Command("download-package", Description = "Downloads a NuGet package from a NuGet feed")] public class DownloadPackageCommand : Command { private readonly IScriptEngine scriptEngine; readonly IVariables variables; readonly ICalamariFileSystem fileSystem; readonly ILog log; readonly ICommandLineRunner commandLineRunner; string packageId; string packageVersion; bool forcePackageDownload; string feedId; string feedUri; string feedUsername; string feedPassword; string maxDownloadAttempts = "5"; string attemptBackoffSeconds = "10"; private FeedType feedType = FeedType.NuGet; private VersionFormat versionFormat = VersionFormat.Semver; public DownloadPackageCommand( IScriptEngine scriptEngine, IVariables variables, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner, ILog log) { this.scriptEngine = scriptEngine; this.variables = variables; this.fileSystem = fileSystem; this.log = log; this.commandLineRunner = commandLineRunner; Options.Add("packageId=", "Package ID to download", v => packageId = v); Options.Add("packageVersion=", "Package version to download", v => packageVersion = v); Options.Add("packageVersionFormat=", $"[Optional] Format of version. Options {string.Join(", ", Enum.GetNames(typeof(VersionFormat)))}. Defaults to `{VersionFormat.Semver}`.", v => { if (!Enum.TryParse(v, out VersionFormat format)) { throw new CommandException($"The provided version format `{format}` is not recognised."); } versionFormat = format; }); Options.Add("feedId=", "Id of the feed", v => feedId = v); Options.Add("feedUri=", "URL to feed", v => feedUri = v); Options.Add("feedUsername=", "[Optional] Username to use for an authenticated feed", v => feedUsername = v); Options.Add("feedPassword=", "[Optional] Password to use for an authenticated feed", v => feedPassword = v); Options.Add("feedType=", $"[Optional] Type of feed. Options {string.Join(", ", Enum.GetNames(typeof(FeedType)))}. Defaults to `{FeedType.NuGet}`.", v => { if (!Enum.TryParse(v, out FeedType type)) { throw new CommandException($"The provided feed type `{type}` is not recognised."); } feedType = type; }); Options.Add("attempts=", $"[Optional] The number of times to attempt downloading the package. Default: {maxDownloadAttempts}", v => maxDownloadAttempts = v); Options.Add("attemptBackoffSeconds=", $"[Optional] The number of seconds to apply as a linear backoff between each download attempt. Default: {attemptBackoffSeconds}", v => attemptBackoffSeconds = v); Options.Add("forcePackageDownload", "[Optional, Flag] if specified, the package will be downloaded even if it is already in the package cache", v => forcePackageDownload = true); } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); try { CheckArguments( packageId, packageVersion, feedId, feedUri, feedUsername, feedPassword, maxDownloadAttempts, attemptBackoffSeconds, out var version, out var uri, out var parsedMaxDownloadAttempts, out var parsedAttemptBackoff); var packageDownloaderStrategy = new PackageDownloaderStrategy(log, scriptEngine, fileSystem, commandLineRunner, variables); var pkg = packageDownloaderStrategy.DownloadPackage( packageId, version, feedId, uri, feedType, feedUsername, feedPassword, forcePackageDownload, parsedMaxDownloadAttempts, parsedAttemptBackoff); log.VerboseFormat("Package {0} v{1} successfully downloaded from feed: '{2}'", packageId, version, feedUri); log.SetOutputVariableButDoNotAddToVariables("StagedPackage.Hash", pkg.Hash); log.SetOutputVariableButDoNotAddToVariables("StagedPackage.Size", pkg.Size.ToString(CultureInfo.InvariantCulture)); log.SetOutputVariableButDoNotAddToVariables("StagedPackage.FullPathOnRemoteMachine", pkg.FullFilePath); } catch (Exception ex) { log.ErrorFormat("Failed to download package {0} v{1} from feed: '{2}'", packageId, packageVersion, feedUri); return ConsoleFormatter.PrintError(log, ex); } return 0; } // ReSharper disable UnusedParameter.Local void CheckArguments( string packageId, string packageVersion, string feedId, string feedUri, string feedUsername, string feedPassword, string maxDownloadAttempts, string attemptBackoffSeconds, out IVersion version, out Uri uri, out int parsedMaxDownloadAttempts, out TimeSpan parsedAttemptBackoff) { Guard.NotNullOrWhiteSpace(packageId, "No package ID was specified. Please pass --packageId YourPackage"); Guard.NotNullOrWhiteSpace(packageVersion, "No package version was specified. Please pass --packageVersion 1.0.0.0"); Guard.NotNullOrWhiteSpace(feedId, "No feed ID was specified. Please pass --feedId feed-id"); Guard.NotNullOrWhiteSpace(feedUri, "No feed URI was specified. Please pass --feedUri https://url/to/nuget/feed"); version = VersionFactory.TryCreateVersion(packageVersion, versionFormat); if (version == null) { throw new CommandException($"Package version '{packageVersion}' specified is not a valid {versionFormat.ToString()} version string"); } if (!Uri.TryCreate(feedUri, UriKind.Absolute, out uri)) throw new CommandException($"URI specified '{feedUri}' is not a valid URI"); if (!String.IsNullOrWhiteSpace(feedUsername) && String.IsNullOrWhiteSpace(feedPassword)) throw new CommandException("A username was specified but no password was provided. Please pass --feedPassword \"<PASSWORD>\""); if (!int.TryParse(maxDownloadAttempts, out parsedMaxDownloadAttempts)) throw new CommandException($"The requested number of download attempts '{maxDownloadAttempts}' is not a valid integer number"); if (parsedMaxDownloadAttempts <= 0) throw new CommandException("The requested number of download attempts should be more than zero"); int parsedAttemptBackoffSeconds; if (!int.TryParse(attemptBackoffSeconds, out parsedAttemptBackoffSeconds)) throw new CommandException($"Retry requested download attempt retry backoff '{attemptBackoffSeconds}' is not a valid integer number of seconds"); if (parsedAttemptBackoffSeconds < 0) throw new CommandException("The requested download attempt retry backoff should be a positive integer number of seconds"); parsedAttemptBackoff = TimeSpan.FromSeconds(parsedAttemptBackoffSeconds); } } }<file_sep>#if USE_NUGET_V2_LIBS using System; using System.Net; using System.Threading; namespace Calamari.Tests.Fixtures.Integration.Packages { public class TestHttpServer : IDisposable { readonly HttpListener listener; public int Port { get; } public TimeSpan ResponseTime { get; } public string BaseUrl => $"http://localhost:{Port}"; public TestHttpServer(int port, TimeSpan responseTime) { Port = port; ResponseTime = responseTime; listener = new HttpListener { Prefixes = { BaseUrl + "/" } }; listener.Start(); listener.BeginGetContext(OnRequest, listener); } void OnRequest(IAsyncResult result) { var context = listener.EndGetContext(result); Thread.Sleep(ResponseTime); var response = context.Response; response.StatusCode = 200; response.OutputStream.Close(); } public void Dispose() { listener.Stop(); } } } #endif<file_sep>using System; using System.Diagnostics; using System.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace Calamari { public static class AssemblyExtensions { public static string GetInformationalVersion(this Assembly assembly) { var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); return fileVersionInfo.ProductVersion; } public static string FullLocalPath(this Assembly assembly) { var codeBase = assembly.CodeBase; var uri = new UriBuilder(codeBase); var root = Uri.UnescapeDataString(uri.Path); root = root.Replace('/', Path.DirectorySeparatorChar); return root; } } }<file_sep>using System; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureCloudService { public class FindCloudServicePackageBehaviour : IAfterPackageExtractionBehaviour { readonly ICalamariFileSystem fileSystem; public FindCloudServicePackageBehaviour(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { context.Variables.Set(SpecialVariables.Action.Azure.CloudServicePackagePath, FindPackage(context.CurrentDirectory)); return this.CompletedTask(); } string FindPackage(string workingDirectory) { var packages = fileSystem.EnumerateFiles(workingDirectory, "*.cspkg").ToList(); if (packages.Count == 0) { // Try subdirectories packages = fileSystem.EnumerateFilesRecursively(workingDirectory, "*.cspkg").ToList(); } if (packages.Count == 0) { throw new CommandException("Your package does not appear to contain any Azure Cloud Service package (.cspkg) files."); } if (packages.Count > 1) { throw new CommandException("Your deployment package contains more than one Cloud Service package (.cspkg) file, which is unsupported. Files: " + string.Concat(packages.Select(p => Environment.NewLine + " - " + p))); } return packages.Single(); } } }<file_sep>#if IIS_SUPPORT using System; using Calamari.Integration.Iis; using Calamari.Testing.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Iis { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class IisFixture { readonly WebServerSupport webServer = WebServerSupport.AutoDetect(); string siteName; [SetUp] public void SetUp() { siteName = "Test-" + Guid.NewGuid(); webServer.CreateWebSiteOrVirtualDirectory(siteName, "/", "C:\\InetPub\\wwwroot", 1081); webServer.CreateWebSiteOrVirtualDirectory(siteName, "/Foo", "C:\\InetPub\\wwwroot", 1081); webServer.CreateWebSiteOrVirtualDirectory(siteName, "/Foo/Bar/Baz", "C:\\InetPub\\wwwroot", 1081); } [Test] public void CanUpdateIisSite() { var server = new InternetInformationServer(); var success = server.OverwriteHomeDirectory(siteName, "C:\\Windows\\system32", false); Assert.IsTrue(success, "Home directory was not overwritten"); var path = webServer.GetHomeDirectory(siteName, "/"); Assert.AreEqual("C:\\Windows\\system32", path); } [Test] public void CanUpdateIisSiteWithVirtualDirectory() { var server = new InternetInformationServer(); var success = server.OverwriteHomeDirectory(siteName + "/Foo", "C:\\Windows\\Microsoft.NET", false); Assert.IsTrue(success, "Home directory was not overwritten"); var path = webServer.GetHomeDirectory(siteName, "/Foo"); Assert.AreEqual("C:\\Windows\\Microsoft.NET", path); } [Test] public void CanUpdateIisSiteWithNestedVirtualDirectory() { var server = new InternetInformationServer(); var success = server.OverwriteHomeDirectory(siteName + "/Foo/Bar/Baz", "C:\\Windows\\Microsoft.NET\\Framework", false); Assert.IsTrue(success, "Home directory was not overwritten"); var path = webServer.GetHomeDirectory(siteName, "/Foo/Bar/Baz"); Assert.AreEqual("C:\\Windows\\Microsoft.NET\\Framework", path); } [TearDown] public void TearDown() { webServer.DeleteWebSite(siteName); } } } #endif<file_sep>#if AWS using System.Linq; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using System.Threading.Tasks; using System; using System.Collections.Generic; using System.IO; using System.Net; using Amazon; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using Calamari.Aws.Commands; using Calamari.Aws.Deployment; using Calamari.Aws.Integration.S3; using Calamari.Aws.Serialization; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Extensions; using Calamari.Serialization; using Calamari.Tests.Fixtures.Deployment.Packages; using FluentAssertions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using NUnit.Framework; using Octopus.CoreUtilities.Extensions; using Octostache; using Calamari.Testing; using Calamari.Testing.Helpers; using SharpCompress.Archives.Zip; namespace Calamari.Tests.AWS { [TestFixture] [Category(TestCategory.RunOnceOnWindowsAndLinux)] public class S3FixtureForExistingBucket : S3Fixture { // S3 Bucket operations are only eventually consistent (https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html#ConsistencyModel), // For this fixture, we pre-create the bucket to avoid any timing issues where we get told "Bucket does not exist" when trying to validate // what we uploaded. Bucket creation is tested in S3FixtureForNewBucket. [OneTimeSetUp] public Task SetUpInfrastructure() { return Validate(async client => { await client.PutBucketAsync(bucketName); await client.PutBucketTaggingAsync(bucketName, new List<Tag> { new Tag { Key = "VantaOwner", Value = "<EMAIL>" }, new Tag { Key = "VantaNonProd", Value = "true" }, new Tag { Key = "VantaNoAlert", Value = "Ephemeral bucket created during unit tests and not used in production" }, new Tag { Key = "VantaContainsUserData", Value = "false" }, new Tag { Key = "VantaUserDataStored", Value = "N/A" }, new Tag { Key = "VantaDescription", Value = "Ephemeral bucket created during unit tests" } }); }); } [Test] public async Task UploadPackage1() { TestContext.WriteLine("Region: " + region); var fileSelections = new List<S3TargetPropertiesBase> { new S3MultiFileSelectionProperties { Pattern = "Content/**/*", Type = S3FileSelectionTypes.MultipleFiles, StorageClass = "STANDARD", CannedAcl = "private" }, new S3SingleFileSelectionProperties { Path = "Extra/JavaScript.js", Type = S3FileSelectionTypes.SingleFile, StorageClass = "STANDARD", CannedAcl = "private", BucketKeyBehaviour = BucketKeyBehaviourType.Filename } }; var prefix = Upload("Package1", fileSelections); await Validate(async client => { await client.GetObjectAsync(bucketName, $"{prefix}Resources/TextFile.txt"); await client.GetObjectAsync(bucketName, $"{prefix}root/Page.html"); await client.GetObjectAsync(bucketName, $"{prefix}Extra/JavaScript.js"); }); } [Test] public async Task UploadPackage2() { var fileSelections = new List<S3TargetPropertiesBase> { new S3MultiFileSelectionProperties { Pattern = "**/Things/*", Type = S3FileSelectionTypes.MultipleFiles, StorageClass = "STANDARD", CannedAcl = "private" } }; var prefix = Upload("Package2", fileSelections); await Validate(async client => { await client.GetObjectAsync(bucketName, $"{prefix}Wild/Things/TextFile2.txt"); try { await client.GetObjectAsync(bucketName, $"{prefix}Wild/Ignore/TextFile1.txt"); } catch (AmazonS3Exception e) { if (e.StatusCode != HttpStatusCode.NotFound) { throw; } } }); } [Test] public async Task UploadPackage3() { var fileSelections = new List<S3TargetPropertiesBase> { new S3MultiFileSelectionProperties { Pattern = "*.json", Type = S3FileSelectionTypes.MultipleFiles, StorageClass = "STANDARD", CannedAcl = "private", StructuredVariableSubstitutionPatterns = "*.json" } }; var variables = new CalamariVariables(); variables.Set("Property1:Property2:Value", "InjectedValue"); var prefix = Upload("Package3", fileSelections, variables); await Validate(async client => { var file = await client.GetObjectAsync(bucketName, $"{prefix}file.json"); var text = new StreamReader(file.ResponseStream).ReadToEnd(); JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue"); }); } [Test] public async Task UploadPackage3Complete() { var packageOptions = new List<S3TargetPropertiesBase> { new S3PackageOptions() { StorageClass = "STANDARD", CannedAcl = "private", StructuredVariableSubstitutionPatterns = "*.json", BucketKeyBehaviour = BucketKeyBehaviourType.Filename, } }; var variables = new CalamariVariables(); variables.Set("Property1:Property2:Value", "InjectedValue"); var prefix = Upload("Package3", packageOptions, variables, S3TargetMode.EntirePackage); await Validate(async client => { var file = await client.GetObjectAsync(bucketName, $"{prefix}Package3.1.0.0.zip"); var memoryStream = new MemoryStream(); await file.ResponseStream.CopyToAsync(memoryStream); var text = await new StreamReader(ZipArchive.Open(memoryStream).Entries.First(entry => entry.Key == "file.json").OpenEntryStream()).ReadToEndAsync(); JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue"); }); } [Test] public void UploadPackageWithContentHashAppended() { var packageOptions = new List<S3TargetPropertiesBase> { new S3PackageOptions() { StorageClass = "STANDARD", CannedAcl = "private", StructuredVariableSubstitutionPatterns = "*.json", BucketKeyBehaviour = BucketKeyBehaviourType.FilenameWithContentHash, } }; var variables = new CalamariVariables(); variables.Set("Property1:Property2:Value", "InjectedValue"); Upload("Package3", packageOptions, variables, S3TargetMode.EntirePackage); } [Test] public async Task UploadPackage3Individual() { var fileSelections = new List<S3TargetPropertiesBase> { new S3SingleFileSelectionProperties { Path = "file.json", Type = S3FileSelectionTypes.SingleFile, StorageClass = "STANDARD", CannedAcl = "private", BucketKeyBehaviour = BucketKeyBehaviourType.Custom, BucketKey = "myfile.json", PerformStructuredVariableSubstitution = true } }; var variables = new CalamariVariables(); variables.Set("Property1:Property2:Value", "InjectedValue"); Upload("Package3", fileSelections, variables); await Validate(async client => { var file = await client.GetObjectAsync(bucketName, $"myfile.json"); var text = new StreamReader(file.ResponseStream).ReadToEnd(); JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue"); }); } IDictionary<string, string> specialHeaders = new Dictionary<string, string>() { { "Cache-Control", "max-age=123" }, { "Content-Disposition", "some disposition" }, { "Content-Encoding", "some-encoding" }, { "Content-Type", "application/html" }, { "Expires", DateTime.UtcNow.AddDays(1).ToString("r") }, // Need to use RFC1123 format to match how the request is serialized { "x-amz-website-redirect-location", "/anotherPage.html" }, }; IDictionary<string, string> userDefinedMetadata = new Dictionary<string, string>() { { "Expect", "some-expect" }, { "Content-MD5", "somemd5" }, { "Content-Length", "12345" }, { "x-amz-tagging", "sometag" }, { "x-amz-storage-class", "GLACIER" }, { "x-amz-meta", "somemeta" } }; [Test] public async Task UploadPackageWithMetadata() { var fileSelections = new List<S3TargetPropertiesBase> { new S3SingleFileSelectionProperties { Path = "Extra/JavaScript.js", Type = S3FileSelectionTypes.SingleFile, StorageClass = "STANDARD", CannedAcl = "private", BucketKeyBehaviour = BucketKeyBehaviourType.Filename, Metadata = specialHeaders.Concat(userDefinedMetadata).ToList(), Tags = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("Environment", "Test") } } }; var prefix = Upload("Package1", fileSelections); await Validate(async client => { var response = await client.GetObjectAsync(bucketName, $"{prefix}Extra/JavaScript.js"); var headers = response.Headers; var metadata = response.Metadata; foreach (var specialHeader in specialHeaders) { if (specialHeader.Key == "Expires") { //There's a serialization bug in Json.Net that ends up changing the time to local. //Fix this assertion once that's done. var expectedDate = DateTime.Parse(specialHeader.Value.TrimEnd('Z')).ToUniversalTime(); response.Expires.Should().Be(expectedDate); } else if (specialHeader.Key == "x-amz-website-redirect-location") { response.WebsiteRedirectLocation.Should().Be(specialHeader.Value); } else headers[specialHeader.Key].Should().Be(specialHeader.Value); } foreach (var userMetadata in userDefinedMetadata) metadata["x-amz-meta-" + userMetadata.Key.ToLowerInvariant()] .Should() .Be(userMetadata.Value); response.TagCount.Should().Be(1); }); } [Test] [TestCase("TestZipPackage", "1.0.0", "zip")] [TestCase("TestJarPackage", "0.0.1-beta", "jar")] public async Task SubstituteVariablesAndUploadZipArchives(string packageId, string packageVersion, string packageExtension) { var fileName = $"{packageId}.{packageVersion}.{packageExtension}"; var packageOptions = new List<S3PackageOptions> { new S3PackageOptions { StorageClass = "STANDARD", CannedAcl = "private", StructuredVariableSubstitutionPatterns = "*.json", BucketKeyBehaviour = BucketKeyBehaviourType.Filename, } }; var variables = new CalamariVariables(); variables.Set("Property1:Property2:Value", "InjectedValue"); var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", fileName); var prefix = UploadEntireCompressedPackage(packageFilePath, packageId, packageVersion, packageOptions, variables); await Validate(async client => { var file = await client.GetObjectAsync(bucketName, $"{prefix}{fileName}"); var memoryStream = new MemoryStream(); await file.ResponseStream.CopyToAsync(memoryStream); var text = await new StreamReader(ZipArchive.Open(memoryStream).Entries.First(entry => entry.Key == "file.json").OpenEntryStream()).ReadToEndAsync(); JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue"); memoryStream.Close(); }); } [Test] public async Task SubstituteVariablesAndUploadTarArchives() { const string packageId = "TestTarPackage"; const string packageVersion = "0.0.1"; const string packageExtension = "tar"; var fileName = $"{packageId}.{packageVersion}.{packageExtension}"; var packageOptions = new List<S3PackageOptions> { new S3PackageOptions { StorageClass = "STANDARD", CannedAcl = "private", StructuredVariableSubstitutionPatterns = "*.json", BucketKeyBehaviour = BucketKeyBehaviourType.Filename, } }; var variables = new CalamariVariables(); variables.Set("Property1:Property2:Value", "InjectedValue"); var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", fileName); var prefix = UploadEntireCompressedPackage(packageFilePath, packageId, packageVersion, packageOptions, variables); await Validate(async client => { var file = await client.GetObjectAsync(bucketName, $"{prefix}{fileName}"); var tempFileName = Path.GetTempFileName(); var tempDirectoryName = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(tempFileName)); try { using (var fs = File.OpenWrite(tempFileName)) { await file.ResponseStream.CopyToAsync(fs); } var log = new InMemoryLog(); var extractor = new TarPackageExtractor(log); extractor.Extract(tempFileName, tempDirectoryName); var text = File.ReadAllText(Path.Combine(tempDirectoryName, "file.json")); JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue"); } finally { File.Delete(tempFileName); Directory.Delete(tempDirectoryName, true); } }); } [Test] public async Task SubstituteVariablesAndUploadTarGzipArchives() { const string packageId = "TestTarGzipPackage"; const string packageVersion = "0.0.1"; const string packageExtension = "tar.gz"; var fileName = $"{packageId}.{packageVersion}.{packageExtension}"; var packageOptions = new List<S3PackageOptions> { new S3PackageOptions { StorageClass = "STANDARD", CannedAcl = "private", StructuredVariableSubstitutionPatterns = "*.json", BucketKeyBehaviour = BucketKeyBehaviourType.Filename, } }; var variables = new CalamariVariables(); variables.Set("Property1:Property2:Value", "InjectedValue"); var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", fileName); var prefix = UploadEntireCompressedPackage(packageFilePath, packageId, packageVersion, packageOptions, variables); await Validate(async client => { var file = await client.GetObjectAsync(bucketName, $"{prefix}{fileName}"); var tempFileName = Path.GetTempFileName(); var tempDirectoryName = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(tempFileName)); try { using (var fs = File.OpenWrite(tempFileName)) { await file.ResponseStream.CopyToAsync(fs); } var log = new InMemoryLog(); var extractor = new TarGzipPackageExtractor(log); extractor.Extract(tempFileName, tempDirectoryName); var text = File.ReadAllText(Path.Combine(tempDirectoryName, "file.json")); JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue"); } finally { File.Delete(tempFileName); Directory.Delete(tempDirectoryName, true); } }); } [Test] public async Task SubstituteVariablesAndUploadTarBZip2Archives() { const string packageId = "TestTarBzip2Package"; const string packageVersion = "0.0.1"; const string packageExtension = "tar.bz2"; var fileName = $"{packageId}.{packageVersion}.{packageExtension}"; var packageOptions = new List<S3PackageOptions> { new S3PackageOptions { StorageClass = "STANDARD", CannedAcl = "private", StructuredVariableSubstitutionPatterns = "*.json", BucketKeyBehaviour = BucketKeyBehaviourType.Filename, } }; var variables = new CalamariVariables(); variables.Set("Property1:Property2:Value", "InjectedValue"); var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", fileName); var prefix = UploadEntireCompressedPackage(packageFilePath, packageId, packageVersion, packageOptions, variables); await Validate(async client => { var file = await client.GetObjectAsync(bucketName, $"{prefix}{fileName}"); var tempFileName = Path.GetTempFileName(); var tempDirectoryName = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(tempFileName)); try { using (var fs = File.OpenWrite(tempFileName)) { await file.ResponseStream.CopyToAsync(fs); } var log = new InMemoryLog(); var extractor = new TarBzipPackageExtractor(log); extractor.Extract(tempFileName, tempDirectoryName); var text = File.ReadAllText(Path.Combine(tempDirectoryName, "file.json")); JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue"); } finally { File.Delete(tempFileName); Directory.Delete(tempDirectoryName, true); } }); } } [TestFixture] [Category(TestCategory.RunOnceOnWindowsAndLinux)] public class S3FixtureForNewBucket : S3Fixture { [Test] public async Task UploadPackage1() { TestContext.WriteLine("Region: " + region); var fileSelections = new List<S3TargetPropertiesBase> { new S3MultiFileSelectionProperties { Pattern = "Content/**/*", Type = S3FileSelectionTypes.MultipleFiles, StorageClass = "STANDARD", CannedAcl = "private" }, new S3SingleFileSelectionProperties { Path = "Extra/JavaScript.js", Type = S3FileSelectionTypes.SingleFile, StorageClass = "STANDARD", CannedAcl = "private", BucketKeyBehaviour = BucketKeyBehaviourType.Filename } }; var prefix = Upload("Package1", fileSelections); await DoSafelyWithRetries(async () => { await Validate(async client => { await client.GetObjectAsync(bucketName, $"{prefix}Resources/TextFile.txt"); await client.GetObjectAsync(bucketName, $"{prefix}root/Page.html"); await client.GetObjectAsync(bucketName, $"{prefix}Extra/JavaScript.js"); }); }, 5); } async Task DoSafelyWithRetries(Func<Task> action, int maxRetries) { for (int retry = 1; retry <= maxRetries; retry++) { try { await action(); TestContext.WriteLine($"Validate succeeded on retry {retry}"); break; } catch (Exception e) { TestContext.WriteLine($"Validate failed on retry {retry}: {e.Message}"); if (retry == maxRetries) throw; await Task.Delay(500); } } } } public abstract class S3Fixture { protected string region; protected string bucketName; public S3Fixture() { region = RegionRandomiser.GetARegion(); bucketName = $"calamari-s3fixture-{Guid.NewGuid():N}"; } [OneTimeTearDown] public Task TearDownInfrastructure() { return Validate(async client => { var response = await client.ListObjectsAsync(bucketName); foreach (var s3Object in response.S3Objects) { await client.DeleteObjectAsync(bucketName, s3Object.Key); } await client.DeleteBucketAsync(bucketName); }); } protected static JsonSerializerSettings GetEnrichedSerializerSettings() { return JsonSerialization.GetDefaultSerializerSettings() .Tee(x => { x.Converters.Add(new FileSelectionsConverter()); x.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); } protected async Task Validate(Func<AmazonS3Client, Task> execute) { var credentials = new BasicAWSCredentials( ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey), ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); var config = new AmazonS3Config { AllowAutoRedirect = true, RegionEndpoint = RegionEndpoint.GetBySystemName(region) }; using (var client = new AmazonS3Client(credentials, config)) { await execute(client); } } protected string Upload(string packageName, List<S3TargetPropertiesBase> propertiesList, VariableDictionary customVariables = null, S3TargetMode s3TargetMode = S3TargetMode.FileSelections) { const string packageVersion = "1.0.0"; var bucketKeyPrefix = $"calamaritest/{Guid.NewGuid():N}/"; var variables = new CalamariVariables(); propertiesList.ForEach(properties => { switch (properties) { case S3MultiFileSelectionProperties multiFileSelectionProperties: multiFileSelectionProperties.BucketKeyPrefix = bucketKeyPrefix; variables.Set(AwsSpecialVariables.S3.FileSelections, JsonConvert.SerializeObject(propertiesList, GetEnrichedSerializerSettings())); break; case S3SingleFileSelectionProperties singleFileSelectionProperties: singleFileSelectionProperties.BucketKeyPrefix = bucketKeyPrefix; variables.Set(AwsSpecialVariables.S3.FileSelections, JsonConvert.SerializeObject(propertiesList, GetEnrichedSerializerSettings())); break; case S3PackageOptions packageOptions: packageOptions.BucketKeyPrefix = bucketKeyPrefix; variables.Set(AwsSpecialVariables.S3.PackageOptions, JsonConvert.SerializeObject(packageOptions, GetEnrichedSerializerSettings())); variables.Set(PackageVariables.PackageId, packageName); variables.Set(PackageVariables.PackageVersion, packageVersion); break; } }); var variablesFile = Path.GetTempFileName(); variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount"); variables.Set("AWSAccount.AccessKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey)); variables.Set("AWSAccount.SecretKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); variables.Set("Octopus.Action.Aws.Region", region); if (customVariables != null) variables.Merge(customVariables); variables.Save(variablesFile); var packageDirectory = TestEnvironment.GetTestPath("AWS", "S3", packageName); using (var package = new TemporaryFile(PackageBuilder.BuildSimpleZip(packageName, packageVersion, packageDirectory))) using (new TemporaryFile(variablesFile)) { var log = new InMemoryLog(); var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); var command = new UploadAwsS3Command( log, variables, fileSystem, new SubstituteInFiles(log, fileSystem, new FileSubstituter(log, fileSystem), variables), new ExtractPackage(new CombinedPackageExtractor(log, variables, new CommandLineRunner(log, variables)), fileSystem, variables, log), new StructuredConfigVariablesService(new PrioritisedList<IFileFormatVariableReplacer> { new JsonFormatVariableReplacer(fileSystem, log), new XmlFormatVariableReplacer(fileSystem, log), new YamlFormatVariableReplacer(fileSystem, log), new PropertiesFormatVariableReplacer(fileSystem, log), }, variables, fileSystem, log) ); var result = command.Execute(new[] { "--package", $"{package.FilePath}", "--variables", $"{variablesFile}", "--bucket", bucketName, "--targetMode", s3TargetMode.ToString() }); result.Should().Be(0); } return bucketKeyPrefix; } protected string UploadEntireCompressedPackage(string packageFilePath, string packageId, string packageVersion, List<S3PackageOptions> propertiesList, VariableDictionary customVariables = null) { var bucketKeyPrefix = $"calamaritest/{Guid.NewGuid():N}/"; var variables = new CalamariVariables(); propertiesList.ForEach(properties => { properties.BucketKeyPrefix = bucketKeyPrefix; variables.Set(AwsSpecialVariables.S3.PackageOptions, JsonConvert.SerializeObject(properties, GetEnrichedSerializerSettings())); variables.Set(PackageVariables.PackageId, packageId); variables.Set(PackageVariables.PackageVersion, packageVersion); }); var variablesFile = Path.GetTempFileName(); variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount"); variables.Set("AWSAccount.AccessKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey)); variables.Set("AWSAccount.SecretKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); variables.Set("Octopus.Action.Aws.Region", region); if (customVariables != null) variables.Merge(customVariables); variables.Save(variablesFile); using (new TemporaryFile(variablesFile)) { var log = new InMemoryLog(); var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); var command = new UploadAwsS3Command( log, variables, fileSystem, new SubstituteInFiles(log, fileSystem, new FileSubstituter(log, fileSystem), variables), new ExtractPackage(new CombinedPackageExtractor(log, variables, new CommandLineRunner(log, variables)), fileSystem, variables, log), new StructuredConfigVariablesService(new PrioritisedList<IFileFormatVariableReplacer> { new JsonFormatVariableReplacer(fileSystem, log), new XmlFormatVariableReplacer(fileSystem, log), new YamlFormatVariableReplacer(fileSystem, log), new PropertiesFormatVariableReplacer(fileSystem, log), }, variables, fileSystem, log) ); var result = command.Execute(new[] { "--package", $"{packageFilePath}", "--variables", $"{variablesFile}", "--bucket", bucketName, "--targetMode", S3TargetMode.EntirePackage.ToString() }); result.Should().Be(0); } return bucketKeyPrefix; } } } #endif<file_sep>using System.Text.RegularExpressions; using Calamari.Common.Plumbing; namespace Calamari.Aws.Integration.S3 { public class ETag { private static readonly Regex EtagRegex = new Regex("(?<=\")(?<etag>\\w+)(?=\")"); public ETag(string value) { Guard.NotNullOrWhiteSpace(value, "Etag value should may not be null or empty."); var match = EtagRegex.Match(value); RawValue = value; Hash = match.Success ? match.Groups["etag"].Value : RawValue; } public string RawValue { get; } public string Hash { get; } } }<file_sep>#if IIS_SUPPORT using System; using System.DirectoryServices; using System.Linq; using Calamari.Common.Plumbing.Logging; namespace Calamari.Integration.Iis { public class WebServerSixSupport : WebServerSupport { public override void CreateWebSiteOrVirtualDirectory(string webSiteName, string virtualDirectoryPath, string webRootPath, int port) { var siteId = GetSiteId(webSiteName); if (siteId == null) { using (var w3Svc = new DirectoryEntry("IIS://localhost/w3svc")) { siteId = ((int) w3Svc.Invoke("CreateNewSite", new object[] { webSiteName, new object[] { "*:" + port + ":" }, webRootPath })).ToString(); w3Svc.CommitChanges(); } } var virtualParts = (virtualDirectoryPath ?? string.Empty).Split('/', '\\').Select(x => x.Trim()).Where(x => x.Length > 0).ToArray(); if (virtualParts.Length == 0) return; CreateVirtualDirectory("IIS://localhost/w3svc/" + siteId + "/Root", virtualParts[0], webRootPath, virtualParts.Skip(1).ToArray()); } static void CreateVirtualDirectory(string parentPath, string name, string homeDirectory, string[] remainingPaths) { name = name.Trim('/'); using (var parent = new DirectoryEntry(parentPath)) { string existingChildPath = null; foreach (var child in parent.Children.OfType<DirectoryEntry>()) { if (child.SchemaClassName == "IIsWebVirtualDir" && child.Name.ToLowerInvariant() == name.ToLowerInvariant()) { existingChildPath = child.Path; } child.Close(); } if (existingChildPath == null) { var child = parent.Children.Add(name.Trim('/'), "IIsWebVirtualDir"); child.Properties["Path"][0] = homeDirectory; child.CommitChanges(); parent.CommitChanges(); existingChildPath = child.Path; child.Close(); } if (remainingPaths.Length > 0) { CreateVirtualDirectory(existingChildPath, remainingPaths.First(), homeDirectory, remainingPaths.Skip(1).ToArray()); } } } public override string GetHomeDirectory(string webSiteName, string virtualDirectoryPath) { var siteId = GetSiteId(webSiteName); if (siteId == null) { throw new Exception("The site: " + webSiteName + " does not exist"); } var root = "IIS://localhost/w3svc/" + siteId + "/Root"; var virtualParts = (virtualDirectoryPath ?? string.Empty).Split('/', '\\').Select(x => x.Trim()).Where(x => x.Length > 0).ToArray(); if (virtualParts.Length == 0) { using (var entry = new DirectoryEntry(root)) { return (string) entry.Properties["Path"][0]; } } return FindHomeDirectory(root, virtualParts[0], virtualParts.Skip(1).ToArray()); } static string FindHomeDirectory(string parentPath, string virtualDirectoryName, string[] childDirectoryNames) { using (var parent = new DirectoryEntry(parentPath)) { string existingChildPath = null; foreach (var child in parent.Children.OfType<DirectoryEntry>()) { if (child.SchemaClassName == "IIsWebVirtualDir" && child.Name.ToLowerInvariant() == virtualDirectoryName.ToLowerInvariant()) { if (childDirectoryNames.Length == 0) { return (string) child.Properties["Path"][0]; } existingChildPath = child.Path; } child.Close(); } if (existingChildPath == null) { throw new Exception("The virtual directory: " + virtualDirectoryName + " does not exist"); } return FindHomeDirectory(existingChildPath, childDirectoryNames.First(), childDirectoryNames.Skip(1).ToArray()); } } public override void DeleteWebSite(string webSiteName) { var id = GetSiteId(webSiteName); if (id == null) return; using (var w3Svc = new DirectoryEntry("IIS://localhost/w3svc")) { var child = w3Svc.Children.Find(id, "IIsWebServer"); child.DeleteTree(); child.Dispose(); w3Svc.CommitChanges(); } } public override bool ChangeHomeDirectory(string iisWebSiteName, string virtualDirectory, string newWebRootPath) { var iisRoot = new DirectoryEntry("IIS://localhost/W3SVC"); iisRoot.RefreshCache(); var result = false; foreach (DirectoryEntry webSite in iisRoot.Children) { if (webSite.SchemaClassName == "IIsWebServer" && webSite.Properties.Contains("ServerComment") && (string)webSite.Properties["ServerComment"].Value == iisWebSiteName) { foreach (DirectoryEntry webRoot in webSite.Children) { if (virtualDirectory == null) { if (webRoot.Properties.Contains("Path")) { webRoot.Properties["Path"].Value = newWebRootPath; webRoot.CommitChanges(); result = true; } } else { try { var virtualDir = webRoot.Children.Find(virtualDirectory, "IIsWebVirtualDir"); virtualDir.Properties["Path"].Value = newWebRootPath; virtualDir.CommitChanges(); result = true; } catch (Exception ex) { Log.ErrorFormat("Unable to find the virtual directory '{0}': {1}", virtualDirectory, ex.Message); result = false; } } webRoot.Close(); } } webSite.Close(); } iisRoot.Close(); return result; } static string GetSiteId(string webSiteName) { string result = null; using (var w3Svc = new DirectoryEntry("IIS://localhost/w3svc")) { foreach (var child in w3Svc.Children.OfType<DirectoryEntry>()) { if (child.SchemaClassName == "IIsWebServer" && (string)child.Properties["ServerComment"].Value == webSiteName) { result = child.Name; } child.Dispose(); } } return result; } } } #endif<file_sep>#if USE_NUGET_V3_LIBS using System; using System.Net; using System.Threading; using NuGet.Configuration; using NuGet.Common; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using System.IO; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Extensions; using NuGet.DependencyResolver; using NuGet.LibraryModel; using Octopus.Versioning; namespace Calamari.Integration.Packages.NuGet { public class NuGetV3LibDownloader { public static void DownloadPackage(string packageId, IVersion version, Uri feedUri, ICredentials feedCredentials, string targetFilePath) { ILogger logger = new NugetLogger(); var sourceRepository = Repository.Factory.GetCoreV3(feedUri.AbsoluteUri); if (feedCredentials != null) { var cred = feedCredentials.GetCredential(feedUri, "basic"); sourceRepository.PackageSource.Credentials = new PackageSourceCredential("octopus", cred.UserName, cred.Password, true); } using (var sourceCacheContext = new SourceCacheContext() { NoCache = true }) { var providers = new SourceRepositoryDependencyProvider(sourceRepository, logger, sourceCacheContext); var libraryIdentity = new LibraryIdentity(packageId, version.ToNuGetVersion(), LibraryType.Package); var targetPath = Directory.GetParent(targetFilePath).FullName; if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } string targetTempNupkg = Path.Combine(targetPath, Path.GetRandomFileName()); using (var nupkgStream = new FileStream(targetTempNupkg, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete, 4096, true)) { providers.CopyToAsync(libraryIdentity, nupkgStream, CancellationToken.None) .GetAwaiter() .GetResult(); } File.Move(targetTempNupkg, targetFilePath); } } public class NugetLogger : ILogger { public void LogDebug(string data) => Log.Verbose(data); public void LogVerbose(string data) => Log.Verbose(data); public void LogInformation(string data) => Log.Info(data); public void LogMinimal(string data) => Log.Verbose(data); public void LogWarning(string data) => Log.Warn(data); public void LogError(string data) => Log.Error(data); public void LogSummary(string data) => Log.Info(data); public void LogInformationSummary(string data) => Log.Info(data); public void LogErrorSummary(string data) => Log.Error(data); } } } #endif<file_sep>using System; namespace Calamari.Tests.AWS { public static class RegionRandomiser { static Random random = new Random(); // Only a subset of regions are currently // allowed to make it easier to manage // if we need to do cleanups or allocate // higher quotas. static string[] regions = { // "ap-northeast-1", // "ap-northeast-2", // "ap-northeast-3", // "ap-south-1", "ap-southeast-1", "ap-southeast-2", // "ca-central-1", // "eu-central-1", // "eu-north-1", // "eu-west-1", // "eu-west-2", // "eu-west-3", // "sa-east-1", "us-east-1", // "us-east-2", // "us-west-1", // "us-west-2" }; public static string GetARegion() { return regions[random.Next(0, regions.Length - 1)]; } } }<file_sep>using System; using SharpCompress.Archives; namespace Calamari.Common.Features.Packages { public interface IPackageExtractor { string[] Extensions { get; } int Extract(string packageFile, string directory); } public interface IPackageEntryExtractor : IPackageExtractor { void ExtractEntry(string directory, IArchiveEntry entry); } } <file_sep>createartifact("C:\Path\File.txt") <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calamari.Common.Features.Discovery { public class TargetMatchResult { private readonly string? role; private readonly IEnumerable<string> failureReasons; private TargetMatchResult(string role) { this.role = role; this.failureReasons = Enumerable.Empty<string>(); } private TargetMatchResult(IEnumerable<string> failureReasons) { this.failureReasons = failureReasons; } public string Role => this.role ?? throw new InvalidOperationException("Cannot get Role from failed target match result."); public IEnumerable<string> FailureReasons => this.failureReasons; public bool IsSuccess => this.role != null; public static TargetMatchResult Success(string role) => new TargetMatchResult(role); public static TargetMatchResult Failure(IEnumerable<string> failureReasons) => new TargetMatchResult(failureReasons); } } <file_sep>using System; using System.IO; using System.IO.Compression; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Processes; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using Calamari.Util; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Packages { public class PackageBuilder { public static string BuildSamplePackage(string name, string version, bool modifyPackage = false) { var packageDirectory = TestEnvironment.GetTestPath("Fixtures", "Deployment", "Packages", name); Assert.That(Directory.Exists(packageDirectory), string.Format("Package {0} is not available (expected at {1}).", name, packageDirectory)); #if NETFX var nugetCommandLine = TestEnvironment.GetTestPath("NuGet", "NuGet.exe"); Assert.That(File.Exists(nugetCommandLine), string.Format("NuGet.exe is not available (expected at {0}).", nugetCommandLine)); var target = GetNixFileOrDefault(packageDirectory, name, ".nuspec"); #else var nugetCommandLine = "dotnet"; var target = GetNixFileOrDefault(packageDirectory, name, ".csproj"); #endif var output = Path.Combine(Path.GetTempPath(), "CalamariTestPackages"); Directory.CreateDirectory(output); var path = Path.Combine(output, name + "." + version + ".nupkg"); if (File.Exists(path)) File.Delete(path); var runner = new CommandLineRunner(ConsoleLog.Instance, new CalamariVariables()); #if NETCORE var restoreResult = runner.Execute(new CommandLine(nugetCommandLine) .Action("restore") .Argument(target) .Build()); restoreResult.VerifySuccess(); #endif var result = runner.Execute(new CommandLine(nugetCommandLine) .Action("pack") .Argument(target) #if NETFX .Argument("Version", version) .Flag("NoPackageAnalysis") .Argument("OutputDirectory", output) #else .Argument("-output", output) .PositionalArgument("/p:Version=" + version) #endif .Build()); result.VerifySuccess(); Assert.That(File.Exists(path), string.Format("The generated nupkg was unable to be found (expected at {0}).", path)); return path; } static string GetNixFileOrDefault(string filePath, string filePrefix, string fileSuffix) { if (CalamariEnvironment.IsRunningOnWindows) { return GetWindowsOrDefaultPath(); } else { var path = Path.Combine(filePath, filePrefix + ".Nix" + fileSuffix); return File.Exists(path) ? path : GetWindowsOrDefaultPath(); } string GetWindowsOrDefaultPath() { var path = Path.Combine(filePath, filePrefix + fileSuffix); Assert.That(File.Exists(path), $"{fileSuffix} for {filePrefix} is not available (expected at {path}."); return path; } } static string AddFileToPackage(string packageDirectory) { var indexFilePath = Path.Combine(packageDirectory, "index.html"); var content = "<!DOCTYPE html>\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "<head>\n" + " <title>Acme.Web</title>\n" + "</head>\n" + "<body>\n" + " <h1>Welcome to Acme!</h1>\n" + " <h3>A Company that Makes Everything</h3>\n" + "</body>\n" + "</html>"; using (var indexFile = File.CreateText(indexFilePath)) { indexFile.Write(content); indexFile.Flush(); } Assert.That(File.Exists(indexFilePath)); return indexFilePath; } public static string BuildSimpleZip(string name, string version, string directory) { Assert.That(Directory.Exists(directory), string.Format("Package {0} is not available (expected at {1}).", name, directory)); var output = Path.Combine(Path.GetTempPath(), "CalamariTestPackages"); Directory.CreateDirectory(output); var path = Path.Combine(output, name + "." + version + ".zip"); if (File.Exists(path)) File.Delete(path); ZipFile.CreateFromDirectory(directory, path); return path; } } } <file_sep>using Newtonsoft.Json; namespace Calamari.Kubernetes.ResourceStatus.Resources { // Subset of: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.22/#endpoint-v1-discovery-k8s-io public class Endpoint { [JsonProperty("addresses")] public string[] Addresses { get; set; } } } <file_sep>using System; using System.Xml.Linq; namespace Calamari.AzureCloudService.CloudServicePackage.ManifestSchema { public class FileDescription { public static readonly XName ElementName = PackageDefinition.AzureNamespace + "FileDescription"; static readonly XName DataContentReferenceElementName = PackageDefinition.AzureNamespace + "DataContentReference"; static readonly XName ReadOnlyElementName = PackageDefinition.AzureNamespace + "ReadOnly"; static readonly XName CreatedTimeElementName = PackageDefinition.AzureNamespace + "CreatedTimeUtc"; static readonly XName ModifiedTimeElementName = PackageDefinition.AzureNamespace + "ModifiedTimeUtc"; public FileDescription() { } public FileDescription(XElement element) { DataContentReference = element.Element(DataContentReferenceElementName).Value; ReadOnly = Boolean.Parse(element.Element(ReadOnlyElementName).Value); Created = DateTime.Parse(element.Element(CreatedTimeElementName).Value); Modified = DateTime.Parse(element.Element(ModifiedTimeElementName).Value); } public string DataContentReference { get; set; } public bool ReadOnly { get; set; } public DateTime Created { get; set; } public DateTime Modified { get; set; } public XElement ToXml() { return new XElement(ElementName, new XElement(DataContentReferenceElementName, DataContentReference), new XElement(CreatedTimeElementName, Created), new XElement(ModifiedTimeElementName, Modified), new XElement(ReadOnlyElementName, ReadOnly) ); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; namespace Calamari.Kubernetes.Integration { public class GCloud : CommandLineTool { public GCloud(ILog log, ICommandLineRunner commandLineRunner, string workingDirectory, Dictionary<string, string> environmentVars) : base(log, commandLineRunner, workingDirectory, environmentVars) { } public bool TrySetGcloud() { var result = CalamariEnvironment.IsRunningOnWindows ? ExecuteCommandAndReturnOutput("where", "gcloud.cmd") : ExecuteCommandAndReturnOutput("which", "gcloud"); var foundExecutable = result.Output.InfoLogs.FirstOrDefault(); if (string.IsNullOrEmpty(foundExecutable)) { log.Error("Could not find gcloud. Make sure gcloud is on the PATH."); return false; } ExecutableLocation = foundExecutable.Trim(); return true; } public void ConfigureGcloudAccount(string project, string region, string zone, string jsonKey, bool useVmServiceAccount, string impersonationEmails) { if (!string.IsNullOrEmpty(project)) { environmentVars.Add("CLOUDSDK_CORE_PROJECT", project); } if (!string.IsNullOrEmpty(region)) { environmentVars.Add("CLOUDSDK_COMPUTE_REGION", region); } if (!string.IsNullOrEmpty(zone)) { environmentVars.Add("CLOUDSDK_COMPUTE_ZONE", zone); } if (!useVmServiceAccount) { if (jsonKey == null) { log.Error("Failed to authenticate with gcloud. Key file is empty."); return; } log.Verbose("Authenticating to gcloud with key file"); var bytes = Convert.FromBase64String(jsonKey); using (var keyFile = new TemporaryFile(Path.Combine(workingDirectory, "gcpJsonKey.json"))) { File.WriteAllBytes(keyFile.FilePath, bytes); var result = ExecuteCommandAndLogOutput(new CommandLineInvocation(ExecutableLocation, "auth", "activate-service-account", $"--key-file=\"{keyFile.FilePath}\"")); result.VerifySuccess(); } log.Verbose("Successfully authenticated with gcloud"); } else { log.Verbose("Bypassing authentication with gcloud"); } if (!string.IsNullOrEmpty(impersonationEmails)) environmentVars.Add("CLOUDSDK_AUTH_IMPERSONATE_SERVICE_ACCOUNT", impersonationEmails); } public void ConfigureGkeKubeCtlAuthentication(Kubectl kubectlCli, string gkeClusterName, string region, string zone, string @namespace, bool useClusterInternalIp) { log.Info($"Creating kubectl context to GKE Cluster called {gkeClusterName} (namespace {@namespace}) using a Google Cloud Account"); var arguments = new List<string>(new[] { "container", "clusters", "get-credentials", gkeClusterName }); if (useClusterInternalIp) { arguments.Add("--internal-ip"); } if (!string.IsNullOrWhiteSpace(zone)) { arguments.Add($"--zone={zone}"); } else if (!string.IsNullOrWhiteSpace(region)) { arguments.Add($"--region={region}"); } else { throw new ArgumentException("Either zone or region must be defined."); } var result = ExecuteCommandAndLogOutput(new CommandLineInvocation(ExecutableLocation, arguments.ToArray())); result.VerifySuccess(); kubectlCli.ExecuteCommandAndAssertSuccess("config", "set-context", "--current", $"--namespace={@namespace}"); } } }<file_sep>using System; using System.Diagnostics; using System.Linq; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment.PackageRetention.Caching; using Calamari.Deployment.PackageRetention.Model; using Calamari.Tests.Fixtures.Integration.FileSystem; using Calamari.Tests.Fixtures.PackageRetention.Repository; using FluentAssertions; using NSubstitute; using NUnit.Framework; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.PackageRetention { [TestFixture] public class LeastFrequentlyUsedWithAgingSortPerformanceFixture { [Test] public void Performs() { var journalRepo = SeedJournal(); var stopWatch = new Stopwatch(); stopWatch.Start(); var algo = new LeastFrequentlyUsedWithAgingSort(); var result = algo .Sort(journalRepo.GetAllJournalEntries()) .ToList(); result.Should().NotBeEmpty(); stopWatch.Stop(); stopWatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(10)); } static InMemoryJournalRepository SeedJournal() { var journalRepo = new InMemoryJournalRepository(); var journal = new PackageJournal(journalRepo, Substitute.For<ILog>(), new TestCalamariPhysicalFileSystem(), Substitute.For<IRetentionAlgorithm>(), new SystemSemaphoreManager()); var serverTask = new ServerTaskId("ServerTasks-1"); for (var i = 0; i < 50000; i++) { var package = new PackageIdentity(new PackageId($"Package-{i % 100}"), new SemanticVersion(1, 0, i), new PackagePath($"C:\\{i}")); journal.RegisterPackageUse(package, serverTask, 100); } journal.RemoveAllLocks(serverTask); return journalRepo; } } }<file_sep>using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; namespace Calamari.Deployment.Conventions { /// <summary> /// This convention is used to detect PreDeploy.ps1, Deploy.ps1 and PostDeploy.ps1 scripts. /// </summary> public class PackagedScriptConvention : IInstallConvention { readonly PackagedScriptBehaviour packagedScriptBehaviour; public PackagedScriptConvention(PackagedScriptBehaviour packagedScriptBehaviour) { this.packagedScriptBehaviour = packagedScriptBehaviour; } public void Install(RunningDeployment deployment) { if (packagedScriptBehaviour.IsEnabled(deployment)) { packagedScriptBehaviour.Execute(deployment).Wait(); } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using Calamari.AzureWebApp.Util; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.Rest; using Microsoft.Rest.TransientFaultHandling; namespace Calamari.AzureWebApp.Integration.Websites.Publishing { class ResourceManagerPublishProfileProvider { readonly ILog log; public ResourceManagerPublishProfileProvider(ILog log) { this.log = log; } public async Task<WebDeployPublishSettings> GetPublishProperties(AzureServicePrincipalAccount account, string resourceGroupName, AzureTargetSite azureTargetSite) { if (account.ResourceManagementEndpointBaseUri != DefaultVariables.ResourceManagementEndpoint) log.InfoFormat("Using override for resource management endpoint - {0}", account.ResourceManagementEndpointBaseUri); if (account.ActiveDirectoryEndpointBaseUri != DefaultVariables.ActiveDirectoryEndpoint) log.InfoFormat("Using override for Azure Active Directory endpoint - {0}", account.ActiveDirectoryEndpointBaseUri); var token = await ServicePrincipal.GetAuthorizationToken(account.TenantId, account.ClientId, account.Password, account.ResourceManagementEndpointBaseUri, account.ActiveDirectoryEndpointBaseUri); var baseUri = new Uri(account.ResourceManagementEndpointBaseUri); using (var resourcesClient = new ResourceManagementClient(new TokenCredentials(token)) { SubscriptionId = account.SubscriptionNumber, BaseUri = baseUri, }) using (var webSiteClient = new WebSiteManagementClient(new Uri(account.ResourceManagementEndpointBaseUri), new TokenCredentials(token)) { SubscriptionId = account.SubscriptionNumber }) { webSiteClient.SetRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), 3)); resourcesClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); resourcesClient.HttpClient.BaseAddress = baseUri; log.Verbose($"Looking up site {azureTargetSite.Site} {(string.IsNullOrWhiteSpace(resourceGroupName) ? string.Empty : $"in resourceGroup {resourceGroupName}")}"); Site matchingSite; if (string.IsNullOrWhiteSpace(resourceGroupName)) { matchingSite = await FindSiteByNameWithRetry(account, azureTargetSite, webSiteClient) ?? throw new CommandException(GetSiteNotFoundExceptionMessage(account, azureTargetSite)); resourceGroupName = matchingSite.ResourceGroup; } else { var site = await webSiteClient.WebApps.GetAsync(resourceGroupName, azureTargetSite.Site); log.Verbose("Found site:"); logSite(site); matchingSite = site ?? throw new CommandException(GetSiteNotFoundExceptionMessage(account, azureTargetSite, resourceGroupName)); } // ARM resource ID of the source app. App resource ID is of the form: // - /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName} for production slots and // - /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/slots/{slotName} for other slots. // We allow the slot to be defined on both the target directly (which will come through on the matchingSite.Name) or on the // step for backwards compatibility with older Azure steps. if (azureTargetSite.HasSlot) { log.Verbose($"Using the deployment slot {azureTargetSite.Slot}"); } return await GetWebDeployPublishProfile(webSiteClient, resourceGroupName, matchingSite.Name, azureTargetSite.HasSlot ? azureTargetSite.Slot : null); } } async Task<WebDeployPublishSettings> GetWebDeployPublishProfile(WebSiteManagementClient webSiteClient, string resourceGroupName, string site, string slot = null) { var options = new CsmPublishingProfileOptions {Format = "WebDeploy"}; var stream = await (slot == null ? webSiteClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(resourceGroupName, site, options) : webSiteClient.WebApps.ListPublishingProfileXmlWithSecretsSlotAsync(resourceGroupName, site, options, slot) ); string text; using (var streamReader = new StreamReader(stream)) { text = await streamReader.ReadToEndAsync(); } var document = XDocument.Parse(text); var profile = (from el in document.Descendants("publishProfile") where string.Compare(el.Attribute("publishMethod")?.Value, "MSDeploy", StringComparison.OrdinalIgnoreCase) == 0 select new { PublishUrl = $"https://{el.Attribute("publishUrl")?.Value}", Username = el.Attribute("userName")?.Value, Password = el.Attribute("<PASSWORD>")?.Value, Site = el.Attribute("msdeploySite")?.Value }).FirstOrDefault(); if (profile == null) { throw new Exception("Failed to retrieve publishing profile."); } return new WebDeployPublishSettings(profile.Site, new SitePublishProfile(profile.Username, profile.Password, new Uri(profile.PublishUrl))); } async Task<Site> FindSiteByNameWithRetry(AzureServicePrincipalAccount account, AzureTargetSite azureTargetSite, WebSiteManagementClient webSiteClient) { Site matchingSite = null; var retry = AzureRetryTracker.GetDefaultRetryTracker(); while (retry.Try() && matchingSite == null) { var sites = await webSiteClient.WebApps.ListAsync(); var matchingSites = sites.Where(webApp => string.Equals(webApp.Name, azureTargetSite.Site, StringComparison.OrdinalIgnoreCase)).ToList(); logFoundSites(sites.ToList()); if (!matchingSites.Any()) { throw new CommandException(GetSiteNotFoundExceptionMessage(account, azureTargetSite)); } if (matchingSites.Count > 1) { throw new CommandException( $"Found {matchingSites.Count} matching the site name '{azureTargetSite.Site}' in subscription '{account.SubscriptionNumber}'. Please supply a Resource Group name."); } matchingSite = matchingSites.Single(); // ensure the site loaded the resource group if (string.IsNullOrWhiteSpace(matchingSite.ResourceGroup)) { if (retry.CanRetry()) { if (retry.ShouldLogWarning()) { log.Warn( $"Azure Site query failed to return the resource group, trying again in {retry.Sleep().TotalMilliseconds:n0} ms."); } matchingSite = null; await Task.Delay(retry.Sleep()); } else { throw new CommandException(GetSiteNotFoundExceptionMessage(account, azureTargetSite)); } } } return matchingSite; } string GetSiteNotFoundExceptionMessage(AzureServicePrincipalAccount account, AzureTargetSite azureTargetSite, string resourceGroupName = null) { var hasResourceGroup = !string.IsNullOrWhiteSpace(resourceGroupName); var sb = new StringBuilder($"Could not find Azure WebSite '{azureTargetSite.Site}'"); sb.Append(hasResourceGroup ? $" in resource group '{resourceGroupName}'" : string.Empty); sb.Append($" in subscription '{account.SubscriptionNumber}'."); sb.Append(hasResourceGroup ? string.Empty : " Please supply a Resource Group name."); return sb.ToString(); } void logFoundSites(List<Site> sites) { if (sites.Any()) { log.Verbose("Found sites:"); foreach (var site in sites) { logSite(site); } } } void logSite(Site site) { if (site != null) { string resourceGroup = string.IsNullOrWhiteSpace(site.ResourceGroup) ? string.Empty : $"{site.ResourceGroup} / "; log.Verbose($"\t{resourceGroup}{site.Name}"); } } } } <file_sep>using System.IO; using System.Linq; using System.Xml.Linq; using Assent; using Calamari.Common.Commands; using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.ConfigurationTransforms { [TestFixture] public class ConfigurationTransformsFixture : CalamariFixture { InMemoryLog log; ConfigurationTransformer configurationTransformer; [SetUp] public void SetUp() { log = new InMemoryLog(); var variables = new CalamariVariables(); configurationTransformer = ConfigurationTransformer.FromVariables(variables, log); } [Test] public void XmlWithNamespacesIsCorrectlyProcessed() { var text = PerformTest(GetFixtureResource("Samples", "nlog.config"), GetFixtureResource("Samples", "nlog.Release.config")); var document = XDocument.Parse(text); this.Assent(document.ToString(), AssentConfiguration.Default); } [Test] [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 public void WebReleaseConfig() { var text = PerformTest(GetFixtureResource("Samples", "Web.config"), GetFixtureResource("Samples", "Web.Release.config")); var contents = XDocument.Parse(text); Assert.IsNull(GetDebugAttribute(contents)); Assert.AreEqual(GetAppSettingsValue(contents).Value, "Release!"); Assert.IsNull(GetCustomErrors(contents)); log.Messages.Should().NotContain(m => m.Level == InMemoryLog.Level.Error, "Should not log errors"); log.Messages.Should().NotContain(m => m.Level == InMemoryLog.Level.Warn, "Should not log warnings"); } [Test] [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 [ExpectedException(typeof(System.Xml.XmlException))] public void ShouldThrowExceptionForBadConfig() { PerformTest(GetFixtureResource("Samples", "Bad.config"), GetFixtureResource("Samples", "Web.Release.config")); } [Test] [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 public void ShouldSupressExceptionForBadConfig_WhenFlagIsSet() { var variables = new CalamariVariables(); variables.Set(SpecialVariables.Package.IgnoreConfigTransformationErrors, "true"); configurationTransformer = ConfigurationTransformer.FromVariables(variables, log); PerformTest(GetFixtureResource("Samples", "Bad.config"), GetFixtureResource("Samples", "Web.Release.config")); } [Test] [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 [ExpectedException(typeof(CommandException))] public void ShouldThrowExceptionForTransformWarnings() { PerformTest(GetFixtureResource("Samples", "Web.config"), GetFixtureResource("Samples", "Web.Warning.config")); } [Test] [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 public void ShouldSuppressExceptionForTransformWarnings_WhenFlagIsSet() { var variables = new CalamariVariables(); variables.Set(SpecialVariables.Package.TreatConfigTransformationWarningsAsErrors, "false"); configurationTransformer = ConfigurationTransformer.FromVariables(variables, log); PerformTest(GetFixtureResource("Samples", "Web.config"), GetFixtureResource("Samples", "Web.Warning.config")); } [Test] [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 public void ShouldShowMessageWhenResultIsInvalidXml() { PerformTest(GetFixtureResource("Samples", "Web.config"), GetFixtureResource("Samples", "Web.Empty.config")); log.Messages.Where(m => m.Level == InMemoryLog.Level.Error) .Select(m => m.MessageFormat) .Should() .Contain("The XML configuration file {0} no longer has a root element and is invalid after being transformed by {1}"); } string PerformTest(string configurationFile, string transformFile) { var temp = Path.GetTempFileName(); File.Copy(configurationFile, temp, true); using (new TemporaryFile(temp)) { configurationTransformer.PerformTransform(temp, transformFile, temp); return File.ReadAllText(temp); } } static XAttribute GetDebugAttribute(XDocument document) { return document.Descendants("compilation").First().Attribute("debug"); } static XAttribute GetAppSettingsValue(XDocument document) { return document.Descendants("appSettings").Descendants("add").First().Attribute("value"); } XElement GetCustomErrors(XDocument document) { return document.Descendants("customErrors").FirstOrDefault(); } } } <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Newtonsoft.Json.Linq; namespace Calamari.Terraform.Behaviours { class ApplyBehaviour : TerraformDeployBehaviour { readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; public ApplyBehaviour(ILog log, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner) : base(log) { this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; } protected override Task Execute(RunningDeployment deployment, Dictionary<string, string> environmentVariables) { using var cli = new TerraformCliExecutor(log, fileSystem, commandLineRunner, deployment, environmentVariables); cli.ExecuteCommand("apply", "-no-color", "-auto-approve", cli.TerraformVariableFiles, cli.ActionParams); // Attempt to get the outputs. This will fail if none are defined in versions prior to v0.11.15 // Please note that we really don't want to log the following command output as it can contain sensitive variables etc. hence the IgnoreCommandOutput() if (cli.ExecuteCommand(out var result, false, "output", "-no-color", "-json") .ExitCode != 0) return this.CompletedTask(); foreach (var (name, token) in OutputVariables(result)) { bool.TryParse(token.SelectToken("sensitive")?.ToString(), out var isSensitive); var json = token.ToString(); var value = token.SelectToken("value")?.ToString(); log.SetOutputVariable($"TerraformJsonOutputs[{name}]", json, deployment.Variables, isSensitive); if (value != null) log.SetOutputVariable($"TerraformValueOutputs[{name}]", value, deployment.Variables, isSensitive); log.Info( $"Saving {(isSensitive ? "sensitive " : string.Empty)}variable 'Octopus.Action[{deployment.Variables["Octopus.Action.StepName"]}].Output.TerraformJsonOutputs[\"{name}\"]' with the JSON value only of '{json}'"); if (value != null) log.Info( $"Saving {(isSensitive ? "sensitive " : string.Empty)}variable 'Octopus.Action[{deployment.Variables["Octopus.Action.StepName"]}].Output.TerraformValueOutputs[\"{name}\"]' with the value only of '{value}'"); } return this.CompletedTask(); } IEnumerable<(string, JToken)> OutputVariables(string result) { var jObj = JObject.Parse(result); foreach (var property in jObj.Properties()) yield return (property.Name, property.Value); } } }<file_sep>using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class PersistentVolumeClaim: Resource { public string Status { get; } public string Volume { get; } public string Capacity { get; } public IEnumerable<string> AccessModes { get; } public string StorageClass { get; } public PersistentVolumeClaim(JObject json, Options options) : base(json, options) { Status = Field("$.status.phase"); Volume = Field("$.spec.volumeName"); Capacity = Field("$.status.capacity.storage"); AccessModes = data.SelectToken("$.status.accessModes")?.Values<string>() ?? new string[] { }; StorageClass = Field("$.spec.storageClassName"); } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<PersistentVolumeClaim>(lastStatus); return last.Status != Status || last.Volume != Volume || last.Capacity != Capacity || !last.AccessModes.SequenceEqual(AccessModes) || last.StorageClass != StorageClass; } } } <file_sep>using Newtonsoft.Json; namespace Calamari.Common.Features.Discovery { /// <summary> /// For account-based authentication scopes. /// </summary> public class AccountAuthenticationDetails<TAccountDetails> : ITargetDiscoveryAuthenticationDetails { [JsonConstructor] public AccountAuthenticationDetails (string type, string accountId, TAccountDetails accountDetails) { Type = type; AccountId = accountId; AccountDetails = accountDetails; } public string Type { get; set; } public string AccountId { get; set; } public TAccountDetails AccountDetails { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Calamari.Common.Plumbing; using NUnit.Framework; namespace Calamari.Tests { // using statements [SetUpFixture] public class GlobalTestSetup { [OneTimeSetUp] public void EnableAllSecurityProtocols() { // Enabling of TLS1.2 happens on Calamari.exe startup in main, // however this will ensure it is applied during Unit Tests which will bypass the main entrypoint SecurityProtocols.EnableAllSecurityProtocols(); } } } <file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; using Calamari.Terraform.Behaviours; namespace Calamari.Terraform.Commands { [Command("plan-terraform", Description = "Plans the creation of a Terraform deployment")] public class PlanCommand : TerraformCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<PlanBehaviour>(); } } }<file_sep>using System.IO; using Calamari.Common.Features.Scripting.Bash; using Calamari.Common.Plumbing.FileSystem; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Scripting { [TestFixture] public class BashScriptEngineFixture : ScriptEngineFixtureBase { [Test] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void BashDecryptsVariables() { using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "sh"))) { File.WriteAllText(scriptFile.FilePath, "#!/bin/bash\necho $(get_octopusvariable \"mysecrect\")"); var result = ExecuteScript(new BashScriptExecutor(), scriptFile.FilePath, GetVariables()); result.AssertOutput("KingKong"); } } } } <file_sep>using System.Collections.Generic; using System.IO; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Features.Java { /// <summary> /// A base class for features that run Java against the Octopus Deploy /// Java library /// </summary> public class JavaRunner { readonly ICommandLineRunner commandLineRunner; readonly IVariables variables; public JavaRunner(ICommandLineRunner commandLineRunner, IVariables variables) { this.commandLineRunner = commandLineRunner; this.variables = variables; } /// <summary> /// Execute java running the Octopus Deploy Java library /// </summary> public void Run(string mainClass, Dictionary<string, string> environmentVariables) { var javaLib = variables.Get(SpecialVariables.Action.Java.JavaLibraryEnvVar, ""); var result = commandLineRunner.Execute( new CommandLineInvocation( JavaRuntime.CmdPath, $"-Djdk.logger.finder.error=QUIET -cp calamari.jar {mainClass}" ) { WorkingDirectory = Path.Combine(javaLib, "contentFiles", "any", "any"), EnvironmentVars = environmentVariables } ); result.VerifySuccess(); } } }<file_sep>using System; using Newtonsoft.Json; using Octopus.Versioning; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public class PackageIdentity { public PackageId PackageId { get; } [JsonConverter(typeof(VersionConverter))] public IVersion Version { get; } public PackagePath Path { get; } [JsonConstructor] public PackageIdentity(PackageId packageId, IVersion version, PackagePath path) { PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); Version = version ?? throw new ArgumentNullException(nameof(version)); Path = path ?? throw new ArgumentNullException(nameof(path)); } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj) || obj.GetType() != GetType()) return false; if (ReferenceEquals(this, obj)) return true; var other = (PackageIdentity)obj; return this == other; } protected bool Equals(PackageIdentity other) { return Equals(PackageId, other.PackageId) && Equals(Version, other.Version) && Equals(Path, other.Path); } public override int GetHashCode() { unchecked { //Generated by rider return (PackageId.GetHashCode() * 397) ^ Version.GetHashCode(); } } public static bool operator ==(PackageIdentity first, PackageIdentity second) { return first.Equals(second); } public static bool operator !=(PackageIdentity first, PackageIdentity second) { return !(first == second); } public override string ToString() { return $"{PackageId} v{Version}"; } } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class DaemonSetTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""DaemonSet"", ""metadata"": { ""name"": ""my-ds"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""spec"": { ""template"": { ""spec"": { ""nodeSelector"": { ""os"": ""linux"", ""arch"": ""amd64"" } } } }, ""status"": { ""currentNumberScheduled"": 1, ""desiredNumberScheduled"": 2, ""numberAvailable"": 1, ""numberReady"": 1, ""updatedNumberScheduled"": 1 } }"; var daemonSet = ResourceFactory.FromJson(input, new Options()); daemonSet.Should().BeEquivalentTo(new { Kind = "DaemonSet", Name = "my-ds", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Desired = 2, Current = 1, Ready = 1, UpToDate = 1, Available = 1, NodeSelector = "arch=amd64,os=linux", ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress }); } } } <file_sep>System.Console.WriteLine("I have failed! DeployFailed.csx"); <file_sep>using System; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.Helpers; using FluentAssertions; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; using Microsoft.WindowsAzure.Management.Storage; using Microsoft.WindowsAzure.Management.Storage.Models; using NUnit.Framework; namespace Calamari.AzureCloudService.Tests { public class DeployAzureCloudServiceCommandFixture { string storageName; StorageManagementClient storageClient; CertificateCloudCredentials subscriptionCloudCredentials; X509Certificate2 managementCertificate; string subscriptionId; string certificate; string pathToPackage; [OneTimeSetUp] public async Task Setup() { storageName = $"Test{Guid.NewGuid().ToString("N").Substring(0, 10)}".ToLower(); certificate = ExternalVariables.Get(ExternalVariable.AzureSubscriptionCertificate); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); managementCertificate = CreateManagementCertificate(certificate); subscriptionCloudCredentials = new CertificateCloudCredentials(subscriptionId, managementCertificate); storageClient = new StorageManagementClient(subscriptionCloudCredentials); pathToPackage = TestEnvironment.GetTestPath("Packages", "Octopus.Sample.AzureCloudService.6.0.0.nupkg"); await storageClient.StorageAccounts.CreateAsync(new StorageAccountCreateParameters(storageName, "test") { Location = "West US", AccountType = "Standard_LRS" }); } [OneTimeTearDown] public async Task Cleanup() { await storageClient.StorageAccounts.DeleteAsync(storageName); storageClient.Dispose(); managementCertificate.Dispose(); } [Test] public async Task Deploy_Package_To_Stage() { var serviceName = $"{nameof(DeployAzureCloudServiceCommandFixture)}-{Guid.NewGuid().ToString("N").Substring(0, 12)}"; var deploymentSlot = DeploymentSlot.Staging; using var client = new ComputeManagementClient(subscriptionCloudCredentials); try { await client.HostedServices.CreateAsync(new HostedServiceCreateParameters(serviceName, "test") { Location = "West US" }); await Deploy(); await EnsureDeploymentStatus(DeploymentStatus.Running, client, serviceName, deploymentSlot); // Suspend state var operation = await client.Deployments.UpdateStatusByDeploymentSlotAsync(serviceName, deploymentSlot, new DeploymentUpdateStatusParameters(UpdatedDeploymentStatus.Suspended)); await WaitForOperation(client, operation); //Run again to test upgrading an existing slot and status should not change await Deploy(); await EnsureDeploymentStatus(DeploymentStatus.Suspended, client, serviceName, deploymentSlot); } finally { await DeleteDeployment(client, serviceName, deploymentSlot); await client.HostedServices.DeleteAsync(serviceName); } async Task Deploy() { await CommandTestBuilder.CreateAsync<DeployAzureCloudServiceCommand, Program>() .WithArrange(context => { context.Variables.Add(SpecialVariables.Action.Azure.SubscriptionId, subscriptionId); context.Variables.Add(SpecialVariables.Action.Azure.CertificateThumbprint, managementCertificate.Thumbprint); context.Variables.Add(SpecialVariables.Action.Azure.CertificateBytes, certificate); context.Variables.Add(SpecialVariables.Action.Azure.CloudServiceName, serviceName); context.Variables.Add(SpecialVariables.Action.Azure.StorageAccountName, storageName); context.Variables.Add(SpecialVariables.Action.Azure.Slot, deploymentSlot.ToString()); context.Variables.Add(SpecialVariables.Action.Azure.SwapIfPossible, bool.FalseString); context.Variables.Add(SpecialVariables.Action.Azure.UseCurrentInstanceCount, bool.FalseString); context.Variables.Add(SpecialVariables.Action.Azure.DeploymentLabel, "v1.0.0"); context.WithPackage(pathToPackage, "Octopus.Sample.AzureCloudService", "6.0.0"); }) .Execute(); } } [Test] public async Task Deploy_Package_To_Stage_And_Swap() { var serviceName = $"{nameof(DeployAzureCloudServiceCommandFixture)}-{Guid.NewGuid().ToString("N").Substring(0, 12)}"; using var client = new ComputeManagementClient(subscriptionCloudCredentials); try { await client.HostedServices.CreateAsync(new HostedServiceCreateParameters(serviceName, "test") { Location = "West US" }); await CommandTestBuilder.CreateAsync<DeployAzureCloudServiceCommand, Program>() .WithArrange(context => { context.Variables.Add(SpecialVariables.Action.Azure.SubscriptionId, subscriptionId); context.Variables.Add(SpecialVariables.Action.Azure.CertificateThumbprint, managementCertificate.Thumbprint); context.Variables.Add(SpecialVariables.Action.Azure.CertificateBytes, certificate); context.Variables.Add(SpecialVariables.Action.Azure.CloudServiceName, serviceName); context.Variables.Add(SpecialVariables.Action.Azure.StorageAccountName, storageName); context.Variables.Add(SpecialVariables.Action.Azure.Slot, DeploymentSlot.Staging.ToString()); context.Variables.Add(SpecialVariables.Action.Azure.SwapIfPossible, bool.FalseString); context.Variables.Add(SpecialVariables.Action.Azure.UseCurrentInstanceCount, bool.FalseString); context.Variables.Add(SpecialVariables.Action.Azure.DeploymentLabel, "v1.0.0"); context.WithPackage(pathToPackage, "Octopus.Sample.AzureCloudService", "6.0.0"); }) .Execute(); await CommandTestBuilder.CreateAsync<DeployAzureCloudServiceCommand, Program>() .WithArrange(context => { context.Variables.Add(SpecialVariables.Action.Azure.SubscriptionId, subscriptionId); context.Variables.Add(SpecialVariables.Action.Azure.CertificateThumbprint, managementCertificate.Thumbprint); context.Variables.Add(SpecialVariables.Action.Azure.CertificateBytes, certificate); context.Variables.Add(SpecialVariables.Action.Azure.CloudServiceName, serviceName); context.Variables.Add(SpecialVariables.Action.Azure.StorageAccountName, storageName); context.Variables.Add(SpecialVariables.Action.Azure.Slot, DeploymentSlot.Production.ToString()); context.Variables.Add(SpecialVariables.Action.Azure.SwapIfPossible, bool.TrueString); context.Variables.Add(SpecialVariables.Action.Azure.UseCurrentInstanceCount, bool.FalseString); context.Variables.Add(SpecialVariables.Action.Azure.DeploymentLabel, "v1.0.0"); context.WithPackage(pathToPackage, "Octopus.Sample.AzureCloudService", "6.0.0"); }) .Execute(); await EnsureDeploymentStatus(DeploymentStatus.Running, client, serviceName, DeploymentSlot.Production); Func<Task> act = async () => await client.Deployments.GetBySlotAsync(serviceName, DeploymentSlot.Staging); (await act.Should().ThrowAsync<CloudException>()) .WithMessage("ResourceNotFound: No deployments were found."); } finally { await DeleteDeployment(client, serviceName, DeploymentSlot.Production); await client.HostedServices.DeleteAsync(serviceName); } } [Test] public async Task Deploy_Ensure_Tools_Are_Configured() { var serviceName = $"{nameof(DeployAzureCloudServiceCommandFixture)}-{Guid.NewGuid().ToString("N").Substring(0, 12)}"; var deploymentSlot = DeploymentSlot.Staging; using var client = new ComputeManagementClient(subscriptionCloudCredentials); try { await client.HostedServices.CreateAsync(new HostedServiceCreateParameters(serviceName, "test") { Location = "West US" }); await Deploy(); } finally { await DeleteDeployment(client, serviceName, deploymentSlot); await client.HostedServices.DeleteAsync(serviceName); } async Task Deploy() { await CommandTestBuilder.CreateAsync<DeployAzureCloudServiceCommand, Program>() .WithArrange(context => { context.Variables.Add(SpecialVariables.Action.Azure.SubscriptionId, subscriptionId); context.Variables.Add(SpecialVariables.Action.Azure.CertificateThumbprint, managementCertificate.Thumbprint); context.Variables.Add(SpecialVariables.Action.Azure.CertificateBytes, certificate); context.Variables.Add(SpecialVariables.Action.Azure.CloudServiceName, serviceName); context.Variables.Add(SpecialVariables.Action.Azure.StorageAccountName, storageName); context.Variables.Add(SpecialVariables.Action.Azure.Slot, deploymentSlot.ToString()); context.Variables.Add(SpecialVariables.Action.Azure.SwapIfPossible, bool.FalseString); context.Variables.Add(SpecialVariables.Action.Azure.UseCurrentInstanceCount, bool.FalseString); context.Variables.Add(SpecialVariables.Action.Azure.DeploymentLabel, "v1.0.0"); context.WithPackage(pathToPackage, "Octopus.Sample.AzureCloudService", "6.0.0"); context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts); context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.PostDeploy, ScriptSyntax.FSharp), "printfn \"Hello from F#\""); }) .WithAssert(result => { result.FullLog.Should().Contain("Hello from F#"); }) .Execute(); } } static async Task DeleteDeployment(ComputeManagementClient client, string serviceName, DeploymentSlot deploymentSlot) { try { var operation = await client.Deployments.DeleteBySlotAsync(serviceName, deploymentSlot); await WaitForOperation(client, operation); } catch { // Ignore } } static async Task WaitForOperation(ComputeManagementClient client, OperationStatusResponse operation) { var maxWait = 30; // 1 minute while (maxWait-- >= 0) { await Task.Delay(TimeSpan.FromSeconds(2)); var operationStatus = await client.GetOperationStatusAsync(operation.RequestId); if (operationStatus.Status == OperationStatus.InProgress) { continue; } break; } } async Task EnsureDeploymentStatus(DeploymentStatus requiredStatus, ComputeManagementClient client, string serviceName, DeploymentSlot deploymentSlot) { DeploymentStatus status; var counter = 0; do { var deployment = await client.Deployments.GetBySlotAsync(serviceName, deploymentSlot); status = deployment.Status; if (status == requiredStatus) { break; } await Task.Delay(TimeSpan.FromSeconds(2)); } while (counter++ < 5); status.Should().Be(requiredStatus); } static X509Certificate2 CreateManagementCertificate(string certificate) { var bytes = Convert.FromBase64String(certificate); return new X509Certificate2(bytes); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Amazon; using Amazon.EKS; using Amazon.EKS.Model; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.Logging; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Kubernetes.Discovery { public class AwsKubernetesDiscoverer : KubernetesDiscovererBase { public AwsKubernetesDiscoverer(ILog log) : base(log) { } /// <remarks> /// This type value here must be the same as in Octopus.Server.Orchestration.ServerTasks.Deploy.TargetDiscovery.AwsAuthenticationContext /// This value is hardcoded because: /// a) There is currently no existing project to place code shared between server and Calamari, and /// b) We expect a bunch of stuff in the Sashimi/Calamari space to be refactored back into the OctopusDeploy solution soon. /// </remarks> public override string Type => "Aws"; public override IEnumerable<KubernetesCluster> DiscoverClusters(string contextJson) { if (!TryGetDiscoveryContext<AwsAuthenticationDetails>(contextJson, out var authenticationDetails, out var workerPoolId)) yield break; var accessKeyOrWorkerCredentials = authenticationDetails.Credentials.Type == "account" ? $"Access Key: {authenticationDetails.Credentials.Account.AccessKey}" : $"Using Worker Credentials on Worker Pool: {workerPoolId}"; Log.Verbose("Looking for Kubernetes clusters in AWS using:"); Log.Verbose($" Regions: [{string.Join(",",authenticationDetails.Regions)}]"); Log.Verbose(" Account:"); Log.Verbose($" {accessKeyOrWorkerCredentials}"); if (authenticationDetails.Role.Type == "assumeRole") { Log.Verbose(" Role:"); Log.Verbose($" ARN: {authenticationDetails.Role.Arn}"); if (!authenticationDetails.Role.SessionName.IsNullOrEmpty()) Log.Verbose($" Session Name: {authenticationDetails.Role.SessionName}"); if (authenticationDetails.Role.SessionDuration != null) Log.Verbose($" Session Duration: {authenticationDetails.Role.SessionDuration}"); if (!authenticationDetails.Role.ExternalId.IsNullOrEmpty()) Log.Verbose($" External Id: {authenticationDetails.Role.ExternalId}"); } else { Log.Verbose(" Role: No IAM Role provided."); } if (!authenticationDetails.TryGetCredentials(Log, out var credentials)) yield break; foreach (var region in authenticationDetails.Regions) { var client = new AmazonEKSClient(credentials, RegionEndpoint.GetBySystemName(region)); var clusters = client.ListClustersAsync(new ListClustersRequest()).GetAwaiter().GetResult(); foreach (var cluster in clusters.Clusters.Select(c => client.DescribeClusterAsync(new DescribeClusterRequest { Name = c }).GetAwaiter().GetResult().Cluster)) { var credentialsRole = authenticationDetails.Role; var assumedRole = credentialsRole.Type == "assumeRole" ? new AwsAssumeRole(credentialsRole.Arn, credentialsRole.SessionName, credentialsRole.SessionDuration, credentialsRole.ExternalId) : null; yield return KubernetesCluster.CreateForEks(cluster.Arn, cluster.Name, cluster.Endpoint, authenticationDetails.Credentials.AccountId, assumedRole, workerPoolId, cluster.Tags.ToTargetTags()); } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.ServiceMessages; using FluentAssertions; using Newtonsoft.Json.Linq; using NUnit.Framework; using NUnit.Framework.Constraints; namespace Calamari.Testing.Helpers { public class CalamariResult { private readonly int exitCode; private readonly CaptureCommandInvocationOutputSink captured; public CalamariResult(int exitCode, CaptureCommandInvocationOutputSink captured) { this.exitCode = exitCode; this.captured = captured; } public int ExitCode { get { return exitCode; } } public CaptureCommandInvocationOutputSink CapturedOutput { get { return captured; } } public void AssertSuccess() { var capturedErrors = string.Join(Environment.NewLine, captured.Errors); Assert.That(ExitCode, Is.EqualTo(0), string.Format("Expected command to return exit code 0, instead returned {2}{0}{0}Output:{0}{1}", Environment.NewLine, capturedErrors, ExitCode)); } public void AssertFailure() { Assert.That(ExitCode, Is.Not.EqualTo(0), "Expected a non-zero exit code"); } public void AssertFailure(int code) { Assert.That(ExitCode, Is.EqualTo(code), $"Expected an exit code of {code}"); } public void AssertOutput(string expectedOutputFormat, params object[] args) { AssertOutput(String.Format(expectedOutputFormat, args)); } public void AssertOutputVariable(string name, IResolveConstraint resolveConstraint) { var variable = captured.OutputVariables.Get(name); Assert.That(variable, resolveConstraint); } public void AssertServiceMessage(string name, IResolveConstraint? resolveConstraint = null, Dictionary<string, object>? properties = null, string message = "", params object[] args) { switch (name) { case ServiceMessageNames.CalamariFoundPackage.Name: Assert.That(captured.CalamariFoundPackage, resolveConstraint, message, args); break; case ServiceMessageNames.FoundPackage.Name: Assert.That(captured.FoundPackage, Is.Not.Null); if (properties != null) { Assert.That(resolveConstraint, Is.Not.Null, "Resolve constraint was not provided"); foreach (var property in properties) { var fp = JObject.FromObject(captured.FoundPackage); string value; if (property.Key.Contains(".")) { var props = property.Key.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries); value = fp[props[0]][props[1]].ToString(); } else { value = fp[property.Key].ToString(); } AssertServiceMessageValue(property.Key, property.Value, value, resolveConstraint); } } break; case ServiceMessageNames.PackageDeltaVerification.Name: if (!string.IsNullOrWhiteSpace(message)) { Assert.That(captured?.DeltaError?.Replace("\r\n", "\n"), Is.EqualTo(message)); break; } Assert.That(captured.DeltaVerification, Is.Not.Null); if (properties != null) { foreach (var property in properties) { var dv = JObject.FromObject(captured.DeltaVerification); string value; if (property.Key.Contains(".")) { var props = property.Key.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries); value = dv[props[0]][props[1]].ToString(); } else { value = dv[property.Key].ToString(); } AssertServiceMessageValue(property.Key, property.Value, value, resolveConstraint); } } break; } } static void AssertServiceMessageValue(string property, object expected, string actual, IResolveConstraint? resolveConstraint) { Assert.That(actual, Is.Not.Null); Assert.That(actual, Is.Not.Empty); Assert.That(actual.Equals(expected), resolveConstraint, "Expected property '{0}' to have value '{1}' but was actually '{2}'", property, expected, actual); } public void AssertNoOutput(string expectedOutput) { var allOutput = string.Join(Environment.NewLine, captured.Infos); Assert.That(allOutput, Does.Not.Contain(expectedOutput)); } public void AssertOutput(string expectedOutput) { var allOutput = string.Join(Environment.NewLine, captured.Infos); Assert.That(allOutput, Does.Contain(expectedOutput)); } public void AssertOutputContains(string expected) { var allOutput = string.Join(Environment.NewLine, captured.Infos); allOutput.Should().Contain(expected); } public void AssertOutputMatches(string regex, string? message = null) { var allOutput = string.Join(Environment.NewLine, captured.Infos); Assert.That(allOutput, Does.Match(regex), message); } public void AssertNoOutputMatches(string regex) { var allOutput = string.Join(Environment.NewLine, captured.Infos); Assert.That(allOutput, Does.Not.Match(regex)); } public string GetOutputForLineContaining(string expectedOutput) { var found = captured.Infos.SingleOrDefault(i => i.ContainsIgnoreCase(expectedOutput)); found.Should().NotBeNull($"'{expectedOutput}' should exist"); return found; } public void AssertErrorOutput(string expectedOutputFormat, params object[] args) { AssertErrorOutput(String.Format(expectedOutputFormat, args)); } public void AssertErrorOutput(string expectedOutput, bool noNewLines = false) { var separator = noNewLines ? String.Empty : Environment.NewLine; var allOutput = string.Join(separator, captured.Errors); Assert.That(allOutput, Does.Contain(expectedOutput)); } //Assuming we print properties like: //"name: expectedValue" public void AssertPropertyValue(string name, params string[] expectedValues) { var title = name + ":"; string line = GetOutputForLineContaining(title); line.Replace(title, "").Should().BeOneOf(expectedValues); } public void AssertProcessNameAndId(string processName) { AssertOutputMatches(@"HostProcess: (Calamari|dotnet|mono-sgen32|mono-sgen64|mono-sgen) \([0-9]+\)", "Calamari process name and id are printed"); AssertOutputMatches($@"HostProcess: ({processName}|mono-sgen32|mono-sgen64|mono-sgen) \([0-9]+\)", $"{processName} process name and id are printed"); } } }<file_sep>using NUnit.Framework; namespace Calamari.AzureResourceGroup.Tests { [TestFixture] public class DeployAzureResourceGroupConventionFixture { [Test] public void GivenShortStepName_Then_Can_Generate_Deployment_Name_Appropriately() { // Given / When var deploymentName = DeployAzureResourceGroupBehaviour.GenerateDeploymentNameFromStepName("StepA"); // Then Assert.That(deploymentName, Has.Length.LessThanOrEqualTo(64)); Assert.That(deploymentName, Has.Length.EqualTo(38)); Assert.That(deploymentName, Does.StartWith("stepa-")); } [Test] public void GivenNormalStepName_Then_Can_Generate_Deployment_Name_Appropriately() { // Given / When var deploymentName = DeployAzureResourceGroupBehaviour.GenerateDeploymentNameFromStepName("1234567890123456789012345678901"); // 31 chars // Then Assert.That(deploymentName, Has.Length.EqualTo(64)); Assert.That(deploymentName, Does.StartWith("1234567890123456789012345678901-")); } [Test] public void GivenLongStepName_Then_Can_Generate_Deployment_Name_Appropriately() { // Given / When var deploymentName = DeployAzureResourceGroupBehaviour.GenerateDeploymentNameFromStepName("1234567890123456789012345678901234567890"); // 40 chars // Then Assert.That(deploymentName, Has.Length.EqualTo(64)); Assert.That(deploymentName, Does.StartWith("1234567890123456789012345678901-")); // 27 Characters Allow } } }<file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Calamari.Common.Features.Packages.NuGet; using Octopus.Versioning; using Octopus.Versioning.Maven; using Octopus.Versioning.Octopus; using Octopus.Versioning.Semver; /// These classes are shared with Octopus.Server. Ideally should be moved to a common location. namespace Calamari.Common.Features.Packages { public static class PackageName { internal const char SectionDelimiter = '@'; public static string ToCachedFileName(string packageId, IVersion version, string extension) { var cacheBuster = BitConverter.ToString(Guid.NewGuid().ToByteArray()).Replace("-", string.Empty); return SearchPattern(packageId, version, extension, cacheBuster); } static string SearchPattern(string packageId, IVersion? version = null, string? extension = null, string? cacheBuster = null) { var ver = version == null ? "*" : EncodeVersion(version); return $"{Encode(packageId)}{SectionDelimiter}{ver}{SectionDelimiter}{cacheBuster ?? "*"}{extension ?? "*"}"; } public static string ToRegexPattern(string packageId, IVersion version, string rootDir = "") { var pattern = SearchPattern(packageId, version, string.Empty, string.Empty); if (!string.IsNullOrWhiteSpace(rootDir)) pattern = Path.Combine(rootDir, pattern); return Regex.Escape(pattern) + "[a-fA-F0-9]{32}\\..*\\b"; } public static string[] ToSearchPatterns(string packageId, IVersion? version = null, string[]? extensions = null) { extensions = extensions ?? new[] { "*" }; // Lets not bother tring to also match old pattern return extensions.Select(ext => $"{SearchPattern(packageId, version, ext)}") //.Union(extensions.Select(ext =>$"{Encode(packageId)}.{(version == null ? "*" : Encode(version.ToString()))}{ext}-*")) .Distinct() .ToArray(); } /// <summary> /// Old school parser for those file not yet sourced directly from the cache. /// Expects pattern {PackageId}.{Version}.{Extension} /// </summary> /// <param name="fileName"></param> /// <param name="packageId"></param> /// <param name="version"></param> /// <param name="extension"></param> /// <returns></returns> static bool TryParseUnsafeFileName(string fileName, [NotNullWhen(true)]out string? packageId, [NotNullWhen(true)]out IVersion? version, [NotNullWhen(true)]out string? extension) { packageId = null; version = null; extension = null; const string packageIdPattern = @"(?<packageId>(\w+([_.-]\w+)*?))"; const string semanticVersionPattern = @"(?<semanticVersion>(\d+(\.\d+){0,3}" // Major Minor Patch + @"(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?)" // Pre-release identifiers + @"(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?)"; // Build Metadata var fileNamePattern = $@"{packageIdPattern}\.{semanticVersionPattern}"; // here we're getting opinionated about how we split up packages that have both // pre-release identifiers and/or build metadata and also a two-part extension name. // for example "foo.1.0.0-release.tar.gz" could mean: // - release tag: "release.tar" and extension: "gz" // - release tag: "release" and extension: "tar.gz" // The thinking here is // - "tar.gz" and friends are extensions we know about // - this is a method specific to packages and archives // - cases like the above "tar" are unlikely to be part of a release tag or build metadata // so the below method strips out the extensions we know about before performing // the match on the filename. If we don't find any extensions we know about // we fall back to trying to pattern match one in the filename. if (TryMatchKnownExtensions(fileName, out var strippedFileName, out var extensionMatch)) { fileName = strippedFileName; } else { const string extensionPattern = @"(?<extension>(\.([a-zA-Z0-9])+)+)"; //Extension (wont catch two part extensions like .tar.gz if there is a pre-release tag) fileNamePattern += extensionPattern; } var match = Regex.Match(fileName, $"^{fileNamePattern}$", RegexOptions.IgnoreCase); var packageIdMatch = match.Groups["packageId"]; var versionMatch = match.Groups["semanticVersion"]; extensionMatch = extensionMatch.Success ? extensionMatch : match.Groups["extension"]; if (!packageIdMatch.Success || !versionMatch.Success || !extensionMatch.Success) return false; version = VersionFactory.TryCreateSemanticVersion(versionMatch.Value, true); if (version == null) return false; packageId = packageIdMatch.Value; extension = extensionMatch.Value; return true; } static bool TryMatchKnownExtensions(string fileName, out string strippedFileName, out Group extensionMatch) { // At the moment we only have one use case for this: files ending in ".tar.xyz" (see tests) // But if in the future we have more, we can modify this method to accomodate more cases. var knownExtensionPatterns = @"\.tar((\.[a-zA-Z0-9]+)?)"; var match = new Regex($"(?<fileName>.*)(?<extension>{knownExtensionPatterns})$").Match(fileName); strippedFileName = match.Success ? match.Groups["fileName"].Value : fileName; extensionMatch = match.Groups["extension"]; return match.Success; } static bool TryParseEncodedFileName(string fileName, [NotNullWhen(true)]out string? packageId, [NotNullWhen(true)]out IVersion? version, [NotNullWhen(true)]out string? extension) { packageId = null; version = null; extension = null; var sections = fileName.Split(SectionDelimiter); if (sections.Length != 3) return false; try { packageId = Decode(sections[0]); version = DecodeVersion(sections[1]); var extensionStart = sections[2].IndexOf('.'); extension = sections[2].Substring(extensionStart); return true; } catch { return false; } } public static PackageFileNameMetadata FromFile(string? path) { var fileName = Path.GetFileName(path) ?? ""; if (!TryParseEncodedFileName(fileName, out var packageId, out var fileVersion, out var extension) && !TryParseUnsafeFileName(fileName, out packageId, out fileVersion, out extension)) throw new Exception($"Unexpected file format in {fileName}.\nExpected Octopus cached file format: `<PackageId>{SectionDelimiter}<Version>{SectionDelimiter}<CacheBuster>.<Extension>` or `<PackageId>.<SemverVersion>.<Extension>`"); var version = fileVersion; //TODO: Extract... Obviously _could_ be an issue for .net core if (extension.Equals(".nupkg", StringComparison.OrdinalIgnoreCase) && File.Exists(path)) { // var metaData = new FileSystemNuGetPackage(path); // version = metaData.Version; // packageId = metaData.PackageId; var metaData = new LocalNuGetPackage(path!).Metadata; version = SemVerFactory.CreateVersion(metaData.Version.ToString()); packageId = metaData.Id; } return new PackageFileNameMetadata(packageId, version, fileVersion, extension); } public static bool TryMatchTarExtensions(string fileName, out string strippedFileName, out string extension) { // At the moment we only have one use case for this: files ending in ".tar.xyz" // As that is the only format of multiple part extensions we currently supported: https://octopus.com/docs/packaging-applications // But if in the future we have more, we can modify this method to accomodate more cases. var knownExtensionPatterns = @"\.tar((\.[a-zA-Z0-9]+)?)"; var match = new Regex($"(?<fileName>.*)(?<extension>{knownExtensionPatterns})$").Match(fileName); strippedFileName = match.Success ? match.Groups["fileName"].Value : fileName; extension = match.Groups["extension"].Value; return match.Success; } public static bool TryFromFile(string? path, out PackageFileNameMetadata? metadata) { try { metadata = FromFile(path); return true; } catch { metadata = default; return false; } } static string Encode(string input) { return FileNameEscaper.Escape(input); } static string Decode(string input) { return FileNameEscaper.Unescape(input); } static string EncodeVersion(IVersion version) { switch (version) { case MavenVersion _: return "M" + Encode(version.ToString()); case SemanticVersion _: return "S" + Encode(version.ToString()); case OctopusVersion _: return "O" + Encode(version.ToString()); } throw new Exception($"Unrecognised Version format `{version.GetType().Name}`"); } static IVersion DecodeVersion(string input) { switch (input[0]) { case 'S': return VersionFactory.CreateSemanticVersion(Decode(input.Substring(1)), true); case 'M': return VersionFactory.CreateMavenVersion(Decode(input.Substring(1))); case 'O': return VersionFactory.CreateOctopusVersion(Decode(input.Substring(1))); } throw new Exception($"Unrecognised Version format `{input}`"); } } } <file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Octopus.CoreUtilities.Extensions; namespace Calamari.Common.Features.Behaviours { public class SubstituteInFilesBehaviour : IBehaviour { readonly ISubstituteInFiles substituteInFiles; private readonly string subdirectory; public SubstituteInFilesBehaviour( ISubstituteInFiles substituteInFiles, string subdirectory = "") { this.substituteInFiles = substituteInFiles; this.subdirectory = subdirectory; } public bool IsEnabled(RunningDeployment context) { return context.Variables.IsFeatureEnabled(KnownVariables.Features.SubstituteInFiles); } public Task Execute(RunningDeployment context) { substituteInFiles.SubstituteBasedSettingsInSuppliedVariables(Path.Combine(context.CurrentDirectory, subdirectory)); return this.CompletedTask(); } } }<file_sep>using System; using System.IO; using System.Reflection; using System.Security.Cryptography; namespace Calamari.Common.Plumbing.Extensions { public class HashCalculator { public static byte[] Hash(Stream stream, Func<HashAlgorithm> factory) { return factory().ComputeHash(stream); } public static string Hash(Stream stream) { return DefaultAgorithm().ComputeHash(stream).ToHexString(); } public static string Hash(string filename) { using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { return Hash(stream); } } public static byte[] Hash(string filename, Func<HashAlgorithm> factory) { using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { return Hash(stream, factory); } } static HashAlgorithm DefaultAgorithm() { return SHA1.Create(); } /// <summary> /// When FIPS mode is enabled certain algorithms such as MD5 may not be available. /// </summary> /// <param name="factory">A callback function used to create the associated algorithm i.e. MD5.Create</param> /// <returns></returns> public static bool IsAvailableHashingAlgorithm(Func<HashAlgorithm> factory) { Guard.NotNull(factory, "Factory method is required"); try { var result = factory(); return result != null; } catch (TargetInvocationException) { return false; } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Azure.ResourceManager.Resources.Models; using Calamari.AzureAppService.Azure; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.LogParser; using FluentAssertions; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.Rest; using NUnit.Framework; using Polly; using Polly.Retry; using FileShare = System.IO.FileShare; using Sku = Microsoft.Azure.Management.Storage.Models.Sku; using StorageManagementClient = Microsoft.Azure.Management.Storage.StorageManagementClient; namespace Calamari.AzureAppService.Tests { public class LegacyAppServiceBehaviorFixture { [TestFixture] public class WhenUsingAWindowsDotNetAppService : LegacyAppServiceIntegrationTest { private string servicePlanId; protected override async Task ConfigureTestResources(ResourceGroup resourceGroup) { var svcPlan = await RetryPolicy.ExecuteAsync(async () => await webMgmtClient.AppServicePlans.BeginCreateOrUpdateAsync( resourceGroupName: resourceGroup.Name, name: resourceGroup.Name, new AppServicePlan(resourceGroup.Location) { Sku = new SkuDescription("S1", "Standard") } )); servicePlanId = svcPlan.Id; site = await RetryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.BeginCreateOrUpdateAsync( resourceGroupName: resourceGroup.Name, name: resourceGroup.Name, new Site(resourceGroup.Location) { ServerFarmId = svcPlan.Id } )); } [Test] public async Task CanDeployWebAppZip() { var packageInfo = PrepareZipPackage(); await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageInfo.packagePath, packageInfo.packageName, packageInfo.packageVersion); AddVariables(context); }) .Execute(); await AssertContent(site.DefaultHostName, $"Hello {greeting}"); } [Test] public async Task CanDeployWebAppZip_WithAzureCloudEnvironment() { var packageinfo = PrepareZipPackage(); await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); context.AddVariable(AccountVariables.Environment, "AzureCloud"); }) .Execute(); await AssertContent(site.DefaultHostName, $"Hello {greeting}"); } [Test] public async Task CanDeployWebAppZip_ToDeploymentSlot() { var slotName = "stage"; greeting = "stage"; (string packagePath, string packageName, string packageVersion) packageinfo; var slotTask = RetryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.BeginCreateOrUpdateSlotAsync(resourceGroupName, resourceGroupName, site, slotName)); var tempPath = TemporaryDirectory.Create(); new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage"); File.WriteAllText(Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"), "Hello #{Greeting}"); packageinfo.packagePath = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.zip"; packageinfo.packageVersion = "1.0.0"; packageinfo.packageName = "AzureZipDeployPackage"; ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath); var siteSlot = await slotTask; await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); context.Variables.Add("Octopus.Action.Azure.DeploymentSlot", slotName); }) .Execute(); await AssertContent(siteSlot.DefaultHostName, $"Hello {greeting}"); } [Test] public async Task CanDeployNugetPackage() { (string packagePath, string packageName, string packageVersion) packageinfo; greeting = "nuget"; var tempPath = TemporaryDirectory.Create(); new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage"); var doc = new XDocument(new XElement("package", new XAttribute("xmlns", @"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd"), new XElement("metadata", new XElement("id", "AzureZipDeployPackage"), new XElement("version", "1.0.0"), new XElement("title", "AzureZipDeployPackage"), new XElement("authors", "<NAME>"), new XElement("description", "Test Package used to test nuget package deployments") ) )); await Task.Run(() => File.WriteAllText( Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"), "Hello #{Greeting}")); using (var writer = new XmlTextWriter( Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "AzureZipDeployPackage.nuspec"), Encoding.UTF8)) { doc.Save(writer); } packageinfo.packagePath = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.nupkg"; packageinfo.packageVersion = "1.0.0"; packageinfo.packageName = "AzureZipDeployPackage"; ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath); await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); }) .Execute(); //await new AzureAppServiceBehaviour(new InMemoryLog()).Execute(runningContext); await AssertContent(site.DefaultHostName, $"Hello {greeting}"); } [Test] public async Task CanDeployWarPackage() { // Need to spin up a specific app service with Tomcat installed // Need java installed on the test runner (MJH 2022-05-06: is this actually true? I don't see why we'd need java on the test runner) var javaSite = await RetryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.BeginCreateOrUpdateAsync(resourceGroupName, $"{resourceGroupName}-java", new Site(site.Location) { ServerFarmId = servicePlanId, SiteConfig = new SiteConfig { JavaVersion = "1.8", JavaContainer = "TOMCAT", JavaContainerVersion = "9.0" } })); (string packagePath, string packageName, string packageVersion) packageinfo; var assemblyFileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location); packageinfo.packagePath = Path.Combine(assemblyFileInfo.Directory.FullName, "sample.1.0.0.war"); packageinfo.packageVersion = "1.0.0"; packageinfo.packageName = "sample"; greeting = "java"; await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); context.Variables["Octopus.Action.Azure.WebAppName"] = javaSite.Name; context.Variables[PackageVariables.SubstituteInFilesTargets] = "test.jsp"; }) .Execute(); await AssertContent(javaSite.DefaultHostName, $"Hello! {greeting}", "test.jsp"); } [Test] public async Task DeployingWithInvalidEnvironment_ThrowsAnException() { var packageinfo = PrepareZipPackage(); var commandResult = await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); context.AddVariable(AccountVariables.Environment, "NonSenseEnvironment"); }) .Execute(false); commandResult.Outcome.Should().Be(TestExecutionOutcome.Unsuccessful); } [Test] public async Task DeployToTwoTargetsInParallel_Succeeds() { // Arrange var packageInfo = PrepareFunctionAppZipPackage(); // Without larger changes to Calamari and the Test Framework, it's not possible to run two Calamari // processes in parallel in the same test method. Simulate the file locking behaviour by directly // opening the affected file instead var fileLock = File.Open(packageInfo.packagePath, FileMode.Open, FileAccess.Read, FileShare.Read); try { // Act var deployment = await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageInfo.packagePath, packageInfo.packageName, packageInfo.packageVersion); AddVariables(context); context.Variables[KnownVariables.Package.EnabledFeatures] = null; }) .Execute(); // Assert deployment.Outcome.Should().Be(TestExecutionOutcome.Successful); } finally { fileLock.Close(); } } private static (string packagePath, string packageName, string packageVersion) PrepareZipPackage() { (string packagePath, string packageName, string packageVersion) packageinfo; var tempPath = TemporaryDirectory.Create(); new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage"); File.WriteAllText(Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"), "Hello #{Greeting}"); packageinfo.packagePath = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.zip"; packageinfo.packageVersion = "1.0.0"; packageinfo.packageName = "AzureZipDeployPackage"; ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath); return packageinfo; } private static (string packagePath, string packageName, string packageVersion) PrepareFunctionAppZipPackage() { (string packagePath, string packageName, string packageVersion) packageInfo; var testAssemblyLocation = new FileInfo(Assembly.GetExecutingAssembly().Location); var sourceZip = Path.Combine(testAssemblyLocation.Directory.FullName, "functionapp.1.0.0.zip"); packageInfo.packagePath = sourceZip; packageInfo.packageVersion = "1.0.0"; packageInfo.packageName = "functionapp"; return packageInfo; } private void AddVariables(CommandTestBuilderContext context) { AddAzureVariables(context); context.Variables.Add("Greeting", greeting); context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.SubstituteInFiles); context.Variables.Add(PackageVariables.SubstituteInFilesTargets, "index.html"); context.Variables.Add(SpecialVariables.Action.Azure.DeploymentType, "ZipDeploy"); } } [TestFixture] public class WhenUsingALinuxAppService : LegacyAppServiceIntegrationTest { // For some reason we are having issues creating these linux resources on Standard in EastUS protected override string DefaultResourceGroupLocation => "westus2"; protected override async Task ConfigureTestResources(ResourceGroup resourceGroup) { var storageClient = new StorageManagementClient(new TokenCredentials(authToken)) { SubscriptionId = subscriptionId }; var storageAccountName = resourceGroupName.Replace("-", "").Substring(0, 20); var storageAccount = await RetryPolicy.ExecuteAsync(async () => await storageClient.StorageAccounts.CreateAsync(resourceGroupName, accountName: storageAccountName, new StorageAccountCreateParameters { Sku = new Sku("Standard_LRS"), Kind = "Storage", Location = resourceGroupLocation } )); var keys = await storageClient.StorageAccounts.ListKeysAsync(resourceGroupName, storageAccountName); var linuxSvcPlan = await RetryPolicy.ExecuteAsync(async () => await webMgmtClient.AppServicePlans.BeginCreateOrUpdateAsync(resourceGroupName, $"{resourceGroupName}-linux-asp", new AppServicePlan(resourceGroupLocation) { Sku = new SkuDescription("S1", "Standard"), Kind = "linux", Reserved = true } )); site = await RetryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.BeginCreateOrUpdateAsync(resourceGroupName, $"{resourceGroupName}-linux", new Site(resourceGroupLocation) { ServerFarmId = linuxSvcPlan.Id, Kind = "functionapp,linux", Reserved = true, SiteConfig = new SiteConfig { AlwaysOn = true, LinuxFxVersion = "DOTNET|6.0", Use32BitWorkerProcess = true, AppSettings = new List<NameValuePair> { new NameValuePair("FUNCTIONS_WORKER_RUNTIME", "dotnet"), new NameValuePair("FUNCTIONS_EXTENSION_VERSION", "~4"), new NameValuePair("AzureWebJobsStorage", $"DefaultEndpointsProtocol=https;AccountName={storageAccount.Name};AccountKey={keys.Keys.First().Value};EndpointSuffix=core.windows.net") } } } )); } [Test] public async Task CanDeployZip_ToLinuxFunctionApp() { // Arrange var packageInfo = PrepareZipPackage(); // Act await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageInfo.packagePath, packageInfo.packageName, packageInfo.packageVersion); AddVariables(context); }) .Execute(); // Assert await DoWithRetries(10, async () => { await AssertContent(site.DefaultHostName, rootPath: $"api/HttpExample?name={greeting}", actualText: $"Hello, {greeting}"); }, secondsBetweenRetries: 10); } [Test] public async Task CanDeployZip_ToLinuxFunctionApp_WithRunFromPackageFlag() { // Arrange var settings = await RetryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.ListApplicationSettingsAsync(resourceGroupName, site.Name)); settings.Properties["WEBSITE_RUN_FROM_PACKAGE"] = "1"; await RetryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.UpdateApplicationSettingsAsync(resourceGroupName, site.Name, settings)); var packageInfo = PrepareZipPackage(); // Act await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageInfo.packagePath, packageInfo.packageName, packageInfo.packageVersion); AddVariables(context); }) .Execute(); // Assert await DoWithRetries(10, async () => { await AssertContent(site.DefaultHostName, rootPath: $"api/HttpExample?name={greeting}", actualText: $"Hello, {greeting}"); }, secondsBetweenRetries: 10); } private static (string packagePath, string packageName, string packageVersion) PrepareZipPackage() { // Looks like there's some file locking issues if multiple tests try to copy from the same file when running in parallel. // For each test that needs one, create a temporary copy. (string packagePath, string packageName, string packageVersion) packageInfo; var tempPath = TemporaryDirectory.Create(); new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage"); var testAssemblyLocation = new FileInfo(Assembly.GetExecutingAssembly().Location); var sourceZip = Path.Combine(testAssemblyLocation.Directory.FullName, "functionapp.1.0.0.zip"); var temporaryZipLocationForTest = $"{tempPath.DirectoryPath}/functionapp.1.0.0.zip"; File.Copy(sourceZip, temporaryZipLocationForTest); packageInfo.packagePath = temporaryZipLocationForTest; packageInfo.packageVersion = "1.0.0"; packageInfo.packageName = "functionapp"; return packageInfo; } private void AddVariables(CommandTestBuilderContext context) { AddAzureVariables(context); context.Variables.Add(SpecialVariables.Action.Azure.DeploymentType, "ZipDeploy"); } } } }<file_sep>#nullable disable using System; using System.Net; using System.Threading.Tasks; using Azure.ResourceManager.AppService; using Azure.ResourceManager.AppService.Models; using Azure.ResourceManager.Resources; using Calamari.Common.Plumbing.Proxies; using Calamari.Testing; using FluentAssertions; using NUnit.Framework; using NUnit.Framework.Internal; namespace Calamari.AzureAppService.Tests { [TestFixture] [NonParallelizable] class AzureWebAppHealthCheckActionHandlerFixture : AppServiceIntegrationTest { const string NonExistentProxyHostname = "non-existent-proxy.local"; const int NonExistentProxyPort = 3128; readonly IWebProxy originalProxy = WebRequest.DefaultWebProxy; readonly string originalProxyHost = Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost); readonly string originalProxyPort = Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort); protected override async Task ConfigureTestResources(ResourceGroupResource resourceGroup) { var (_, webSiteResource) = await CreateAppServicePlanAndWebApp(resourceGroup, new AppServicePlanData(resourceGroup.Data.Location) { Sku = new AppServiceSkuDescription { Name = "B1", Tier = "Basic" } }, new WebSiteData(resourceGroup.Data.Location) { SiteConfig = new SiteConfigProperties { NetFrameworkVersion = "v6.0" } }); WebSiteResource = webSiteResource; } public override async Task Cleanup() { RestoreLocalEnvironmentProxySettings(); RestoreCiEnvironmentProxySettings(); await base.Cleanup(); } [Test] [NonParallelizable] public async Task WebAppIsFound_WithAndWithoutProxy() { await CommandTestBuilder.CreateAsync<HealthCheckCommand, Program>() .WithArrange(SetUpVariables) .WithAssert(result => result.WasSuccessful.Should().BeTrue()) .Execute(); // Here we verify whether the proxy is correctly picked up // Since the proxy we use here is non-existent, health check to the same Web App should fail due this this proxy setting SetLocalEnvironmentProxySettings(NonExistentProxyHostname, NonExistentProxyPort); SetCiEnvironmentProxySettings(NonExistentProxyHostname, NonExistentProxyPort); await CommandTestBuilder.CreateAsync<HealthCheckCommand, Program>() .WithArrange(SetUpVariables) .WithAssert(result => result.WasSuccessful.Should().BeFalse()) .Execute(false); } [Test] [NonParallelizable] public async Task WebAppIsNotFound() { var randomName = Randomizer.CreateRandomizer().GetString(34, "abcdefghijklmnopqrstuvwxyz1234567890"); await CommandTestBuilder.CreateAsync<HealthCheckCommand, Program>() .WithArrange(SetUpVariables) .WithAssert(result => result.WasSuccessful.Should().BeFalse()) .Execute(false); } static void SetLocalEnvironmentProxySettings(string hostname, int port) { var proxySettings = new UseCustomProxySettings(hostname, port, null!, null!).CreateProxy().Value; WebRequest.DefaultWebProxy = proxySettings; } static void SetCiEnvironmentProxySettings(string hostname, int port) { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, hostname); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, $"{port}"); } void RestoreLocalEnvironmentProxySettings() { WebRequest.DefaultWebProxy = originalProxy; } void RestoreCiEnvironmentProxySettings() { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, originalProxyHost); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, originalProxyPort); } void SetUpVariables(CommandTestBuilderContext context) { AddAzureVariables(context.Variables); context.Variables.Add("Octopus.Account.AccountType", "AzureServicePrincipal"); } } }<file_sep>using SharpCompress.Archives; namespace Calamari.Common.Features.Packages.Decorators { /// <summary> /// A base Decorator which allows addition to the behaviour of an IPackageEntryExtractor /// </summary> /// <remarks> /// IPackageEntryExtractor is a more specific IPackageExtractor, which provides a hook to the extraction /// of each individual ArchiveEntry. /// </remarks> public class PackageEntryExtractorDecorator : IPackageEntryExtractor { readonly IPackageEntryExtractor concreteEntryExtractor; protected PackageEntryExtractorDecorator(IPackageEntryExtractor concreteEntryExtractor) { this.concreteEntryExtractor = concreteEntryExtractor; } public virtual int Extract(string packageFile, string directory) { return concreteEntryExtractor.Extract(packageFile, directory); } public virtual void ExtractEntry(string directory, IArchiveEntry entry) { concreteEntryExtractor.ExtractEntry(directory, entry); } public string[] Extensions => concreteEntryExtractor.Extensions; } } <file_sep>using System; using System.Linq; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.FileSystem; using Octopus.Versioning; namespace Calamari.Commands { [Command("find-package", Description = "Finds the package that matches the specified ID and version. If no exact match is found, it returns a list of the nearest packages that matches the ID")] public class FindPackageCommand : Command { readonly ILog log; readonly IPackageStore packageStore; string packageId; string rawPackageVersion; string packageHash; bool exactMatchOnly; VersionFormat versionFormat = VersionFormat.Semver; public FindPackageCommand(ILog log, IPackageStore packageStore) { this.log = log; this.packageStore = packageStore; Options.Add("packageId=", "Package ID to find", v => packageId = v); Options.Add("packageVersion=", "Package version to find", v => rawPackageVersion = v); Options.Add("packageHash=", "Package hash to compare against", v => packageHash = v); Options.Add("packageVersionFormat=", $"[Optional] Format of version. Options {string.Join(", ", Enum.GetNames(typeof(VersionFormat)))}. Defaults to `{VersionFormat.Semver}`.", v => { if (!Enum.TryParse(v, out VersionFormat format)) { throw new CommandException($"The provided version format `{format}` is not recognised."); } versionFormat = format; }); Options.Add("exactMatch=", "Only return exact matches", v => exactMatchOnly = bool.Parse(v)); } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); Guard.NotNullOrWhiteSpace(packageId, "No package ID was specified. Please pass --packageId YourPackage"); Guard.NotNullOrWhiteSpace(rawPackageVersion, "No package version was specified. Please pass --packageVersion 1.0.0.0"); Guard.NotNullOrWhiteSpace(packageHash, "No package hash was specified. Please pass --packageHash YourPackageHash"); var version = VersionFactory.TryCreateVersion(rawPackageVersion, versionFormat); if (version == null) throw new CommandException($"Package version '{rawPackageVersion}' is not a valid {versionFormat} version string. Please pass --packageVersionFormat with a different version type."); var package = packageStore.GetPackage(packageId, version, packageHash); if (package == null) { log.Verbose($"Package {packageId} version {version} hash {packageHash} has not been uploaded."); if (exactMatchOnly) return 0; FindEarlierPackages(version); return 0; } log.VerboseFormat("Package {0} {1} hash {2} has already been uploaded", package.PackageId, package.Version, package.Hash); LogPackageFound( package.PackageId, package.FileVersion, package.Hash, package.Extension, package.FullFilePath, true ); return 0; } void FindEarlierPackages(IVersion version) { log.VerboseFormat("Finding earlier packages that have been uploaded to this Tentacle."); var nearestPackages = packageStore.GetNearestPackages(packageId, version).ToList(); if (!nearestPackages.Any()) { log.VerboseFormat("No earlier packages for {0} has been uploaded", packageId); } log.VerboseFormat("Found {0} earlier {1} of {2} on this Tentacle", nearestPackages.Count, nearestPackages.Count == 1 ? "version" : "versions", packageId); foreach (var nearestPackage in nearestPackages) { log.VerboseFormat(" - {0}: {1}", nearestPackage.Version, nearestPackage.FullFilePath); LogPackageFound( nearestPackage.PackageId, nearestPackage.FileVersion, nearestPackage.Hash, nearestPackage.Extension, nearestPackage.FullFilePath, false ); } } public void LogPackageFound( string packageId, IVersion packageVersion, string packageHash, string packageFileExtension, string packageFullPath, bool exactMatchExists ) { if (exactMatchExists) log.Verbose("##octopus[calamari-found-package]"); log.VerboseFormat("##octopus[foundPackage id=\"{0}\" version=\"{1}\" versionFormat=\"{2}\" hash=\"{3}\" remotePath=\"{4}\" fileExtension=\"{5}\"]", AbstractLog.ConvertServiceMessageValue(packageId), AbstractLog.ConvertServiceMessageValue(packageVersion.ToString()), AbstractLog.ConvertServiceMessageValue(packageVersion.Format.ToString()), AbstractLog.ConvertServiceMessageValue(packageHash), AbstractLog.ConvertServiceMessageValue(packageFullPath), AbstractLog.ConvertServiceMessageValue(packageFileExtension)); } } }<file_sep>namespace Calamari.Aws.Integration.S3 { public class S3PackageOptions : S3TargetPropertiesBase, IHaveBucketKeyBehaviour { public string BucketKey { get; set; } public string BucketKeyPrefix { get; set; } public BucketKeyBehaviourType BucketKeyBehaviour { get; set; } public string VariableSubstitutionPatterns { get; set; } = ""; public string StructuredVariableSubstitutionPatterns { get; set; } = ""; } }<file_sep>using System; using System.Text; namespace Calamari.Common.Features.Processes { public class CommandLineException : Exception { public CommandLineException( string commandLine, int exitCode, string? additionalInformation, string? workingDirectory = null) : base(FormatMessage(commandLine, exitCode, additionalInformation, workingDirectory)) { } static string FormatMessage( string commandLine, int exitCode, string? additionalInformation, string? workingDirectory) { var sb = new StringBuilder("The following command: "); sb.AppendLine(commandLine); if (!string.IsNullOrEmpty(workingDirectory)) sb.Append("With the working directory of: ") .AppendLine(workingDirectory); sb.Append("Failed with exit code: ").Append(exitCode).AppendLine(); if (!string.IsNullOrWhiteSpace(additionalInformation)) sb.AppendLine(additionalInformation); return sb.ToString(); } } }<file_sep>#if AWS using Calamari.Common.Plumbing.Variables; using System.Threading.Tasks; using System; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.AWS.CloudFormation { [TestFixture] [Category(TestCategory.RunOnceOnWindowsAndLinux)] public class CloudFormationFixture { string GenerateStackName() => $"calamaricloudformation{Guid.NewGuid():N}"; [Test] public async Task CreateOrUpdateCloudFormationTemplate() { var cloudFormationFixtureHelpers = new CloudFormationFixtureHelpers(); var stackName = GenerateStackName(); var templateFilePath = cloudFormationFixtureHelpers.WriteTemplateFile(CloudFormationFixtureHelpers.GetBasicS3Template(stackName)); try { cloudFormationFixtureHelpers.DeployTemplate(stackName, templateFilePath, new CalamariVariables()); await cloudFormationFixtureHelpers.ValidateStackExists(stackName, true); await cloudFormationFixtureHelpers.ValidateS3BucketExists(stackName); } finally { cloudFormationFixtureHelpers.CleanupStack(stackName); } } [Test] public async Task CreateOrUpdateCloudFormationS3Template() { var cloudFormationFixtureHelpers = new CloudFormationFixtureHelpers("us-east-1"); var stackName = GenerateStackName(); try { cloudFormationFixtureHelpers.DeployTemplateS3(stackName, new CalamariVariables()); await cloudFormationFixtureHelpers.ValidateStackExists(stackName, true); } finally { cloudFormationFixtureHelpers.CleanupStack(stackName); } } [Test] public async Task DeleteCloudFormationStack() { var cloudFormationFixtureHelpers = new CloudFormationFixtureHelpers(); var stackName = GenerateStackName(); var templateFilePath = cloudFormationFixtureHelpers.WriteTemplateFile(CloudFormationFixtureHelpers.GetBasicS3Template(stackName)); cloudFormationFixtureHelpers.DeployTemplate(stackName, templateFilePath, new CalamariVariables()); cloudFormationFixtureHelpers.DeleteStack(stackName); await cloudFormationFixtureHelpers.ValidateStackExists(stackName, false); } } } #endif<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using Calamari.Aws.Deployment; using Calamari.Aws.Util; using Calamari.CloudAccounts; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Common.Util; using Octopus.CoreUtilities; using StackStatus = Calamari.Aws.Deployment.Conventions.StackStatus; namespace Calamari.Aws.Integration.CloudFormation.Templates { public class CloudFormationS3Template : BaseTemplate { const string ParametersFile = "parameters.json"; readonly string templateS3Url; public CloudFormationS3Template(ITemplateInputs<Parameter> parameters, string templateS3Url, string stackName, List<string> iamCapabilities, bool disableRollback, string roleArn, IEnumerable<KeyValuePair<string, string>> tags, StackArn stack, Func<IAmazonCloudFormation> clientFactory, IVariables variables) : base(parameters.Inputs, stackName, iamCapabilities, disableRollback, roleArn, tags, stack, clientFactory, variables) { this.templateS3Url = templateS3Url; } public static ICloudFormationRequestBuilder Create(string templateS3Url, string templateParameterS3Url, ICalamariFileSystem fileSystem, IVariables variables, ILog log, string stackName, List<string> capabilities, bool disableRollback, string roleArn, IEnumerable<KeyValuePair<string, string>> tags, StackArn stack, Func<IAmazonCloudFormation> clientFactory) { if (!string.IsNullOrWhiteSpace(templateParameterS3Url) && !templateParameterS3Url.StartsWith("http")) throw new CommandException("Parameters file must start with http: " + templateParameterS3Url); if (!string.IsNullOrWhiteSpace(templateS3Url) && !templateS3Url.StartsWith("http")) throw new CommandException("Template file must start with http: " + templateS3Url); var templatePath = string.IsNullOrWhiteSpace(templateParameterS3Url) ? Maybe<ResolvedTemplatePath>.None : new ResolvedTemplatePath(ParametersFile).AsSome(); if (templatePath.Some()) { DownloadS3(variables, log, templateParameterS3Url); } var parameters = CloudFormationParametersFile.Create(templatePath, fileSystem, variables); return new CloudFormationS3Template(parameters, templateS3Url, stackName, capabilities, disableRollback, roleArn, tags, stack, clientFactory, variables); } /// <summary> /// The SDK allows us to deploy a template from a URL, but does not apply parameters from a URL. So we /// must download the parameters file and parse it locally. /// </summary> static void DownloadS3(IVariables variables, ILog log, string templateParameterS3Url) { try { var environment = AwsEnvironmentGeneration.Create(log, variables).GetAwaiter().GetResult(); var s3Uri = new AmazonS3Uri(templateParameterS3Url); using (IAmazonS3 client = ClientHelpers.CreateS3Client(environment)) { var request = new GetObjectRequest { BucketName = s3Uri.Bucket, Key = s3Uri.Key }; var response = client.GetObjectAsync(request).GetAwaiter().GetResult(); response.WriteResponseStreamToFileAsync(ParametersFile, false, new CancellationTokenSource().Token).GetAwaiter().GetResult(); } } catch (UriFormatException ex) { log.Error($"The parameters URL of {templateParameterS3Url} is invalid"); throw; } } public override CreateStackRequest BuildCreateStackRequest() { return new CreateStackRequest { StackName = stackName, TemplateURL = templateS3Url, Parameters = Inputs.ToList(), Capabilities = capabilities, DisableRollback = disableRollback, RoleARN = roleArn, Tags = tags }; } public override UpdateStackRequest BuildUpdateStackRequest() { return new UpdateStackRequest { StackName = stackName, TemplateURL = templateS3Url, Parameters = Inputs.ToList(), Capabilities = capabilities, RoleARN = roleArn, Tags = tags }; } public override async Task<CreateChangeSetRequest> BuildChangesetRequest() { return new CreateChangeSetRequest { StackName = stack.Value, TemplateURL = templateS3Url, Parameters = Inputs.ToList(), ChangeSetName = variables[AwsSpecialVariables.CloudFormation.Changesets.Name], ChangeSetType = await GetStackStatus() == StackStatus.DoesNotExist ? ChangeSetType.CREATE : ChangeSetType.UPDATE, Capabilities = capabilities, RoleARN = roleArn }; } } }<file_sep>namespace Calamari.Kubernetes.ResourceStatus.Resources { public interface IResourceIdentity { string Kind { get; } string Name { get; } string Namespace { get; } } }<file_sep>using System; namespace Calamari.Common.Features.Packages { public enum FeedType { None = 0, NuGet, Docker, Maven, GitHub, Helm, OciRegistry, AwsElasticContainerRegistry, S3, AzureContainerRegistry, GoogleContainerRegistry, } }<file_sep>using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace Calamari.Testing.Requirements { public class RequiresDotNetCoreAttribute: NUnitAttribute, IApplyToTest { static bool IsNetCore() { #if NETCORE return true; #else return false; #endif } public void ApplyToTest(Test test) { if (!IsNetCore()) { test.RunState = RunState.Skipped; test.Properties.Set(PropertyNames.SkipReason, "Requires dotnet core"); } } } }<file_sep>namespace Calamari.Aws.Integration.CloudFormation { public class ChangeSetArn { public string Value { get; } public ChangeSetArn(string value) { Value = value; } } }<file_sep>using System; using Calamari.Deployment.PackageRetention; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public class PackageId : CaseInsensitiveTinyType { public PackageId(string value) : base(value) { } } }<file_sep>using System; using System.Security.Cryptography.X509Certificates; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Certificates; namespace Calamari.Deployment.Features { public class IisWebSiteBeforeDeployFeature : IisWebSiteFeature { public override string DeploymentStage => DeploymentStages.BeforeDeploy; public override void Execute(RunningDeployment deployment) { var variables = deployment.Variables; if (variables.GetFlag(SpecialVariables.Action.IisWebSite.DeployAsWebSite, false)) { #if WINDOWS_CERTIFICATE_STORE_SUPPORT // Any certificate-variables used by IIS bindings must be placed in the // LocalMachine certificate store EnsureCertificatesUsedInBindingsAreInStore(variables); #endif } } #if WINDOWS_CERTIFICATE_STORE_SUPPORT static void EnsureCertificatesUsedInBindingsAreInStore(IVariables variables) { foreach (var binding in GetEnabledBindings(variables)) { string certificateVariable = binding.certificateVariable; if (string.IsNullOrWhiteSpace(certificateVariable)) continue; EnsureCertificateInStore(variables, certificateVariable.Trim()); } } static void EnsureCertificateInStore(IVariables variables, string certificateVariable) { var thumbprint = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Thumbprint}"); var storeName = FindCertificateInLocalMachineStore(thumbprint); if (storeName != null) { Log.Verbose($"Found existing certificate with thumbprint '{thumbprint}' in Cert:\\LocalMachine\\{storeName}"); } else { storeName = AddCertificateToLocalMachineStore(variables, certificateVariable); } Log.SetOutputVariable(SpecialVariables.Action.IisWebSite.Output.CertificateStoreName, storeName, variables); } static string FindCertificateInLocalMachineStore(string thumbprint) { foreach (var storeName in WindowsX509CertificateStore.GetStoreNames(StoreLocation.LocalMachine)) { var store = new X509Store(storeName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (found.Count != 0 && found[0].HasPrivateKey) { return storeName; } store.Close(); } return null; } static string AddCertificateToLocalMachineStore(IVariables variables, string certificateVariable) { var pfxBytes = Convert.FromBase64String(variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Pfx}")); var password = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Password}"); var subject = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Subject}"); Log.Info($"Adding certificate '{subject}' into Cert:\\LocalMachine\\My"); try { WindowsX509CertificateStore.ImportCertificateToStore(pfxBytes, password, StoreLocation.LocalMachine, "My", true); return "My"; } catch (Exception) { Log.Error("Exception while attempting to add certificate to store"); throw; } } #endif } }<file_sep>using System; using System.Collections.Generic; using Octopus.CoreUtilities; namespace Calamari.Testing.Tools { //TODO: This is pulled in from Sashimi.Server.Contracts as an attempt to run Calamari Commands with Tools. Ideally this wouldn't be duplicated. public interface IDeploymentTool { string Id { get; } Maybe<string> SubFolder { get; } bool AddToPath { get; } Maybe<string> ToolPathVariableToSet { get; } string[] SupportedPlatforms { get; } Maybe<DeploymentToolPackage> GetCompatiblePackage(string platform); } public class DeploymentToolPackage { public DeploymentToolPackage(IDeploymentTool tool, string id) { Tool = tool; Id = id; BootstrapperModulePaths = new string[0]; } public DeploymentToolPackage(IDeploymentTool tool, string id, IReadOnlyList<string> modulePaths) { Tool = tool; Id = id; BootstrapperModulePaths = modulePaths; } public IDeploymentTool Tool { get; } public string Id { get; } public IReadOnlyList<string> BootstrapperModulePaths { get; set; } } }<file_sep>//Copied from https://github.com/chentiangemalc/ProxyUtils/blob/master/SetProxy/ProxyRoutines.cs /* * by <NAME> http://chentiangemalc.wordpress.com * Twitter @chentiangemalc * free to use as you wish...just if you make it better, send me the fixes! :) * * Based on information from: * * - WinInet.H in Windows SDK * - MSDN InternetSetOption Documentation http://msdn.microsoft.com/en-us/library/windows/desktop/aa385114(v=vs.85).aspx * - Frame of the native interop calls borrowed from Mudasir Mirza's post here http://stackoverflow.com/questions/9319906/set-proxy-username-and-password-using-wininet-in-c-sharp * * Most common failure from InternetSetOption will be error code '87' which means "Invalid Parameter" * * Other things to watch out for: * * If you have per-machine proxy policy set, you must be admin to change proxy refer to http://msdn.microsoft.com/en-us/library/ms815135.aspx */ using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace Calamari.Tests { static class ProxyRoutines { #region WinInet Structures [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] private struct InternetPerConnOptionList : IDisposable { public int dwSize; // size of INTERNET_PER_CONN_OPTION_LIST struct public IntPtr szConnection; // connection name to set/query options public int dwOptionCount; // number of options to set/query public int dwOptionError; // on error, which option failed public IntPtr options; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // The bulk of the clean-up code is implemented in Dispose(bool) private void Dispose(bool disposing) { if (disposing) { if (szConnection != IntPtr.Zero) { Marshal.FreeHGlobal(szConnection); szConnection= IntPtr.Zero; } if (options != IntPtr.Zero) { Marshal.FreeHGlobal(options); options = IntPtr.Zero; } } } }; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] private struct InternetConnectionOption { static readonly int Size = Marshal.SizeOf(typeof(InternetConnectionOption)); public PerConnOption m_Option; public InternetConnectionOptionValue m_Value; // Nested Types [StructLayout(LayoutKind.Explicit)] public struct InternetConnectionOptionValue : IDisposable { // Fields [FieldOffset(0)] public System.Runtime.InteropServices.ComTypes.FILETIME m_FileTime; [FieldOffset(0)] public int m_Int; [FieldOffset(0)] public IntPtr m_StringPtr; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // The bulk of the clean-up code is implemented in Dispose(bool) private void Dispose(bool disposing) { if (disposing) { if (m_StringPtr != IntPtr.Zero) { Marshal.FreeHGlobal(m_StringPtr); m_StringPtr = IntPtr.Zero; } } } } } #endregion #region WinInet enums // // options manifests for Internet{Query|Set}Option // private enum InternetOption : uint { INTERNET_OPTION_REFRESH = 0x00000025, INTERNET_OPTION_SETTINGS_CHANGED = 0x00000027, INTERNET_OPTION_PROXY_SETTINGS_CHANGED = 0x0000005F, INTERNET_OPTION_PER_CONNECTION_OPTION = 0x0000004B } // // Options used in INTERNET_PER_CONN_OPTON struct // private enum PerConnOption : int { INTERNET_PER_CONN_FLAGS = 1, // Sets or retrieves the connection type. The Value member will contain one or more of the values from PerConnFlags INTERNET_PER_CONN_PROXY_SERVER = 2, // Sets or retrieves a string containing the proxy servers. INTERNET_PER_CONN_PROXY_BYPASS = 3, // Sets or retrieves a string containing the URLs that do not use the proxy server. INTERNET_PER_CONN_AUTOCONFIG_URL = 4, // Sets or retrieves a string containing the URL to the automatic configuration script. INTERNET_PER_CONN_AUTODISCOVERY_FLAGS = 5 // Sets or AutoDiscovery Flags } // // PER_CONN_FLAGS // [Flags] private enum PerConnFlags : int { PROXY_TYPE_DIRECT = 0x00000001, // direct to net PROXY_TYPE_PROXY = 0x00000002, // via named proxy PROXY_TYPE_AUTO_PROXY_URL = 0x00000004, // autoproxy URL PROXY_TYPE_AUTO_DETECT = 0x00000008 // use autoproxy detection } [Flags] private enum AutoDetectFlags : int { AUTO_PROXY_FLAG_USER_SET = 0x00000001, AUTO_PROXY_FLAG_ALWAYS_DETECT = 0x00000002, AUTO_PROXY_FLAG_DETECTION_RUN = 0x00000004, AUTO_PROXY_FLAG_MIGRATED = 0x00000008, AUTO_PROXY_FLAG_DONT_CACHE_PROXY_RESULT = 0x00000010, AUTO_PROXY_FLAG_CACHE_INIT_RUN = 0x00000020, AUTO_PROXY_FLAG_DETECTION_SUSPECT = 0x00000040 } #endregion private static class NativeMethods { [DllImport("WinInet.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool InternetSetOption(IntPtr hInternet, InternetOption dwOption, IntPtr lpBuffer, int dwBufferLength); } public static bool SetProxy(bool EnableProxy) { return SetProxy(EnableProxy, false, "", "", "",""); } public static bool SetProxy(string ProxyAddress) { return SetProxy(true, false, ProxyAddress, "", "",""); } public static bool SetProxy(string ProxyAddress, string ProxyExceptions) { return SetProxy(true, false, ProxyAddress, ProxyExceptions,"",""); } public static bool SetAutoConfigURL(string AutoConfigURL) { return SetProxy(false, false, "", "", AutoConfigURL,""); } /// <summary> /// Sets proxy. /// </summary> /// <param name="EnableProxy">If true enables proxy, false disables.</param> /// <param name="EnableAutoDetect">If true enables Auto-Detect setting, false disables.</param> /// <param name="ProxyAddress">If you want a specific proxy server</param> /// <param name="ProxyExceptions">Exceptions if you need it</param> /// <param name="AutoConfigURL">If you want an autoconfig URL i.e. PAC file</param> /// <param name="ConnectionName">If you want to apply Proxy Setting to dial up connection, specify name here.</param> /// <returns></returns> public static bool SetProxy(bool EnableProxy,bool EnableAutoDetect,string ProxyAddress,string ProxyExceptions, string AutoConfigURL, string ConnectionName="") { // use this to store our proxy settings InternetPerConnOptionList list = new InternetPerConnOptionList(); // get count of number of options we need...starting with a base of 2. int optionCount = 1; // count out how many options we are going to need to set... if (EnableProxy) optionCount++; if (EnableAutoDetect) optionCount++; if (!string.IsNullOrEmpty(ProxyExceptions)) optionCount++; if (!string.IsNullOrEmpty(AutoConfigURL)) optionCount++; // we'll use this array to store our options InternetConnectionOption[] options = new InternetConnectionOption[optionCount]; // a counter to identify what option we are setting at the moment...there will always be option [0] at a minimum... int optionCurrent = 1; // our per connection flags get stored here... options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS; // enable or disable proxy? if (EnableProxy) { options[1].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER; options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(ProxyAddress); options[0].m_Value.m_Int = (int)PerConnFlags.PROXY_TYPE_PROXY; optionCurrent++; } else { options[0].m_Value.m_Int = (int)PerConnFlags.PROXY_TYPE_DIRECT; } // options[optionCurrent].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS; // optionCurrent++; // configure proxy exceptions...use <local> to bypass proxy for local addresses... if (!string.IsNullOrEmpty(ProxyExceptions)) { options[optionCurrent].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPASS; options[optionCurrent].m_Value.m_StringPtr = Marshal.StringToHGlobalUni(ProxyExceptions); optionCurrent++; } // configure auto config URLw if (!string.IsNullOrEmpty(AutoConfigURL)) { options[optionCurrent].m_Option = PerConnOption.INTERNET_PER_CONN_AUTOCONFIG_URL; options[optionCurrent].m_Value.m_StringPtr = Marshal.StringToHGlobalUni(AutoConfigURL); options[0].m_Value.m_Int = (int)PerConnFlags.PROXY_TYPE_AUTO_PROXY_URL | (int)options[0].m_Value.m_Int; optionCurrent++; } if (EnableAutoDetect) { options[0].m_Value.m_Int = (int)PerConnFlags.PROXY_TYPE_AUTO_DETECT | (int)options[0].m_Value.m_Int; options[optionCurrent].m_Option = PerConnOption.INTERNET_PER_CONN_AUTODISCOVERY_FLAGS; options[optionCurrent].m_Value.m_Int=(int)AutoDetectFlags.AUTO_PROXY_FLAG_ALWAYS_DETECT; optionCurrent++; } // default stuff list.dwSize = Marshal.SizeOf(list); // do we have a connection name specified? if (string.IsNullOrEmpty(ConnectionName)) { // no - the proxy will apply to 'LAN Connections' list.szConnection = IntPtr.Zero; } else { // yes - we will apply proxy to a specific connection list.szConnection = Marshal.StringToHGlobalAuto(ConnectionName); } list.dwOptionCount = options.Length; list.dwOptionError = 0; int optSize = Marshal.SizeOf(typeof(InternetConnectionOption)); // make a pointer out of all that ... IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length); // copy the array over into that spot in memory ... for (int i = 0; i < options.Length; ++i) { IntPtr opt = new IntPtr((long)(optionsPtr.ToInt64() + (i * optSize))); Marshal.StructureToPtr(options[i], opt, false); } list.options = optionsPtr; // and then make a pointer out of the whole list IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((int)list.dwSize); Marshal.StructureToPtr(list, ipcoListPtr, false); // and finally, call the API method! int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero, InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION, ipcoListPtr, list.dwSize) ? -1 : 0; if (returnvalue == 0) { // get the error codes, they might be helpful returnvalue = Marshal.GetLastWin32Error(); } // FREE the data Marshal.FreeCoTaskMem(optionsPtr); Marshal.FreeCoTaskMem(ipcoListPtr); if (returnvalue > 0) { // throw the error codes, they might be helpful (Most likely not!) throw new Win32Exception(returnvalue); } // refresh IE settings - so we don't need to re-launch internet explorer! NativeMethods.InternetSetOption(IntPtr.Zero, InternetOption.INTERNET_OPTION_PROXY_SETTINGS_CHANGED, IntPtr.Zero, 0); return (returnvalue < 0); } } }<file_sep>namespace Calamari.AzureScripting { public static class SpecialVariables { public static class Action { public static class Azure { public static readonly string Environment = "Octopus.Action.Azure.Environment"; public static readonly string SubscriptionId = "Octopus.Action.Azure.SubscriptionId"; public static readonly string ClientId = "Octopus.Action.Azure.ClientId"; public static readonly string TenantId = "Octopus.Action.Azure.TenantId"; public static readonly string Password = "<PASSWORD>"; public static readonly string StorageAccountName = "Octopus.Action.Azure.StorageAccountName"; public static readonly string CertificateBytes = "Octopus.Action.Azure.CertificateBytes"; public static readonly string CertificateThumbprint = "Octopus.Action.Azure.CertificateThumbprint"; public static readonly string ExtensionsDirectory = "Octopus.Action.Azure.ExtensionsDirectory"; } } public static class Account { public const string Name = "Octopus.Account.Name"; public const string AccountType = "Octopus.Account.AccountType"; public const string Username = "Octopus.Account.Username"; public const string Password = "<PASSWORD>"; public const string Token = "Octopus.Account.Token"; } } }<file_sep>using System; namespace Calamari.LaunchTools { public enum LaunchTools { Calamari, Node } public class LaunchToolMeta { public LaunchTools Tool { get; set; } } [AttributeUsage(AttributeTargets.Class)] public class LaunchToolAttribute : Attribute { public LaunchToolAttribute(LaunchTools tool) { Tool = tool; } public LaunchTools Tool { get; } } }<file_sep>using System; using System.Net.Http; #if NETSTANDARD || NETCORE namespace Calamari.Testing; public sealed class TestHttpClientFactory : IHttpClientFactory, IDisposable { readonly Lazy<HttpMessageHandler> lazyHandler = new(() => new HttpClientHandler()); public HttpClient CreateClient(string name) => new(lazyHandler.Value, disposeHandler: false); public void Dispose() { if (lazyHandler.IsValueCreated) { lazyHandler.Value.Dispose(); } } } #endif<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Util { public class RelativeGlobMatch { public string MappedRelativePath { get; } public string WorkingDirectory { get; } public string FilePath { get; } public RelativeGlobMatch(string filePath, string mappedRelativePath, string workingDirectory) { MappedRelativePath = mappedRelativePath; WorkingDirectory = workingDirectory; FilePath = filePath; } } public class RelativeGlobber { private readonly Func<string, string, IEnumerable<string>> enumerateWithGlob; public string WorkingDirectory { get; } public RelativeGlobber(Func<string, string, IEnumerable<string>> enumerateWithGlob, string workingDirectory) { this.enumerateWithGlob = enumerateWithGlob; WorkingDirectory = workingDirectory; } private (string glob, string? output) ParsePattern(string pattern) { var segments = Regex.Split(pattern, "=>"); var output = segments.Length > 1 ? segments[1].Trim() : null; var glob = segments.First().Trim(); return (glob, output); } public IEnumerable<RelativeGlobMatch> EnumerateFilesWithGlob(string pattern) { var (glob, outputPattern) = ParsePattern(pattern); var strategy = GetBasePathStrategy(outputPattern); var result = enumerateWithGlob(WorkingDirectory, glob); return result.Select(x => new RelativeGlobMatch(x, strategy(glob, WorkingDirectory, x).Replace("\\","/"), WorkingDirectory)); } private Func<string, string, string, string> GetBasePathStrategy(string? outputPattern) { if (string.IsNullOrEmpty(outputPattern)) { return (pattern, cwd, file) => GetGlobBase("*", GetBaseSegmentFromGlob(pattern), file.AsRelativePathFrom(cwd)); } if (outputPattern.Contains("**") || !outputPattern.Contains("*")) { return (pattern, cwd, file) => GetGlobBase(outputPattern, GetBaseSegmentFromGlob(pattern), file.AsRelativePathFrom(cwd)); } //Be careful of Path.GetFileName, it will bite you on linux return (pattern, cwd, file) => Path.Combine(outputPattern.Replace("*", string.Empty), new Uri(file).Segments.Last()); } private string GetBaseSegmentFromGlob(string pattern) { var segments = pattern.Split('/', '\\'); var result = string.Empty; foreach (var segment in segments) { if (!segment.Contains("*")) { result = $"{result}{segment}/"; } else { break; } } return result; } private string GetGlobBase(string outputPattern, string segmentBase, string fileSegment) { return Path.Combine(outputPattern.Replace("*", string.Empty), string.IsNullOrEmpty(segmentBase) ? fileSegment : fileSegment.Replace(segmentBase, string.Empty)); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Scripting.WindowsPowerShell; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Integration.FileSystem; using Calamari.Integration.Processes; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Scripting { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class PowerShellCoreBootstrapperFixture { [Test] public void PathToPowerShellExecutable_ShouldReturnLatestPath() { var result = GetPathToPowerShell(new [] {"6", "7-preview", "7", "8-preview"}); result.Should().Be("C:\\Program Files\\PowerShell\\8-preview\\pwsh.exe"); } [Test] public void PathToPowerShellExecutable_SpecifyingMajorVersionShouldReturnPath() { var result = GetPathToPowerShellWithCustomVersion(new [] {"6", "7"}, "6"); result.Should().Be("C:\\Program Files\\PowerShell\\6\\pwsh.exe"); } [Test] public void PathToPowerShellExecutable_SpecifyingMajorVersionAndPreReleaseVersionShouldReturnPath() { var result = GetPathToPowerShellWithCustomVersion(new [] {"6", "7", "7-preview"}, "7-preview"); result.Should().Be("C:\\Program Files\\PowerShell\\7-preview\\pwsh.exe"); } [Test] public void PathToPowerShellExecutable_IncorrectVersionShouldThrowException() { ShouldThrowPowerShellVersionNotFoundException(() => GetPathToPowerShellWithCustomVersion(new [] {"7"}, "6")); } [Test] public void PathToPowerShellExecutable_ShouldThrowExceptionWhenPreReleaseTagMissingFromVersion() { ShouldThrowPowerShellVersionNotFoundException(() => GetPathToPowerShellWithCustomVersion(new [] {"6", "7-preview"}, "7")); } [Test] public void PathToPowerShellExecutable_CustomVersionSpecifiedButNoVersionInstalledShouldThrowException() { ShouldThrowPowerShellVersionNotFoundException(() => GetPathToPowerShellWithCustomVersion(Enumerable.Empty<string>(), "6")); } [Test] public void PathToPowerShellExecutable_ShouldReturnPwshWhenNoVersionsInstalledOrSpecified() { var result = GetPathToPowerShell(Enumerable.Empty<string>()); result.Should().Be("pwsh.exe"); } static void ShouldThrowPowerShellVersionNotFoundException(Action action) { action.Should().Throw<PowerShellVersionNotFoundException>(); } static string GetPathToPowerShellWithCustomVersion(IEnumerable<string> versionInstalled, string customVersion) { var fileSystem = CreateFileSystem(versionInstalled); var variables = new CalamariVariables { {PowerShellVariables.CustomPowerShellVersion, customVersion} }; return CreateBootstrapper(fileSystem).PathToPowerShellExecutable(variables); } static string GetPathToPowerShell(IEnumerable<string> versionInstalled) { var fileSystem = CreateFileSystem(versionInstalled); return CreateBootstrapper(fileSystem).PathToPowerShellExecutable(new CalamariVariables()); } static ICalamariFileSystem CreateFileSystem(IEnumerable<string> versions) { var fileSystem = Substitute.For<ICalamariFileSystem>(); const string parentDirectoryPath = "C:\\Program Files\\PowerShell"; var versionsAndPaths = versions.Select(v => (version: v, path: $"{parentDirectoryPath}\\{v}")).ToArray(); var powerShellPaths = versionsAndPaths.Select(vap => vap.path).ToArray(); fileSystem.EnumerateDirectories(parentDirectoryPath).Returns(powerShellPaths); fileSystem.DirectoryExists(parentDirectoryPath).Returns(true); foreach(var (version, path) in versionsAndPaths) fileSystem.GetDirectoryName(path).Returns(version); foreach (var t in powerShellPaths) fileSystem.FileExists($"{t}\\pwsh.exe").Returns(true); return fileSystem; } static WindowsPowerShellCoreBootstrapper CreateBootstrapper(ICalamariFileSystem mockFileSystem) { return new WindowsPowerShellCoreBootstrapper(mockFileSystem); } } }<file_sep>using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures.Integration.Proxies; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Python { [TestFixture] public class PythonProxyFixture : WindowsScriptProxyFixtureBase { [RequiresMinimumPython3Version(4)] public override void Initialize_NoSystemProxy_NoProxy() { base.Initialize_NoSystemProxy_NoProxy(); } [RequiresMinimumPython3Version(4)] public override void Initialize_NoSystemProxy_CustomProxy() { base.Initialize_NoSystemProxy_CustomProxy(); } [RequiresMinimumPython3Version(4)] public override void Initialize_NoSystemProxy_CustomProxyWithCredentials() { base.Initialize_NoSystemProxy_CustomProxyWithCredentials(); } [RequiresMinimumPython3Version(4)] public override void Initialize_NoSystemProxy_UseSystemProxy() { base.Initialize_NoSystemProxy_UseSystemProxy(); } [RequiresMinimumPython3Version(4)] public override void Initialize_NoSystemProxy_UseSystemProxyWithCredentials() { base.Initialize_NoSystemProxy_UseSystemProxyWithCredentials(); } [RequiresMinimumPython3Version(4)] public override void Initialize_HasSystemProxy_NoProxy() { base.Initialize_HasSystemProxy_NoProxy(); } [RequiresMinimumPython3Version(4)] public override void Initialize_HasSystemProxy_CustomProxy() { base.Initialize_HasSystemProxy_CustomProxy(); } [RequiresMinimumPython3Version(4)] public override void Initialize_HasSystemProxy_CustomProxyWithCredentials() { base.Initialize_HasSystemProxy_CustomProxyWithCredentials(); } [RequiresMinimumPython3Version(4)] public override void Initialize_HasSystemProxy_UseSystemProxy() { base.Initialize_HasSystemProxy_UseSystemProxy(); } [RequiresMinimumPython3Version(4)] public override void Initialize_HasSystemProxy_UseSystemProxyWithCredentials() { base.Initialize_HasSystemProxy_UseSystemProxyWithCredentials(); } protected override CalamariResult RunScript() { return RunScript("proxy.py").result; } protected override bool TestWebRequestDefaultProxy => false; } }<file_sep>using System.Collections.Generic; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Deployment.Features.Java; namespace Calamari.Commands.Java { [Command("java-library", Description = "Invokes the Octopus java library")] public class JavaLibraryCommand : Command { readonly ILog log; string actionType; readonly IScriptEngine scriptEngine; readonly ICalamariFileSystem fileSystem; readonly IVariables variables; readonly ICommandLineRunner commandLineRunner; public JavaLibraryCommand(IScriptEngine scriptEngine, ICalamariFileSystem fileSystem, IVariables variables, ICommandLineRunner commandLineRunner, ILog log) { Options.Add("actionType=", "The step type being invoked.", v => actionType = v); this.scriptEngine = scriptEngine; this.fileSystem = fileSystem; this.variables = variables; this.commandLineRunner = commandLineRunner; this.log = log; } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); JavaRuntime.VerifyExists(); var embeddedResources = new AssemblyEmbeddedResources(); var conventions = new List<IConvention> { new JavaStepConvention(actionType, new JavaRunner(commandLineRunner, variables)), new FeatureRollbackConvention(DeploymentStages.DeployFailed, fileSystem, scriptEngine, commandLineRunner, embeddedResources) }; var deployment = new RunningDeployment(null, variables); var conventionRunner = new ConventionProcessor(deployment, conventions, log); conventionRunner.RunConventions(); return 0; } } }<file_sep>using System; using System.Text; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Substitutions { public class FileSubstituter : IFileSubstituter { readonly ILog log; readonly ICalamariFileSystem fileSystem; public FileSubstituter(ILog log, ICalamariFileSystem fileSystem) { this.log = log; this.fileSystem = fileSystem; } public void PerformSubstitution(string sourceFile, IVariables variables) { PerformSubstitution(sourceFile, variables, sourceFile); } public void PerformSubstitution(string sourceFile, IVariables variables, string targetFile) { log.Verbose($"Performing variable substitution on '{sourceFile}'"); var source = fileSystem.ReadFile(sourceFile, out var sourceFileEncoding); var encoding = GetEncoding(variables, sourceFileEncoding); var result = variables.Evaluate(source, out var error, false); if (!string.IsNullOrEmpty(error)) log.VerboseFormat("Parsing file '{0}' with Octostache returned the following error: `{1}`", sourceFile, error); fileSystem.OverwriteFile(targetFile, result, encoding); } Encoding GetEncoding(IVariables variables, Encoding fileEncoding) { var requestedEncoding = variables.Get(PackageVariables.SubstituteInFilesOutputEncoding); if (requestedEncoding == null) return fileEncoding; try { return Encoding.GetEncoding(requestedEncoding); } catch (ArgumentException) { return fileEncoding; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Logging; using Calamari.Tests.KubernetesFixtures; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Logger { [TestFixture] public class AbstractLogFixture { const string Password = "<PASSWORD>"; [Test] public void AddValueToRedact_ReplacesRedactedStringWithGivenPlaceholder() { const string placeholder = "<placeholder-for-secrets>"; Func<string,string> logMessage = s => $"here is my super cool message with {s} but is it redacted?"; var log = new TestLog(); log.AddValueToRedact(Password, placeholder); log.Info(logMessage(Password)); // Skip 1 because the first log is setting the log level ('##octopus[stdout-default]') log.AllOutput.Skip(1).Should().ContainSingle().Which.Should().Be(logMessage(placeholder)); } [Test] public void AddValueToRedact_RedactsAllInstancesOfGivenString_WhenAddedBeforeLogging() { const string logMessage = "here is a message with " + Password + " and other text"; const string logFormatString = "here is a log format string {0} where stuff is added in the middle"; var log = new TestLog(); log.AddValueToRedact(Password, "<password>"); log.Error(logMessage); log.ErrorFormat(logFormatString, Password); log.Warn(logMessage); log.WarnFormat(logFormatString, Password); log.Info(logMessage); log.InfoFormat(logFormatString, Password); log.Verbose(logMessage); log.VerboseFormat(logFormatString, Password); log.AllOutput.Should().NotContain(m => m.Contains(Password)); } [Test] public void AddValueToRedact_ValueReplacementsCanBeUpdated() { var log = new DoNotDoubleLog(); log.AddValueToRedact(Password, "<my-placeholder>"); Action act = () => log.AddValueToRedact(Password, "<password>"); act.Should().NotThrow(because: "you can update the placeholder for a given redacted value."); } public class TestLog : AbstractLog { public List<string> AllOutput { get; } = new List<string>(); protected override void StdOut(string message) { AllOutput.Add(message); } protected override void StdErr(string message) { AllOutput.Add(message); } } } }<file_sep>using System.IO; using Calamari.Common.Commands; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class SubstituteInFilesFixture { static readonly string StagingDirectory = TestEnvironment.ConstructRootedPath("Applications", "Acme"); [Test] public void ShouldPerformSubstitutions() { string glob = "**\\*config.json"; string actualMatch = "config.json"; var variables = new CalamariVariables(); variables.Set(PackageVariables.SubstituteInFilesTargets, glob); variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.SubstituteInFiles); var deployment = new RunningDeployment(TestEnvironment.ConstructRootedPath("packages"), variables) { StagingDirectory = StagingDirectory }; var fileSystem = Substitute.For<ICalamariFileSystem>(); fileSystem.EnumerateFilesWithGlob(StagingDirectory, GlobMode.GroupExpansionMode, glob).Returns(new[] { Path.Combine(StagingDirectory, actualMatch) }); var substituter = Substitute.For<IFileSubstituter>(); new SubstituteInFiles(new InMemoryLog(), fileSystem, substituter, variables) .SubstituteBasedSettingsInSuppliedVariables(deployment.CurrentDirectory); substituter.Received().PerformSubstitution(Path.Combine(StagingDirectory, actualMatch), variables); } } }<file_sep>using System; using System.Security.Cryptography.X509Certificates; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Certificates; namespace Calamari.Deployment.Conventions { public class EnsureCertificateInstalledInStoreConvention : IInstallConvention { private readonly ICertificateStore certificateStore; private readonly string certificateIdVariableName; private readonly string? storeLocationVariableName; private readonly string? storeNameVariableName; public EnsureCertificateInstalledInStoreConvention( ICertificateStore certificateStore, string certificateIdVariableName, string? storeLocationVariableName = null, string? storeNameVariableName = null) { this.certificateStore = certificateStore; this.certificateIdVariableName = certificateIdVariableName; this.storeLocationVariableName = storeLocationVariableName; this.storeNameVariableName = storeNameVariableName; } public void Install(RunningDeployment deployment) { var variables = deployment.Variables; var clientCertVariable = variables.Get(certificateIdVariableName); if (!string.IsNullOrEmpty(clientCertVariable)) { EnsureCertificateInStore(variables, clientCertVariable); } } void EnsureCertificateInStore(IVariables variables, string certificateVariable) { var storeLocation = StoreLocation.LocalMachine; if (!string.IsNullOrWhiteSpace(storeLocationVariableName) && Enum.TryParse(variables.Get(storeLocationVariableName, StoreLocation.LocalMachine.ToString()), out StoreLocation storeLocationOverride)) storeLocation = storeLocationOverride; var storeName = StoreName.My; if (!string.IsNullOrWhiteSpace(storeNameVariableName) && Enum.TryParse(variables.Get(storeNameVariableName, StoreName.My.ToString()), out StoreName storeNameOverride)) storeName = storeNameOverride; certificateStore.GetOrAdd(variables, certificateVariable, storeName, storeLocation); } } }<file_sep>using System; using System.Diagnostics; using System.Linq; using Calamari.Common.Plumbing; namespace Calamari.Common.Features.Processes.Semaphores { public class ProcessFinder : IProcessFinder { public bool ProcessIsRunning(int processId, string processName) { // borrowed from https://github.com/sillsdev/libpalaso/blob/7c7e5eed0a3d9c8a961b01887cbdebbf1b63b899/SIL.Core/IO/FileLock/SimpleFileLock.cs (Apache 2.0 license) Process process; try { // First, look for a process with this processId process = Process.GetProcesses().FirstOrDefault(x => x.Id == processId); } catch (NotSupportedException) { //FreeBSD does not support EnumProcesses //assume that the process is running return true; } // If there is no process with this processId, it is not running. if (process == null) return false; // Next, check for a match on processName. var isRunning = process.ProcessName == processName; // If a match was found or this is running on Windows, this is as far as we need to go. if (isRunning || CalamariEnvironment.IsRunningOnWindows) return isRunning; // We need to look a little deeper on Linux. // If the name of the process is not "mono" or does not start with "mono-", this is not // a mono application, and therefore this is not the process we are looking for. if (process.ProcessName.ToLower() != "mono" && !process.ProcessName.ToLower().StartsWith("mono-")) return false; // The mono application will have a module with the same name as the process, with ".exe" added. var moduleName = processName.ToLower() + ".exe"; return process.Modules.Cast<ProcessModule>().Any(mod => mod.ModuleName.ToLower() == moduleName); } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class CopyPackageToCustomInstallationDirectoryConventionFixture { RunningDeployment deployment; ICalamariFileSystem fileSystem; IVariables variables; readonly string customInstallationDirectory = (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) ? "/var/tmp/myCustomInstallDir" : "C:\\myCustomInstallDir"; readonly string stagingDirectory = (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) ? "/var/tmp/applications/Acme/1.0.0" : "C:\\applications\\Acme\\1.0.0"; readonly string packageFilePath = (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) ? "/var/tmp/packages" : "C:\\packages"; [SetUp] public void SetUp() { variables = new CalamariVariables(); variables.Set(KnownVariables.OriginalPackageDirectoryPath, stagingDirectory); fileSystem = Substitute.For<ICalamariFileSystem>(); deployment = new RunningDeployment(packageFilePath, variables); } [Test] public void ShouldCopyFilesWhenCustomInstallationDirectoryIsSupplied() { variables.Set(PackageVariables.CustomInstallationDirectory, customInstallationDirectory); CreateConvention().Install(deployment); fileSystem.Received().CopyDirectory( stagingDirectory, customInstallationDirectory); } [Test] public void ShouldNotCopyFilesWhenCustomInstallationDirectoryNotSupplied() { CreateConvention().Install(deployment); fileSystem.DidNotReceive().CopyDirectory(Arg.Any<string>(), customInstallationDirectory); } [Test] [TestCase(GlobMode.GroupExpansionMode)] [TestCase(GlobMode.LegacyMode)] public void ShouldPurgeCustomInstallationDirectoryWhenFlagIsSet(GlobMode globMode) { if (globMode == GlobMode.LegacyMode) { variables.AddFeatureToggles(FeatureToggle.GlobPathsGroupSupportInvertedFeatureToggle); } variables.Set(PackageVariables.CustomInstallationDirectory, customInstallationDirectory); variables.Set(PackageVariables.CustomInstallationDirectoryShouldBePurgedBeforeDeployment, true.ToString()); CreateConvention().Install(deployment); // Assert directory was purged fileSystem.Received().PurgeDirectory(customInstallationDirectory, Arg.Any<FailureOptions>(), globMode); } [Test] [TestCase(GlobMode.GroupExpansionMode)] [TestCase(GlobMode.LegacyMode)] public void ShouldPassGlobsToPurgeWhenSet(GlobMode globMode) { if (globMode == GlobMode.LegacyMode) { variables.AddFeatureToggles(FeatureToggle.GlobPathsGroupSupportInvertedFeatureToggle); } variables.Set(PackageVariables.CustomInstallationDirectory, customInstallationDirectory); variables.Set(PackageVariables.CustomInstallationDirectoryShouldBePurgedBeforeDeployment, true.ToString()); variables.Set(PackageVariables.CustomInstallationDirectoryPurgeExclusions, "firstglob\nsecondglob"); CreateConvention().Install(deployment); // Assert we handed in the exclusion globs fileSystem.Received().PurgeDirectory(customInstallationDirectory, Arg.Any<FailureOptions>(), globMode, Arg.Is<string[]>(a => a[0] == "firstglob" && a[1] == "secondglob")); } [Test] public void ShouldNotPurgeCustomInstallationDirectoryWhenFlagIsNotSet() { variables.Set(PackageVariables.CustomInstallationDirectory, customInstallationDirectory); variables.Set(PackageVariables.CustomInstallationDirectoryShouldBePurgedBeforeDeployment, false.ToString()); CreateConvention().Install(deployment); // Assert directory was purged fileSystem.DidNotReceive().PurgeDirectory(customInstallationDirectory, Arg.Any<FailureOptions>()); } [Test] public void ShouldSetCustomInstallationDirectoryVariable() { variables.Set(PackageVariables.CustomInstallationDirectory, customInstallationDirectory); CreateConvention().Install(deployment); Assert.AreEqual(variables.Get(PackageVariables.CustomInstallationDirectory), customInstallationDirectory); } [Test] [ExpectedException(ExpectedMessage = "An error occurred when evaluating the value for the custom install directory. The following tokens were unable to be evaluated: '#{CustomInstalDirectory}'")] public void ShouldFailIfCustomInstallationDirectoryVariableIsNotEvaluated() { variables.Set("CustomInstallDirectory", customInstallationDirectory); variables.Set(PackageVariables.CustomInstallationDirectory, "#{CustomInstalDirectory}"); CreateConvention().Install(deployment); } [Test] [ExpectedException(ExpectedMessage = "The custom install directory 'relative/path/to/folder' is a relative path, please specify the path as an absolute path or a UNC path.")] public void ShouldFailIfCustomInstallationDirectoryIsRelativePath() { const string relativeInstallDirectory = "relative/path/to/folder"; variables.Set(PackageVariables.CustomInstallationDirectory, relativeInstallDirectory); CreateConvention().Install(deployment); } [Test] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] [ExpectedException(ExpectedMessage = "Access to the path /var/tmp/myCustomInstallDir was denied. Ensure that the application that uses this directory is not running.")] public void ShouldNotIncludeIISRelatedInfoInErrorMessageWhenAccessDeniedException() { variables.Set(PackageVariables.CustomInstallationDirectory, customInstallationDirectory); fileSystem.CopyDirectory(Arg.Any<string>(), Arg.Any<string>()) .ThrowsForAnyArgs( new UnauthorizedAccessException($"Access to the path {customInstallationDirectory} was denied.")); CreateConvention().Install(deployment); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] [ExpectedException(ExpectedMessage = "Access to the path C:\\myCustomInstallDir was denied. Ensure that the application that uses this directory is not running. If this is an IIS website, stop the application pool or use an app_offline.htm file (see https://g.octopushq.com/TakingWebsiteOffline).")] public void ShouldIncludeIISRelatedInfoInErrorMessageWhenAccessDeniedException() { variables.Set(PackageVariables.CustomInstallationDirectory, customInstallationDirectory); fileSystem.CopyDirectory(Arg.Any<string>(), Arg.Any<string>()) .ThrowsForAnyArgs( new UnauthorizedAccessException($"Access to the path {customInstallationDirectory} was denied.")); CreateConvention().Install(deployment); } private CopyPackageToCustomInstallationDirectoryConvention CreateConvention() { return new CopyPackageToCustomInstallationDirectoryConvention(fileSystem); } } }<file_sep>using System.IO; using System.Threading.Tasks; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Newtonsoft.Json.Linq; using NUnit.Framework; // ReSharper disable MethodHasAsyncOverload - File.ReadAllTextAsync does not exist for .net framework targets namespace Calamari.AzureResourceGroup.Tests { [TestFixture] internal class AzureResourceGroupActionHandlerFixture { private string clientId; private string clientSecret; private string tenantId; private string subscriptionId; private IResourceGroup resourceGroup; private IAzure azure; [OneTimeSetUp] public async Task Setup() { clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); var resourceGroupName = SdkContext.RandomResourceName(nameof(AzureResourceGroupActionHandlerFixture), 60); var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud); azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithSubscription(subscriptionId); resourceGroup = await azure.ResourceGroups .Define(resourceGroupName) .WithRegion(Region.USWest) .CreateAsync(); } [OneTimeTearDown] public async Task Cleanup() { if (resourceGroup != null) { await azure.ResourceGroups.DeleteByNameAsync(resourceGroup.Name); } } [Test] public async Task Deploy_with_template_in_package() { var packagePath = TestEnvironment.GetTestPath("Packages", "AzureResourceGroup"); await CommandTestBuilder.CreateAsync<DeployAzureResourceGroupCommand, Program>() .WithArrange(context => { AddDefaults(context); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupDeploymentMode, "Complete"); context.Variables.Add("Octopus.Action.Azure.TemplateSource", "Package"); context.Variables.Add("Octopus.Action.Azure.ResourceGroupTemplate", "azure_website_template.json"); context.Variables.Add("Octopus.Action.Azure.ResourceGroupTemplateParameters", "azure_website_params.json"); context.WithFilesToCopy(packagePath); }) .Execute(); } [Test] public async Task Deploy_with_template_inline() { var packagePath = TestEnvironment.GetTestPath("Packages", "AzureResourceGroup"); var templateFileContent = File.ReadAllText(Path.Combine(packagePath, "azure_website_template.json")); var paramsFileContent = File.ReadAllText(Path.Combine(packagePath, "azure_website_params.json")); var parameters = JObject.Parse(paramsFileContent)["parameters"].ToString(); await CommandTestBuilder.CreateAsync<DeployAzureResourceGroupCommand, Program>() .WithArrange(context => { AddDefaults(context); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupDeploymentMode, "Complete"); context.Variables.Add("Octopus.Action.Azure.TemplateSource", "Inline"); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupTemplate, File.ReadAllText(Path.Combine(packagePath, "azure_website_template.json"))); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupTemplateParameters, parameters); context.WithFilesToCopy(packagePath); AddTemplateFiles(context, templateFileContent, paramsFileContent); }) .Execute(); } [Test] [WindowsTest] [RequiresPowerShell5OrAbove] public async Task Deploy_Ensure_Tools_Are_Configured() { var packagePath = TestEnvironment.GetTestPath("Packages", "AzureResourceGroup"); var templateFileContent = File.ReadAllText(Path.Combine(packagePath, "azure_website_template.json")); var paramsFileContent = File.ReadAllText(Path.Combine(packagePath, "azure_website_params.json")); var parameters = JObject.Parse(paramsFileContent)["parameters"].ToString(); const string psScript = @" $ErrorActionPreference = 'Continue' az --version Get-AzureEnvironment az group list"; await CommandTestBuilder.CreateAsync<DeployAzureResourceGroupCommand, Program>() .WithArrange(context => { AddDefaults(context); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupDeploymentMode, "Complete"); context.Variables.Add("Octopus.Action.Azure.TemplateSource", "Inline"); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupTemplate, File.ReadAllText(Path.Combine(packagePath, "azure_website_template.json"))); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupTemplateParameters, parameters); context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts); context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.Deploy, ScriptSyntax.PowerShell), psScript); context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.PreDeploy, ScriptSyntax.CSharp), "Console.WriteLine(\"Hello from C#\");"); context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.PostDeploy, ScriptSyntax.FSharp), "printfn \"Hello from F#\""); context.WithFilesToCopy(packagePath); AddTemplateFiles(context, templateFileContent, paramsFileContent); }) .Execute(); } private void AddDefaults(CommandTestBuilderContext context) { context.Variables.Add("Octopus.Account.AccountType", "AzureServicePrincipal"); context.Variables.Add(AzureAccountVariables.SubscriptionId, subscriptionId); context.Variables.Add(AzureAccountVariables.TenantId, tenantId); context.Variables.Add(AzureAccountVariables.ClientId, clientId); context.Variables.Add(AzureAccountVariables.Password, clientSecret); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupName, resourceGroup.Name); context.Variables.Add("ResourceGroup", resourceGroup.Name); context.Variables.Add("SKU", "Shared"); context.Variables.Add("WebSite", SdkContext.RandomResourceName(string.Empty, 12)); context.Variables.Add("Location", resourceGroup.RegionName); context.Variables.Add("AccountPrefix", SdkContext.RandomResourceName(string.Empty, 6)); } private static void AddTemplateFiles(CommandTestBuilderContext context, string template, string parameters) { context.WithDataFile(template, "template.json"); context.WithDataFile(parameters, "parameters.json"); } } }<file_sep>using System; namespace Calamari.Testing.LogParser { public class ProcessOutput { readonly ProcessOutputSource source; readonly string text; readonly DateTimeOffset occurred; public ProcessOutput(ProcessOutputSource source, string text) : this(source, text, DateTimeOffset.UtcNow) { } public ProcessOutput(ProcessOutputSource source, string text, DateTimeOffset occurred) { this.source = source; this.text = text; this.occurred = occurred; } public ProcessOutputSource Source { get { return this.source; } } public DateTimeOffset Occurred { get { return this.occurred; } } public string Text { get { return this.text; } } } }<file_sep>using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Exceptions; using Octopus.CoreUtilities.Extensions; using Octopus.Versioning; using Octopus.Versioning.Maven; namespace Calamari.Integration.Packages.Download { /// <summary> /// The Calamari Maven artifact downloader. /// </summary> public class MavenPackageDownloader : IPackageDownloader { /// <summary> /// These are extensions that can be handled by extractors other than the Java one. We accept these /// because not all artifacts from Maven will be used by Java. /// </summary> public static readonly string[] AdditionalExtensions = { ".nupkg", ".tar.bz2", ".tar.bz", ".tbz", ".tgz", ".tar.gz", ".tar.Z", ".tar" }; static readonly IPackageDownloaderUtils PackageDownloaderUtils = new PackageDownloaderUtils(); readonly ICalamariFileSystem fileSystem; public MavenPackageDownloader(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } public PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, string? feedUsername, string? feedPassword, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; var cacheDirectory = PackageDownloaderUtils.GetPackageRoot(feedId); fileSystem.EnsureDirectoryExists(cacheDirectory); if (!forcePackageDownload) { var downloaded = SourceFromCache(packageId, version, cacheDirectory); if (downloaded != null) { Log.VerboseFormat("Package was found in cache. No need to download. Using file: '{0}'", downloaded.FullFilePath); return downloaded; } } return DownloadPackage(packageId, version, feedUri, GetFeedCredentials(feedUsername, feedPassword), cacheDirectory, maxDownloadAttempts, downloadAttemptBackoff); } /// <summary> /// Attempt to find a package id and version in the local cache /// </summary> /// <param name="packageId">The desired package id</param> /// <param name="version">The desired version</param> /// <param name="cacheDirectory">The location of cached files</param> /// <returns>The path to a cached version of the file, or null if none are found</returns> PackagePhysicalFileMetadata? SourceFromCache(string packageId, IVersion version, string cacheDirectory) { Log.VerboseFormat("Checking package cache for package {0} v{1}", packageId, version.ToString()); var files = fileSystem.EnumerateFilesRecursively(cacheDirectory, PackageName.ToSearchPatterns(packageId, version, JarPackageExtractor.SupportedExtensions)); foreach (var file in files) { var package = PackageName.FromFile(file); if (package == null) continue; var idMatches = string.Equals(package.PackageId, packageId, StringComparison.OrdinalIgnoreCase); var versionExactMatch = string.Equals(package.Version.ToString(), version.ToString(), StringComparison.OrdinalIgnoreCase); var nugetVerMatches = package.Version.Equals(version); if (idMatches && (nugetVerMatches || versionExactMatch)) return PackagePhysicalFileMetadata.Build(file, package); } return null; } /// <summary> /// Downloads the artifact from the Maven repo. This method first checks the repo for /// artifacts with all available extensions, as we have no indication what type of artifact /// (jar, war, zip etc) that we are attempting to download. /// </summary> /// <param name="packageId">The package id</param> /// <param name="version">The package version</param> /// <param name="feedUri">The maven repo uri</param> /// <param name="feedCredentials">The mavben repo credentials</param> /// <param name="cacheDirectory">The directory to download the file into</param> /// <param name="maxDownloadAttempts">How many times to try the download</param> /// <param name="downloadAttemptBackoff">How long to wait between attempts</param> /// <returns>The path to the downloaded artifact</returns> PackagePhysicalFileMetadata DownloadPackage( string packageId, IVersion version, Uri feedUri, ICredentials feedCredentials, string cacheDirectory, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { Guard.NotNullOrWhiteSpace(packageId, "packageId can not be null"); Guard.NotNull(version, "version can not be null"); Guard.NotNullOrWhiteSpace(cacheDirectory, "cacheDirectory can not be null"); Guard.NotNull(feedUri, "feedUri can not be null"); Log.Info("Downloading Maven package {0} v{1} from feed: '{2}'", packageId, version, feedUri); Log.VerboseFormat("Downloaded package will be stored in: '{0}'", cacheDirectory); var mavenPackageId = MavenPackageID.CreatePackageIdFromOctopusInput(packageId, version); var snapshotMetadata = GetSnapshotMetadata(mavenPackageId, feedUri, feedCredentials, maxDownloadAttempts, downloadAttemptBackoff); var found = FirstToRespond(mavenPackageId, feedUri, feedCredentials, snapshotMetadata); Log.VerboseFormat("Found package {0} v{1}", packageId, version); return DownloadArtifact( found, packageId, version, feedUri, feedCredentials, cacheDirectory, maxDownloadAttempts, downloadAttemptBackoff, snapshotMetadata); } /// <summary> /// Actually download the maven file. /// </summary> /// <returns>The path to the downloaded file</returns> PackagePhysicalFileMetadata DownloadArtifact( MavenPackageID mavenGavFirst, string packageId, IVersion version, Uri feedUri, ICredentials feedCredentials, string cacheDirectory, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff, XmlDocument? snapshotMetadata) { Guard.NotNull(mavenGavFirst, "mavenGavFirst can not be null"); Guard.NotNullOrWhiteSpace(packageId, "packageId can not be null"); Guard.NotNull(version, "version can not be null"); Guard.NotNullOrWhiteSpace(cacheDirectory, "cacheDirectory can not be null"); Guard.NotNull(feedUri, "feedUri can not be null"); var localDownloadName = Path.Combine(cacheDirectory, PackageName.ToCachedFileName(packageId, version, "." + mavenGavFirst.Packaging)); var downloadUrl = feedUri.ToString().TrimEnd('/') + (snapshotMetadata == null ? mavenGavFirst.DefaultArtifactPath : mavenGavFirst.SnapshotArtifactPath(GetLatestSnapshotRelease( snapshotMetadata, mavenGavFirst.Packaging, mavenGavFirst.Classifier, mavenGavFirst.Version))); for (var retry = 0; retry < maxDownloadAttempts; ++retry) try { Log.Verbose($"Downloading Attempt {downloadUrl} TO {localDownloadName}"); using (var client = new WebClient { Credentials = feedCredentials }) { client.DownloadFile(downloadUrl, localDownloadName); var packagePhysicalFileMetadata = PackagePhysicalFileMetadata.Build(localDownloadName); return packagePhysicalFileMetadata ?? throw new CommandException($"Unable to retrieve metadata for package {packageId}, version {version}"); } } catch (Exception ex) { if ((retry + 1) == maxDownloadAttempts) throw new MavenDownloadException("Failed to download the Maven artifact.\r\nLast Exception Message: " + ex.Message); Thread.Sleep(downloadAttemptBackoff); } throw new MavenDownloadException("Failed to download the Maven artifact"); } /// <summary> /// Find the first artifact to respond to a HTTP head request. We use this to find the extension /// of the artifact that we are trying to download. /// </summary> /// <returns>The details of the first (and only) artifact to respond to a head request</returns> MavenPackageID FirstToRespond( MavenPackageID mavenPackageId, Uri feedUri, ICredentials feedCredentials, XmlDocument? snapshotMetadata) { Guard.NotNull(mavenPackageId, "mavenPackageId can not be null"); Guard.NotNull(feedUri, "feedUri can not be null"); var errors = new ConcurrentBag<string>(); var fileChecks = JarPackageExtractor.SupportedExtensions .Union(AdditionalExtensions) // Either consider all supported extensions, or select only the specified extension .Where(e => string.IsNullOrEmpty(mavenPackageId.Packaging) || e == "." + mavenPackageId.Packaging) .Select(extension => { var packageId = new MavenPackageID( mavenPackageId.Group, mavenPackageId.Artifact, mavenPackageId.Version, Regex.Replace(extension, "^\\.", ""), mavenPackageId.Classifier); var result = MavenPackageExists(packageId, feedUri, feedCredentials, snapshotMetadata); errors.Add(result.ErrorMsg); return new { result.Found, MavenPackageId = packageId }; }); var firstFound = fileChecks.FirstOrDefault(res => res.Found); if (firstFound != null) return firstFound.MavenPackageId; throw new MavenDownloadException($"Failed to find the Maven artifact.\r\nReceived Error(s):\r\n{string.Join("\r\n", errors.Distinct().ToList())}"); } /// <summary> /// Performs the actual HTTP head request to check for the presence of a maven artifact with a /// given extension. /// </summary> /// <returns>true if the package exists, and false otherwise</returns> (bool Found, string ErrorMsg) MavenPackageExists(MavenPackageID mavenGavParser, Uri feedUri, ICredentials feedCredentials, XmlDocument? snapshotMetadata) { var uri = feedUri.ToString().TrimEnd('/') + (snapshotMetadata == null ? mavenGavParser.DefaultArtifactPath : mavenGavParser.SnapshotArtifactPath( GetLatestSnapshotRelease( snapshotMetadata, mavenGavParser.Packaging, mavenGavParser.Classifier, mavenGavParser.Version))); try { var req = WebRequest.Create(uri); req.Method = "HEAD"; req.Credentials = feedCredentials; using (var response = (HttpWebResponse)req.GetResponse()) { return ((int)response.StatusCode >= 200 && (int)response.StatusCode <= 299, $"Unexpected Response: {response.StatusCode}"); } } catch (Exception ex) { return (false, $"Failed to download {uri}\n" + ex.Message); } } /// <summary> /// Attempt to get the snapshot maven-metadata.xml file, which we will need to use to build up /// the filenames of snapshot versions. /// </summary> /// <returns>The snapshot maven-metadata.xml file if it exists, and a null result otherwise</returns> XmlDocument? GetSnapshotMetadata( MavenPackageID mavenPackageID, Uri feedUri, ICredentials feedCredentials, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { var url = feedUri.ToString().TrimEnd('/') + mavenPackageID.GroupVersionMetadataPath; for (var retry = 0; retry < maxDownloadAttempts; ++retry) try { var request = WebRequest.Create(url); request.Credentials = feedCredentials; using (var response = (HttpWebResponse)request.GetResponse()) { if (response.IsSuccessStatusCode() || (int)response.StatusCode == 404) using (var respStream = response.GetResponseStream()) { var xmlDoc = new XmlDocument(); xmlDoc.Load(respStream); return xmlDoc; } } return null; } catch (WebException ex) when (ex.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.NotFound) { return null; } catch (Exception ex) { if (retry == maxDownloadAttempts) throw new MavenDownloadException("Unable to retrieve Maven Snapshot Metadata.\r\nLast Exception Message: " + ex.Message); Thread.Sleep(downloadAttemptBackoff); } return null; } //Shared code with Server. Should live in Common Location public string GetLatestSnapshotRelease(XmlDocument? snapshotMetadata, string? extension, string? classifier, string defaultVersion) { return snapshotMetadata?.ToEnumerable() .Select(doc => doc.DocumentElement?.SelectSingleNode("./*[local-name()='versioning']")) .Select(node => node?.SelectNodes("./*[local-name()='snapshotVersions']/*[local-name()='snapshotVersion']")) .Where(nodes => nodes != null) .SelectMany(nodes => nodes.Cast<XmlNode>()) .Where(node => (node.SelectSingleNode("./*[local-name()='extension']")?.InnerText.Trim() ?? "").Equals(extension?.Trim(), StringComparison.OrdinalIgnoreCase)) // Classifier is optional, and the XML element does not exists if the artifact has no classifier .Where(node => classifier == null || (node.SelectSingleNode("./*[local-name()='classifier']")?.InnerText.Trim() ?? "").Equals(classifier.Trim(), StringComparison.OrdinalIgnoreCase)) .OrderByDescending(node => node.SelectSingleNode("./*[local-name()='updated']")?.InnerText) .Select(node => node.SelectSingleNode("./*[local-name()='value']")?.InnerText) .FirstOrDefault() ?? defaultVersion; } static ICredentials GetFeedCredentials(string? feedUsername, string? feedPassword) { ICredentials credentials = CredentialCache.DefaultNetworkCredentials; if (!String.IsNullOrWhiteSpace(feedUsername)) { credentials = new NetworkCredential(feedUsername, feedPassword); } return credentials; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Integration; namespace Calamari.Kubernetes { public class KubernetesContextScriptWrapper : IScriptWrapper { readonly IVariables variables; readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly ICalamariEmbeddedResources embeddedResources; public KubernetesContextScriptWrapper(IVariables variables, ILog log, ICalamariEmbeddedResources embeddedResources, ICalamariFileSystem fileSystem) { this.variables = variables; this.log = log; this.fileSystem = fileSystem; this.embeddedResources = embeddedResources; } public int Priority => ScriptWrapperPriorities.KubernetesContextPriority; /// <summary> /// One of these fields must be present for a k8s step /// </summary> public bool IsEnabled(ScriptSyntax syntax) { var hasClusterUrl = !string.IsNullOrEmpty(variables.Get(SpecialVariables.ClusterUrl)); var hasClusterName = !string.IsNullOrEmpty(variables.Get(SpecialVariables.AksClusterName)) || !string.IsNullOrEmpty(variables.Get(SpecialVariables.EksClusterName)) || !string.IsNullOrEmpty(variables.Get(SpecialVariables.GkeClusterName)); return hasClusterUrl || hasClusterName; } public IScriptWrapper NextWrapper { get; set; } public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string> environmentVars) { var workingDirectory = Path.GetDirectoryName(script.File); if (environmentVars == null) { environmentVars = new Dictionary<string, string>(); } var kubectl = new Kubectl(variables, log, commandLineRunner, workingDirectory, environmentVars); var setupKubectlAuthentication = new SetupKubectlAuthentication(variables, log, commandLineRunner, kubectl, environmentVars, workingDirectory); var accountType = variables.Get("Octopus.Account.AccountType"); try { var result = setupKubectlAuthentication.Execute(accountType); if (result.ExitCode != 0) { return result; } } catch (CommandLineException) { return new CommandResult(String.Empty, 1); } if (scriptSyntax == ScriptSyntax.PowerShell && accountType == "AzureServicePrincipal") { variables.Set("OctopusKubernetesTargetScript", $"{script.File}"); variables.Set("OctopusKubernetesTargetScriptParameters", script.Parameters); using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory))) { return NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars); } } return NextWrapper.ExecuteScript(script, scriptSyntax, commandLineRunner, environmentVars); } string CreateContextScriptFile(string workingDirectory) { const string contextFile = "AzurePowershellContext.ps1"; var contextScriptFile = Path.Combine(workingDirectory, $"Octopus.{contextFile}"); var contextScript = embeddedResources.GetEmbeddedResourceText(Assembly.GetExecutingAssembly(), $"Calamari.Kubernetes.Scripts.{contextFile}"); fileSystem.OverwriteFile(contextScriptFile, contextScript); return contextScriptFile; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Scripts; namespace Calamari.Common.Features.FunctionScriptContributions { class CodeGenFunctionsRegistry { readonly Dictionary<ScriptSyntax, ICodeGenFunctions> codeGenerators; public CodeGenFunctionsRegistry(IEnumerable<ICodeGenFunctions> functionCodeGenerators) { codeGenerators = functionCodeGenerators.ToDictionary(functions => functions.Syntax); } public ScriptSyntax[] SupportedScriptSyntax => codeGenerators.Keys.ToArray(); public ICodeGenFunctions GetCodeGenerator(ScriptSyntax syntax) { return codeGenerators[syntax]; } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Calamari.Common.Plumbing.Variables { public interface IVariables : IEnumerable<KeyValuePair<string, string>> { string? this[string name] { get; set; } bool IsSet(string name); void Set(string name, string? value); void SetStrings(string variableName, IEnumerable<string> values, string separator); string? GetRaw(string variableName); [return: NotNullIfNotNull("defaultValue")] string? Get(string variableName, string? defaultValue = null); [return: NotNullIfNotNull("defaultValue")] string? Get(string variableName, out string? error, string? defaultValue = null); [return: NotNullIfNotNull("expressionOrVariableOrText")] public string? Evaluate(string? expressionOrVariableOrText, out string? error, bool haltOnError = true); string? Evaluate(string? expressionOrVariableOrText); List<string> GetStrings(string variableName, params char[] separators); List<string> GetPaths(string variableName); bool GetFlag(string variableName, bool defaultValueIfUnset = false); int? GetInt32(string variableName); List<string> GetNames(); List<string> GetIndexes(string variableCollectionName); void Add(string key, string? value); void AddFlag(string key, bool value); IVariables Clone(); IVariables CloneAndEvaluate(); string SaveAsString(); } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Assent; using Calamari.Common; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.FunctionScriptContributions; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using Newtonsoft.Json; using NUnit.Framework; namespace Calamari.Tests.Fixtures.FunctionCodeGen { [TestFixture] [RequiresNonFreeBSDPlatform] [Category(TestCategory.PlatformAgnostic)] public class DynamicFunctionFixture { [Test] public Task EnsurePowerShellLanguageCodeGen() { using (var scriptFile = new TemporaryFile(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()))) { var serializedRegistrations = JsonConvert.SerializeObject(new[] { new ScriptFunctionRegistration("MyFunc", String.Empty, "create-something", new Dictionary<string, FunctionParameter> { { "mystring", new FunctionParameter(ParameterType.String) }, { "myboolean", new FunctionParameter(ParameterType.Bool) }, { "mynumber", new FunctionParameter(ParameterType.Int) } }), new ScriptFunctionRegistration("MyFunc2", String.Empty, "create-something2", new Dictionary<string, FunctionParameter> { { "mystring", new FunctionParameter(ParameterType.String, "myboolean") }, { "myboolean", new FunctionParameter(ParameterType.Bool) }, { "mynumber", new FunctionParameter(ParameterType.Int, "myboolean") } }) }); return CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts); var script = @"New-MyFunc -mystring 'Hello' -myboolean -mynumber 1 New-MyFunc2 -mystring 'Hello' -myboolean -mynumber 1 New-MyFunc2 -mystring 'Hello' -mynumber 1"; context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.Deploy, ScriptSyntax.PowerShell), script); context.Variables.Add(ScriptFunctionsVariables.Registration, serializedRegistrations); context.Variables.Add(ScriptFunctionsVariables.CopyScriptWrapper, scriptFile.FilePath); }) .WithAssert(result => { var script = File.ReadAllText(scriptFile.FilePath); this.Assent(script, AssentConfiguration.Default); }) .Execute(); } } class MyProgram : CalamariFlavourProgramAsync { public MyProgram(ILog log) : base(log) { } } [Command("mycommand")] class MyCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield break; } } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Behaviours { public abstract class PackagedScriptBehaviour : PackagedScriptRunner, IBehaviour { protected PackagedScriptBehaviour(ILog log, string scriptFilePrefix, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(log, scriptFilePrefix, fileSystem, scriptEngine, commandLineRunner) { } public bool IsEnabled(RunningDeployment context) { return context.Variables.GetFlag(KnownVariables.Package.RunPackageScripts, true); } public Task Execute(RunningDeployment context) { RunPreferredScript(context); if (context.Variables.GetFlag(KnownVariables.DeleteScriptsOnCleanup, true)) { DeleteScripts(context); } return this.CompletedTask(); } } public class PreDeployPackagedScriptBehaviour : PackagedScriptBehaviour, IPreDeployBehaviour { public PreDeployPackagedScriptBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(log, DeploymentStages.PreDeploy, fileSystem, scriptEngine, commandLineRunner) { } } public class DeployPackagedScriptBehaviour : PackagedScriptBehaviour, IDeployBehaviour { public DeployPackagedScriptBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(log, DeploymentStages.Deploy, fileSystem, scriptEngine, commandLineRunner) { } } public class PostDeployPackagedScriptBehaviour : PackagedScriptBehaviour, IPostDeployBehaviour { public PostDeployPackagedScriptBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(log, DeploymentStages.PostDeploy, fileSystem, scriptEngine, commandLineRunner) { } } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Calamari.AzureCloudService.CloudServicePackage.ManifestSchema { public class LayoutDefinition { public static readonly XName ElementName = PackageDefinition.AzureNamespace + "LayoutDefinition"; static readonly XName NameElementName = PackageDefinition.AzureNamespace + "Name"; static readonly XName LayoutDescriptionElementName = PackageDefinition.AzureNamespace + "LayoutDescription"; public LayoutDefinition() { FileDefinitions = new List<FileDefinition>(); } public LayoutDefinition(XElement element) { Name = element.Element(NameElementName).Value; FileDefinitions = element.Element(LayoutDescriptionElementName) .Elements(FileDefinition.ElementName) .Select(x => new FileDefinition(x)) .ToList(); } public string Name { get; set; } public ICollection<FileDefinition> FileDefinitions { get; private set; } public XElement ToXml() { return new XElement(ElementName, new XElement(NameElementName, Name), new XElement(LayoutDescriptionElementName, FileDefinitions.Select(x => x.ToXml()).ToArray())); } } }<file_sep>using System.Collections.Generic; using System.Linq; using Autofac; using Autofac.Builder; using Autofac.Features.Metadata; using Calamari.Common.Util; namespace Calamari.Common.Plumbing.Extensions { public static class ContainerBuilderServicePrioritisationExtensions { const string RegistrationPriorityMetadataKey = "RegistrationPriority"; public static void WithPriority<TLimit, TActivatorData, TRegistrationStyle>(this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> target, int priority) { target.WithMetadata(RegistrationPriorityMetadataKey, priority); } public static void RegisterPrioritisedList<T>(this ContainerBuilder builder) { builder.Register(c => { var registeredServices = c.Resolve<IEnumerable<Meta<T>>>().ToList(); // Start by getting the core list of prioritised registrations var prioritisedServices = registeredServices .Where(t => t.Metadata.ContainsKey(RegistrationPriorityMetadataKey)) .OrderBy(t => t.Metadata[RegistrationPriorityMetadataKey]) .Select(t => t.Value); // Also grab any extras that had no priority metadata var unprioritisedServices = registeredServices .Where(t => t.Metadata.ContainsKey(RegistrationPriorityMetadataKey) != true) .Select(t => t.Value); // Return the prioritised services first, followed by the unprioritised ones in any order return new PrioritisedList<T>(prioritisedServices.Union(unprioritisedServices)); }); } } /// <summary> /// Helper class to enable the DI container to provide a list of services where order is important, /// supported by registration of specific metadata using <see cref="ContainerBuilderServicePrioritisationExtensions"/> /// </summary> /// <typeparam name="T">Service requiring prioritisation</typeparam> public class PrioritisedList<T> : List<T> { public PrioritisedList() { } public PrioritisedList(IEnumerable<T> collection) : base(collection) { } } } <file_sep>using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Calamari.AzureResourceGroup { /// <summary> /// There are 2 ways the parameters can be passed to Calamari but the Resource Group Client supports only one format so we need to /// normalize the input. Have a look at ResourceGroupTemplateNormalizerFixture for more details. /// </summary> class ResourceGroupTemplateNormalizer : IResourceGroupTemplateNormalizer { public string Normalize(string json) { try { var envelope = JsonConvert.DeserializeObject<ParameterEnvelope>(json); return JsonConvert.SerializeObject(envelope.Parameters); } catch (JsonSerializationException) { return json; } } class ParameterEnvelope { [JsonProperty("parameters", Required = Required.Always)] public JObject Parameters { get; set; } } } }<file_sep>using System; using System.IO; namespace Calamari.Common.Plumbing.Extensions { public static class PathExtensions { public static bool IsChildOf(this string child, string parent) { var childDir = GetSanitizedDirInfo(child); var parentDir = GetSanitizedDirInfo(parent); var isParent = false; if (childDir.FullName == parentDir.FullName) return true; while (childDir.Parent != null) { if (childDir.Parent.FullName == parentDir.FullName) { isParent = true; break; } childDir = childDir.Parent; } return isParent; } static DirectoryInfo GetSanitizedDirInfo(string dir) { if (dir == "/") return new DirectoryInfo(dir); dir = dir.TrimEnd('\\', '/'); // normal paths need trailing path separator removed to match if (CalamariEnvironment.IsRunningOnWindows) { if (dir.EndsWith(":")) // c: needs trailing slash to match dir = dir + "\\"; dir = dir.ToLowerInvariant(); } return new DirectoryInfo(dir); } } }<file_sep>using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Behaviours { public class ConfiguredScriptBehaviour : IBehaviour { readonly string deploymentStage; readonly ILog log; readonly IScriptEngine scriptEngine; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; public ConfiguredScriptBehaviour(string deploymentStage, ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) { this.deploymentStage = deploymentStage; this.log = log; this.scriptEngine = scriptEngine; this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; } public bool IsEnabled(RunningDeployment context) { return context.Variables.IsFeatureEnabled(KnownVariables.Features.CustomScripts); } public Task Execute(RunningDeployment context) { foreach (ScriptSyntax scriptType in Enum.GetValues(typeof(ScriptSyntax))) { var scriptName = KnownVariables.Action.CustomScripts.GetCustomScriptStage(deploymentStage, scriptType); var scriptBody = context.Variables.Get(scriptName, out var error); if (!string.IsNullOrEmpty(error)) log.VerboseFormat( "Parsing script for phase {0} with Octostache returned the following error: `{1}`", deploymentStage, error); if (string.IsNullOrWhiteSpace(scriptBody)) continue; if (!scriptEngine.GetSupportedTypes().Contains(scriptType)) throw new CommandException($"{scriptType} scripts are not supported on this platform ({deploymentStage})"); var scriptFile = Path.Combine(context.CurrentDirectory, scriptName); var scriptBytes = scriptType == ScriptSyntax.Bash ? scriptBody.EncodeInUtf8NoBom() : scriptBody.EncodeInUtf8Bom(); fileSystem.WriteAllBytes(scriptFile, scriptBytes); // Execute the script log.VerboseFormat("Executing '{0}'", scriptFile); var result = scriptEngine.Execute(new Script(scriptFile), context.Variables, commandLineRunner); if (result.ExitCode != 0) { throw new CommandException($"{deploymentStage} script returned non-zero exit code: {result.ExitCode}"); } if (result.HasErrors && context.Variables.GetFlag(KnownVariables.Action.FailScriptOnErrorOutput, false)) { throw new CommandException($"{deploymentStage} script returned zero exit code but had error output."); } if (context.Variables.GetFlag(KnownVariables.DeleteScriptsOnCleanup, true)) { // And then delete it (this means if the script failed, it will persist, which may assist debugging) fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure); } } return this.CompletedTask(); } } public class PreDeployConfiguredScriptBehaviour : ConfiguredScriptBehaviour, IPreDeployBehaviour { public PreDeployConfiguredScriptBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(DeploymentStages.PreDeploy, log, fileSystem, scriptEngine, commandLineRunner) { } } public class DeployConfiguredScriptBehaviour : ConfiguredScriptBehaviour, IDeployBehaviour { public DeployConfiguredScriptBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(DeploymentStages.Deploy, log, fileSystem, scriptEngine, commandLineRunner) { } } public class PostDeployConfiguredScriptBehaviour : ConfiguredScriptBehaviour, IPostDeployBehaviour { public PostDeployConfiguredScriptBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(DeploymentStages.PostDeploy, log, fileSystem, scriptEngine, commandLineRunner) { } } }<file_sep>using System; using System.Text; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Microsoft.Identity.Client; namespace Calamari.AzureAppService { internal class Auth { public static async Task<string> GetBasicAuthCreds(ServicePrincipalAccount principalAccount, AzureTargetSite targetSite) { var publishingProfile = await PublishingProfile.GetPublishingProfile(targetSite, principalAccount); string credential = Convert.ToBase64String( Encoding.ASCII.GetBytes($"{publishingProfile.Username}:{publishingProfile.Password}")); return credential; } public static async Task<string> GetAuthTokenAsync(ServicePrincipalAccount principalAccount) { return await GetAuthTokenAsync(principalAccount.TenantId, principalAccount.ClientId, principalAccount.Password, principalAccount.ResourceManagementEndpointBaseUri, principalAccount.ActiveDirectoryEndpointBaseUri); } public static async Task<string> GetAuthTokenAsync(string tenantId, string applicationId, string password, string managementEndPoint, string activeDirectoryEndPoint) { var authContext = GetContextUri(activeDirectoryEndPoint, tenantId); var app = ConfidentialClientApplicationBuilder.Create(applicationId) .WithClientSecret(password) .WithAuthority(authContext) .Build(); var result = await app.AcquireTokenForClient( new [] { $"{managementEndPoint}/.default" }) .WithTenantId(tenantId) .ExecuteAsync() .ConfigureAwait(false); return result.AccessToken; } static string GetContextUri(string activeDirectoryEndPoint, string tenantId) { if (!activeDirectoryEndPoint.EndsWith("/")) { return $"{activeDirectoryEndPoint}/{tenantId}"; } return $"{activeDirectoryEndPoint}{tenantId}"; } } } <file_sep>using System; using System.Threading.Tasks; using Microsoft.Azure.Management.WebSites; using Microsoft.Rest; namespace Calamari.AzureWebApp { static class AzureServicePrincipalAccountExtensions { public static async Task<ServiceClientCredentials> Credentials(this AzureServicePrincipalAccount account) { return new TokenCredentials(await GetAuthorizationToken(account)); } public static async Task<WebSiteManagementClient> CreateWebSiteManagementClient(this AzureServicePrincipalAccount account) { return string.IsNullOrWhiteSpace(account.ResourceManagementEndpointBaseUri) ? new WebSiteManagementClient(await account.Credentials()) { SubscriptionId = account.SubscriptionNumber } : new WebSiteManagementClient(new Uri(account.ResourceManagementEndpointBaseUri), await account.Credentials()) { SubscriptionId = account.SubscriptionNumber }; } static Task<string> GetAuthorizationToken(AzureServicePrincipalAccount account) { return ServicePrincipal.GetAuthorizationToken(account.TenantId, account.ClientId, account.Password, account.ResourceManagementEndpointBaseUri, account.ActiveDirectoryEndpointBaseUri); } } }<file_sep>using System; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Common.Features.Packages.Decorators.ArchiveLimits { public class ArchiveLimitException : InvalidOperationException { public const string CorruptedHeaderWarning = "The given archive may be corrupt, or a security risk: the archive headers did not match the actual file sizes. As a precaution, those files have been truncated to their declared size. Please see https://oc.to/ArchiveDecompressionLimits for information on why we do this, and how to modify these settings if the archive is legitimate."; ArchiveLimitException(string message) : base(message) { } public static ArchiveLimitException FromUncompressedSizeBreach(long totalUncompressedBytes) { var totalUncompressedText = totalUncompressedBytes.ToFileSizeString(); return new ArchiveLimitException($"The given archive may be a security risk: it would extract to {totalUncompressedText}. As a precaution, we’ve blocked decompression. Please see https://oc.to/ArchiveDecompressionLimits for information on why we do this, and how to modify these settings if the archive is legitimate."); } public static ArchiveLimitException FromCompressionRatioBreach(long totalCompressedBytes, long totalUncompressedBytes) { var totalCompressedText = totalCompressedBytes.ToFileSizeString(); var totalUncompressedText = totalUncompressedBytes.ToFileSizeString(); return new ArchiveLimitException($"The given archive may be a security risk: it is {totalCompressedText} compressed, but would extract to {totalUncompressedText}. As a precaution, we’ve blocked decompression. Please see https://oc.to/ArchiveDecompressionLimits for information on why we do this, and how to modify these settings if the archive is legitimate."); } } }<file_sep>using Nuke.Common.ProjectModel; namespace Calamari.Build; public class CalamariPackageMetadata { public Project? Project { get; init; } public string? Framework { get; init; } public string? Architecture { get; init; } public bool IsCrossPlatform { get; init; } }<file_sep>using System.Threading.Tasks; using Calamari.Common.Plumbing.Logging; using Microsoft.Identity.Client; namespace Calamari.AzureResourceGroup { static class ServicePrincipal { public static async Task<string> GetAuthorizationToken(string tenantId, string applicationId, string password, string managementEndPoint, string activeDirectoryEndPoint) { var authContext = GetContextUri(activeDirectoryEndPoint, tenantId); Log.Verbose($"Authentication Context: {authContext}"); var app = ConfidentialClientApplicationBuilder.Create(applicationId) .WithClientSecret(password) .WithAuthority(authContext) .Build(); var result = await app.AcquireTokenForClient( new [] { $"{managementEndPoint}/.default" }) .WithTenantId(tenantId) .ExecuteAsync() .ConfigureAwait(false); return result.AccessToken; } static string GetContextUri(string activeDirectoryEndPoint, string tenantId) { if (!activeDirectoryEndPoint.EndsWith("/")) { return $"{activeDirectoryEndPoint}/{tenantId}"; } return $"{activeDirectoryEndPoint}{tenantId}"; } } }<file_sep>using System; using System.Linq; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Variables; namespace Calamari.Tests.Helpers { public static class VariableExtensions { public static void AddFeatureToggles(this IVariables variables, params FeatureToggle[] featureToggles) { var existingToggles = variables.Get(KnownVariables.EnabledFeatureToggles)?.Split(',') .Select(t => (FeatureToggle)Enum.Parse(typeof(FeatureToggle), t)) ?? Enumerable.Empty<FeatureToggle>(); var allToggles = existingToggles.Concat(featureToggles).Distinct(); variables.Set(KnownVariables.EnabledFeatureToggles, string.Join(",", allToggles.Select(t => t.ToString()))); } } }<file_sep>namespace Calamari.AzureResourceGroup { static class DefaultVariables { public const string ResourceManagementEndpoint = "https://management.azure.com/"; public const string ActiveDirectoryEndpoint = "https://login.windows.net/"; } }<file_sep>using System; using System.IO; using System.Reflection; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; namespace Calamari.Tests.Fixtures.Integration.FileSystem { public class TestCalamariPhysicalFileSystem : CalamariPhysicalFileSystem { public new static ICalamariFileSystem GetPhysicalFileSystem() { if (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) { return new TestNixCalamariPhysicalFileSystem(); } return new TestWindowsPhysicalFileSystem(); } public void SetFileBasePath(string basePath) => File = new TestFile(basePath); public override bool GetDiskFreeSpace(string directoryPath, out ulong totalNumberOfFreeBytes) { throw new NotImplementedException("*testing* this is in TestCalamariPhysicalFileSystem"); } public override bool GetDiskTotalSpace(string directoryPath, out ulong totalNumberOfBytes) { throw new NotImplementedException("*testing* this is in TestCalamariPhysicalFileSystem"); } private class TestNixCalamariPhysicalFileSystem : NixCalamariPhysicalFileSystem, ICalamariFileSystem { public new string CreateTemporaryDirectory() { var path = Path.Combine("/tmp", Guid.NewGuid().ToString()); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } } private class TestWindowsPhysicalFileSystem : WindowsPhysicalFileSystem, ICalamariFileSystem { public new string CreateTemporaryDirectory() { var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); path = Path.Combine(path, Assembly.GetEntryAssembly()?.GetName().Name ?? Guid.NewGuid().ToString()); path = Path.Combine(path, Guid.NewGuid().ToString()); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.Decorators; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Deployment.Features; using Calamari.Deployment.Features.Java; namespace Calamari.Commands.Java { [Command("deploy-java-archive", Description = "Deploys a Java archive (.jar, .war, .ear)")] public class DeployJavaArchiveCommand : Command { PathToPackage archiveFile; readonly ILog log; readonly IScriptEngine scriptEngine; readonly IVariables variables; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; readonly ISubstituteInFiles substituteInFiles; readonly IExtractPackage extractPackage; readonly IStructuredConfigVariablesService structuredConfigVariablesService; readonly IDeploymentJournalWriter deploymentJournalWriter; public DeployJavaArchiveCommand( ILog log, IScriptEngine scriptEngine, IVariables variables, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner, ISubstituteInFiles substituteInFiles, IExtractPackage extractPackage, IStructuredConfigVariablesService structuredConfigVariablesService, IDeploymentJournalWriter deploymentJournalWriter) { Options.Add("archive=", "Path to the Java archive to deploy.", v => archiveFile = new PathToPackage(Path.GetFullPath(v))); this.log = log; this.scriptEngine = scriptEngine; this.variables = variables; this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; this.substituteInFiles = substituteInFiles; this.extractPackage = extractPackage; this.structuredConfigVariablesService = structuredConfigVariablesService; this.deploymentJournalWriter = deploymentJournalWriter; } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); Guard.NotNullOrWhiteSpace(archiveFile, "No archive file was specified. Please pass --archive YourPackage.jar"); JavaRuntime.VerifyExists(); if (!File.Exists(archiveFile)) throw new CommandException("Could not find archive file: " + archiveFile); Log.Info("Deploying: " + archiveFile); var semaphore = SemaphoreFactory.Get(); var journal = new DeploymentJournal(fileSystem, semaphore, variables); var jarTools = new JarTool(commandLineRunner, log, variables); var packageExtractor = new JarPackageExtractor(jarTools).WithExtractionLimits(log, variables); var embeddedResources = new AssemblyEmbeddedResources(); var javaRunner = new JavaRunner(commandLineRunner, variables); var featureClasses = new List<IFeature> { new TomcatFeature(javaRunner), new WildflyFeature(javaRunner) }; var deployExploded = variables.GetFlag(SpecialVariables.Action.Java.DeployExploded); var conventions = new List<IConvention> { new AlreadyInstalledConvention(log, journal), // If we are deploying the package exploded then extract directly to the application directory. // Else, if we are going to re-pack, then we extract initially to a temporary directory deployExploded ? (IInstallConvention)new DelegateInstallConvention(d => extractPackage.ExtractToApplicationDirectory(archiveFile, packageExtractor)) : new DelegateInstallConvention(d => extractPackage.ExtractToStagingDirectory(archiveFile, packageExtractor)), new FeatureConvention(DeploymentStages.BeforePreDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new ConfiguredScriptConvention(new PreDeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new PackagedScriptConvention(new PreDeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new FeatureConvention(DeploymentStages.AfterPreDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new SubstituteInFilesConvention(new SubstituteInFilesBehaviour(substituteInFiles)), new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(structuredConfigVariablesService)), new RePackArchiveConvention(log, fileSystem, jarTools), new CopyPackageToCustomInstallationDirectoryConvention(fileSystem), new FeatureConvention(DeploymentStages.BeforeDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new PackagedScriptConvention(new DeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new ConfiguredScriptConvention(new DeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new FeatureConvention(DeploymentStages.AfterDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new FeatureConvention(DeploymentStages.BeforePostDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new PackagedScriptConvention(new PostDeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new ConfiguredScriptConvention(new PostDeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new FeatureConvention(DeploymentStages.AfterPostDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new RollbackScriptConvention(log, DeploymentStages.DeployFailed, fileSystem, scriptEngine, commandLineRunner), new FeatureRollbackConvention(DeploymentStages.DeployFailed, fileSystem, scriptEngine, commandLineRunner, embeddedResources) }; var deployment = new RunningDeployment(archiveFile, variables); var conventionRunner = new ConventionProcessor(deployment, conventions, log); try { conventionRunner.RunConventions(); deploymentJournalWriter.AddJournalEntry(deployment, true, archiveFile); } catch (Exception) { deploymentJournalWriter.AddJournalEntry(deployment, false, archiveFile); throw; } return 0; } } }<file_sep>using System; using Calamari.Common.Plumbing.Logging; using Calamari.Tests.Helpers; namespace Calamari.Tests { public static class TestProgramWrapper { //This is a shell around Calamari.exe so we can use it in .net core testing, since in .net core when we reference the //Calamari project we only get the dll, not the exe public static int Main(string[] args) { return new TestProgram(ConsoleLog.Instance).Execute(args); } } }<file_sep>using System; using Calamari.Common.Features.Packages; using SharpCompress.Archives; namespace Calamari.Tests.Fixtures.Integration.Packages.ArchiveLimits { public class NullExtractor : IPackageEntryExtractor { public string[] Extensions => new[] { ".zip" }; public int Extract(string packageFile, string directory) { return 1; } public void ExtractEntry(string directory, IArchiveEntry entry) { } } }<file_sep>namespace Calamari.AzureWebApp { static class SpecialVariables { public static class Action { public static class Azure { public static readonly string Environment = "Octopus.Action.Azure.Environment"; public static readonly string SubscriptionId = "Octopus.Action.Azure.SubscriptionId"; public static readonly string ResourceGroupName = "Octopus.Action.Azure.ResourceGroupName"; public static readonly string WebAppName = "Octopus.Action.Azure.WebAppName"; public static readonly string WebAppSlot = "Octopus.Action.Azure.DeploymentSlot"; public static readonly string RemoveAdditionalFiles = "Octopus.Action.Azure.RemoveAdditionalFiles"; public static readonly string AppOffline = "Octopus.Action.Azure.AppOffline"; public static readonly string PreserveAppData = "Octopus.Action.Azure.PreserveAppData"; public static readonly string PreservePaths = "Octopus.Action.Azure.PreservePaths"; public static readonly string PhysicalPath = "Octopus.Action.Azure.PhysicalPath"; public static readonly string UseChecksum = "Octopus.Action.Azure.UseChecksum"; } } public static class Account { public const string Name = "Octopus.Account.Name"; public const string AccountType = "Octopus.Account.AccountType"; public const string Username = "Octopus.Account.Username"; public const string Password = "<PASSWORD>"; public const string Token = "Octopus.Account.Token"; } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Microsoft.Azure.Management.WebSites; using Microsoft.Rest; namespace Calamari.AzureAppService.Behaviors { public class LegacyRestartAzureWebAppBehaviour : IDeployBehaviour { ILog Log { get; } public LegacyRestartAzureWebAppBehaviour(ILog log) { Log = log; } public bool IsEnabled(RunningDeployment context) => !FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.IsEnabled(context.Variables); public async Task Execute(RunningDeployment context) { var variables = context.Variables; var webAppName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); var resourceGroupName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName); var principalAccount = ServicePrincipalAccount.CreateFromKnownVariables(variables); var token = await Auth.GetAuthTokenAsync(principalAccount); var webAppClient = new WebSiteManagementClient(new Uri(principalAccount.ResourceManagementEndpointBaseUri), new TokenCredentials(token)) {SubscriptionId = principalAccount.SubscriptionNumber}; var targetSite = new AzureTargetSite(principalAccount.SubscriptionNumber, resourceGroupName, webAppName, slotName); Log.Info("Performing soft restart of web app"); await webAppClient.WebApps.RestartAsync(targetSite, true); } } }<file_sep>using System; using System.Threading.Tasks; namespace Calamari.Common.Plumbing.Pipeline { public static class IBehaviourExtensions { public static Task CompletedTask(this IBehaviour _) { #if NETSTANDARD return Task.CompletedTask; #elif NET452 return Task.FromResult(0); #else return Net40CompletedTask; #endif } #if NET40 static readonly Task Net40CompletedTask = CreateNet40CompletedTask(); static Task<int> CreateNet40CompletedTask() { var taskCompletionSource = new TaskCompletionSource<int>(); taskCompletionSource.SetResult(0); return taskCompletionSource.Task; } #endif } }<file_sep>#if NETCORE using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Calamari.Azure; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Kubernetes.Commands; using Calamari.Testing; using Calamari.Testing.Helpers; using FluentAssertions; using Newtonsoft.Json.Linq; using NUnit.Framework; using SpecialVariables = Calamari.Kubernetes.SpecialVariables; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] [Category(TestCategory.RunOnceOnWindowsAndLinux)] public class KubernetesContextScriptWrapperLiveFixtureAks: KubernetesContextScriptWrapperLiveFixture { string aksClusterHost; string aksClusterClientCertificate; string aksClusterClientKey; string aksClusterCaCertificate; string aksClusterName; string azurermResourceGroup; string aksPodServiceAccountToken; string azureSubscriptionId; protected override string KubernetesCloudProvider => "AKS"; protected override IEnumerable<string> ToolsToAddToPath(InstallTools tools) { yield return tools.KubeloginExecutable; } protected override async Task InstallOptionalTools(InstallTools tools) { await tools.InstallKubelogin(); } protected override void ExtractVariablesFromTerraformOutput(JObject jsonOutput) { aksClusterHost = jsonOutput.Get<string>("aks_cluster_host", "value"); aksClusterClientCertificate = jsonOutput.Get<string>("aks_cluster_client_certificate", "value"); aksClusterClientKey = jsonOutput.Get<string>("aks_cluster_client_key", "value"); aksClusterCaCertificate = jsonOutput.Get<string>("aks_cluster_ca_certificate", "value"); aksClusterName = jsonOutput.Get<string>("aks_cluster_name", "value"); aksPodServiceAccountToken = jsonOutput.Get<string>("aks_service_account_token", "value"); azurermResourceGroup = jsonOutput.Get<string>("aks_rg_name", "value"); } protected override Dictionary<string, string> GetEnvironmentVars() { azureSubscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); return new Dictionary<string, string>() { { "ARM_SUBSCRIPTION_ID", azureSubscriptionId}, { "ARM_CLIENT_ID", ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId) }, { "ARM_CLIENT_SECRET", ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword) }, { "ARM_TENANT_ID", ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId) }, { "TF_VAR_aks_client_id", ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId) }, { "TF_VAR_aks_client_secret", ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword) }, { "TF_VAR_test_namespace", TestNamespace }, }; } [Test] [TestCase(true)] [TestCase(false)] public void AuthorisingWithPodServiceAccountToken(bool runAsScript) { variables.Set(SpecialVariables.ClusterUrl, aksClusterHost); using (var dir = TemporaryDirectory.Create()) using (var podServiceAccountToken = new TemporaryFile(Path.Combine(dir.DirectoryPath, "podServiceAccountToken"))) using (var certificateAuthority = new TemporaryFile(Path.Combine(dir.DirectoryPath, "certificateAuthority"))) { File.WriteAllText(podServiceAccountToken.FilePath, aksPodServiceAccountToken); File.WriteAllText(certificateAuthority.FilePath, aksClusterCaCertificate); variables.Set("Octopus.Action.Kubernetes.PodServiceAccountTokenPath", podServiceAccountToken.FilePath); variables.Set("Octopus.Action.Kubernetes.CertificateAuthorityPath", certificateAuthority.FilePath); if (runAsScript) { DeployWithKubectlTestScriptAndVerifyResult(); } else { ExecuteCommandAndVerifyResult(TestableKubernetesDeploymentCommand.Name); } } } [Test] [TestCase(true)] [TestCase(false)] public void AuthorisingWithAzureServicePrincipal(bool runAsScript) { variables.Set(Deployment.SpecialVariables.Account.AccountType, "AzureServicePrincipal"); variables.Set("Octopus.Action.Kubernetes.AksClusterResourceGroup", azurermResourceGroup); variables.Set(SpecialVariables.AksClusterName, aksClusterName); variables.Set("Octopus.Action.Kubernetes.AksAdminLogin", Boolean.FalseString); variables.Set("Octopus.Action.Azure.SubscriptionId", ExternalVariables.Get(ExternalVariable.AzureSubscriptionId)); variables.Set("Octopus.Action.Azure.TenantId", ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId)); variables.Set("Octopus.Action.Azure.Password", ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword)); variables.Set("Octopus.Action.Azure.ClientId", ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId)); if (runAsScript) { DeployWithKubectlTestScriptAndVerifyResult(); } else { ExecuteCommandAndVerifyResult(TestableKubernetesDeploymentCommand.Name); } } [Test] [TestCase(true)] [TestCase(false)] public void AuthorisingWithClientCertificate(bool runAsScript) { variables.Set(SpecialVariables.ClusterUrl, aksClusterHost); var certificateAuthority = "myauthority"; variables.Set("Octopus.Action.Kubernetes.CertificateAuthority", certificateAuthority); variables.Set($"{certificateAuthority}.CertificatePem", aksClusterCaCertificate); var clientCert = "myclientcert"; variables.Set("Octopus.Action.Kubernetes.ClientCertificate", clientCert); variables.Set($"{clientCert}.CertificatePem", aksClusterClientCertificate); variables.Set($"{clientCert}.PrivateKeyPem", aksClusterClientKey); if (runAsScript) { DeployWithKubectlTestScriptAndVerifyResult(); } else { ExecuteCommandAndVerifyResult(TestableKubernetesDeploymentCommand.Name); } } [Test] public void UnreachableK8Cluster_ShouldExecuteTargetScript() { const string certificateAuthority = "myauthority"; const string unreachableClusterUrl = "https://example.kubernetes.com"; const string clientCert = "myclientcert"; variables.Set(SpecialVariables.ClusterUrl, unreachableClusterUrl); variables.Set("Octopus.Action.Kubernetes.CertificateAuthority", certificateAuthority); variables.Set($"{certificateAuthority}.CertificatePem", aksClusterCaCertificate); variables.Set("Octopus.Action.Kubernetes.ClientCertificate", clientCert); variables.Set($"{clientCert}.CertificatePem", aksClusterClientCertificate); variables.Set($"{clientCert}.PrivateKeyPem", aksClusterClientKey); DeployWithNonKubectlTestScriptAndVerifyResult(); } [Test] [TestCase(false)] [TestCase(true)] public void DiscoverKubernetesClusterWithAzureServicePrincipalAccount(bool setHealthCheckContainer) { var scope = new TargetDiscoveryScope("TestSpace", "Staging", "testProject", null, new[] { "discovery-role" }, "WorkerPool-1", setHealthCheckContainer ? new FeedImage("MyImage:with-tag", "Feeds-123") : null); var account = new ServicePrincipalAccount( ExternalVariables.Get(ExternalVariable.AzureSubscriptionId), ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId), ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId), ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword), null, null, null); var authenticationDetails = new AccountAuthenticationDetails<ServicePrincipalAccount>( "Azure", "Accounts-1", account); var targetDiscoveryContext = new TargetDiscoveryContext<AccountAuthenticationDetails<ServicePrincipalAccount>>(scope, authenticationDetails); ExecuteDiscoveryCommandAndVerifyResult(targetDiscoveryContext); var targetName = $"aks/{azureSubscriptionId}/{azurermResourceGroup}/{aksClusterName}"; var serviceMessageProperties = new Dictionary<string, string> { { "name", targetName }, { "clusterName", aksClusterName }, { "clusterResourceGroup", azurermResourceGroup }, { "skipTlsVerification", bool.TrueString }, { "octopusDefaultWorkerPoolIdOrName", scope.WorkerPoolId }, { "octopusAccountIdOrName", "Accounts-1" }, { "octopusRoles", "discovery-role" }, { "updateIfExisting", bool.TrueString }, { "isDynamic", bool.TrueString }, { "awsUseWorkerCredentials", bool.FalseString }, { "awsAssumeRole", bool.FalseString } }; if (scope.HealthCheckContainer != null) { serviceMessageProperties.Add("healthCheckContainerImageFeedIdOrName", scope.HealthCheckContainer.FeedIdOrName); serviceMessageProperties.Add("healthCheckContainerImage", scope.HealthCheckContainer.ImageNameAndTag); } var expectedServiceMessage = new ServiceMessage( KubernetesDiscoveryCommand.CreateKubernetesTargetServiceMessageName, serviceMessageProperties); Log.ServiceMessages.Should() .ContainSingle(s => s.Properties.ContainsKey("name") && s.Properties["name"] == targetName) .Which.Should() .BeEquivalentTo(expectedServiceMessage); } } } #endif<file_sep>using System.IO; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; namespace Calamari.Tests.Fixtures.Commands { /// <summary> /// A cut down command that runs a script without any journaling, variable substitution or /// other optional steps. /// </summary> [Command("run-test-script", Description = "Invokes a PowerShell or dotnet-script script")] public class RunTestScriptCommand : Command { private string scriptFile; private readonly IVariables variables; private readonly IScriptEngine scriptEngine; public RunTestScriptCommand( IVariables variables, IScriptEngine scriptEngine) { Options.Add("script=", "Path to the script to execute.", v => scriptFile = Path.GetFullPath(v)); this.variables = variables; this.scriptEngine = scriptEngine; } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); var runner = new CommandLineRunner(ConsoleLog.Instance, variables); Log.VerboseFormat("Executing '{0}'", scriptFile); var result = scriptEngine.Execute(new Script(scriptFile, ""), variables, runner); if (result.ExitCode == 0 && result.HasErrors && variables.GetFlag(SpecialVariables.Action.FailScriptOnErrorOutput, false)) { return -1; } return result.ExitCode; } } } <file_sep>using System; using Calamari.Common.Plumbing.Variables; namespace Calamari.Util { /// <summary> /// Defines a service for replacing template markup in files /// </summary> public interface ITemplateReplacement { /// <summary> /// Reads a file and replaces any template markup with the values from the supplied variables /// </summary> /// <param name="fetch">Callback to fetch the content given the absolute template path</param> /// <param name="relativeFilePath">The relative path to the file to process</param> /// <param name="inPackage">True if the file is in a package, and false otherwise</param> /// <param name="variables">The variables used for the replacement values</param> /// <returns>The contents of the source file with the variables replaced</returns> string ResolveAndSubstituteFile( Func<string, string> fetch, string relativeFilePath, bool inPackage, IVariables variables); string ResolveAndSubstituteFile( Func<string> resolve, Func<string, string> fetch, IVariables variables); } }<file_sep> using System; Octopus.SetVariable("Donkey","Kong"); <file_sep>namespace Calamari.Integration.Packages.Download { /// <summary> /// Defines some common utility functions for package downloaders /// </summary> public interface IPackageDownloaderUtils { string TentacleHome { get; } string RootDirectory { get; } string GetPackageRoot(string prefix); } }<file_sep>using System; namespace Calamari.Common.Plumbing { internal static class AppDomainConfiguration { public static readonly TimeSpan DefaultRegexMatchTimeout = TimeSpan.FromSeconds(1); /// <summary> /// Adds default max timeout to avoid ReDoS attacks /// </summary> public static void SetDefaultRegexMatchTimeout() => AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", DefaultRegexMatchTimeout); } }<file_sep>using System; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures.Integration.Proxies; using NUnit.Framework; namespace Calamari.Tests.Fixtures.DotnetScript { [TestFixture] [Category(TestCategory.ScriptingSupport.DotnetScript)] [RequiresDotNetCore] public class DotnetScriptProxyFixture : WindowsScriptProxyFixtureBase { protected override CalamariResult RunScript() { return RunScript("Proxy.csx").result; } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public override void Initialize_HasSystemProxy_UseSystemProxyWithExceptions() { // If the HTTP_PROXY environment variable have been set .NET Core will only take entries in the NO_PROXY environment variable into account, // it will not look at Exceptions listed under Proxy Settings in Internet Options on Windows. // As the NO_PROXY environment variable is set to a fixed list of addresses, the Initialize_HasSystemProxy_UseSystemProxyWithExceptions test fails // as the address we want to bypass the proxy doesn't isn't configured. Assert.Ignore("Some proxy tests currently fail with dotnet-script, currently ignoring them until this has been addressed."); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public override void Initialize_HasSystemProxy_UseSystemProxyWithCredentials() { // .NET Core first unescapes the username and password, then splits the auth string on ':' and finally escapes the username and password again. // https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.cs#L175C18-L175C18 // According to this issue https://github.com/dotnet/runtime/issues/23132 this is expected behavior as per the // HTTP Authentication: Basic and Digest Access Authentication RFC (https://datatracker.ietf.org/doc/html/rfc2617#section-2) auth does not // support ':' in domain. Assert.Ignore(".NET Core currently does weird things when proxy username contains ':'."); } protected override bool TestWebRequestDefaultProxy => true; } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Common; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.NewPipeline { [TestFixture] [RequiresNonFreeBSDPlatform] [Category(TestCategory.PlatformAgnostic)] public class PipelineCommandFixture { readonly string[] defaultScriptStages = { DeploymentStages.PreDeploy, DeploymentStages.Deploy, DeploymentStages.PostDeploy }; [Test] public Task EnsureAllContainerRegistrationsAreMet() { return CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .Execute(); } [Test] public Task AssertNextBehaviourIsNotCalledWhenPreviousBehaviourSetsSkipFlag() { return CommandTestBuilder.CreateAsync<SkipNextCommand, MyProgram>() .Execute(); } [Test] public Task AssertPipelineExtensionsAreExecuted() { return CommandTestBuilder.CreateAsync<MyLoggingCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(ActionVariables.Name, "Boo"); }) .WithAssert(result => { result.OutputVariables["ExecutionStages"].Value.Should().Be("IBeforePackageExtractionBehaviour;IAfterPackageExtractionBehaviour;IPreDeployBehaviour;IDeployBehaviour;IPostDeployBehaviour"); }) .Execute(); } [Test] public async Task AssertStagedPackageIsExtracted() { using (var tempPath = TemporaryDirectory.Create()) { File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "Hello.html"), "Hello World!"); await CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .WithArrange(context => { context.WithNewNugetPackage(tempPath.DirectoryPath, "MyPackage", "1.0.0"); }) .WithAssert(result => { File.Exists(Path.Combine(tempPath.DirectoryPath, "Hello.html")).Should().BeTrue(); }) .Execute(); } } [Test] public async Task AssertSubstituteInFilesRuns() { using (var tempPath = TemporaryDirectory.Create()) { var targetPath = Path.Combine(tempPath.DirectoryPath, "myconfig.json"); File.WriteAllText(targetPath, "{ foo: '#{Hello}' }"); string glob = "**/*config.json"; await CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.SubstituteInFiles); context.Variables.Add(PackageVariables.SubstituteInFilesTargets, glob); context.Variables.Add("Hello", "Hello World"); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { File.ReadAllText(targetPath).Should().Be("{ foo: 'Hello World' }"); }) .Execute(); } } [Test] public async Task AssertConfigurationTransformsRuns() { using (var tempPath = TemporaryDirectory.Create()) { var expected = @"<configuration> <appSettings> <add key=""Environment"" value=""Test"" /> </appSettings> </configuration>".Replace("\r", String.Empty); var targetPath = Path.Combine(tempPath.DirectoryPath, "bar.config"); File.WriteAllText(targetPath, @"<configuration> <appSettings> <add key=""Environment"" value=""Dev"" /> </appSettings> </configuration>"); File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "bar.Release.config"), @"<configuration xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform""> <appSettings> <add key=""Environment"" value=""Test"" xdt:Transform=""SetAttributes"" xdt:Locator=""Match(key)"" /> </appSettings> </configuration>"); await CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationTransforms); context.Variables.Add(KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles, bool.TrueString); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { File.ReadAllText(targetPath).Replace("\r", String.Empty).Should().Be(expected); }) .Execute(); } } [Test] public async Task AssertConfigurationVariablesRuns() { using (var tempPath = TemporaryDirectory.Create()) { var expected = @"<configuration> <appSettings> <add key=""Environment"" value=""Test"" /> </appSettings> </configuration>".Replace("\r", String.Empty); var targetPath = Path.Combine(tempPath.DirectoryPath, "Web.config"); File.WriteAllText(targetPath, @"<configuration> <appSettings> <add key=""Environment"" value=""Dev"" /> </appSettings> </configuration>"); await CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationTransforms + "," + KnownVariables.Features.ConfigurationVariables); context.Variables.Add(KnownVariables.Package.AutomaticallyUpdateAppSettingsAndConnectionStrings, "true"); context.Variables.Add("Environment", "Test"); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { File.ReadAllText(targetPath).Replace("\r", String.Empty).Should().Be(expected); }) .Execute(); } } [Test] public async Task AssertStructuredConfigurationVariablesRuns() { using (var tempPath = TemporaryDirectory.Create()) { var expected = @"{ ""Environment"": ""Test"" }".Replace("\r", String.Empty); var targetPath = Path.Combine(tempPath.DirectoryPath, "myfile.json"); File.WriteAllText(targetPath, @"{ ""Environment"": ""Dev"" }"); await CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); context.Variables.Add(ActionVariables.StructuredConfigurationVariablesTargets, "*.json"); context.Variables.Add("Environment", "Test"); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { File.ReadAllText(targetPath).Replace("\r", String.Empty).Should().Be(expected); }) .Execute(); } } [Test] public async Task AssertInlineScriptsAreRun() { await CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts); foreach (var stage in defaultScriptStages) { context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(stage, ScriptSyntax.PowerShell), $"echo 'Hello from {stage}'"); } }) .WithAssert(result => { var currentIndex = 0; foreach (var stage in defaultScriptStages) { var index = result.FullLog.IndexOf($"Hello from {stage}", StringComparison.Ordinal); index.Should().BeGreaterThan(currentIndex); currentIndex = index; } }) .Execute(); } [Test] [TestCase(true, TestName = nameof(AssertPackageScriptsAreRun) + " and delete script after")] [TestCase(false, TestName = nameof(AssertPackageScriptsAreRun) + " and keep script after")] public async Task AssertPackageScriptsAreRun(bool deleteScripts) { using (var tempPath = TemporaryDirectory.Create()) { foreach (var stage in defaultScriptStages) { File.WriteAllText(Path.Combine(tempPath.DirectoryPath, $"{stage}.ps1"), $"echo 'Hello from {stage}'"); } await CommandTestBuilder.CreateAsync<MyCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.RunPackageScripts, bool.TrueString); context.Variables.Add(KnownVariables.DeleteScriptsOnCleanup, deleteScripts.ToString()); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { var currentIndex = 0; foreach (var stage in defaultScriptStages) { var index = result.FullLog.IndexOf($"Hello from {stage}", StringComparison.Ordinal); index.Should().BeGreaterThan(currentIndex); currentIndex = index; File.Exists(Path.Combine(tempPath.DirectoryPath, $"{stage}.ps1")).Should().Be(!deleteScripts); } }) .Execute(); } } [TestCase(true, TestName = nameof(AssertDeployFailedScriptIsRunOnFailure) + " and delete script after")] [TestCase(false, TestName = nameof(AssertDeployFailedScriptIsRunOnFailure) + " and keep script after")] public async Task AssertDeployFailedScriptIsRunOnFailure(bool deleteScripts) { using (var tempPath = TemporaryDirectory.Create()) { File.WriteAllText(Path.Combine(tempPath.DirectoryPath, $"{DeploymentStages.DeployFailed}.ps1"), $"echo 'Hello from {DeploymentStages.DeployFailed}'"); await CommandTestBuilder.CreateAsync<MyBadCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.RunPackageScripts, bool.TrueString); context.Variables.Add(KnownVariables.DeleteScriptsOnCleanup, deleteScripts.ToString()); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { result.WasSuccessful.Should().BeFalse(); result.FullLog.Should().Contain($"Hello from {DeploymentStages.DeployFailed}"); File.Exists(Path.Combine(tempPath.DirectoryPath, $"{DeploymentStages.DeployFailed}.ps1")).Should().Be(!deleteScripts); }) .Execute(false); } } [Test] public async Task PackagedScriptDoesNotExecute() { using (var tempPath = TemporaryDirectory.Create()) { foreach (var stage in defaultScriptStages) { File.WriteAllText(Path.Combine(tempPath.DirectoryPath, $"{stage}.ps1"), $"echo 'Hello from {stage}'"); } await CommandTestBuilder.CreateAsync<NoPackagedScriptCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.RunPackageScripts, bool.TrueString); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { result.WasSuccessful.Should().BeTrue(); foreach (var stage in defaultScriptStages) { result.FullLog.Should().NotContain($"Hello from {stage}"); } }) .Execute(true); } } [Test] public async Task ConfiguredScriptDoesNotExecute() { using (var tempPath = TemporaryDirectory.Create()) { await CommandTestBuilder.CreateAsync<NoConfiguredScriptCommand, MyProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Features.CustomScripts, bool.TrueString); foreach (var stage in defaultScriptStages) { context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(stage, ScriptSyntax.PowerShell), $"echo 'Hello from {stage}"); } }) .WithAssert(result => { result.WasSuccessful.Should().BeTrue(); foreach (var stage in defaultScriptStages) { result.FullLog.Should().NotContain($"Hello from {stage}"); } }) .Execute(true); } } class MyProgram : CalamariFlavourProgramAsync { public MyProgram(ILog log) : base(log) { } } [Command("mycommand")] class MyCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<MyEmptyBehaviour>(); } } [Command("mybadcommand")] class MyBadCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<MyBadBehaviour>(); } } [Command("skipcommand")] class SkipNextCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<SkipNextBehaviour>(); yield return resolver.Create<MyBadBehaviour>(); } } [Command("nopackagedscriptcommand")] class NoPackagedScriptCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield break; } protected override bool IncludePackagedScriptBehaviour => false; } [Command("noconfiguredscriptcommand")] class NoConfiguredScriptCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield break; } protected override bool IncludeConfiguredScriptBehaviour => false; } [Command("logcommand")] class MyLoggingCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<DeployBehaviour>(); } protected override IEnumerable<IBeforePackageExtractionBehaviour> BeforePackageExtraction(BeforePackageExtractionResolver resolver) { yield return resolver.Create<BeforePackageExtractionBehaviour>(); } protected override IEnumerable<IAfterPackageExtractionBehaviour> AfterPackageExtraction(AfterPackageExtractionResolver resolver) { yield return resolver.Create<AfterPackageExtractionBehaviour>(); } protected override IEnumerable<IPreDeployBehaviour> PreDeploy(PreDeployResolver resolver) { yield return resolver.Create<PreDeployBehaviour>(); } protected override IEnumerable<IPostDeployBehaviour> PostDeploy(PostDeployResolver resolver) { yield return resolver.Create<PostDeployBehaviour>(); } } class SkipNextBehaviour : IDeployBehaviour { public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { context.Variables.AddFlag(KnownVariables.Action.SkipRemainingConventions, true); return this.CompletedTask(); } } class MyBadBehaviour : IDeployBehaviour { public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { throw new Exception("Boom!!!"); } } class MyEmptyBehaviour : IDeployBehaviour { public bool IsEnabled(RunningDeployment context) { return false; } public Task Execute(RunningDeployment context) { throw new NotImplementedException(); } } class BeforePackageExtractionBehaviour : LoggingBehaviour, IBeforePackageExtractionBehaviour { public BeforePackageExtractionBehaviour(ILog log) : base(log) { } } class AfterPackageExtractionBehaviour : LoggingBehaviour, IAfterPackageExtractionBehaviour { public AfterPackageExtractionBehaviour(ILog log) : base(log) { } } class PreDeployBehaviour : LoggingBehaviour, IPreDeployBehaviour { public PreDeployBehaviour(ILog log) : base(log) { } } class DeployBehaviour : LoggingBehaviour, IDeployBehaviour { public DeployBehaviour(ILog log) : base(log) { } } class PostDeployBehaviour : LoggingBehaviour, IPostDeployBehaviour { public PostDeployBehaviour(ILog log) : base(log) { } } class LoggingBehaviour: IBehaviour { readonly ILog log; public LoggingBehaviour(ILog log) { this.log = log; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var stages = context.Variables.GetStrings("ExecutionStages", ';'); var name = GetType().FindInterfaces((type, criteria) => type != typeof(IBehaviour), "").Single().Name; stages.Add(name); log.SetOutputVariable("ExecutionStages", string.Join(";", stages), context.Variables); return this.CompletedTask(); } } } }<file_sep>namespace Calamari.Integration.Iis { public interface IInternetInformationServer { /// <summary> /// Sets the home directory (web root) of the given IIS website to the given path. /// </summary> /// <param name="iisWebSiteName">The name of the web site under IIS.</param> /// <param name="path">The path to point the site to.</param> /// <param name="legacySupport">If true, forces using the IIS6 compatible IIS support. Otherwise, try to auto-detect.</param> /// <returns>True if the IIS site was found and updated. False if it could not be found.</returns> bool OverwriteHomeDirectory(string iisWebSiteName, string path, bool legacySupport); } }<file_sep>using System; using System.Threading.Tasks; namespace Calamari.Common.Commands { /// <summary> /// A command that requires the command line arguments passed to it. We are transitioning away from this interface /// </summary> public interface ICommand { int Execute(); } public interface ICommandAsync { Task Execute(); } }<file_sep>using System; namespace Calamari.Common.Features.Processes.Semaphores { public class MissingFileLock : IFileLock { } }<file_sep>using System; namespace Calamari.Common.Plumbing.Deployment { public enum DeploymentWorkingDirectory { StagingDirectory, CustomDirectory } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Newtonsoft.Json; using Octostache; namespace Calamari.Common.Plumbing.Variables { public class VariablesFactory { public static readonly string AdditionalVariablesPathVariable = "AdditionalVariablesPath"; readonly ICalamariFileSystem fileSystem; public VariablesFactory(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } public IVariables Create(CommonOptions options) { var variables = new CalamariVariables(); ReadUnencryptedVariablesFromFile(options, variables); ReadEncryptedVariablesFromFile(options, variables); ReadOutputVariablesFromOfflineDropPreviousSteps(options, variables); AddEnvironmentVariables(variables); variables.Set(TentacleVariables.Agent.InstanceName, "#{env:TentacleInstanceName}"); ReadAdditionalVariablesFromFile(variables); DeploymentJournalVariableContributor.Contribute(fileSystem, variables); return variables; } void ReadUnencryptedVariablesFromFile(CommonOptions options, CalamariVariables variables) { var variablesFile = options.InputVariables.VariablesFile; if (string.IsNullOrEmpty(variablesFile)) return; if (!fileSystem.FileExists(variablesFile)) throw new CommandException("Could not find variables file: " + variablesFile); var readVars = new VariableDictionary(variablesFile); variables.Merge(readVars); } void ReadEncryptedVariablesFromFile(CommonOptions options, CalamariVariables variables) { foreach (var sensitiveFilePath in options.InputVariables.SensitiveVariablesFiles.Where(f => !string.IsNullOrEmpty(f))) { var sensitiveFilePassword = options.InputVariables.SensitiveVariablesPassword; var rawVariables = string.IsNullOrWhiteSpace(sensitiveFilePassword) ? fileSystem.ReadFile(sensitiveFilePath) : Decrypt(fileSystem.ReadAllBytes(sensitiveFilePath), sensitiveFilePassword); try { var sensitiveVariables = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawVariables); foreach (var variable in sensitiveVariables) variables.Set(variable.Key, variable.Value); } catch (JsonReaderException) { throw new CommandException("Unable to parse sensitive-variables as valid JSON."); } } } void ReadOutputVariablesFromOfflineDropPreviousSteps(CommonOptions options, CalamariVariables variables) { var outputVariablesFilePath = options.InputVariables.OutputVariablesFile; if (string.IsNullOrEmpty(outputVariablesFilePath)) return; var rawVariables = DecryptWithMachineKey(fileSystem.ReadFile(outputVariablesFilePath), options.InputVariables.OutputVariablesPassword); try { var outputVariables = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawVariables); foreach (var variable in outputVariables) variables.Set(variable.Key, variable.Value); } catch (JsonReaderException) { throw new CommandException("Unable to parse output variables as valid JSON."); } } static void AddEnvironmentVariables(IVariables variables) { var environmentVariables = Environment.GetEnvironmentVariables(); foreach (var name in environmentVariables.Keys) variables["env:" + name] = (environmentVariables[name] ?? string.Empty).ToString(); } void ReadAdditionalVariablesFromFile(CalamariVariables variables) { var path = variables.Get(AdditionalVariablesPathVariable) ?? variables.Get($"env:{AdditionalVariablesPathVariable}"); string BuildExceptionMessage(string reason) { return $"Could not read additional variables from JSON file at '{path}'. " + $"{reason} Make sure the file can be read or remove the " + $"'{AdditionalVariablesPathVariable}' environment variable. " + "See inner exception for details."; } if (string.IsNullOrEmpty(path)) return; if (!fileSystem.FileExists(path)) throw new CommandException(BuildExceptionMessage("File does not exist.")); try { var readVars = new VariableDictionary(path); variables.Merge(readVars); } catch (Exception e) { throw new CommandException(BuildExceptionMessage("The file could not be read."), e); } } static string Decrypt(byte[] encryptedVariables, string encryptionPassword) { try { return new AesEncryption(encryptionPassword).Decrypt(encryptedVariables); } catch (CryptographicException) { throw new CommandException("Cannot decrypt sensitive-variables. Check your password is correct."); } } static string DecryptWithMachineKey(string base64EncodedEncryptedVariables, string? password) { try { var encryptedVariables = Convert.FromBase64String(base64EncodedEncryptedVariables); var bytes = ProtectedData.Unprotect(encryptedVariables, Convert.FromBase64String(password ?? string.Empty), DataProtectionScope.CurrentUser); return Encoding.UTF8.GetString(bytes); } catch (CryptographicException) { throw new CommandException("Cannot decrypt output variables."); } } } }<file_sep>using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Calamari.AzureServiceFabric.Tests")]<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.XPath; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Wmhelp.XPath2; namespace Calamari.Common.Features.StructuredVariables { public class XmlFormatVariableReplacer : IFileFormatVariableReplacer { readonly ICalamariFileSystem fileSystem; readonly ILog log; public XmlFormatVariableReplacer(ICalamariFileSystem fileSystem, ILog log) { this.fileSystem = fileSystem; this.log = log; } public string FileFormatName => StructuredConfigVariablesFileFormats.Xml; public bool IsBestReplacerForFileName(string fileName) { return fileName.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase); } public void ModifyFile(string filePath, IVariables variables) { var encodingPrecedence = new List<Encoding>(CalamariPhysicalFileSystem.DefaultInputEncodingPrecedence); var fileBytes = fileSystem.ReadAllBytes(filePath); if (TryGetDeclaredEncoding(fileBytes) is {} declaredEncoding) encodingPrecedence.Insert(0, declaredEncoding); var fileText = fileSystem.ReadAllText(fileBytes, out var encoding, encodingPrecedence); var lineEnding = fileText.GetMostCommonLineEnding(); var doc = new XmlDocument(); try { doc.LoadXml(fileText); } catch (XmlException e) { throw new StructuredConfigFileParseException(e.Message, e); } var nsManager = BuildNsManagerFromDocument(doc); var navigator = doc.CreateNavigator(); var replaced = 0; foreach (var variable in variables) if (TryGetXPathFromVariableKey(variable.Key, nsManager) is {} xPathExpression) { var selectedNodes = navigator.XPath2SelectNodes(xPathExpression, nsManager); var variableValue = variables.Get(variable.Key); foreach (XPathNavigator selectedNode in selectedNodes) { log.Verbose(StructuredConfigMessages.StructureFound(variable.Key)); replaced++; switch (selectedNode.UnderlyingObject) { case XmlText text: text.Data = variableValue; break; case XmlAttribute attribute: attribute.Value = variableValue; break; case XmlComment comment: comment.Data = variableValue; break; case XmlElement element: if (element.ChildNodes.Count == 1 && element.ChildNodes[0].NodeType == XmlNodeType.CDATA) // Try to preserve CDatas in the output. element.ChildNodes[0].Value = variableValue; else if (ContainsElements(element)) TrySetInnerXml(element, variable.Key, variableValue); else element.InnerText = variableValue; break; case XmlCharacterData cData: cData.Data = variableValue; break; case XmlProcessingInstruction processingInstruction: processingInstruction.Data = variableValue; break; case XmlNode node: log.Warn($"XML Node of type '{node.NodeType}' is not supported"); break; default: log.Warn($"XPath returned an object of type '{selectedNode.GetType().FullName}', which is not supported"); break; } } } if (replaced == 0) log.Info(StructuredConfigMessages.NoStructuresFound); fileSystem.OverwriteFile(filePath, textWriter => { var xmlWriterSettings = new XmlWriterSettings { Indent = true, NewLineChars = lineEnding == StringExtensions.LineEnding.Dos ? "\r\n" : "\n", OmitXmlDeclaration = doc.FirstChild.NodeType != XmlNodeType.XmlDeclaration }; using (var writer = XmlWriter.Create(textWriter, xmlWriterSettings)) { doc.Save(writer); writer.Close(); } }, encoding); } void TrySetInnerXml(XmlElement element, string xpathExpression, string? variableValue) { var previousInnerXml = element.InnerXml; try { element.InnerXml = variableValue; } catch (XmlException) { element.InnerXml = previousInnerXml; log.Warn("Could not set the value of the XML element at XPath " + $"'{xpathExpression}' to '{variableValue}'. Expected " + "a valid XML fragment. Skipping replacement of this " + "element."); } } bool ContainsElements(XmlElement element) { return element.ChildNodes .Cast<XmlNode>() .Any(n => n.NodeType == XmlNodeType.Element); } XmlNamespaceManager BuildNsManagerFromDocument(XmlDocument doc) { var nsManager = new XmlNamespaceManager(doc.NameTable); var namespaces = GetNamespacesFromNodeAndDescendants(doc); foreach (var ns in namespaces) { var existing = nsManager.LookupNamespace(ns.Prefix); if (existing != null && existing != ns.NamespaceUri) { var msg = $"The namespace '{ns.NamespaceUri}' could not be mapped to the '{ns.Prefix}' " + $"prefix, as another namespace '{existing}' is already mapped to that " + "prefix. XPath selectors using this prefix may not return the expected nodes. " + "You can avoid this by ensuring all namespaces in your document have unique " + "prefixes."; log.Warn(msg); } else { nsManager.AddNamespace(ns.Prefix, ns.NamespaceUri); } } return nsManager; } IEnumerable<NamespaceDeclaration> GetNamespacesFromNodeAndDescendants(XmlNode node) { if (node.Attributes != null) foreach (var namespaceFromAttribute in node.Attributes .OfType<XmlAttribute>() .Where(attr => attr.NamespaceURI == "http://www.w3.org/2000/xmlns/" && attr.LocalName != "xmlns") .Select(attr => new NamespaceDeclaration(attr.LocalName, attr.Value))) yield return namespaceFromAttribute; foreach (var namespaceFromDescendants in node.ChildNodes .OfType<XmlNode>() .SelectMany(GetNamespacesFromNodeAndDescendants)) yield return namespaceFromDescendants; } XPath2Expression? TryGetXPathFromVariableKey(string variableKey, IXmlNamespaceResolver nsResolver) { // Prevent 'Octopus*' and other unintended variables being recognized as XPath expressions selecting the document node if (!variableKey.Contains("/") && !variableKey.Contains(":")) return null; try { return XPath2Expression.Compile(variableKey, nsResolver); } catch (XPath2Exception) { return null; } } public static Encoding? TryGetDeclaredEncoding(byte[] bytes) { try { using (var stream = new MemoryStream(bytes)) using (var xmlReader = XmlReader.Create(stream)) { if (xmlReader.Read() && xmlReader.NodeType == XmlNodeType.XmlDeclaration) return Encoding.GetEncoding(xmlReader.GetAttribute("encoding"), EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); return null; } } catch { return null; } } class NamespaceDeclaration { public NamespaceDeclaration(string prefix, string namespaceUri) { Prefix = prefix; NamespaceUri = namespaceUri; } public string Prefix { get; } public string NamespaceUri { get; } } } }<file_sep>using System; using NUnit.Framework; using NUnit.Framework.Interfaces; namespace Calamari.Tests.Fixtures.PackageDownload { [AttributeUsage(AttributeTargets.Method)] public class AuthenticatedTestAttribute : Attribute, ITestAction { readonly string feedUri; readonly string feedUsernameVariable; readonly string feedPasswordVariable; public AuthenticatedTestAttribute(string feedUri, string feedUsernameVariable, string feedPasswordVariable) { this.feedUri = feedUri; this.feedUsernameVariable = feedUsernameVariable; this.feedPasswordVariable = feedPasswordVariable; } public void BeforeTest(ITest testDetails) { if (String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(feedUri)) || String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(feedUsernameVariable)) || String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(feedPasswordVariable))) { Assert.Ignore("The authenticated feed tests were skipped because the " + feedUri + ", " + feedUsernameVariable + " and " +feedPasswordVariable + " environment variables are not set."); } } public void AfterTest(ITest testDetails) { } public ActionTargets Targets { get; private set; } } } <file_sep>using System; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Integration; using Octopus.CoreUtilities; using Octopus.Versioning.Semver; namespace Calamari.Kubernetes.Authentication { public class GoogleKubernetesEngineAuth { readonly GCloud gcloudCli; readonly GkeGcloudAuthPlugin authPluginCli; readonly Kubectl kubectlCli; readonly IVariables deploymentVariables; readonly ILog log; /// <summary> /// This class is responsible for configuring the kubectl auth against a GKE cluster for an Octopus Deployment /// </summary> /// <param name="gcloudCli"></param> /// <param name="authPluginCli"></param> /// <param name="kubectlCli"></param> /// <param name="deploymentVariables"></param> public GoogleKubernetesEngineAuth(GCloud gcloudCli,GkeGcloudAuthPlugin authPluginCli, Kubectl kubectlCli, IVariables deploymentVariables, ILog log) { this.gcloudCli = gcloudCli; this.authPluginCli = authPluginCli; this.kubectlCli = kubectlCli; this.deploymentVariables = deploymentVariables; this.log = log; } public bool TryConfigure(bool useVmServiceAccount, string @namespace) { if (!gcloudCli.TrySetGcloud()) return false; var accountVariable = deploymentVariables.Get("Octopus.Action.GoogleCloudAccount.Variable"); var jsonKey = deploymentVariables.Get($"{accountVariable}.JsonKey"); if (string.IsNullOrEmpty(accountVariable) || string.IsNullOrEmpty(jsonKey)) { jsonKey = deploymentVariables.Get("Octopus.Action.GoogleCloudAccount.JsonKey"); } string impersonationEmails = null; if (deploymentVariables.GetFlag("Octopus.Action.GoogleCloud.ImpersonateServiceAccount")) { impersonationEmails = deploymentVariables.Get("Octopus.Action.GoogleCloud.ServiceAccountEmails"); } var project = deploymentVariables.Get("Octopus.Action.GoogleCloud.Project") ?? string.Empty; var region = deploymentVariables.Get("Octopus.Action.GoogleCloud.Region") ?? string.Empty; var zone = deploymentVariables.Get("Octopus.Action.GoogleCloud.Zone") ?? string.Empty; gcloudCli.ConfigureGcloudAccount(project, region, zone, jsonKey, useVmServiceAccount, impersonationEmails); WarnCustomersAboutAuthToolingRequirements(); var gkeClusterName = deploymentVariables.Get(SpecialVariables.GkeClusterName); var useClusterInternalIp = deploymentVariables.GetFlag(SpecialVariables.GkeUseClusterInternalIp); gcloudCli.ConfigureGkeKubeCtlAuthentication(kubectlCli, gkeClusterName, region, zone, @namespace, useClusterInternalIp); return true; } /// <summary> /// Provide a clear warning in the deployment logs if the customer's environment has a known incompatible combination of tooling /// </summary> /// <remarks> /// From Kubectl 1.26 onward, the `gke-gcloud-auth-plugin` is required to be available on the path. /// Without it, generating the `kubeconfig` will succeed, but authentication will fail. /// </remarks> void WarnCustomersAboutAuthToolingRequirements() { var kubeCtlVersion = kubectlCli.GetVersion(); if (kubeCtlVersion.None() || kubeCtlVersion.Value < new SemanticVersion("1.26.0")) return; if (!authPluginCli.ExistsOnPath()) log.Warn("From kubectl v1.26 onward, the gke-gcloud-auth-plugin needs to be available on the PATH to authenticate against GKE clusters. See https://oc.to/KubectlAuthChangesGke for more information."); } } }<file_sep>using System; using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Assent; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Variables; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.StructuredVariables { [TestFixture] public class PropertiesVariableReplacerFixture : VariableReplacerFixture { public PropertiesVariableReplacerFixture() : base((fs, log) => new PropertiesFormatVariableReplacer(fs, log)) { } [Test] public void DoesNothingIfThereAreNoVariables() { var vars = new CalamariVariables(); RunTest(vars, "example.properties"); } [Test] public void DoesNothingIfThereAreNoMatchingVariables() { Replace(new CalamariVariables { { "Non-matching", "variable" } }, "example.properties"); Log.MessagesInfoFormatted.Should().Contain(StructuredConfigMessages.NoStructuresFound); Log.MessagesVerboseFormatted.Should().NotContain(m => Regex.IsMatch(m, StructuredConfigMessages.StructureFound(".*"))); } [Test] public void HandlesAnEmptyFile() { var vars = new CalamariVariables(); RunTest(vars, "blank.properties"); } [Test] public void CanReplaceASimpleKeyValuePair() { var vars = new CalamariVariables { { "key1", "new-value" } }; RunTest(vars, "example.properties"); Log.MessagesVerboseFormatted.Count(m => Regex.IsMatch(m, StructuredConfigMessages.StructureFound(".*"))).Should().Be(1); Log.MessagesVerboseFormatted.Should().Contain(StructuredConfigMessages.StructureFound("key1")); Log.MessagesInfoFormatted.Should().NotContain(StructuredConfigMessages.NoStructuresFound); } [Test] public void CanReplaceAKeyThatContainsAPhysicalNewLine() { var vars = new CalamariVariables { { "key3", "new-value" } }; RunTest(vars, "example.properties"); } [Test] public void OnlyReplacesExistingKeys() { var vars = new CalamariVariables { { "no-such-key", "new-value" } }; RunTest(vars, "example.properties"); } [Test] public void EscapesSlashesInValues() { var vars = new CalamariVariables { { "key1", "new\\value" } }; RunTest(vars, "example.properties"); } [Test] public void EscapesDosNewLinesInValues() { var vars = new CalamariVariables { { "key1", "new\r\nvalue" } }; RunTest(vars, "example.properties"); } [Test] public void EscapesNixNewLinesInValues() { var vars = new CalamariVariables { { "key1", "new\nvalue" } }; RunTest(vars, "example.properties"); } [Test] public void EscapesTabsInValues() { var vars = new CalamariVariables { { "key1", "new\tvalue" } }; RunTest(vars, "example.properties"); } [Test] public void EscapesALeadingSpaceInValues() { var vars = new CalamariVariables { { "key1", " new value" } }; RunTest(vars, "example.properties"); } [Test] public void CanReplaceAValueInAKeyThatDoesntHaveAValue() { var vars = new CalamariVariables { { "key5", " new value" } }; RunTest(vars, "example.properties"); } [Test] public void CanReplaceAValueInAKeyThatHasNeitherSeparatorNorValue() { var vars = new CalamariVariables { { "key6", " new value" } }; RunTest(vars, "example.properties"); } [Test] public void ShouldIgnoreOctopusPrefix() { var vars = new CalamariVariables { { "Octopus.Release.Id", "999" } }; RunTest(vars, "example.properties"); } [Test] public void HandlesVariablesThatReferenceOtherVariables() { var vars = new CalamariVariables { { "key1", "#{a}" }, { "a", "#{b}" }, { "b", "new-value" }, }; RunTest(vars, "example.properties"); } [Test] public void UnicodeCharsInValuesAreEscaped() { var vars = new CalamariVariables { { "key1", "Θctopus" } }; RunTest(vars, "example.properties"); } [Test] public void UnicodeCharsInKeysAreHandled() { var vars = new CalamariVariables { { "kḛy", "new-value" } }; RunTest(vars, "unicode-key.properties"); } [Test] public void ShouldPreserveEncodingUtf8DosBom() { var vars = new CalamariVariables(); RunHexTest(vars, "enc-utf8-dos-bom.properties"); } [Test] public void ShouldPreserveEncodingUtf8UnixNoBom() { var vars = new CalamariVariables(); RunHexTest(vars, "enc-utf8-unix-nobom.properties"); } [Test] public void ShouldPreserveEncodingUtf16DosBom() { var vars = new CalamariVariables(); RunHexTest(vars, "enc-utf16-dos-bom.properties"); } [Test] public void ShouldPreserveEncodingWindows1252DosNoBom() { var vars = new CalamariVariables(); RunHexTest(vars, "enc-windows1252-dos-nobom.properties"); } void RunTest(CalamariVariables vars, string file, [CallerMemberName] string testName = null, [CallerFilePath] string filePath = null) { // ReSharper disable once ExplicitCallerInfoArgument this.Assent(Replace(vars, file), AssentConfiguration.Properties, testName, filePath); } void RunHexTest(CalamariVariables vars, string file, [CallerMemberName] string testName = null, [CallerFilePath] string filePath = null) { // ReSharper disable once ExplicitCallerInfoArgument this.Assent(ReplaceToHex(vars, file), AssentConfiguration.Default, testName, filePath); } } }<file_sep>using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Common.FeatureToggles { [TestFixture] public class FeatureToggleExtensionsFixture { [Test] public void IsEnabled_GivenFeatureToggleNotInVariable_EvaluatesToFalsee() { var variables = GenerateVariableSet("FooFeatureToggle,BarFeatureToggle"); FeatureToggle.SkunkworksFeatureToggle.IsEnabled(variables).Should().BeFalse(); } [Test] public void IsEnabled_GivenFeatureToggleInVariable_EvaluatesToTrue() { var variables = GenerateVariableSet($"FooFeatureToggle,{FeatureToggle.SkunkworksFeatureToggle.ToString()},BarFeatureToggle"); FeatureToggle.SkunkworksFeatureToggle.IsEnabled(variables).Should().BeTrue(); } IVariables GenerateVariableSet(string variableValue) { var variables = new CalamariVariables(); variables.Set(KnownVariables.EnabledFeatureToggles, variableValue); return variables; } } }<file_sep>using System; using Azure.ResourceManager; using Calamari.AzureAppService; using Calamari.AzureAppService.Azure; using NUnit.Framework; namespace Calamari.AzureAppService.Tests { public class AzureClientFixture { [Test] [TestCase("", "https://login.microsoftonline.com/")] [TestCase("AzureCloud", "https://login.microsoftonline.com/")] [TestCase("AzureGlobalCloud", "https://login.microsoftonline.com/")] [TestCase("AzureChinaCloud", "https://login.chinacloudapi.cn/")] [TestCase("AzureGermanCloud", "https://login.microsoftonline.de/")] [TestCase("AzureUSGovernment", "https://login.microsoftonline.us/")] public void AzureClientOptions_IdentityAuth_UsesCorrectEndpointsForRegions(string azureCloud, string expectedAuthorityHost) { // Arrange var servicePrincipalAccount = GetAccountFor(azureCloud); // Act var (_, tokenCredentialOptions) = servicePrincipalAccount.GetArmClientOptions(); // Assert Assert.AreEqual(new Uri(expectedAuthorityHost), tokenCredentialOptions.AuthorityHost); } [Test] [TestCase("", "https://management.azure.com")] [TestCase("AzureCloud", "https://management.azure.com")] [TestCase("AzureGlobalCloud", "https://management.azure.com")] [TestCase("AzureChinaCloud", "https://management.chinacloudapi.cn")] [TestCase("AzureGermanCloud", "https://management.microsoftazure.de")] [TestCase("AzureUSGovernment", "https://management.usgovcloudapi.net")] public void AzureClientOptions_ApiCall_UsesCorrectEndpointsForRegions(string azureCloud, string expectedManagementEndpoint) { // Arrange var servicePrincipalAccount = GetAccountFor(azureCloud); // Act var (armClientOptions, _) = servicePrincipalAccount.GetArmClientOptions(); // Assert Assert.AreEqual(new Uri(expectedManagementEndpoint), armClientOptions.Environment.Value.Endpoint); } private ServicePrincipalAccount GetAccountFor(string azureCloud) { return new ServicePrincipalAccount("<PASSWORD>", "clientId", "tenantId", "p<PASSWORD>", azureCloud, null, null); } } }<file_sep>using System.Text.RegularExpressions; namespace Calamari.Util { public static class GoDurationParser { /// <summary> /// https://golang.org/pkg/time/#ParseDuration /// A duration string is a possibly signed sequence of decimal numbers, each with optional fraction /// and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), /// "ms", "s", "m", "h". /// </summary> static readonly Regex DurationRegex = new Regex(@"^[+-]?(\d+(\.\d+)?(ns|us|µs|ms|s|m|h)?)+$"); public static bool ValidateTimeout(string timeout) { return DurationRegex.IsMatch(timeout.Trim()); } } }<file_sep>using System; using System.IO; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripting.WindowsPowerShell; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Packages { public class VhdBuilder { public static string BuildSampleVhd(string name, bool twoPartitions = false) { var packageDirectory = TestEnvironment.GetTestPath("Fixtures", "Deployment", "Packages", name); Assert.That(Directory.Exists(packageDirectory), string.Format("Package {0} is not available (expected at {1}).", name, packageDirectory)); var output = GetTemporaryDirectory(); //create a new temp dir because later we'll zip it up and we want it to be empty var vhdPath = Path.Combine(output, name + ".vhdx"); if (File.Exists(vhdPath)) File.Delete(vhdPath); using (var scriptFile = new TemporaryFile(Path.GetTempFileName())) { // create an uninistialized VHD with diskpart // can't use New-VHD cmdlet as it requires the Hyper-V service which // won't run in EC2 File.WriteAllText(scriptFile.FilePath, CreateVhdDiskPartScrtipt(vhdPath)); var silentProcessResult = SilentProcessRunner.ExecuteCommand("diskpart", $"/s {scriptFile.FilePath}", output, Console.WriteLine, Console.Error.WriteLine); silentProcessResult.ExitCode.Should().Be(0); } using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1"))) { File.WriteAllText(scriptFile.FilePath, InitializeAndCopyFilesScript(vhdPath, packageDirectory, twoPartitions)); var result = ExecuteScript(new PowerShellScriptExecutor(), scriptFile.FilePath, new CalamariVariables()); result.AssertSuccess(); } return vhdPath; } private static string GetTemporaryDirectory() { string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } private static CalamariResult ExecuteScript(IScriptExecutor psse, string scriptName, IVariables variables) { var runner = new TestCommandLineRunner(ConsoleLog.Instance, variables); var result = psse.Execute(new Script(scriptName), variables, runner); return new CalamariResult(result.ExitCode, runner.Output); } private static string CreateVhdDiskPartScrtipt(string path) { return $"create vdisk file={path} type=fixed maximum=20"; } private static string InitializeAndCopyFilesScript(string vhdpath, string includefolder, bool twoPartitions) { var script = $@" Function CopyFilesToPartition($partition){{ Format-Volume -Partition $partition -Confirm:$false -FileSystem NTFS -force Add-PartitionAccessPath -InputObject $partition -AssignDriveLetter $volume = Get-Volume -Partition $partition $drive = $volume.DriveLetter $drive = $drive + "":\"" Write-Host ""Copying from {includefolder} to $drive"" Copy-Item -Path {includefolder}\InVhd\* -Destination $drive -Recurse }} Mount-DiskImage -ImagePath {vhdpath} -NoDriveLetter $diskImage = Get-DiskImage -ImagePath {vhdpath} Initialize-Disk -Number $diskImage.Number -PartitionStyle MBR $partition = New-Partition -DiskNumber $diskImage.Number -Size 10MB -AssignDriveLetter:$false -MbrType IFS CopyFilesToPartition $partition "; if (twoPartitions) { script += @" $partition = New-Partition -DiskNumber $diskImage.Number -UseMaximumSize -AssignDriveLetter:$false -MbrType IFS CopyFilesToPartition $partition "; } script += $@" Dismount-DiskImage -ImagePath {vhdpath} $zipDestination = Split-Path {vhdpath} Copy-Item -Path {includefolder}\InZip\* -Destination $zipDestination -Recurse "; return script; } } }<file_sep>using System; using System.IO; namespace Calamari.Common.Features.Processes { public static class EmbeddedResource { public static string ReadEmbeddedText(string name) { var thisType = typeof(EmbeddedResource); using (var resource = thisType.Assembly.GetManifestResourceStream(name)) using (var reader = new StreamReader(resource)) { return reader.ReadToEnd(); } } } }<file_sep>print("Hello!") printverbose("Hello verbose!") printwarning("Hello warning!") printhighlight("Hello highlight!")<file_sep>using System; using System.Collections.Generic; namespace Calamari.Common.Features.FunctionScriptContributions { public class ScriptFunctionRegistration { public string Name { get; } public string Description { get; } public string ServiceMessageName { get; } public IDictionary<string, FunctionParameter> Parameters { get; } public ScriptFunctionRegistration( string name, string description, string serviceMessageName, IDictionary<string, FunctionParameter> parameters) { Name = name; Description = description; ServiceMessageName = serviceMessageName; Parameters = parameters; } } }<file_sep>using Calamari.Deployment.PackageRetention; using NUnit.Framework; namespace Calamari.Tests.Fixtures.PackageRetention { [TestFixture] public class CaseInsensitiveTinyTypeFixture { [Test] public void EquivalentValuesOfSameTypesAreEqual() { var tt1 = ATinyType.Create<ATinyType>("value"); var tt2 = ATinyType.Create<ATinyType>("value"); Assert.IsTrue(tt1.Equals(tt2)); } [Test] public void EquivalentValuesOfDifferentTypesAreNotEqual() { var tt1 = ATinyType.Create<ATinyType>("value"); var tt2 = AnotherTinyType.Create<AnotherTinyType>("value"); Assert.IsFalse(tt1.Equals(tt2)); } [Test] public void EquivalentValuesWithDifferentCasesOfSameTypesAreEqual() { var tt1 = ATinyType.Create<ATinyType>("VALUE"); var tt2 = ATinyType.Create<ATinyType>("value"); Assert.IsTrue(tt1.Equals(tt2)); } [Test] public void EquivalentValuesWithDifferentCasesOfSameTypesHaveEqualHashCodes() { var tt1 = ATinyType.Create<ATinyType>("VALUE"); var tt2 = ATinyType.Create<ATinyType>("value"); Assert.AreEqual(tt1.GetHashCode(), tt2.GetHashCode()); } [Test] public void EquivalentValuesOfDifferentTypesHaveUnequalHashCodes() { var tt1 = ATinyType.Create<ATinyType>("value"); var tt2 = AnotherTinyType.Create<AnotherTinyType>("value"); Assert.AreNotEqual(tt1.GetHashCode(), tt2.GetHashCode()); } class ATinyType : CaseInsensitiveTinyType { public ATinyType(string value) : base(value) { } } class AnotherTinyType : CaseInsensitiveTinyType { public AnotherTinyType(string value) : base(value) { } } } }<file_sep>using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Octopus.Versioning; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public class VersionConverter : JsonConverter { public override bool CanWrite => true; public override bool CanRead => true; public override bool CanConvert(Type objectType) => objectType == typeof(IVersion); public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var version = value as IVersion ?? throw new Exception("Type must implement IVersion to use this converter."); var outputVersion = new { Version = version.ToString(), Format = version.Format.ToString() }; serializer.Serialize(writer, outputVersion); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jsonObject = JObject.Load(reader); var versionString = jsonObject["Version"].Value<string>(); var versionFormat = (VersionFormat) Enum.Parse(typeof(VersionFormat), jsonObject["Format"].Value<string>()); var version = VersionFactory.CreateVersion(versionString, versionFormat); return version; } } }<file_sep>using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Terraform.Helpers; using Newtonsoft.Json.Linq; using NuGet.Versioning; namespace Calamari.Terraform.Behaviours { public class PlanBehaviour : TerraformDeployBehaviour { public const string LineEndingRE = "\r\n?|\n"; public const string TerraformPlanJsonMinVersion = "0.12"; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; public PlanBehaviour(ILog log, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner) : base(log) { this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; } protected virtual string ExtraParameter => ""; bool IsUsingPlanJSON(RunningDeployment deployment, Version version) { return !version.IsLessThan(TerraformPlanJsonMinVersion) && deployment.Variables.GetFlag(TerraformSpecialVariables.Action.Terraform.PlanJsonOutput); } public string GetOutputParameter(RunningDeployment deployment, Version version) { return IsUsingPlanJSON(deployment, version) ? "--json" : ""; } protected override Task Execute(RunningDeployment deployment, Dictionary<string, string> environmentVariables) { string results; using (var cli = new TerraformCliExecutor(log, fileSystem, commandLineRunner, deployment, environmentVariables)) { if (cli.Version.IsLessThan(TerraformPlanJsonMinVersion) && deployment.Variables.GetFlag(TerraformSpecialVariables.Action.Terraform.PlanJsonOutput)) { log.Warn($"JSON output is not supported in versions of Terraform prior to {TerraformPlanJsonMinVersion}. The version of Terraform being used is {cli.Version}"); } var commandResult = cli.ExecuteCommand(out results, "plan", "-no-color", "-detailed-exitcode", GetOutputParameter(deployment, cli.Version), ExtraParameter, cli.TerraformVariableFiles, cli.ActionParams); var resultCode = commandResult.ExitCode; cli.VerifySuccess(commandResult, r => r.ExitCode == 0 || r.ExitCode == 2); log.Info( $"Saving variable 'Octopus.Action[{deployment.Variables["Octopus.Action.StepName"]}].Output.{TerraformSpecialVariables.Action.Terraform.PlanDetailedExitCode}' with the detailed exit code of the plan, with value '{resultCode}'."); log.SetOutputVariable(TerraformSpecialVariables.Action.Terraform.PlanDetailedExitCode, resultCode.ToString(), deployment.Variables); if (IsUsingPlanJSON(deployment, cli.Version)) { CaptureJsonOutput(deployment, results); } else { CapturePlainTextOutput(deployment, results); } } return this.CompletedTask(); } void CapturePlainTextOutput(RunningDeployment deployment, string results) { log.Info( $"Saving variable 'Octopus.Action[{deployment.Variables["Octopus.Action.StepName"]}].Output.{TerraformSpecialVariables.Action.Terraform.PlanOutput}' with the details of the plan"); log.SetOutputVariable(TerraformSpecialVariables.Action.Terraform.PlanOutput, results, deployment.Variables); } public void CaptureJsonOutput(RunningDeployment deployment, string results) { var lines = Regex.Split(results, LineEndingRE); for (var index = 0; index < lines.Length; ++index) { var variableName = $"TerraformPlanLine[{index}].JSON"; log.Info( $"Saving variable 'Octopus.Action[{deployment.Variables["Octopus.Action.StepName"]}].Output.{variableName}' with the details of the plan"); log.SetOutputVariable(variableName, lines[index], deployment.Variables); CaptureChangeSummary(deployment, lines[index]); } } void CaptureChangeSummary(RunningDeployment deployment, string line) { try { var parsed = JObject.Parse(line); if (parsed["type"].ToString() != "change_summary") return; log.Info( $"Saving variable 'Octopus.Action[{deployment.Variables["Octopus.Action.StepName"]}].Output.{TerraformSpecialVariables.Action.Terraform.PlanJsonChangesAdd}' with the the number of added resources in the plan"); log.SetOutputVariable(TerraformSpecialVariables.Action.Terraform.PlanJsonChangesAdd, parsed["changes"]?["add"]?.ToString() ?? "", deployment.Variables); log.Info( $"Saving variable 'Octopus.Action[{deployment.Variables["Octopus.Action.StepName"]}].Output.{TerraformSpecialVariables.Action.Terraform.PlanJsonChangesRemove}' with the the number of removed resources in the plan"); log.SetOutputVariable(TerraformSpecialVariables.Action.Terraform.PlanJsonChangesRemove, parsed["changes"]?["remove"]?.ToString() ?? "", deployment.Variables); log.Info( $"Saving variable 'Octopus.Action[{deployment.Variables["Octopus.Action.StepName"]}].Output.{TerraformSpecialVariables.Action.Terraform.PlanJsonChangesChange}' with the the number of changed resources in the plan"); log.SetOutputVariable(TerraformSpecialVariables.Action.Terraform.PlanJsonChangesChange, parsed["changes"]?["change"]?.ToString() ?? "", deployment.Variables); } catch { log.Warn("Terraform output invalid JSON in the line: " + line); } } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using Microsoft.Win32.SafeHandles; using static Calamari.Integration.Certificates.WindowsNative.WindowsX509Native; using Native = Calamari.Integration.Certificates.WindowsNative.WindowsX509Native; namespace Calamari.Integration.Certificates.WindowsNative { internal static class CertificatePal { public static bool HasProperty(IntPtr certificateContext, CertificateProperty property) { byte[] buffer = null; var bufferSize = 0; // ReSharper disable once ExpressionIsAlwaysNull var hasProperty = CertGetCertificateContextProperty(certificateContext, property, buffer, ref bufferSize); // ReSharper disable once InconsistentNaming const int ERROR_MORE_DATA = 0x000000ea; return hasProperty || Marshal.GetLastWin32Error() == ERROR_MORE_DATA; } /// <summary> /// Get a property of a certificate formatted as a structure /// </summary> public static T GetCertificateProperty<T>(IntPtr certificateContext, CertificateProperty property) where T : struct { var rawProperty = GetCertificateProperty(certificateContext, property); var gcHandle = GCHandle.Alloc(rawProperty, GCHandleType.Pinned); var typedProperty = (T)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(T)); gcHandle.Free(); return typedProperty; } public static byte[] GetCertificateProperty(IntPtr certificateContext, CertificateProperty property) { byte[] buffer = null; var bufferSize = 0; // ReSharper disable once ExpressionIsAlwaysNull if (!CertGetCertificateContextProperty(certificateContext, property, buffer, ref bufferSize)) { // ReSharper disable once InconsistentNaming const int ERROR_MORE_DATA = 0x000000ea; var errorCode = Marshal.GetLastWin32Error(); if (errorCode != ERROR_MORE_DATA) { throw new CryptographicException(errorCode); } } buffer = new byte[bufferSize]; if (!CertGetCertificateContextProperty(certificateContext, property, buffer, ref bufferSize)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } return buffer; } public static SafeCspHandle GetCspPrivateKey(SafeCertContextHandle certificate) { SafeCspHandle cspHandle; var keySpec = 0; var freeKey = true; if (!Native.CryptAcquireCertificatePrivateKey(certificate, Native.AcquireCertificateKeyOptions.AcquireSilent, IntPtr.Zero, out cspHandle, out keySpec, out freeKey)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } if (cspHandle.IsInvalid) throw new Exception("Could not acquire private key"); if (!freeKey) { var addedRef = false; cspHandle.DangerousAddRef(ref addedRef); } return cspHandle; } public static byte[] GetCspPrivateKeySecurity(SafeCspHandle cspHandle) { byte[] buffer = null; var bufferSize = 0; // ReSharper disable once ExpressionIsAlwaysNull if (!Native.CryptGetProvParam(cspHandle, WindowsX509Native.CspProperties.SecurityDescriptor, buffer, ref bufferSize, WindowsX509Native.SecurityDesciptorParts.DACL_SECURITY_INFORMATION)) { // ReSharper disable once InconsistentNaming const int ERROR_MORE_DATA = 0x000000ea; var errorCode = Marshal.GetLastWin32Error(); if (errorCode != ERROR_MORE_DATA) { throw new CryptographicException(errorCode); } } buffer = new byte[bufferSize]; if (!Native.CryptGetProvParam(cspHandle, WindowsX509Native.CspProperties.SecurityDescriptor, buffer, ref bufferSize, WindowsX509Native.SecurityDesciptorParts.DACL_SECURITY_INFORMATION)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } return buffer; } public static byte[] GetCngPrivateKeySecurity(SafeNCryptKeyHandle hObject) { int bufferSize = 0; byte[] buffer = null; var errorCode = Native.NCryptGetProperty(hObject, Native.NCryptProperties.SecurityDescriptor, null, 0, ref bufferSize, (int)Native.NCryptFlags.Silent | (int)Native.SecurityDesciptorParts.DACL_SECURITY_INFORMATION); if (errorCode != (int)Native.NCryptErrorCode.Success && errorCode != (int)Native.NCryptErrorCode.BufferTooSmall) { throw new CryptographicException(errorCode); } buffer = new byte[bufferSize]; errorCode = Native.NCryptGetProperty(hObject, Native.NCryptProperties.SecurityDescriptor, buffer, bufferSize, ref bufferSize, (int)Native.NCryptFlags.Silent | (int)Native.SecurityDesciptorParts.DACL_SECURITY_INFORMATION); if (errorCode != (int)Native.NCryptErrorCode.Success) { throw new CryptographicException(errorCode); } return buffer; } public static SafeNCryptKeyHandle GetCngPrivateKey(SafeCertContextHandle certificate) { SafeNCryptKeyHandle key; int keySpec; var freeKey = true; if (!CryptAcquireCertificatePrivateKey(certificate, AcquireCertificateKeyOptions.AcquireOnlyNCryptKeys | AcquireCertificateKeyOptions.AcquireSilent, IntPtr.Zero, out key, out keySpec, out freeKey)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } if (key.IsInvalid) throw new Exception("Could not acquire provide key"); if (!freeKey) { var addedRef = false; key.DangerousAddRef(ref addedRef); } return key; } public static void DeleteCngKey(SafeNCryptKeyHandle key) { var errorCode = NCryptDeleteKey(key, 0); if (errorCode != 0) throw new CryptographicException(errorCode); } public static string GetSubjectName(SafeCertContextHandle certificate) { var flags = CertNameFlags.None; var stringType = CertNameStringType.CERT_X500_NAME_STR | CertNameStringType.CERT_NAME_STR_REVERSE_FLAG; var cchCount = CertGetNameString(certificate, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, null, 0); if (cchCount == 0) throw new CryptographicException(Marshal.GetHRForLastWin32Error()); var sb = new StringBuilder(cchCount); CertGetNameString(certificate, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, sb, cchCount); return sb.ToString(); } } } #endif<file_sep>using System; using Azure.Core; using Azure.ResourceManager.AppService; #nullable enable namespace Calamari.AzureAppService.Azure { public class AzureTargetSite { public string SubscriptionId { get; } public string ResourceGroupName { get; } public string Site { get; } public string? Slot { get; } public string SiteAndSlot => HasSlot ? $"{Site}/{Slot}" : Site; public string ScmSiteAndSlot => HasSlot ? $"{Site}-{Slot}" : Site; public bool HasSlot => !string.IsNullOrWhiteSpace(Slot); public AzureTargetSite(string subscriptionId, string resourceGroupName, string siteAndMaybeSlotName, string? slotName = null) { SubscriptionId = subscriptionId; ResourceGroupName = resourceGroupName; var (parsedSiteName, parsedSlotName) = ParseSiteAndSlotName(siteAndMaybeSlotName, slotName); Site = parsedSiteName; Slot = parsedSlotName; } static (string ParsedSiteName, string? ParsedSlotName) ParseSiteAndSlotName(string siteAndMaybeSlotName, string? slotName) { string parsedSiteName; string? parsedSlotName; if (siteAndMaybeSlotName.Contains("(")) { // legacy site and slot "site(slot)" var parenthesesIndex = siteAndMaybeSlotName.IndexOf("(", StringComparison.Ordinal); parsedSiteName = siteAndMaybeSlotName.Substring(0, parenthesesIndex).Trim(); parsedSlotName = siteAndMaybeSlotName.Substring(parenthesesIndex + 1).Replace(")", string.Empty).Trim(); } else if (siteAndMaybeSlotName.Contains("/")) { // "site/slot" var slashIndex = siteAndMaybeSlotName.IndexOf("/", StringComparison.Ordinal); parsedSiteName = siteAndMaybeSlotName.Substring(0, slashIndex).Trim(); parsedSlotName = siteAndMaybeSlotName.Substring(slashIndex + 1).Trim(); } else { parsedSiteName = siteAndMaybeSlotName; parsedSlotName = slotName; } return (parsedSiteName, parsedSlotName); } /// <summary> /// Creates a new <see cref="ResourceIdentifier"/>, either for a <see cref="WebSiteResource"/> or a <see cref="WebSiteSlotResource"/>, depending on if <see cref="HasSlot"/> is <c>true</c>. /// </summary> /// <returns></returns> public ResourceIdentifier CreateResourceIdentifier() { return HasSlot ? WebSiteSlotResource.CreateResourceIdentifier(SubscriptionId, ResourceGroupName, Site, Slot) : CreateWebSiteResourceIdentifier(); } /// <summary> /// Creates a new <see cref="ResourceIdentifier"/> for the root <see cref="WebSiteSlotResource"/>, even if this is targeting a slot. /// </summary> /// <returns></returns> public ResourceIdentifier CreateWebSiteResourceIdentifier() => WebSiteResource.CreateResourceIdentifier(SubscriptionId, ResourceGroupName, Site); } } #nullable restore<file_sep>using System; using System.Xml.Linq; namespace Calamari.AzureCloudService.CloudServicePackage.ManifestSchema { public class ContentDescription { public static readonly XName ElementName = PackageDefinition.AzureNamespace + "ContentDescription"; static readonly XName LengthInBytesElementName = PackageDefinition.AzureNamespace + "LengthInBytes"; static readonly XName DataStorePathElementName = PackageDefinition.AzureNamespace + "DataStorePath"; static readonly XName HashAlgorithmElementName = PackageDefinition.AzureNamespace + "IntegrityCheckHashAlgortihm"; static readonly XName HashElementName = PackageDefinition.AzureNamespace + "IntegrityCheckHash"; public ContentDescription() { } public ContentDescription(XElement element) { LengthInBytes = int.Parse(element.Element(LengthInBytesElementName).Value); DataStorePath = new Uri(element.Element(DataStorePathElementName).Value, UriKind.Relative); HashAlgorithm = (IntegrityCheckHashAlgorithm)Enum.Parse(typeof(IntegrityCheckHashAlgorithm), element.Element(HashAlgorithmElementName).Value); if (HashAlgorithm != IntegrityCheckHashAlgorithm.None) Hash = element.Element(HashElementName).Value; } public int LengthInBytes { get; set; } public Uri DataStorePath { get; set; } public IntegrityCheckHashAlgorithm HashAlgorithm { get; set; } public string Hash { get; set; } public XElement ToXml() { return new XElement(ElementName, new XElement(LengthInBytesElementName, LengthInBytes.ToString()), new XElement(HashAlgorithmElementName, HashAlgorithm.ToString()), HashAlgorithm == IntegrityCheckHashAlgorithm.None ? new XElement(HashElementName, new XAttribute("{http://www.w3.org/2001/XMLSchema-instance}nil", true)) : new XElement(HashElementName, Hash), new XElement(DataStorePathElementName, DataStorePath) ); } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public static class ProjectVariables { public static readonly string Id = "Octopus.Project.Id"; public static readonly string Name = "Octopus.Project.Name"; } }<file_sep>using System; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class Job: Resource { public string Completions { get; } public string Duration { get; } public Job(JObject json, Options options) : base(json, options) { var succeeded = FieldOrDefault("$.status.succeeded", 0); var desired = FieldOrDefault("$.spec.completions", 0); Completions = $"{succeeded}/{desired}"; var defaultTime = DateTime.UtcNow; var completionTime = FieldOrDefault("$.status.completionTime", defaultTime); var startTime = FieldOrDefault("$.status.startTime", defaultTime); Duration = $"{completionTime - startTime:c}"; var backoffLimit = FieldOrDefault("$.spec.backoffLimit", 0); var failed = FieldOrDefault("$.status.failed", 0); if (!options.WaitForJobs) { ResourceStatus = ResourceStatus.Successful; return; } if (backoffLimit != 0 && failed == backoffLimit) { ResourceStatus = ResourceStatus.Failed; } else if (succeeded == desired) { ResourceStatus = ResourceStatus.Successful; } else { ResourceStatus = ResourceStatus.InProgress; } } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<Job>(lastStatus); return last.Completions != Completions || last.Duration != Duration; } } } <file_sep>using System.Linq; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.Decorators; using Calamari.Common.Features.Packages.Decorators.ArchiveLimits; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Packages.ArchiveLimits { [TestFixture] public class EnforceCompressionRatioDecoratorFixture : CalamariFixture { readonly string[] testZipPath = { "Fixtures", "Integration", "Packages", "Samples", "Acme.Core.1.0.0.0-bugfix.zip" }; [Test] [ExpectedException(typeof(ArchiveLimitException))] public void ShouldEnforceLimit() { var extractor =GetExtractor(WithVariables(maximumCompressionRatio: 1)); extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); } [Test] [TestCase(0)] [TestCase(-1)] public void ShouldIgnoreNonsenseLimit(int ratio) { var extractor = GetExtractor(WithVariables(maximumCompressionRatio: ratio)); var extractedFiles = extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(extractedFiles, Is.EqualTo(1)); } [Test] public void ShouldExtractWhenUnderLimit() { var extractor = GetExtractor(WithVariables(maximumCompressionRatio: 5000)); var extractedFiles = extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(extractedFiles, Is.EqualTo(1)); } [Test] public void ShouldExtractRegardlessOfLimitWithFeatureFlagOff() { var extractor = GetExtractor(WithVariables(featureFlagEnabled: false, maximumCompressionRatio: 1)); var extractedFiles = extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(extractedFiles, Is.EqualTo(1)); } [Test] public void ShouldExtractRegardlessOfLimitWithFeatureFlagNotPresent() { var extractor = GetExtractor(new CalamariVariables()); var extractedFiles = extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(extractedFiles, Is.EqualTo(1)); } IPackageExtractor GetExtractor(CalamariVariables variables) { return new NullExtractor().WithExtractionLimits(Log, variables); } static CalamariVariables WithVariables(int maximumCompressionRatio = 5000, bool featureFlagEnabled = true) { return new CalamariVariables { { KnownVariables.Package.ArchiveLimits.Enabled, featureFlagEnabled.ToString() }, { KnownVariables.Package.ArchiveLimits.MaximumCompressionRatio, maximumCompressionRatio.ToString() } }; } } } <file_sep>using System; namespace Calamari.Common.Commands { [AttributeUsage(AttributeTargets.Class, Inherited = false)] public class CommandAttribute : Attribute { public CommandAttribute(string name) { Name = name; } public string Name { get; set; } public string? Description { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.Rest.Azure; namespace Calamari.AzureAppService { public static class Extensions { /// <summary>Gets the application settings of an app.</summary> /// <remarks> /// Description for Gets the application settings of an app. /// </remarks> /// <param name="operations"> /// The operations group for this extension method. /// </param> /// <param name="targetSite">The target site containing the resource group name, site and (optional) site name</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public static async Task<StringDictionary> ListApplicationSettingsAsync(this IWebAppsOperations operations, AzureTargetSite targetSite, CancellationToken cancellationToken = default) { StringDictionary body; if (targetSite.HasSlot) { using var operationResponse = await operations .ListApplicationSettingsSlotWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, targetSite.Slot, cancellationToken: cancellationToken).ConfigureAwait(false); body = operationResponse.Body; } else { using var operationResponse = await operations .ListApplicationSettingsWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, cancellationToken: cancellationToken).ConfigureAwait(false); body = operationResponse.Body; } return body; } public static async Task<StringDictionary> UpdateApplicationSettingsAsync(this IWebAppsOperations operations, AzureTargetSite targetSite, StringDictionary appSettings, CancellationToken cancellationToken = default) { if (targetSite.HasSlot) { using var operationResponse = await operations.UpdateApplicationSettingsSlotWithHttpMessagesAsync( targetSite.ResourceGroupName, targetSite.Site, appSettings, targetSite.Slot, cancellationToken: cancellationToken); return operationResponse.Body; } else { using var operationResponse = await operations .UpdateApplicationSettingsWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, appSettings, cancellationToken: cancellationToken).ConfigureAwait(false); return operationResponse.Body; } } public static async Task RestartAsync(this IWebAppsOperations operations, AzureTargetSite targetSite, bool? softRestart = null, bool? synchronous = null, CancellationToken cancellationToken = default) { if (targetSite.HasSlot) { await operations.RestartSlotWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, targetSite.Slot, softRestart, synchronous, cancellationToken: cancellationToken); } else { await operations.RestartWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, softRestart, synchronous, cancellationToken: cancellationToken); } } public static async Task<SiteConfigResource> GetConfigurationAsync(this IWebAppsOperations operations, AzureTargetSite targetSite, CancellationToken cancellationToken = default) { if (targetSite.HasSlot) { return (await operations.GetConfigurationSlotWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, targetSite.Slot, cancellationToken: cancellationToken)).Body; } return (await operations.GetConfigurationWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, cancellationToken: cancellationToken)).Body; } public static async Task UpdateConfigurationAsync(this IWebAppsOperations operations, AzureTargetSite targetSite, SiteConfigResource config, CancellationToken cancellationToken = default) { if (targetSite.HasSlot) { await operations.UpdateConfigurationSlotWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, config, targetSite.Slot, cancellationToken: cancellationToken); } else { await operations.UpdateConfigurationWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.ScmSiteAndSlot, config, cancellationToken: cancellationToken); } } public static async Task<ConnectionStringDictionary> ListConnectionStringsAsync(this IWebAppsOperations operations, AzureTargetSite targetSite, CancellationToken cancellationToken = default) { ConnectionStringDictionary body; if (targetSite.HasSlot) { var response = await operations.ListConnectionStringsSlotWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, targetSite.Slot, cancellationToken: cancellationToken).ConfigureAwait(false); body = response.Body; } else { var response = await operations.ListConnectionStringsWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, cancellationToken: cancellationToken).ConfigureAwait(false); body = response.Body; } return body; } public static async Task UpdateConnectionStringsAsync(this IWebAppsOperations operations, AzureTargetSite targetSite, ConnectionStringDictionary connectionStringDictionary, CancellationToken cancellationToken = default) { if (targetSite.HasSlot) { await operations.UpdateConnectionStringsSlotWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, connectionStringDictionary, targetSite.Slot, cancellationToken: cancellationToken); } else { await operations.UpdateConnectionStringsWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site, connectionStringDictionary, cancellationToken: cancellationToken); } } } } <file_sep>using System; namespace Calamari.Common.Util { public static class Uniquifier { public static string UniquifyString(string input, Func<string, bool> isInUse, string format = "-{0}", int startCounter = 1) { return UniquifyUntil(input, s => s, isInUse, format, startCounter); } public static T UniquifyUntil<T>(string input, Func<string, T> creator, Func<T, bool> isInUse, string format = "-{0}", int startCounter = 1) { var inputToTest = input; var i = startCounter; do { var item = creator(inputToTest); if (!isInUse(item)) { return item; } inputToTest = input + string.Format(format, i); i++; } while (true); } public static string UniquifyStringFriendly(string input, Func<string, bool> isInUse) { return UniquifyString(input, isInUse, " (#{0:n0})", 2); } public static string? Normalize(string? input) { return input?.Trim().ToLowerInvariant(); } } }<file_sep>using System; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Calamari.Testing; using FluentAssertions; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; using NUnit.Framework; namespace Calamari.AzureCloudService.Tests { public class HealthCheckCommandFixture { [Test] public async Task CloudService_Is_Found() { var subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); var certificate = ExternalVariables.Get(ExternalVariable.AzureSubscriptionCertificate); var serviceName = $"{nameof(HealthCheckCommandFixture)}-{Guid.NewGuid().ToString("N").Substring(0, 12)}"; using var managementCertificate = CreateManagementCertificate(certificate); using var client = new ComputeManagementClient(new CertificateCloudCredentials(subscriptionId, managementCertificate)); try { await client.HostedServices.CreateAsync(new HostedServiceCreateParameters(serviceName, "test") { Location = "West US" }); await CommandTestBuilder.CreateAsync<HealthCheckCommand, Program>() .WithArrange(context => { context.Variables.Add(SpecialVariables.Action.Azure.SubscriptionId, subscriptionId); context.Variables.Add(SpecialVariables.Action.Azure.CertificateThumbprint, managementCertificate.Thumbprint); context.Variables.Add(SpecialVariables.Action.Azure.CertificateBytes, certificate); context.Variables.Add(SpecialVariables.Action.Azure.CloudServiceName, serviceName); }) .WithAssert(result => result.WasSuccessful.Should().BeTrue()) .Execute(); } finally { await client.HostedServices.DeleteAsync(serviceName); } } [Test] public Task CloudService_Is_Not_Found() { var subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); var certificate = ExternalVariables.Get(ExternalVariable.AzureSubscriptionCertificate); var serviceName = $"{nameof(HealthCheckCommandFixture)}-{Guid.NewGuid().ToString("N").Substring(0, 12)}"; using var managementCertificate = CreateManagementCertificate(certificate); return CommandTestBuilder.CreateAsync<HealthCheckCommand, Program>() .WithArrange(context => { context.Variables.Add(SpecialVariables.Action.Azure.SubscriptionId, subscriptionId); context.Variables.Add(SpecialVariables.Action.Azure.CertificateThumbprint, managementCertificate.Thumbprint); context.Variables.Add(SpecialVariables.Action.Azure.CertificateBytes, certificate); context.Variables.Add(SpecialVariables.Action.Azure.CloudServiceName, serviceName); }) .WithAssert(result => result.WasSuccessful.Should().BeFalse()) .Execute(false); } static X509Certificate2 CreateManagementCertificate(string certificate) { var bytes = Convert.FromBase64String(certificate); return new X509Certificate2(bytes); } } }<file_sep>using System; using Newtonsoft.Json.Linq; namespace Calamari.LaunchTools { public class Instruction { public LaunchTools Launcher { get; set; } public JToken LauncherInstructions { get; set; } public string LauncherInstructionsRaw => LauncherInstructions.ToString(); } }<file_sep>using System; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.Pipeline; using Calamari.Scripting; namespace Calamari.Commands { class AddJournalEntryBehaviour : IOnFinishBehaviour { readonly IDeploymentJournalWriter deploymentJournalWriter; public AddJournalEntryBehaviour(IDeploymentJournalWriter deploymentJournalWriter) { this.deploymentJournalWriter = deploymentJournalWriter; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var exitCode = context.Variables.GetInt32(SpecialVariables.Action.Script.ExitCode); deploymentJournalWriter.AddJournalEntry(context, exitCode == 0, context.PackageFilePath); return this.CompletedTask(); } } }<file_sep>using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.FileSystem.GlobExpressions { public enum GlobMode { LegacyMode, GroupExpansionMode } public static class GlobModeRetriever { public static GlobMode GetFromVariables(IVariables variables) { return FeatureToggle.GlobPathsGroupSupportInvertedFeatureToggle.IsEnabled(variables) ? GlobMode.LegacyMode : GlobMode.GroupExpansionMode; } } }<file_sep>#!/bin/bash # Octopus Linux helper function script # Version: 1.1.0 # ----------------------------------------------------------------------------- sensitiveVariableKey=$1 # ----------------------------------------------------------------------------- # Function to base64 encode a service message value # Accepts 1 argument: # string: the value to encode # ----------------------------------------------------------------------------- function encode_servicemessagevalue { echo -n "$1" | openssl enc -base64 -A } # ----------------------------------------------------------------------------- # Function to base64 decode a service message value # Accepts 1 argument: # string: the value to decode # ----------------------------------------------------------------------------- function decode_servicemessagevalue { echo -n "$1" | openssl enc -base64 -A -d } # ----------------------------------------------------------------------------- # Functions to request server masking of sensitive values # ----------------------------------------------------------------------------- function __mask_sensitive_value { # We want to write to both stdout and stderr due to a racecondition between stdout and stderr # causing error logs to not be masked if stderr event is handled first. echo "##octopus[mask value='$(encode_servicemessagevalue "$1")']" echo "##octopus[mask value='$(encode_servicemessagevalue "$1")']" >&2 } __mask_sensitive_value $sensitiveVariableKey # ----------------------------------------------------------------------------- # Function to decrypt a sensitive variable # Accepts 2 arguments: # string: the value to decrypt (base64 encoded) # string: the decryption iv (hex) # ----------------------------------------------------------------------------- function decrypt_variable { echo $1 | openssl enc -a -A -d -aes-128-cbc -nosalt -K $sensitiveVariableKey -iv $2 } # --------------------------------------------------------------------------- # Function for getting an octopus variable # Accepts 1 argument: # string: value of the name of the octopus variable # --------------------------------------------------------------------------- function get_octopusvariable { INPUT=$( encode_servicemessagevalue "$1" ) case $INPUT in #### VariableDeclarations #### *) echo "" ;; esac } # --------------------------------------------------------------------------- # Function for failing a step with an optional message # Accepts 1 argument: # string: reason for failing # --------------------------------------------------------------------------- function fail_step { if [ ! -z "${1:-}" ] then echo "##octopus[resultMessage message='$(encode_servicemessagevalue "$1")']" fi exit 1; } # --------------------------------------------------------------------------- # Function for setting an octopus variable # Accepts 3 arguments: # string: value of the name of the octopus variable # string: value of the value of the octopus variable # string: optional '-sensitive' to make variable sensitive # --------------------------------------------------------------------------- function set_octopusvariable { MESSAGE="##octopus[setVariable" if [ -n "$1" ] then MESSAGE="$MESSAGE name='$(encode_servicemessagevalue "$1")'" fi if [ -n "$2" ] then MESSAGE="$MESSAGE value='$(encode_servicemessagevalue "$2")'" fi if [ ! -z "${3:-}" ] && [ "$3" = "-sensitive" ] then MESSAGE="$MESSAGE sensitive='$(encode_servicemessagevalue "True")'" fi MESSAGE="$MESSAGE]" echo $MESSAGE } # ----------------------------------------------------------------------------- # Function to create a new octopus artifact # Accepts 2 arguments: # string: value of the path to the artifact # string: value of the original file name of the artifact # ----------------------------------------------------------------------------- function new_octopusartifact { echo "Collecting $1 as an artifact..." if [ ! -e "$1" ] then error_exit $PROGNAME $LINENO "\"$(1)\" does not exist." $E_FILE_NOT_FOUND exit $? fi pth=$1 ofn=$2 len=$(wc -c < $1 ) if [ -z "$ofn" ] then ofn=`basename "$pth"` fi echo "##octopus[stdout-verbose]" echo "Artifact $ofn will be collected from $pth after this step completes" echo "##octopus[stdout-default]" echo "##octopus[createArtifact path='$(encode_servicemessagevalue "$pth")' name='$(encode_servicemessagevalue "$ofn")' length='$(encode_servicemessagevalue $len)']" } function remove-octopustarget { echo "##octopus[delete-target machine='$(encode_servicemessagevalue "$1")']" } function new_octopustarget() ( parameters="" while : do case "$1" in -n | --name) parameters="$parameters name='$(encode_servicemessagevalue "$2")'" shift 2 ;; -t | --target-id) parameters="$parameters targetId='$(encode_servicemessagevalue "$2")'" shift 2 ;; --inputs) parameters="$parameters inputs='$(encode_servicemessagevalue "$2")'" shift 2 ;; --roles) parameters="$parameters octopusRoles='$(encode_servicemessagevalue "$2")'" shift 2 ;; --worker-pool) parameters="$parameters octopusDefaultWorkerPoolIdOrName='$(encode_servicemessagevalue "$2")'" shift 2 ;; --update-if-existing) parameters="$parameters updateIfExisting='$(encode_servicemessagevalue "true")'" shift ;; --) # End of all options. shift break ;; -*) echo "Error: Unknown option: $1" >&2 exit 1 ;; *) # No more options break ;; esac done echo "##octopus[createStepPackageTarget ${parameters}]" ) # ----------------------------------------------------------------------------- # Function to update progress # Accepts 2 arguments: # int: percentage progress # string: message to show # ----------------------------------------------------------------------------- function update_progress { echo "##octopus[progress percentage='$(encode_servicemessagevalue "$1")' message='$(encode_servicemessagevalue "$2")']" } # ----------------------------------------------------------------------------- # Functions write a messages as different levels # ----------------------------------------------------------------------------- function write_verbose { echo "##octopus[stdout-verbose]" echo $1 echo "##octopus[stdout-default]" } function write_highlight { echo "##octopus[stdout-highlight]" echo $1 echo "##octopus[stdout-default]" } function write_wait { echo "##octopus[stdout-wait]" echo $1 echo "##octopus[stdout-default]" } function write_warning { echo "##octopus[stdout-warning]" echo $1 echo "##octopus[stdout-default]" } # ----------------------------------------------------------------------------- # Functions to write the environment information # ----------------------------------------------------------------------------- function log_environment_information { suppressEnvironmentLogging=$(get_octopusvariable "Octopus.Action.Script.SuppressEnvironmentLogging") if [ "$suppressEnvironmentLogging" == "True" ] then return 0 fi echo "##octopus[stdout-verbose]" echo "Bash Environment Information:" echo " OperatingSystem: $(uname -a)" echo " CurrentUser: $(whoami)" echo " HostName: $(hostname)" echo " ProcessorCount: $(getconf _NPROCESSORS_ONLN)" currentDirectory="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" echo " CurrentDirectory: $currentDirectory" tempDirectory=$(dirname $(mktemp -u)) echo " TempDirectory: $tempDirectory" echo " HostProcessID: $$" echo "##octopus[stdout-default]" } log_environment_information<file_sep>using System; using System.Collections.Generic; using Amazon.CloudFormation.Model; using Calamari.Aws.Exceptions; using Calamari.Common.Plumbing.Logging; using Octopus.CoreUtilities; namespace Calamari.Aws.Integration.CloudFormation { public class StackEventLogger { private readonly ILog log; private string lastMessage; private HashSet<string> warnings = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public StackEventLogger(ILog log) { this.log = log; } /// <summary> /// Display an warning message to the user (without duplicates) /// </summary> /// <param name="errorCode">The error message code</param> /// <param name="message">The error message body</param> /// <returns>true if it was displayed, and false otherwise</returns> public bool Warn(string errorCode, string message) { if (!warnings.Contains(errorCode)) { warnings.Add(errorCode); log.Warn($"{errorCode}: {message}\nFor more information visit {log.FormatLink($"https://g.octopushq.com/AwsCloudFormationDeploy#{errorCode.ToLower()}")}"); return true; } return false; } /// <summary> /// Write the state of the stack, but only if it changed since last time. If we are /// writing the same message more than once, do it as verbose logging. /// </summary> /// <param name="status">The current status of the stack</param> public void Log(Maybe<StackEvent> status) { var statusMessage = status.SelectValueOrDefault(x => $"{x.LogicalResourceId} - {x.ResourceType} - {x.ResourceStatus.Value ?? "Does not exist"}{(x.ResourceStatusReason != null ? $" - {x.ResourceStatusReason}" : "")}"); if (statusMessage != lastMessage) { log.Info($"Current stack state: {statusMessage}"); } else { log.Verbose($"Current stack state: {statusMessage}"); } lastMessage = statusMessage; } /// <summary> /// Log an error if we expected success and got a rollback /// </summary> /// <param name="status">The status of the stack, or null if the stack does not exist</param> /// <param name="expectSuccess">True if the status should indicate success</param> /// <param name="missingIsFailure">True if the a missing stack indicates a failure, and false otherwise</param> public void LogRollbackError( Maybe<StackEvent> status, Func<Func<StackEvent, bool>, List<Maybe<StackEvent>>> query, bool expectSuccess, bool missingIsFailure) { var isSuccess = status.Select(x => x.MaybeIndicatesSuccess()).SelectValueOr(x => x.Value, !missingIsFailure); var isStackType = status.SelectValueOr(x => x.ResourceType.Equals("AWS::CloudFormation::Stack"), true); if (expectSuccess && !isSuccess && isStackType) { log.Warn( status.SelectValueOr(x => $"Stack status {x.ResourceStatus.Value} indicated rollback or failed state. ", "Stack was unexpectedly missing during processing. ") + "This means that the stack was not processed correctly. Review the stack events logged below or check the stack in the AWS console to find any errors that may have occured during deployment." ); try { var progressStatuses = query(stack => stack?.ResourceStatusReason != null); foreach (var progressStatus in progressStatuses) { if (progressStatus.Some()) { var progressStatusSuccess = progressStatus.Select(s => s.MaybeIndicatesSuccess()).SelectValueOr(x => x.Value, true); var progressStatusMessage = $"Stack event ({progressStatus.Value.StackName}): {progressStatus.Value.Timestamp:u} - {progressStatus.Value.LogicalResourceId} - {progressStatus.Value.ResourceType} - {progressStatus.Value.ResourceStatus} - {progressStatus.Value.ResourceStatusReason}"; if (progressStatusSuccess) log.Verbose(progressStatusMessage); else log.Warn(progressStatusMessage); } } } catch (PermissionException) { // ignore, it just means we won't display any of the status reasons } throw new RollbackException( "AWS-CLOUDFORMATION-ERROR-0001: CloudFormation stack finished in a rollback or failed state. " + $"For more information visit {log.FormatLink("https://g.octopushq.com/AwsCloudFormationDeploy#aws-cloudformation-error-0001")}"); } } } }<file_sep>using System; using System.IO; using System.Text; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; namespace Calamari.Testing.Helpers { public static class ExecutableHelper { public static void AddExecutePermission(string exePath) { if (CalamariEnvironment.IsRunningOnWindows) return; var stdOut = new StringBuilder(); var stdError = new StringBuilder(); var result = SilentProcessRunner.ExecuteCommand("chmod", $"+x {exePath}", Path.GetDirectoryName(exePath) ?? string.Empty, s => stdOut.AppendLine(s), s => stdError.AppendLine(s)); if (result.ExitCode != 0) throw new Exception(stdOut.ToString() + stdError); } } } <file_sep>namespace Calamari.AzureCloudService { static class DefaultVariables { public const string ServiceManagementEndpoint = "https://management.core.windows.net/"; public const string StorageEndpointSuffix = "core.windows.net"; } }<file_sep>using System; Console.WriteLine("HTTP_PROXY:"+Environment.GetEnvironmentVariable("HTTP_PROXY")); Console.WriteLine("HTTPS_PROXY:"+Environment.GetEnvironmentVariable("HTTPS_PROXY")); Console.WriteLine("NO_PROXY:"+Environment.GetEnvironmentVariable("NO_PROXY")); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { var testUri = new Uri("http://octopustesturl.com"); var octopusProxyUri = System.Net.WebRequest.DefaultWebProxy.GetProxy(testUri); if (octopusProxyUri is not null && octopusProxyUri.Host != "octopustesturl.com") { Console.WriteLine("WebRequest.DefaultProxy:" + octopusProxyUri); } else { Console.WriteLine("WebRequest.DefaultProxy:None"); } } var bypassUri = Environment.GetEnvironmentVariable("TEST_ONLY_PROXY_EXCEPTION_URI"); if (!string.IsNullOrEmpty(bypassUri)) { var bypass = new Uri(bypassUri); // Getting false from IsBypassed does not guarantee that the URI is proxied; // we still need to call the GetProxy method to determine this. // https://learn.microsoft.com/en-us/dotnet/api/system.net.iwebproxy.isbypassed?view=net-6.0#remarks if (System.Net.WebRequest.DefaultWebProxy.IsBypassed(bypass) || System.Net.WebRequest.DefaultWebProxy.GetProxy(bypass) == null) { Console.WriteLine("ProxyBypassed:" + bypassUri); } }<file_sep>using System; namespace Calamari.Common.Plumbing.Extensions { public static class BinaryExtensions { public static string ToHexString(this byte[] data) { return BitConverter.ToString(data).Replace("-", "").ToLowerInvariant(); } } }<file_sep>using System; using System.Globalization; using System.IO; using System.Xml.Linq; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] public class CleanFixture : CalamariFixture { CalamariResult result; ICalamariFileSystem fileSystem; DeploymentJournal deploymentJournal; IVariables variables; string tentacleDirectory; string packagesDirectory; string stagingDirectory; [SetUp] public void SetUp() { fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); // Ensure tenticle directory exists tentacleDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestTentacle"); var tentacleHiddenDirectory = Path.Combine(tentacleDirectory, ".tentacle"); fileSystem.EnsureDirectoryExists(tentacleDirectory); fileSystem.EnsureDirectoryExists(tentacleHiddenDirectory); fileSystem.PurgeDirectory(tentacleHiddenDirectory, FailureOptions.ThrowOnFailure); Environment.SetEnvironmentVariable("TentacleJournal", Path.Combine(tentacleHiddenDirectory, "DeploymentJournal.xml" )); Environment.SetEnvironmentVariable("TentacleHome", tentacleHiddenDirectory); variables = new VariablesFactory(fileSystem).Create(new CommonOptions("test")); deploymentJournal = new DeploymentJournal(fileSystem, SemaphoreFactory.Get(), variables); packagesDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestPackages"); fileSystem.EnsureDirectoryExists(packagesDirectory); stagingDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestStaging"); fileSystem.EnsureDirectoryExists(stagingDirectory); // Create some artificats const string retentionPolicySet1 = "retentionPolicySet1"; CreateDeployment(Path.Combine(packagesDirectory, "Acme.1.0.0.nupkg"), Path.Combine(stagingDirectory, "Acme.1.0.0"), new DateTimeOffset(new DateTime(2015, 01, 26), new TimeSpan(10, 0,0)), retentionPolicySet1); CreateDeployment(Path.Combine(packagesDirectory, "Acme.1.1.0.nupkg"), Path.Combine(stagingDirectory, "Acme.1.1.0"), new DateTimeOffset(new DateTime(2015, 02, 01), new TimeSpan(10, 0,0)), retentionPolicySet1); CreateDeployment(Path.Combine(packagesDirectory, "Acme.1.2.0.nupkg"), Path.Combine(stagingDirectory, "Acme.1.2.0"), new DateTimeOffset(new DateTime(2015, 02, 10), new TimeSpan(10, 0,0)), retentionPolicySet1); } [Test] public void ShouldRemoveArtifactsWhenDaysSpecified() { result = Clean("retentionPolicySet1", 3, null); result.AssertSuccess(); Assert.False(fileSystem.DirectoryExists(Path.Combine(stagingDirectory, "Acme.1.0.0"))); } [Test] public void ShouldRemoveArtifactsWhenReleasesSpecified() { result = Clean("retentionPolicySet1", null, 1); result.AssertSuccess(); Assert.False(fileSystem.DirectoryExists(Path.Combine(stagingDirectory, "Acme.1.0.0"))); } private void CreateDeployment(string extractedFrom, string extractedTo, DateTimeOffset date, string retentionPolicySet) { fileSystem.EnsureDirectoryExists(extractedTo); fileSystem.OverwriteFile(Path.Combine(extractedTo, "an_artifact.txt"), "lorem ipsum"); fileSystem.OverwriteFile(extractedFrom, "lorem ipsum"); deploymentJournal.AddJournalEntry(new JournalEntry(new XElement("Deployment", new XAttribute("Id", Guid.NewGuid().ToString()), new XAttribute("EnvironmentId", "blah"), new XAttribute("ProjectId", "blah"), new XAttribute("PackageId", "blah"), new XAttribute("PackageVersion", "blah"), new XAttribute("InstalledOn", date.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture )), new XAttribute("ExtractedFrom", extractedFrom), new XAttribute("ExtractedTo", extractedTo), new XAttribute("RetentionPolicySet", retentionPolicySet), new XAttribute("WasSuccessFul", true.ToString()) ))); } CalamariResult Clean(string retentionPolicySet, int? days, int? releases) { return Invoke(Calamari() .Action("clean") .Argument("retentionPolicySet", retentionPolicySet) .Argument(days.HasValue ? "days" : "releases", days.HasValue ? days.ToString() : releases.ToString())); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; namespace Calamari.Common.Features.Discovery { public static class TargetTagsExtensions { public static TargetTags ToTargetTags(this IEnumerable<KeyValuePair<string, string>> tags) { var caseInsensitiveTagDictionary = tags.ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.OrdinalIgnoreCase); caseInsensitiveTagDictionary.TryGetValue(TargetTags.EnvironmentTagName, out var environment); caseInsensitiveTagDictionary.TryGetValue(TargetTags.RoleTagName, out var role); caseInsensitiveTagDictionary.TryGetValue(TargetTags.ProjectTagName, out var project); caseInsensitiveTagDictionary.TryGetValue(TargetTags.SpaceTagName, out var space); caseInsensitiveTagDictionary.TryGetValue(TargetTags.TenantTagName, out var tenant); return new TargetTags( environment: environment, role: role, project: project, space: space, tenant: tenant); } } }<file_sep>using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Autofac; using Calamari.AzureScripting; using Calamari.Common; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Util; namespace Calamari.AzureResourceGroup { public class Program : CalamariFlavourProgramAsync { public Program(ILog log) : base(log) { } protected override void ConfigureContainer(ContainerBuilder builder, CommonOptions options) { base.ConfigureContainer(builder, options); builder.RegisterType<TemplateService>(); builder.RegisterType<ResourceGroupTemplateNormalizer>().As<IResourceGroupTemplateNormalizer>(); builder.RegisterType<TemplateResolver>().As<ITemplateResolver>().SingleInstance(); } protected override IEnumerable<Assembly> GetProgramAssembliesToRegister() { yield return typeof(AzureContextScriptWrapper).Assembly; yield return typeof(Program).Assembly; } public static Task<int> Main(string[] args) { return new Program(ConsoleLog.Instance).Run(args); } } }<file_sep>using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Deployment.PackageRetention; namespace Calamari.Commands { [Command("clean-packages", Description = "Apply retention to the package cache")] public class CleanPackagesCommand : Command { readonly IManagePackageCache journal; public CleanPackagesCommand(IManagePackageCache journal) { this.journal = journal; } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); journal.ApplyRetention(); return 0; } } }<file_sep>using System; namespace Calamari.Common.Features.Processes { public interface ICommandLineRunner { CommandResult Execute(CommandLineInvocation invocation); } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Common.Features.Packages { public class PackagePhysicalFileMetadata : PackageFileNameMetadata { public PackagePhysicalFileMetadata(PackageFileNameMetadata identity, string fullFilePath, string hash, long size) : base(identity.PackageId, identity.Version, identity.FileVersion, identity.Extension) { FullFilePath = fullFilePath; Hash = hash; Size = size; } public string FullFilePath { get; } public string Hash { get; } public long Size { get; } public static PackagePhysicalFileMetadata? Build(string fullFilePath) { return Build(fullFilePath, PackageName.FromFile(fullFilePath)); } public static PackagePhysicalFileMetadata? Build(string fullFilePath, PackageFileNameMetadata? identity) { if (identity == null) return null; try { using (var stream = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read)) { return new PackagePhysicalFileMetadata(identity, fullFilePath, HashCalculator.Hash(stream), stream.Length); } } catch (IOException) { return null; } } } }<file_sep>using System; using Octopus.CoreUtilities; namespace Calamari.Testing.Tools; public class InPathDeploymentTool : IDeploymentTool { public InPathDeploymentTool( string id, string? subFolder = null, string? toolPathVariableToSet = null, string[]? supportedPlatforms = null) { this.Id = id; this.SubFolder = subFolder == null ? Maybe<string>.None : Maybe<string>.Some(subFolder); this.ToolPathVariableToSet = toolPathVariableToSet == null ? Maybe<string>.None : Maybe<string>.Some(toolPathVariableToSet); this.SupportedPlatforms = supportedPlatforms ?? new string[0]; } public string Id { get; } public Maybe<string> SubFolder { get; } public bool AddToPath => true; public Maybe<string> ToolPathVariableToSet { get; } public string[] SupportedPlatforms { get; } public virtual Maybe<DeploymentToolPackage> GetCompatiblePackage( string platform) { return new DeploymentToolPackage((IDeploymentTool) this, this.Id).AsSome<DeploymentToolPackage>(); } }<file_sep>using System; namespace Calamari.Common.Features.Scripting { public class MonoVersionCanNotBeDeterminedException : Exception { public MonoVersionCanNotBeDeterminedException(string message) : base(message) { } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.AccessControl; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Threading; using Calamari.Integration.Certificates; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers.Certificates; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Certificates { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class WindowsX509CertificateStoreFixture { [Test] [TestCase(SampleCertificate.CngPrivateKeyId, StoreLocation.LocalMachine, "My")] [TestCase(SampleCertificate.CngPrivateKeyId, StoreLocation.CurrentUser, "My")] [TestCase(SampleCertificate.CngPrivateKeyId, StoreLocation.LocalMachine, "Foo")] [TestCase(SampleCertificate.CapiWithPrivateKeyId, StoreLocation.LocalMachine, "My")] [TestCase(SampleCertificate.CapiWithPrivateKeyId, StoreLocation.CurrentUser, "My")] [TestCase(SampleCertificate.CapiWithPrivateKeyId, StoreLocation.CurrentUser, "Foo")] [TestCase(SampleCertificate.CapiWithPrivateKeyNoPasswordId, StoreLocation.LocalMachine, "My")] public void CanImportCertificate(string sampleCertificateId, StoreLocation storeLocation, string storeName) { var sampleCertificate = SampleCertificate.SampleCertificates[sampleCertificateId]; sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); WindowsX509CertificateStore.ImportCertificateToStore(Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, storeLocation, storeName, sampleCertificate.HasPrivateKey); sampleCertificate.AssertCertificateIsInStore(storeName, storeLocation); if (sampleCertificate.HasPrivateKey) { var certificate = sampleCertificate.GetCertificateFromStore(storeName, storeLocation); Assert.True(certificate.HasPrivateKey); } sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); } [Test(Description = "This test proves, to a degree of certainty, the WindowsX509CertificateStore is safe for concurrent operations. We were seeing exceptions when multiple processes attempted to get/set private key ACLs at the same time.")] public void SafeForConcurrentOperations() { var maxTimeAllowedForTest = TimeSpan.FromSeconds(20); var sw = Stopwatch.StartNew(); try { using (var cts = new CancellationTokenSource(maxTimeAllowedForTest)) { var cancellationToken = cts.Token; var sampleCertificate = SampleCertificate.SampleCertificates[SampleCertificate.CngPrivateKeyId]; var numThreads = 20; var numIterationsPerThread = 1; var exceptions = new BlockingCollection<Exception>(); void Log(string message) => Console.WriteLine($"{sw.Elapsed} {Thread.CurrentThread.Name}: {message}"); WindowsX509CertificateStore.ImportCertificateToStore( Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, StoreLocation.LocalMachine, "My", sampleCertificate.HasPrivateKey); CountdownEvent allThreadsReady = null; CountdownEvent allThreadsFinished = null; ManualResetEventSlim goForIt = new ManualResetEventSlim(false); Thread[] CreateThreads(int number, string name, Action action) => Enumerable.Range(0, number) .Select(i => new Thread(() => { allThreadsReady.Signal(); goForIt.Wait(cancellationToken); for (int j = 0; j < numIterationsPerThread; j++) { try { Log($"{name} {j}"); action(); } catch (Exception e) { Log(e.ToString()); exceptions.Add(e); } } allThreadsFinished.Signal(); }) {Name = $"{name}#{i}"}).ToArray(); var threads = CreateThreads(numThreads, "ImportCertificateToStore", () => { WindowsX509CertificateStore.ImportCertificateToStore( Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, StoreLocation.LocalMachine, "My", sampleCertificate.HasPrivateKey); }) .Concat(CreateThreads(numThreads, "AddPrivateKeyAccessRules", () => { WindowsX509CertificateStore.AddPrivateKeyAccessRules( sampleCertificate.Thumbprint, StoreLocation.LocalMachine, "My", new List<PrivateKeyAccessRule> { new PrivateKeyAccessRule("BUILTIN\\Users", PrivateKeyAccess.FullControl) }); })) .Concat(CreateThreads(numThreads, "GetPrivateKeySecurity", () => { var unused = WindowsX509CertificateStore.GetPrivateKeySecurity( sampleCertificate.Thumbprint, StoreLocation.LocalMachine, "My"); })).ToArray(); allThreadsReady = new CountdownEvent(threads.Length); allThreadsFinished = new CountdownEvent(threads.Length); foreach (var thread in threads) { thread.Start(); } allThreadsReady.Wait(cancellationToken); goForIt.Set(); allThreadsFinished.Wait(cancellationToken); foreach (var thread in threads) { Log($"Waiting for {thread.Name} to join..."); if (!thread.Join(TimeSpan.FromSeconds(1))) { Log($"Aborting {thread.Name}"); thread.Abort(); } } sw.Stop(); sampleCertificate.EnsureCertificateNotInStore("My", StoreLocation.LocalMachine); if (exceptions.Any()) throw new AssertionException( $"The following exceptions were thrown during the test causing it to fail:{Environment.NewLine}{string.Join($"{Environment.NewLine}{new string('=', 80)}", exceptions.GroupBy(ex => ex.Message).Select(g => g.First().ToString()))}"); if (sw.Elapsed > maxTimeAllowedForTest) throw new TimeoutException( $"This test exceeded the {maxTimeAllowedForTest} allowed for this test to complete."); } } catch (OperationCanceledException) { throw new TimeoutException($"This test took longer than {maxTimeAllowedForTest} to run"); } } [Test] public void CanImportCertificateForSpecificUser() { // This test cheats a little bit, using the current user var user = WindowsIdentity.GetCurrent().Name; var storeName = "My"; var sampleCertificate = SampleCertificate.CapiWithPrivateKey; sampleCertificate.EnsureCertificateNotInStore(storeName, StoreLocation.CurrentUser); WindowsX509CertificateStore.ImportCertificateToStore(Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, user, storeName, sampleCertificate.HasPrivateKey); sampleCertificate.AssertCertificateIsInStore(storeName, StoreLocation.CurrentUser); sampleCertificate.EnsureCertificateNotInStore(storeName, StoreLocation.CurrentUser); } [Test] public void CanImportCertificateWithNoPrivateKeyForSpecificUser() { // This test cheats a little bit, using the current user var user = WindowsIdentity.GetCurrent().Name; var storeName = "My"; var sampleCertificate = SampleCertificate.CertWithNoPrivateKey; sampleCertificate.EnsureCertificateNotInStore(storeName, StoreLocation.CurrentUser); WindowsX509CertificateStore.ImportCertificateToStore(Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, user, storeName, sampleCertificate.HasPrivateKey); sampleCertificate.AssertCertificateIsInStore(storeName, StoreLocation.CurrentUser); sampleCertificate.EnsureCertificateNotInStore(storeName, StoreLocation.CurrentUser); } [Test] [TestCase(SampleCertificate.CngPrivateKeyId, StoreLocation.LocalMachine, "My")] [TestCase(SampleCertificate.CngPrivateKeyId, StoreLocation.LocalMachine, "Foo")] [TestCase(SampleCertificate.CapiWithPrivateKeyId, StoreLocation.LocalMachine, "My")] [TestCase(SampleCertificate.CapiWithPrivateKeyId, StoreLocation.LocalMachine, "Foo")] public void ImportExistingCertificateShouldNotOverwriteExistingPrivateKeyRights(string sampleCertificateId, StoreLocation storeLocation, string storeName) { var sampleCertificate = SampleCertificate.SampleCertificates[sampleCertificateId]; sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); WindowsX509CertificateStore.ImportCertificateToStore( Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, storeLocation, storeName, sampleCertificate.HasPrivateKey); WindowsX509CertificateStore.AddPrivateKeyAccessRules(sampleCertificate.Thumbprint, storeLocation, storeName, new List<PrivateKeyAccessRule> { new PrivateKeyAccessRule("BUILTIN\\Users", PrivateKeyAccess.FullControl) }); WindowsX509CertificateStore.ImportCertificateToStore( Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, storeLocation, storeName, sampleCertificate.HasPrivateKey); var privateKeySecurity = WindowsX509CertificateStore.GetPrivateKeySecurity(sampleCertificate.Thumbprint, storeLocation, storeName); AssertHasPrivateKeyRights(privateKeySecurity, "BUILTIN\\Users", CryptoKeyRights.GenericAll); sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); } [Test] [TestCase(SampleCertificate.CertificateChainId, "2E5DEC036985A4028351FD8DF3532E49D7B34049", "CC7ED077F0F292595A8166B01709E20C0884A5F8", StoreLocation.LocalMachine, "My")] [TestCase(SampleCertificate.CertificateChainId, "2E5DEC036985A4028351FD8DF3532E49D7B34049", "CC7ED077F0F292595A8166B01709E20C0884A5F8", StoreLocation.CurrentUser, "My")] [TestCase(SampleCertificate.CertificateChainId, "2E5DEC036985A4028351FD8DF3532E49D7B34049", "CC7ED077F0F292595A8166B01709E20C0884A5F8", StoreLocation.LocalMachine, "Foo")] [TestCase(SampleCertificate.CertificateChainId, "2E5DEC036985A4028351FD8DF3532E49D7B34049", "CC7ED077F0F292595A8166B01709E20C0884A5F8", StoreLocation.CurrentUser, "Foo")] [TestCase(SampleCertificate.ChainSignedByLegacySha1RsaId, null, "A87058F92D01C0B7D4ED21F83D12DD270E864F50", StoreLocation.LocalMachine, "My")] public void CanImportCertificateChain(string sampleCertificateId, string intermediateAuthorityThumbprint, string rootAuthorityThumbprint, StoreLocation storeLocation, string storeName) { var sampleCertificate = SampleCertificate.SampleCertificates[sampleCertificateId]; // intermediate and root authority certificates are always imported to LocalMachine var rootAuthorityStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine); rootAuthorityStore.Open(OpenFlags.ReadWrite); var intermediateAuthorityStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine); intermediateAuthorityStore.Open(OpenFlags.ReadWrite); RemoveChainCertificatesFromStore(rootAuthorityStore, intermediateAuthorityStore, "CC7ED077F0F292595A8166B01709E20C0884A5999", intermediateAuthorityThumbprint); sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); WindowsX509CertificateStore.ImportCertificateToStore(Convert.FromBase64String(sampleCertificate.Base64Bytes()), sampleCertificate.Password, storeLocation, storeName, sampleCertificate.HasPrivateKey); sampleCertificate.AssertCertificateIsInStore(storeName, storeLocation); // Assert chain certificates were imported if (!string.IsNullOrEmpty(intermediateAuthorityThumbprint)) AssertCertificateInStore(intermediateAuthorityStore, intermediateAuthorityThumbprint); AssertCertificateInStore(rootAuthorityStore, rootAuthorityThumbprint); var certificate = sampleCertificate.GetCertificateFromStore(storeName, storeLocation); Assert.True(certificate.HasPrivateKey); sampleCertificate.EnsureCertificateNotInStore(storeName, storeLocation); RemoveChainCertificatesFromStore(rootAuthorityStore, intermediateAuthorityStore, rootAuthorityThumbprint, intermediateAuthorityThumbprint); } void RemoveChainCertificatesFromStore(X509Store rootAuthorityStore, X509Store intermediateAuthorityStore, string rootAuthorityThumbprint, string intermediateAuthorityThumbprint) { WindowsX509CertificateStore.RemoveCertificateFromStore(rootAuthorityThumbprint, StoreLocation.LocalMachine, rootAuthorityStore.Name); if (!string.IsNullOrEmpty(intermediateAuthorityThumbprint)) WindowsX509CertificateStore.RemoveCertificateFromStore(intermediateAuthorityThumbprint, StoreLocation.LocalMachine, intermediateAuthorityStore.Name); } private static void AssertCertificateInStore(X509Store store, string thumbprint) { Thread.Sleep(TimeSpan.FromSeconds(2)); //Lets try this for the hell of it and see if the test gets less flakey var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); Assert.AreEqual(1, found.Count); } void AssertHasPrivateKeyRights(CryptoKeySecurity privateKeySecurity, string identifier, CryptoKeyRights right) { var accessRules = privateKeySecurity.GetAccessRules(true, false, typeof(NTAccount)); var found = accessRules.Cast<CryptoKeyAccessRule>() .Any(x => x.IdentityReference.Value == identifier && x.CryptoKeyRights.HasFlag(right)); Assert.True(found, "Private-Key right was not set"); } } } #endif<file_sep>using System.Collections.Generic; using System.IO; using Calamari.Kubernetes.ResourceStatus.Resources; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; namespace Calamari.Kubernetes.ResourceStatus { public static class KubernetesYaml { private static readonly IDeserializer Deserializer = new DeserializerBuilder().Build(); /// <summary> /// Gets resource identifiers which are defined in a YAML file. /// A YAML file can define multiple resources, separated by '---'. /// </summary> public static IEnumerable<ResourceIdentifier> GetDefinedResources(IEnumerable<string> manifests, string defaultNamespace) { foreach (var manifest in manifests) { var input = new StringReader(manifest); var parser = new Parser(input); parser.Consume<StreamStart>(); while (!parser.Accept<StreamEnd>(out _)) { var definedResource = GetDefinedResource(parser, defaultNamespace); if (!definedResource.HasValue) break; yield return definedResource.Value; } } } private static ResourceIdentifier? GetDefinedResource(IParser parser, string defaultNamespace) { try { var yamlObject = Deserializer.Deserialize<dynamic>(parser); yamlObject["metadata"].TryGetValue("namespace", out object @namespace); return new ResourceIdentifier( yamlObject["kind"], yamlObject["metadata"]["name"], @namespace == null ? defaultNamespace : (string) @namespace); } catch { return null; } } } }<file_sep>using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Testing.Helpers; using FluentAssertions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calamari.Tests.Fixtures.Logging { [TestFixture] public class LoggingFixture { [Test] public void WriteServiceMessage_CorrectlyFormatsMessages() { // Arrange var serviceMessage = ServiceMessage.Create("do-it", ("foo", "1"), ("bar", null)); // Testing functionality from abstract base class, so it doesn't matter that this is a test class. var sut = new InMemoryLog(); // Act sut.WriteServiceMessage(serviceMessage); // Assert sut.Messages.Should().ContainSingle().Which.FormattedMessage.Should().Be("##octopus[do-it foo=\"MQ==\"]"); } } } <file_sep>using System.Collections.Generic; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; namespace Calamari.Tests.Fixtures.Commands { /// <summary> /// A mock script wrapper that we can use to track if it has been executed or not /// </summary> public class ScriptHookMock : IScriptWrapper { /// <summary> /// This is how we know if this wrapper was called or not /// </summary> public static bool WasCalled { get; set; } = false; public int Priority => 1; public bool IsEnabled(ScriptSyntax scriptSyntax) => true; public IScriptWrapper NextWrapper { get; set; } public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string> environmentVars) { WasCalled = true; return NextWrapper.ExecuteScript(script, scriptSyntax, commandLineRunner, environmentVars); } } }<file_sep>using System; using Calamari.Common.Plumbing.Logging; using SharpCompress.Common; namespace Calamari.Common.Features.Packages { public class PackageExtractionOptions : ExtractionOptions { readonly ILog log; public PackageExtractionOptions(ILog log) { this.log = log; ExtractFullPath = true; Overwrite = true; PreserveFileTime = true; WriteSymbolicLink = WarnThatSymbolicLinksAreNotSupported; } void WarnThatSymbolicLinksAreNotSupported(string sourcepath, string targetpath) { log.WarnFormat("Cannot create symbolic link: {0}, Calamari does not currently support the extraction of symbolic links", sourcepath); } } }<file_sep>using System; using System.Diagnostics; using System.Threading; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { [TestFixture] public class LockFileBasedSemaphoreFixture { [Test] public void AttemptsToAcquireLockIfLockFileDoesNotExist() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.LockExists(Arg.Any<string>()).Returns(false); var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.AcquireLock)); } [Test] public void DoesNotAttemptToAcquireLockIfLockFileIsLockedByOtherProcess() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new OtherProcessHasExclusiveLockOnFileLock(); lockIo.LockExists(Arg.Any<string>()).Returns(true); var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.DontAcquireLock)); } [Test] public void DoesNotAttemptToAcquireLockIfWeCantDeserialise() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new UnableToDeserialiseLockFile(DateTime.Now); lockIo.LockExists(Arg.Any<string>()).Returns(true); var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.DontAcquireLock)); } [Test] public void AttemptsToAcquireLockIfWeCantDeserialiseButFileIsOlderThanLockTimeout() { var log = new InMemoryLog(); var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), log); var fileLock = new UnableToDeserialiseLockFile(DateTime.Now.Subtract(TimeSpan.FromMinutes(5))); lockIo.LockExists(Arg.Any<string>()).Returns(true); var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.AcquireLock)); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == "Lock file existed but was not readable, and has existed for longer than lock timeout. Taking lock."); } [Test] public void AttemptsToAcquireLockIfWeCantFindLockFile() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new MissingFileLock(); //when we check for the lock file, it exists lockIo.LockExists(Arg.Any<string>()).Returns(true); //but when we read it, its been released var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.AcquireLock)); } [Test] public void AttemptsToAcquireLockIfItBelongsToUs() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.LockExists(Arg.Any<string>()).Returns(true); var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.AcquireLock)); } [Test] public void AttemptsToAcquireLockIfOtherProcessIsNoLongerRunning() { var log = new InMemoryLog(); var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var processFinder = Substitute.For<IProcessFinder>(); processFinder.ProcessIsRunning(Arg.Any<int>(), Arg.Any<string>()).Returns(false); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder, log); var fileLock = new FileLock(-1, Guid.NewGuid().ToString(), -2, DateTime.Now.Ticks); lockIo.LockExists(Arg.Any<string>()).Returns(true); var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.AcquireLock)); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == "Process -1, thread -2 had lock, but appears to have crashed. Taking lock."); } [Test] public void DoesNotAttemptToAcquireLockIfOwnedBySomeoneElseAndLockHasNotTimedOut() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var processFinder = Substitute.For<IProcessFinder>(); processFinder.ProcessIsRunning(Arg.Any<int>(), Arg.Any<string>()).Returns(true); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder, new InMemoryLog()); var fileLock = new FileLock(0, Guid.NewGuid().ToString(), 0, DateTime.Now.Ticks); lockIo.LockExists(Arg.Any<string>()).Returns(true); var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.DontAcquireLock)); } [Test] public void AttemptsToForciblyAcquireLockIfOwnedBySomeoneElseAndLockHasTimedOut() { var log = new InMemoryLog(); var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var processFinder = Substitute.For<IProcessFinder>(); processFinder.ProcessIsRunning(Arg.Any<int>(), Arg.Any<string>()).Returns(true); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder, log); var fileLock = new FileLock(0, Guid.NewGuid().ToString(), 0, DateTime.Now.Subtract(TimeSpan.FromMinutes(5)).Ticks); lockIo.LockExists(Arg.Any<string>()).Returns(true); var result = semaphore.ShouldAcquireLock(fileLock); Assert.That(result, Is.EqualTo(LockFileBasedSemaphore.AcquireLockAction.ForciblyAcquireLock)); log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == "Forcibly taking lock from process 0, thread 0 as lock has timed out. If this happens regularly, please contact Octopus Support."); } [Test] public void DeletesLockIfOwnedBySomeoneElseAndLockHasTimedOut() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var processFinder = Substitute.For<IProcessFinder>(); processFinder.ProcessIsRunning(Arg.Any<int>(), Arg.Any<string>()).Returns(true); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder, new InMemoryLog()); //not setting processid/threadid, therefore its someone elses var fileLock = new FileLock(0, Guid.NewGuid().ToString(), 0, DateTime.Now.Subtract(TimeSpan.FromMinutes(5)).Ticks); lockIo.ReadLock(Arg.Any<string>()).Returns(fileLock); lockIo.LockExists(Arg.Any<string>()).Returns(true); lockIo.WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()).Returns(true); var result = semaphore.TryAcquireLock(); Assert.That(result, Is.True); lockIo.Received().DeleteLock(Arg.Any<string>()); lockIo.Received().WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()); } [Test] public void WritesLockFile() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var processFinder = Substitute.For<IProcessFinder>(); processFinder.ProcessIsRunning(Arg.Any<int>(), Arg.Any<string>()).Returns(true); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, processFinder, new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.ReadLock(Arg.Any<string>()).Returns(fileLock); lockIo.LockExists(Arg.Any<string>()).Returns(true); lockIo.WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()).Returns(true); var result = semaphore.TryAcquireLock(); Assert.That(result, Is.True); lockIo.DidNotReceive().DeleteLock(Arg.Any<string>()); lockIo.Received().WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()); } [Test] public void CanReleaseLockIfWeCanAcquireIt() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.ReadLock(Arg.Any<string>()).Returns(fileLock); lockIo.LockExists(Arg.Any<string>()).Returns(true); lockIo.WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()).Returns(true); semaphore.ReleaseLock(); lockIo.Received().DeleteLock(Arg.Any<string>()); } [Test] public void CannotReleaseLockIfWeCannotAcquireIt() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.ReadLock(Arg.Any<string>()).Returns(fileLock); lockIo.LockExists(Arg.Any<string>()).Returns(true); //failed to write the lock file (ie, someone else got in first) lockIo.WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()).Returns(false); semaphore.ReleaseLock(); lockIo.DidNotReceive().DeleteLock(Arg.Any<string>()); } [Test] public void WaitOneWithTimeoutTimesOut() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.ReadLock(Arg.Any<string>()).Returns(fileLock); lockIo.LockExists(Arg.Any<string>()).Returns(true); //failed to write the lock file (ie, someone else got in first) lockIo.WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()).Returns(false); var stopwatch = new Stopwatch(); stopwatch.Start(); var result = semaphore.WaitOne(300); Assert.That(result, Is.False); Assert.That(stopwatch.ElapsedMilliseconds, Is.GreaterThan(300)); } [Test] public void WaitOneWithTimeoutDoesNotWaitIfCanAcquireLock() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.ReadLock(Arg.Any<string>()).Returns(fileLock); lockIo.LockExists(Arg.Any<string>()).Returns(true); lockIo.WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()).Returns(true); var stopwatch = new Stopwatch(); stopwatch.Start(); var result = semaphore.WaitOne(300); Assert.That(result, Is.True); Assert.That(stopwatch.ElapsedMilliseconds, Is.LessThan(100)); } [Test] public void WaitOneWithTimeoutReturnsAfterAquiringLock() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.ReadLock(Arg.Any<string>()).Returns(fileLock); lockIo.LockExists(Arg.Any<string>()).Returns(true); lockIo.WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()).Returns(false, false, false, true); var stopwatch = new Stopwatch(); stopwatch.Start(); var result = semaphore.WaitOne(500); Assert.That(result, Is.True); Assert.That(stopwatch.ElapsedMilliseconds, Is.GreaterThan(200)); } [Test] public void WaitOneReturnsAfterAquiringLock() { var lockIo = Substitute.For<ILockIo>(); var name = Guid.NewGuid().ToString(); var semaphore = new LockFileBasedSemaphore(name, TimeSpan.FromSeconds(30), lockIo, Substitute.For<IProcessFinder>(), new InMemoryLog()); var fileLock = new FileLock(System.Diagnostics.Process.GetCurrentProcess().Id, Guid.NewGuid().ToString(), Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); lockIo.ReadLock(Arg.Any<string>()).Returns(fileLock); lockIo.LockExists(Arg.Any<string>()).Returns(true); lockIo.WriteLock(Arg.Any<string>(), Arg.Any<FileLock>()).Returns(false, false, true); var stopwatch = new Stopwatch(); stopwatch.Start(); var result = semaphore.WaitOne(); Assert.That(result, Is.True); Assert.That(stopwatch.ElapsedMilliseconds, Is.GreaterThan(175)); } } }<file_sep>using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Terraform.Behaviours; using NSubstitute; using NUnit.Framework; using Shouldly; namespace Calamari.Terraform.Tests { public class TerraformPlanVariableFixture { const string JsonPlanOutput = @"{""@level"":""info"",""@message"":""Terraform 1.0.4"",""@module"":""terraform.ui"",""@timestamp"":""2021-08-24T07:29:27.798620+10:00"",""terraform"":""1.0.4"",""type"":""version"",""ui"":""0.1.0""} {""@level"":""info"",""@message"":""Plan: 0 to add, 0 to change, 0 to destroy."",""@module"":""terraform.ui"",""@timestamp"":""2021-08-24T07:29:27.884954+10:00"",""changes"":{""add"":0,""change"":0,""remove"":0,""operation"":""plan""},""type"":""change_summary""}"; ILog log; ICalamariFileSystem calamariFileSystem; ICommandLineRunner commandLineRunner; RunningDeployment runningDeployment; IVariables variables; readonly IDictionary<string, string> outputVars = new Dictionary<string, string>(); [SetUp] public void SetUp() { log = Substitute.For<ILog>(); log.When(x => x.SetOutputVariable(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<IVariables>())) .Do(x => outputVars.Add(x.ArgAt<string>(0), x.ArgAt<string>(1))); calamariFileSystem = Substitute.For<ICalamariFileSystem>(); commandLineRunner = Substitute.For<ICommandLineRunner>(); variables = new CalamariVariables(); variables.Set(TerraformSpecialVariables.Action.Terraform.PlanJsonOutput, "True"); runningDeployment = Substitute.For<MockableRunningDeployment>(variables); } [TestCase("0.11", "")] [TestCase("0.11.5", "")] [TestCase("0.12", "--json")] [TestCase("1.0", "--json")] public void EnsurePlanOnlyWorksForTwelveAndAbove(string version, string expected) { new PlanBehaviour(log, calamariFileSystem, commandLineRunner).GetOutputParameter(runningDeployment, new Version(version)).ShouldBe(expected); } [Test] public void TestVariablesAreCaptured() { var splitOutput = Regex.Split(JsonPlanOutput, PlanBehaviour.LineEndingRE); new PlanBehaviour(log, calamariFileSystem, commandLineRunner).CaptureJsonOutput(runningDeployment, JsonPlanOutput); for (var index = 0; index < splitOutput.Length; ++index) { outputVars[$"TerraformPlanLine[{index}].JSON"].ShouldBe(splitOutput[index]); } outputVars[TerraformSpecialVariables.Action.Terraform.PlanJsonChangesAdd].ShouldBe("0"); outputVars[TerraformSpecialVariables.Action.Terraform.PlanJsonChangesRemove].ShouldBe("0"); outputVars[TerraformSpecialVariables.Action.Terraform.PlanJsonChangesChange].ShouldBe("0"); } public class MockableRunningDeployment : RunningDeployment { public MockableRunningDeployment(IVariables variables) : base(variables) { } } } }<file_sep>using System; namespace Calamari.Common.Features.Scripts { public class FileExtensionAttribute : Attribute { public FileExtensionAttribute(string extension) { Extension = extension; } public string Extension { get; } } }<file_sep>using System; using System.IO; using System.Linq; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Deployment.Packages; using NUnit.Framework; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.Integration.FileSystem { [TestFixture] public class PackageStoreFixture { static readonly string TentacleHome = TestEnvironment.GetTestPath("Fixtures", "FileSystem"); static readonly string PackagePath = Path.Combine(TentacleHome, "Files"); [SetUp] public void SetUp() { Environment.SetEnvironmentVariable("TentacleHome", TentacleHome); if (Directory.Exists(PackagePath)) { Directory.Delete(PackagePath, true); } Directory.CreateDirectory(PackagePath); } [TearDown] public void TearDown() { if (Directory.Exists(PackagePath)) Directory.Delete(PackagePath, true); } [Test] public void FiltersPackagesWithHigherVersion() { using (new TemporaryFile(CreatePackage("1.0.0.1"))) using (new TemporaryFile(CreatePackage("1.0.0.2"))) using (new TemporaryFile(CreatePackage("2.0.0.2"))) { var store = new PackageStore( CreatePackageExtractor(), CalamariPhysicalFileSystem.GetPhysicalFileSystem() ); var packages = store.GetNearestPackages("Acme.Web", new SemanticVersion(1, 1, 1, 1)); CollectionAssert.AreEquivalent(new[] { "1.0.0.1", "1.0.0.2" }, packages.Select(c => c.Version.ToString())); } } [Test] public void OldFormatsAreIgnored() { using (new TemporaryFile(CreatePackage("0.5.0.1"))) using (new TemporaryFile(CreatePackage("1.0.0.1", true))) { var store = new PackageStore( CreatePackageExtractor(), CalamariPhysicalFileSystem.GetPhysicalFileSystem() ); var packages = store.GetNearestPackages("Acme.Web", new SemanticVersion(1, 1, 1, 1)); CollectionAssert.AreEquivalent(new[] { "0.5.0.1" }, packages.Select(c => c.Version.ToString())); } } [Test] public void IgnoresInvalidFiles() { using (new TemporaryFile(CreatePackage("1.0.0.1"))) using (new TemporaryFile(CreateEmptyFile("1.0.0.2"))) { var store = new PackageStore( CreatePackageExtractor(), CalamariPhysicalFileSystem.GetPhysicalFileSystem() ); var packages = store.GetNearestPackages("Acme.Web", new SemanticVersion("1.1.1.1")); CollectionAssert.AreEquivalent(new[] { "1.0.0.1" }, packages.Select(c => c.Version.ToString())); } } private string CreateEmptyFile(string version) { var destinationPath = Path.Combine(PackagePath, PackageName.ToCachedFileName("Acme.Web", new SemanticVersion(version), ".nupkg")); File.WriteAllText(destinationPath, "FAKESTUFF"); return destinationPath; } private string CreatePackage(string version, bool oldCacheFormat = false) { var sourcePackage = PackageBuilder.BuildSamplePackage("Acme.Web", version, true); var destinationPath = Path.Combine(PackagePath, oldCacheFormat ? $"Acme.Web.{version}.nupkg-fd55edc5-9b36-414b-a2d0-4a2deeb6b2ec" : PackageName.ToCachedFileName("Acme.Web", new SemanticVersion(version), ".nupkg")); if (File.Exists(destinationPath)) File.Delete(destinationPath); File.Move(sourcePackage, destinationPath); return destinationPath; } ICombinedPackageExtractor CreatePackageExtractor() { var log = new InMemoryLog(); var variables = new CalamariVariables(); var commandLineRunner = new TestCommandLineRunner(log, variables); return new CombinedPackageExtractor(log, variables, commandLineRunner); } } }<file_sep>namespace Calamari.Aws.Integration.CloudFormation { public class StackArn { public StackArn(string value) { Value = value; } public string Value { get; } } }<file_sep>using System; namespace Calamari.Common.Features.Processes.Semaphores { public class OtherProcessOwnsFileLock : FileLock { public OtherProcessOwnsFileLock(FileLock fileLock) : base(fileLock.ProcessId, fileLock.ProcessName, fileLock.ThreadId, fileLock.Timestamp) { } } }<file_sep>using System; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Behaviours { public class RollbackScriptBehaviour : PackagedScriptRunner, IBehaviour { public RollbackScriptBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) : base(log, DeploymentStages.DeployFailed, fileSystem, scriptEngine, commandLineRunner) { } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { RunPreferredScript(context); if (context.Variables.GetFlag(KnownVariables.DeleteScriptsOnCleanup, true)) { DeleteScripts(context); } return this.CompletedTask(); } } }<file_sep>using Amazon.S3.Model; using Octopus.CoreUtilities; namespace Calamari.Aws.Integration.S3 { public class S3UploadResult { private PutObjectRequest Request { get; } private Maybe<PutObjectResponse> Response { get; } public S3UploadResult(PutObjectRequest request, Maybe<PutObjectResponse> response) { Request = request; Response = response; } public bool IsSuccess() { return !Response.None(); } public string BucketName => Request.BucketName; public string BucketKey => Request.Key; /// <summary> /// Return the version from the underlying PutObjectResponse or some user friendly string if the bucket /// is not versioned. /// </summary> public string Version { get { if (Response.Some()) { return string.IsNullOrEmpty(Response.Value.VersionId) ? "Not versioned" : Response.Value.VersionId; } return null; } } } }<file_sep>using Calamari.Common.Commands; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Conventions { public class AlreadyInstalledConvention : IInstallConvention { readonly ILog log; readonly IDeploymentJournal journal; public AlreadyInstalledConvention(ILog log, IDeploymentJournal journal) { this.log = log; this.journal = journal; } public void Install(RunningDeployment deployment) { if (!deployment.Variables.GetFlag(KnownVariables.Package.SkipIfAlreadyInstalled)) { return; } var id = deployment.Variables.Get(PackageVariables.PackageId); var version = deployment.Variables.Get(PackageVariables.PackageVersion); var policySet = deployment.Variables.Get(KnownVariables.RetentionPolicySet); var previous = journal.GetLatestInstallation(policySet, id, version); if (previous == null) return; if (!previous.WasSuccessful) { log.Info("The previous attempt to deploy this package was not successful; re-deploying."); } else { log.Info("The package has already been installed on this machine, so installation will be skipped."); log.SetOutputVariableButDoNotAddToVariables(PackageVariables.Output.InstallationDirectoryPath, previous.ExtractedTo); log.SetOutputVariableButDoNotAddToVariables(PackageVariables.Output.DeprecatedInstallationDirectoryPath, previous.ExtractedTo); deployment.Variables.Set(KnownVariables.Action.SkipRemainingConventions, "true"); deployment.SkipJournal = true; } } } } <file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.ConfigurationVariables; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class ConfigurationVariablesConventionFixture { RunningDeployment deployment; ICalamariFileSystem fileSystem; IConfigurationVariablesReplacer replacer; [SetUp] public void SetUp() { fileSystem = Substitute.For<ICalamariFileSystem>(); fileSystem.EnumerateFilesRecursively(Arg.Any<string>(), Arg.Any<string[]>()).Returns(new[] { "C:\\App\\MyApp\\Web.config", "C:\\App\\MyApp\\Web.Release.config", "C:\\App\\MyApp\\Views\\Web.config" }); deployment = new RunningDeployment("C:\\Packages", new CalamariVariables()); replacer = Substitute.For<IConfigurationVariablesReplacer>(); } [Test] public void ShouldNotRunIfFeatureNotEnabled() { var convention = new ConfigurationVariablesConvention(new ConfigurationVariablesBehaviour(fileSystem, deployment.Variables, replacer, new InMemoryLog())); convention.Install(deployment); replacer.DidNotReceiveWithAnyArgs().ModifyConfigurationFile(null, null); } [Test] public void ShouldNotRunIfConfiguredToNotReplace() { deployment.Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationVariables); deployment.Variables.Set(KnownVariables.Package.AutomaticallyUpdateAppSettingsAndConnectionStrings, "false"); var convention = new ConfigurationVariablesConvention(new ConfigurationVariablesBehaviour(fileSystem, deployment.Variables,replacer, new InMemoryLog())); convention.Install(deployment); replacer.DidNotReceiveWithAnyArgs().ModifyConfigurationFile(null, null); } [Test] public void ShouldFindAndCallDeployScripts() { deployment.Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationVariables); deployment.Variables.Set(KnownVariables.Package.AutomaticallyUpdateAppSettingsAndConnectionStrings, "true"); var convention = new ConfigurationVariablesConvention(new ConfigurationVariablesBehaviour(fileSystem, deployment.Variables,replacer, new InMemoryLog())); convention.Install(deployment); replacer.Received().ModifyConfigurationFile("C:\\App\\MyApp\\Web.config", deployment.Variables); replacer.Received().ModifyConfigurationFile("C:\\App\\MyApp\\Web.Release.config", deployment.Variables); replacer.Received().ModifyConfigurationFile("C:\\App\\MyApp\\Views\\Web.config", deployment.Variables); } } } <file_sep>using System.Collections.Generic; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Integration.Proxies; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.PowerShell { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class PowerShellCoreProxyFixture : WindowsScriptProxyFixtureBase { [SetUp] public void Setup() { Assert.Ignore("Some proxy tests currently fail with PSCore, currently ignoring them until this has been addressed."); } protected override CalamariResult RunScript() { var variables = new Dictionary<string,string>() { {PowerShellVariables.Edition, "Core"} }; return RunScript("Proxy.ps1", variables).result; } protected override bool TestWebRequestDefaultProxy => true; } } <file_sep>using Calamari.Common.Features.Processes; namespace Calamari.Integration.Processes { public class OctoDiffLibraryCallRunner { public CommandLine OctoDiff { get; } public OctoDiffLibraryCallRunner() { OctoDiff = new CommandLine(Octodiff.Program.Main); } public CommandResult Execute() { var runner = new LibraryCallRunner(); var result = runner.Execute(OctoDiff.BuildLibraryCall()); return result; } } }<file_sep>using Calamari.Common.Commands; namespace Calamari.Deployment.Conventions { public interface IInstallConvention : IConvention { void Install(RunningDeployment deployment); } }<file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using FluentAssertions; using NUnit.Framework; using ScriptSyntax = Calamari.Common.Features.Scripts.ScriptSyntax; namespace Calamari.Scripting.Tests { [TestFixture] public class RunScriptCommandFixture { [Test] public Task ExecuteInlineScript() { var psScript = "echo \"Hello $Name #{Name2}\""; return CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); context.Variables.Add(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); context.Variables.Add(ScriptVariables.ScriptBody, psScript); context.Variables.Add("Name", "World"); context.Variables.Add("Name2", "Two"); }) .WithAssert(result => result.FullLog.Should().Contain("Hello World Two")) .Execute(); } [Test] public Task ExecuteWithPackage() { using var tempFolder = TemporaryDirectory.Create(); var scriptFileName = "myscript.ps1"; var psScript = "echo \"Hello $Name #{Name2}\""; File.WriteAllText(Path.Combine(tempFolder.DirectoryPath, scriptFileName), psScript); return CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Package); context.Variables.Add(ScriptVariables.ScriptFileName, scriptFileName); context.Variables.Add("Name", "World"); context.Variables.Add("Name2", "Two"); context.WithFilesToCopy(tempFolder.DirectoryPath); }) .WithAssert(result => result.FullLog.Should().Contain("Hello World Two")) .Execute(); } [Test] public Task ExecuteWithPackageAndParameters() { using var tempFolder = TemporaryDirectory.Create(); var scriptFileName = "myscript.ps1"; var psScript = @" param ($value) echo ""Hello $value"";"; File.WriteAllText(Path.Combine(tempFolder.DirectoryPath, scriptFileName), psScript); return CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Package); context.Variables.Add(ScriptVariables.ScriptFileName, scriptFileName); context.Variables.Add(ScriptVariables.ScriptParameters, "-value abc"); context.WithFilesToCopy(tempFolder.DirectoryPath); }) .WithAssert(result => result.FullLog.Should().Contain("Hello abc")) .Execute(); } [Test] public Task ExecuteWithPackageAndParametersDeployPs1() { using var tempFolder = TemporaryDirectory.Create(); var scriptFileName = "deploy.ps1"; var psScript = @" param ($value) echo ""Hello $value"";"; File.WriteAllText(Path.Combine(tempFolder.DirectoryPath, scriptFileName), psScript); return CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Package); context.Variables.Add(ScriptVariables.ScriptFileName, scriptFileName); context.Variables.Add(ScriptVariables.ScriptParameters, "-value abc"); context.WithFilesToCopy(tempFolder.DirectoryPath); }) .WithAssert(result => result.FullLog.Should().Contain("Hello abc")) .Execute(); } [Test] public Task EnsureWhenScriptReturnsNonZeroCodeDeploymentFails() { using var tempFolder = TemporaryDirectory.Create(); var psScript = "throw 'Error'"; File.WriteAllText(Path.Combine(tempFolder.DirectoryPath, "myscript.ps1"), psScript); return CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); context.Variables.Add(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); context.Variables.Add(ScriptVariables.ScriptBody, psScript); }) .WithAssert(result => result.WasSuccessful.Should().BeFalse()) .Execute(false); } [Test] public Task EnsureWhenInlineScriptFeatureReturnsNonZeroCodeDeploymentFails() { using var tempFolder = TemporaryDirectory.Create(); var psScript = "throw 'Error'"; File.WriteAllText(Path.Combine(tempFolder.DirectoryPath, "myscript.ps1"), psScript); return CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Package); context.Variables.Add("Octopus.Action.Script.ScriptFileName", "myscript.ps1"); context.WithFilesToCopy(tempFolder.DirectoryPath); }) .WithAssert(result => result.WasSuccessful.Should().BeFalse()) .Execute(false); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Deployment.Journal { public class DeploymentJournal : IDeploymentJournal { const string SemaphoreName = "Octopus.Calamari.DeploymentJournal"; readonly ICalamariFileSystem fileSystem; readonly ISemaphoreFactory semaphore; readonly IVariables variables; public DeploymentJournal(ICalamariFileSystem fileSystem, ISemaphoreFactory semaphore, IVariables variables) { this.fileSystem = fileSystem; this.semaphore = semaphore; this.variables = variables; } string? JournalPath => variables.Get(TentacleVariables.Agent.JournalPath); internal void AddJournalEntry(JournalEntry entry) { using (semaphore.Acquire(SemaphoreName, "Another process is using the deployment journal")) { var xElement = entry.ToXmlElement(); Log.VerboseFormat("Adding journal entry:\n{0}", xElement.ToString()); Write(Read().Concat(new[] { xElement })); } } public List<JournalEntry> GetAllJournalEntries() { using (semaphore.Acquire(SemaphoreName, "Another process is using the deployment journal")) { return Read().Select(element => new JournalEntry(element)).ToList(); } } public void RemoveJournalEntries(IEnumerable<string> ids) { using (semaphore.Acquire(SemaphoreName, "Another process is using the deployment journal")) { var elements = Read(); Write(elements.Where(x => { var id = x.Attribute("Id"); return id == null || !ids.Contains(id.Value); })); } } public JournalEntry GetLatestInstallation(string retentionPolicySubset) { return GetLatestInstallation(retentionPolicySubset, null, null); } public JournalEntry GetLatestInstallation(string retentionPolicySubset, string? packageId, string? packageVersion) { return GetAllJournalEntries() .Where(e => string.Equals(retentionPolicySubset, e.RetentionPolicySet, StringComparison.OrdinalIgnoreCase) && (packageId == null && packageVersion == null || e.Packages.Any(deployedPackage => (packageId == null || string.Equals(packageId, deployedPackage.PackageId, StringComparison.OrdinalIgnoreCase)) && (packageVersion == null || string.Equals(packageVersion, deployedPackage.PackageVersion, StringComparison.OrdinalIgnoreCase))))) .OrderByDescending(o => o.InstalledOn) .FirstOrDefault(); } public JournalEntry GetLatestSuccessfulInstallation(string retentionPolicySubset) { return GetLatestSuccessfulInstallation(retentionPolicySubset, null, null); } public JournalEntry GetLatestSuccessfulInstallation(string retentionPolicySubset, string? packageId, string? packageVersion) { return GetAllJournalEntries() .Where(e => string.Equals(retentionPolicySubset, e.RetentionPolicySet, StringComparison.OrdinalIgnoreCase) && (packageId == null && packageVersion == null || e.Packages.Any(deployedPackage => (packageId == null || string.Equals(packageId, deployedPackage.PackageId, StringComparison.OrdinalIgnoreCase)) && (packageVersion == null || string.Equals(packageVersion, deployedPackage.PackageVersion, StringComparison.OrdinalIgnoreCase)))) && e.WasSuccessful) .OrderByDescending(o => o.InstalledOn) .FirstOrDefault(); } IEnumerable<XElement> Read() { if (!fileSystem.FileExists(JournalPath)) yield break; using (var file = fileSystem.OpenFile(JournalPath, FileAccess.Read)) { var document = XDocument.Load(file); foreach (var element in document.Element("Deployments").Elements()) yield return element; } } void Write(IEnumerable<XElement> elements) { if (string.IsNullOrWhiteSpace(JournalPath)) throw new InvalidOperationException("JournalPath has not been set"); fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(JournalPath)); var tempPath = JournalPath + ".temp-" + Guid.NewGuid() + ".xml"; var root = new XElement("Deployments"); var document = new XDocument(root); foreach (var element in elements) root.Add(element); using (var stream = fileSystem.OpenFile(tempPath, FileMode.Create, FileAccess.Write)) { document.Save(stream); } fileSystem.OverwriteAndDelete(JournalPath, tempPath); } } }<file_sep>print("Parameters {} {}".format(sys.argv[1], sys.argv[2]))<file_sep>using System; using System.Linq; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment.PackageRetention.Caching; using Calamari.Deployment.PackageRetention.Repositories; namespace Calamari.Deployment.PackageRetention.Model { public class PackageJournal : IManagePackageCache { readonly IJournalRepository journalRepository; readonly IRetentionAlgorithm retentionAlgorithm; readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly ISemaphoreFactory semaphoreFactory; public PackageJournal(IJournalRepository journalRepository, ILog log, ICalamariFileSystem fileSystem, IRetentionAlgorithm retentionAlgorithm, ISemaphoreFactory semaphoreFactory) { this.journalRepository = journalRepository; this.log = log; this.fileSystem = fileSystem; this.retentionAlgorithm = retentionAlgorithm; this.semaphoreFactory = semaphoreFactory; } public void RegisterPackageUse(PackageIdentity package, ServerTaskId deploymentTaskId, ulong packageSizeBytes) { try { using (AcquireSemaphore()) { journalRepository.Load(); journalRepository.Cache.IncrementCacheAge(); var age = journalRepository.Cache.CacheAge; if (journalRepository.TryGetJournalEntry(package, out var entry)) { entry.AddUsage(deploymentTaskId, age); entry.AddLock(deploymentTaskId, age); } else { entry = new JournalEntry(package, packageSizeBytes); entry.AddUsage(deploymentTaskId, age); entry.AddLock(deploymentTaskId, age); journalRepository.AddJournalEntry(entry); } log.Verbose($"Registered package use/lock for {package} and task {deploymentTaskId}"); journalRepository.Commit(); } } catch (Exception ex) { //We need to ensure that an issue with the journal doesn't interfere with the deployment. log.Info($"Unable to register package use for retention.{Environment.NewLine}{ex.ToString()}"); } } public void RemoveAllLocks(ServerTaskId serverTaskId) { using (AcquireSemaphore()) { log.Verbose($"Releasing package locks for task {serverTaskId}"); journalRepository.Load(); journalRepository.RemoveAllLocks(serverTaskId); journalRepository.Commit(); } } public void ApplyRetention() { try { using (AcquireSemaphore()) { journalRepository.Load(); var packagesToRemove = retentionAlgorithm.GetPackagesToRemove(journalRepository.GetAllJournalEntries()); foreach (var package in packagesToRemove) { if (string.IsNullOrWhiteSpace(package.Path.Value) || !fileSystem.FileExists(package.Path.Value)) { log.Verbose($"Package at {package.Path} not found."); } else { Log.Verbose($"Removing package file '{package.Path}'"); fileSystem.DeleteFile(package.Path.Value, FailureOptions.IgnoreFailure); } journalRepository.RemovePackageEntry(package); } journalRepository.Commit(); } } catch (Exception ex) { Log.Info(ex.Message); } } public void ExpireStaleLocks(TimeSpan timeBeforeExpiration) { try { using (AcquireSemaphore()) { journalRepository.Load(); foreach (var entry in journalRepository.GetAllJournalEntries()) { var locks = entry.GetLockDetails(); var staleLocks = locks .Where(u => u.DateTime.Add(timeBeforeExpiration) <= DateTime.Now) .ToList(); foreach (var staleLock in staleLocks) { entry.RemoveLock(staleLock.DeploymentTaskId); } } journalRepository.Commit(); } } catch (Exception ex) { log.Info($"Unable to expire stale package locks.{Environment.NewLine}{ex.ToString()}"); } } IDisposable AcquireSemaphore() { return semaphoreFactory.Acquire(nameof(PackageJournal), "Another process is using the package journal"); } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Pipeline { public interface IOnFinishBehaviour: IBehaviour { } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; using Octopus.CoreUtilities; using Octopus.Versioning.Semver; namespace Calamari.Kubernetes.Integration { public class Kubectl : CommandLineTool, IKubectl { readonly string customKubectlExecutable; private bool isSet; public Kubectl(IVariables variables, ILog log, ICommandLineRunner commandLineRunner) : this(variables, log, commandLineRunner, Environment.CurrentDirectory, new Dictionary<string, string>()) { } public Kubectl(IVariables variables, ILog log, ICommandLineRunner commandLineRunner, string workingDirectory, Dictionary<string, string> environmentVariables) : base(log, commandLineRunner, workingDirectory, environmentVariables) { customKubectlExecutable = variables.Get("Octopus.Action.Kubernetes.CustomKubectlExecutable"); } public void SetWorkingDirectory(string directory) { workingDirectory = directory; } public void SetEnvironmentVariables(Dictionary<string, string> variables) { environmentVars = variables; } public bool TrySetKubectl() { if (isSet) return true; if (string.IsNullOrEmpty(customKubectlExecutable)) { var result = CalamariEnvironment.IsRunningOnWindows ? base.ExecuteCommandAndReturnOutput("where", "kubectl.exe") : base.ExecuteCommandAndReturnOutput("which", "kubectl"); var foundExecutable = result.Output.InfoLogs.FirstOrDefault(); if (string.IsNullOrEmpty(foundExecutable)) { log.Error("Could not find kubectl. Make sure kubectl is on the PATH. See https://g.octopushq.com/KubernetesTarget for more information."); return false; } ExecutableLocation = foundExecutable?.Trim(); } else { if (!File.Exists(customKubectlExecutable)) { log.Error($"The custom kubectl location of {customKubectlExecutable} does not exist. See https://g.octopushq.com/KubernetesTarget for more information."); return false; } ExecutableLocation = customKubectlExecutable; } if (TryExecuteKubectlCommand("version", "--client", "--output=yaml")) { log.Verbose($"Found kubectl and successfully verified it can be executed."); isSet = true; return true; } log.Error($"Found kubectl at {ExecutableLocation}, but unable to successfully execute it. See https://g.octopushq.com/KubernetesTarget for more information."); return false; } bool TryExecuteKubectlCommand(params string[] arguments) { return ExecuteCommandAndLogOutput(new CommandLineInvocation(ExecutableLocation, arguments.Concat(new[] { "--request-timeout=1m" }).ToArray())).ExitCode == 0; } public CommandResult ExecuteCommand(params string[] arguments) { var kubectlArguments = arguments.Concat(new[] { "--request-timeout=1m" }).ToArray(); var commandInvocation = new CommandLineInvocation(ExecutableLocation, kubectlArguments); return ExecuteCommandAndLogOutput(commandInvocation); } public void ExecuteCommandAndAssertSuccess(params string[] arguments) { var result = ExecuteCommand(arguments); result.VerifySuccess(); } public CommandResultWithOutput ExecuteCommandAndReturnOutput(params string[] arguments) => base.ExecuteCommandAndReturnOutput(ExecutableLocation, arguments); public Maybe<SemanticVersion> GetVersion() { var kubectlVersionOutput = ExecuteCommandAndReturnOutput("version", "--client", "--output=json").Output.InfoLogs; var kubeCtlVersionJson = string.Join(" ", kubectlVersionOutput); try { var clientVersion = JsonConvert.DeserializeAnonymousType(kubeCtlVersionJson, new { clientVersion = new { gitVersion = "1.0.0" } }); var kubectlVersionString = clientVersion?.clientVersion?.gitVersion?.TrimStart('v'); if (kubectlVersionString != null) { return Maybe<SemanticVersion>.Some(new SemanticVersion(kubectlVersionString)); } } catch (Exception e) { log.Verbose($"Unable to determine kubectl version. Failed with error message: {e.Message}"); } return Maybe<SemanticVersion>.None; } } public interface IKubectl { bool TrySetKubectl(); CommandResultWithOutput ExecuteCommandAndReturnOutput(params string[] arguments); } } <file_sep>using System; Octopus.UpdateProgress(50, "Half Way"); <file_sep>#!/bin/bash set -euo pipefail set_octopusvariable "Password" "<PASSWORD>"<file_sep>using System; using System.Runtime.InteropServices; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using OSPlatform = System.Runtime.InteropServices.OSPlatform; namespace Calamari.Testing.Requirements { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class WindowsTestAttribute : NUnitAttribute, IApplyToTest { readonly string message; public WindowsTestAttribute() : this("This test only runs on Windows") { } public WindowsTestAttribute(string message) { this.message = message; } static bool IsRunningOnWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public void ApplyToTest(Test test) { if (test.RunState == RunState.NotRunnable || test.RunState == RunState.Ignored) return; if (!IsRunningOnWindows) { test.RunState = RunState.Skipped; test.Properties.Add(PropertyNames.SkipReason, message); } } } }<file_sep>#if !NET40 using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes; using Calamari.Kubernetes.Integration; namespace Calamari.Commands { [Command("authenticate-to-kubernetes")] public class KubernetesAuthenticationCommand: Command<KubernetesAuthenticationCommandInput> { private readonly ILog log; private readonly IVariables variables; private readonly ICalamariFileSystem fileSystem; private readonly ICommandLineRunner commandLineRunner; private readonly Kubectl kubectl; public KubernetesAuthenticationCommand( ILog log, IVariables variables, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner, Kubectl kubectl) { this.log = log; this.variables = variables; this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; this.kubectl = kubectl; } protected override void Execute(KubernetesAuthenticationCommandInput inputs) { log.Info("Setting up KubeConfig authentication."); var environmentVars = new Dictionary<string, string>(); var runningDeployment = new RunningDeployment(variables); kubectl.SetEnvironmentVariables(environmentVars); kubectl.SetWorkingDirectory(runningDeployment.CurrentDirectory); var setupKubectlAuthentication = new SetupKubectlAuthentication(variables, log, commandLineRunner, kubectl, environmentVars, runningDeployment.CurrentDirectory); var accountType = variables.Get("Octopus.Account.AccountType"); try { var result = setupKubectlAuthentication.Execute(accountType); result.VerifySuccess(); } catch (CommandLineException ex) { log.Error("KubeConfig authentication failed."); throw new CommandException(ex.Message); } variables.Set(SpecialVariables.KubeConfig, fileSystem.GetFullPath(environmentVars["KUBECONFIG"])); } } public class KubernetesAuthenticationCommandInput { } } #endif<file_sep>using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Integration; namespace Calamari.Kubernetes.Authentication { public class AzureKubernetesServicesAuth { readonly AzureCli azureCli; readonly Kubectl kubectlCli; readonly KubeLogin kubeLogin; readonly IVariables deploymentVariables; /// <summary> /// This class is responsible for configuring the kubectl auth against an AKS cluster for an Octopus Deployment /// </summary> /// <param name="azureCli"></param> /// <param name="kubectlCli"></param> /// <param name="KubeLogin"></param> /// <param name="deploymentVariables"></param> public AzureKubernetesServicesAuth(AzureCli azureCli, Kubectl kubectlCli, KubeLogin kubeloginCli, IVariables deploymentVariables) { this.azureCli = azureCli; this.kubectlCli = kubectlCli; this.deploymentVariables = deploymentVariables; this.kubeLogin = kubeloginCli; } public bool TryConfigure(string @namespace, string kubeConfig) { if (!azureCli.TrySetAz()) return false; if (FeatureToggle.KubernetesAksKubeloginFeatureToggle.IsEnabled(deploymentVariables)) { kubeLogin.TrySetKubeLogin(); } var disableAzureCli = deploymentVariables.GetFlag("OctopusDisableAzureCLI"); if (!disableAzureCli) { var azEnvironment = deploymentVariables.Get("Octopus.Action.Azure.Environment") ?? "AzureCloud"; var subscriptionId = deploymentVariables.Get("Octopus.Action.Azure.SubscriptionId"); var tenantId = deploymentVariables.Get("Octopus.Action.Azure.TenantId"); var clientId = deploymentVariables.Get("Octopus.Action.Azure.ClientId"); var password = deploymentVariables.Get("Octopus.Action.Azure.Password"); azureCli.ConfigureAzAccount(subscriptionId, tenantId, clientId, password, azEnvironment); var azureResourceGroup = deploymentVariables.Get("Octopus.Action.Kubernetes.AksClusterResourceGroup"); var azureCluster = deploymentVariables.Get(SpecialVariables.AksClusterName); var azureAdmin = deploymentVariables.GetFlag("Octopus.Action.Kubernetes.AksAdminLogin"); azureCli.ConfigureAksKubeCtlAuthentication(kubectlCli, azureResourceGroup, azureCluster, @namespace, kubeConfig, azureAdmin); if (FeatureToggle.KubernetesAksKubeloginFeatureToggle.IsEnabled(deploymentVariables) && kubeLogin.IsConfigured) { kubeLogin.ConfigureAksKubeLogin(kubeConfig); } } return true; } } } <file_sep>namespace Calamari.Common.Features.StructuredVariables { public static class StructuredConfigVariablesFileFormats { public static readonly string Json = "Json"; public static readonly string Yaml = "Yaml"; public static readonly string Xml = "Xml"; public static readonly string Properties = "Properties"; } }<file_sep>using System; namespace Calamari.Testing.LogParser { public class ServiceMessageNameAttribute : Attribute { } }<file_sep>using Calamari.Common.Plumbing.FileSystem; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.FileSystem { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class WindowsPhysicalFileSystemFixture { [Test] [TestCase("C:\\foo.bar", "C:\\foo.bar", ExpectedResult = "foo.bar")] [TestCase("C:\\foo.bar", "C:\\dir\\foo.bar", ExpectedResult = "dir\\foo.bar")] [TestCase("C:\\folder\\foo.bar", "C:\\foo.bar", ExpectedResult = "..\\foo.bar")] [TestCase("C:\\folder\\foo.bar", "C:\\dir\\foo.bar", ExpectedResult = "..\\dir\\foo.bar")] public string ShouldGetRelativePath(string fromPath, string toPath) { var target = new WindowsPhysicalFileSystem(); return target.GetRelativePath(fromPath, toPath); } } }<file_sep>using System.Collections.Generic; using System.IO; using System.Reflection; namespace Calamari.Common.Features.EmbeddedResources { public class AssemblyEmbeddedResources : ICalamariEmbeddedResources { public IEnumerable<string> GetEmbeddedResourceNames(Assembly assembly) { return assembly.GetManifestResourceNames(); } public string GetEmbeddedResourceText(Assembly assembly, string name) { using (var stream = assembly.GetManifestResourceStream(name)) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } }<file_sep>using System; using System.IO; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.Runtime; using Amazon; using Amazon.S3; using Calamari.Aws.Commands; using Calamari.Aws.Deployment; using Calamari.Aws.Integration.CloudFormation; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Tests.Helpers; using FluentAssertions; using Calamari.Testing; using Calamari.Testing.Helpers; namespace Calamari.Tests.AWS.CloudFormation { public class CloudFormationFixtureHelpers { string region; public CloudFormationFixtureHelpers(string fixedRegion = null) { region = fixedRegion ?? RegionRandomiser.GetARegion(); } public static string GetBasicS3Template(string stackName) { return $@" {{ ""Resources"": {{ ""{stackName}"": {{ ""Type"": ""AWS::S3::Bucket"", ""Properties"": {{ ""BucketName"": {stackName}, ""Tags"" : [ {{ ""Key"" : ""VantaOwner"", ""Value"" : ""<EMAIL>"" }}, {{ ""Key"" : ""VantaNonProd"", ""Value"" : ""true"" }}, {{ ""Key"" : ""VantaNoAlert"", ""Value"" : ""Ephemeral bucket created during unit tests and not used in production"" }}, {{ ""Key"" : ""VantaContainsUserData"", ""Value"" : ""false"" }}, {{ ""Key"" : ""VantaUserDataStored"", ""Value"" : ""N/A"" }}, {{ ""Key"" : ""VantaDescription"", ""Value"" : ""Ephemeral bucket created during unit tests"" }} ] }} }} }} }}"; } public string WriteTemplateFile(string template) { var templateFilePath = Path.GetTempFileName(); File.WriteAllText(templateFilePath, template); return templateFilePath; } public async Task ValidateS3BucketExists(string stackName) { await ValidateS3(async client => { await client.GetBucketLocationAsync(stackName); }); } async Task ValidateS3(Func<AmazonS3Client, Task> execute) { var credentials = new BasicAWSCredentials(ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey), ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); var config = new AmazonS3Config { AllowAutoRedirect = true, RegionEndpoint = RegionEndpoint.GetBySystemName(region) }; using (var client = new AmazonS3Client(credentials, config)) { await execute(client); } } public async Task ValidateStackExists(string stackName, bool shouldExist) { await ValidateCloudFormation(async (client) => { Func<IAmazonCloudFormation> clientFactory = () => client; var stackStatus = await clientFactory.StackExistsAsync(new StackArn(stackName), Aws.Deployment.Conventions.StackStatus.DoesNotExist); stackStatus.Should().Be(shouldExist ? Aws.Deployment.Conventions.StackStatus.Completed : Aws.Deployment.Conventions.StackStatus.DoesNotExist); }); } async Task ValidateCloudFormation(Func<AmazonCloudFormationClient, Task> execute) { var credentials = new BasicAWSCredentials(ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey), ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); var config = new AmazonCloudFormationConfig { AllowAutoRedirect = true, RegionEndpoint = RegionEndpoint.GetBySystemName(region) }; using (var client = new AmazonCloudFormationClient(credentials, config)) { await execute(client); } } public void DeployTemplate(string resourceName, string templateFilePath, IVariables variables) { var variablesFile = Path.GetTempFileName(); variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount"); variables.Set("AWSAccount.AccessKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey)); variables.Set("AWSAccount.SecretKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); variables.Set("Octopus.Action.Aws.Region", region); variables.Save(variablesFile); using (var templateFile = new TemporaryFile(templateFilePath)) using (new TemporaryFile(variablesFile)) { var log = new InMemoryLog(); var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); var command = new DeployCloudFormationCommand( log, variables, fileSystem, new ExtractPackage(new CombinedPackageExtractor(log, variables, new CommandLineRunner(log, variables)), fileSystem, variables, log), new StructuredConfigVariablesService(new PrioritisedList<IFileFormatVariableReplacer> { new JsonFormatVariableReplacer(fileSystem, log), new XmlFormatVariableReplacer(fileSystem, log), new YamlFormatVariableReplacer(fileSystem, log), new PropertiesFormatVariableReplacer(fileSystem, log), }, variables, fileSystem, log) ); var result = command.Execute(new[] { "--template", $"{templateFile.FilePath}", "--variables", $"{variablesFile}", "--stackName", resourceName, "--waitForCompletion", "true" }); result.Should().Be(0); } } public void DeployTemplateS3(string resourceName, IVariables variables) { var variablesFile = Path.GetTempFileName(); variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount"); variables.Set("AWSAccount.AccessKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey)); variables.Set("AWSAccount.SecretKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); variables.Set("Octopus.Action.Aws.Region", "us-east-1"); variables.Save(variablesFile); using (new TemporaryFile(variablesFile)) { var log = new InMemoryLog(); var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); var command = new DeployCloudFormationCommand(log, variables, fileSystem, new ExtractPackage(new CombinedPackageExtractor(log, variables, new CommandLineRunner(log, variables)), fileSystem, variables, log), new StructuredConfigVariablesService(new PrioritisedList<IFileFormatVariableReplacer> { new JsonFormatVariableReplacer(fileSystem, log), new XmlFormatVariableReplacer(fileSystem, log), new YamlFormatVariableReplacer(fileSystem, log), new PropertiesFormatVariableReplacer(fileSystem, log), }, variables, fileSystem, log)); var result = command.Execute(new[] { "--templateS3", "https://calamari-cloudformation-tests.s3.amazonaws.com/s3/empty.yaml", "--templateS3Parameters", "https://calamari-cloudformation-tests.s3.amazonaws.com/s3/properties.json", "--variables", $"{variablesFile}", "--stackName", resourceName, "--waitForCompletion", "true" }); result.Should().Be(0); } } public void CleanupStack(string stackName) { try { DeleteStack(stackName); } catch (Exception e) { Log.Error($"Error occurred while attempting to delete stack {stackName} -> {e}." + $"{Environment.NewLine} Test resources may not have been deleted, please check the AWS console for the status of the stack."); } } public void DeleteStack(string stackName) { var variablesFile = Path.GetTempFileName(); var variables = new CalamariVariables(); variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount"); variables.Set("AWSAccount.AccessKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey)); variables.Set("AWSAccount.SecretKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); variables.Set("Octopus.Action.Aws.Region", region); variables.Set(AwsSpecialVariables.CloudFormation.StackName, stackName); variables.Save(variablesFile); using (new TemporaryFile(variablesFile)) { var log = new InMemoryLog(); var command = new DeleteCloudFormationCommand( log, variables ); var result = command.Execute(new[] { "--variables", $"{variablesFile}", "--waitForCompletion", "true" }); result.Should().Be(0); } } } }<file_sep>using System; using System.Linq; using Calamari.Common.Features.Scripts; namespace Calamari.Common.Plumbing.Variables { public static class ScriptVariables { public static readonly string Syntax = "Octopus.Action.Script.Syntax"; public static readonly string ScriptBody = "Octopus.Action.Script.ScriptBody"; public static readonly string ScriptFileName = "Octopus.Action.Script.ScriptFileName"; public static readonly string ScriptParameters = "Octopus.Action.Script.ScriptParameters"; public static readonly string ScriptSource = "Octopus.Action.Script.ScriptSource"; public static class ScriptSourceOptions { public const string Package = "Package"; public const string Inline = "Inline"; public const string Core = "Core"; } public static string GetLibraryScriptModuleName(string variableName) { return variableName.Replace("Octopus.Script.Module[", "").TrimEnd(']'); } public static bool IsLibraryScriptModule(string variableName) { return variableName.StartsWith("Octopus.Script.Module["); } public static bool IsExcludedFromLocalVariables(string name) { return name.Contains("["); } public static ScriptSyntax GetLibraryScriptModuleLanguage(IVariables variables, string variableName) { var expectedName = variableName.Replace("Octopus.Script.Module[", "Octopus.Script.Module.Language["); var syntaxVariable = variables.GetNames().FirstOrDefault(x => x == expectedName); if (syntaxVariable == null) return ScriptSyntax.PowerShell; return (ScriptSyntax)Enum.Parse(typeof(ScriptSyntax), variables[syntaxVariable]); } } }<file_sep>namespace Calamari.Testing.Requirements { public class RequiresMonoAttribute : RequiresMinimumMonoVersionAttribute { public RequiresMonoAttribute() : base(1, 0, 0) { } } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Reflection; using Amazon.Runtime; namespace Calamari.Aws.Util { public static class ConstantHelpers { public static IEnumerable<T> GetConstantValues<T>() where T : ConstantClass { var type = typeof(T); return type.GetFields(BindingFlags.Public | BindingFlags.GetField | BindingFlags.Static) .Where(x => type.IsAssignableFrom(x.FieldType)).Select(x => (T)x.GetValue(null)); } } } <file_sep>using System; namespace Calamari.AzureResourceGroup { interface IResourceGroupTemplateNormalizer { string Normalize(string json); } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text.RegularExpressions; using Assent; using FluentAssertions; using NSubstitute; using NuGet.Packaging; using NUnit.Framework; using Serilog; using TestStack.BDDfy; namespace Calamari.ConsolidateCalamariPackages.Tests { [TestFixture] public class IntegrationTests { readonly Assent.Configuration assentConfiguration = new Assent.Configuration().UsingSanitiser(s => Sanitise4PartVersions(SanitiseHashes(s))); static readonly string TestPackagesDirectory = "../../../testPackages"; private string temp; private string expectedZip; private List<BuildPackageReference> packageReferences; private bool returnValue; public void SetUp() { temp = Path.GetTempFileName(); File.Delete(temp); Directory.CreateDirectory(temp); packageReferences = new List<BuildPackageReference>(); expectedZip = Path.Combine(temp, $"Calamari.3327050d788658cd16da010e75580d32.zip"); } public void TearDown() { Directory.Delete(temp, true); Directory.Delete(TestPackagesDirectory, true); } public void GivenABunchOfPackageReferences() { var artifacts = Directory.GetFiles(TestPackagesDirectory, "*.nupkg"); foreach (var artifact in artifacts) { using (var zip = ZipFile.OpenRead(artifact)) { var nuspecFileStream = zip.Entries.First(e => e.Name.EndsWith(".nuspec")).Open(); var nuspecReader = new NuspecReader(nuspecFileStream); var metadata = nuspecReader.GetMetadata(); packageReferences.Add(new BuildPackageReference { Name = metadata.Where(kvp => kvp.Key == "id").Select(i => i.Value).First(), Version = metadata.Where(kvp => kvp.Key == "version").Select(i => i.Value).First(), PackagePath = artifact }); } } } public void WhenTheTaskIsExecuted() { var sw = Stopwatch.StartNew(); var task = new Consolidate(Substitute.For<ILogger>()) { AssemblyVersion = "1.2.3" }; (returnValue, _) = task.Execute(temp, packageReferences); Console.WriteLine($"Time: {sw.ElapsedMilliseconds:n0}ms"); } public void ThenTheReturnValueIsTrue() => returnValue.Should().BeTrue(); public void AndThenThePackageIsCreated() { Directory.GetFiles(temp).Should().BeEquivalentTo(new[] {expectedZip}); Console.WriteLine($"Package Size: {new FileInfo(expectedZip).Length / 1024 / 1024}MB"); } public void AndThenThePackageContentsShouldBe() { using (var zip = ZipFile.Open(expectedZip, ZipArchiveMode.Read)) this.Assent(string.Join("\r\n", zip.Entries.Select(e => SanitiseHashes(e.FullName)).OrderBy(k => k)), assentConfiguration); } public void AndThenTheIndexShouldBe() { using (var zip = ZipFile.Open(expectedZip, ZipArchiveMode.Read)) using (var entry = zip.Entries.First(e => e.FullName == "index.json").Open()) using (var sr = new StreamReader(entry)) this.Assent(sr.ReadToEnd(), assentConfiguration); } private static string SanitiseHashes(string s) => Regex.Replace(s, "[a-z0-9]{32}", "<hash>"); private static string Sanitise4PartVersions(string s) => Regex.Replace(s, @"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+", "<version>"); [Test] public void Execute() => this.BDDfy(); } }<file_sep>using System.Collections.Generic; using Calamari.Deployment.PackageRetention.Model; namespace Calamari.Deployment.PackageRetention.Caching { public interface ISortJournalEntries { IEnumerable<JournalEntry> Sort(IEnumerable<JournalEntry> journalEntries); } }<file_sep>using System.Collections.Generic; using System.Reflection; namespace Calamari.Common.Features.EmbeddedResources { public interface ICalamariEmbeddedResources { IEnumerable<string> GetEmbeddedResourceNames(Assembly assembly); string GetEmbeddedResourceText(Assembly assembly, string name); } }<file_sep>using System; using System.Runtime.Serialization; namespace Calamari.Testing.Helpers { /// <summary> /// Use this for short-circuiting eventually-consistent assertions. This exception means that this test will *never* succeed, and /// that there is no point waiting around, hoping for it to do so. /// </summary> /// <remarks> /// Yes, we know this is an example of using an exception for control flow. We're choosing it to optimize for the common /// calling convention (i.e. we don't have an early-exit condition). We can revisit if we end up having more frequent /// usages than we expect. /// </remarks> [Serializable] public class EventualAssertionPermanentlyFailedException : Exception { public EventualAssertionPermanentlyFailedException() { } public EventualAssertionPermanentlyFailedException(string message) : base(message) { } public EventualAssertionPermanentlyFailedException(string message, Exception inner) : base(message, inner) { } protected EventualAssertionPermanentlyFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Deployment.Retention; using Calamari.Integration.Time; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Retention { [TestFixture] public class RetentionPolicyFixture { RetentionPolicy retentionPolicy; ICalamariFileSystem fileSystem; IDeploymentJournal deploymentJournal; IClock clock; DateTimeOffset now; const string policySet1 = "policySet1"; JournalEntry sevenDayOldSuccessfulDeployment; JournalEntry sevenDayOldUnsuccessfulDeployment; JournalEntry sixDayOldSuccessfulDeployment; JournalEntry fiveDayOldUnsuccessfulDeployment; JournalEntry fourDayOldSuccessfulDeployment; JournalEntry threeDayOldSuccessfulDeployment; JournalEntry twoDayOldSuccessfulDeployment; JournalEntry oneDayOldUnsuccessfulDeployment; JournalEntry fourDayOldSameLocationDeployment; JournalEntry fourDayOldMultiPackageDeployment; JournalEntry twoDayOldMultiPackageDeployment; JournalEntry twoDayOldDeploymentWithPackageThatWasNotAcquired; JournalEntry fiveDayOldDeploymentWithPackageThatWasNotAcquired; const string policySet2 = "policySet2"; const string policySet3 = "policySet3"; const string policySet4 = "policySet4"; JournalEntry fiveDayOldNonMatchingDeployment; [SetUp] public void SetUp() { fileSystem = Substitute.For<ICalamariFileSystem>(); deploymentJournal = Substitute.For<IDeploymentJournal>(); clock = Substitute.For<IClock>(); retentionPolicy = new RetentionPolicy(fileSystem, deploymentJournal, clock); now = new DateTimeOffset(new DateTime(2015, 01, 15), new TimeSpan(0, 0, 0)); clock.GetUtcTime().Returns(now); // Deployed 7 days prior to 'now' sevenDayOldSuccessfulDeployment = new JournalEntry("sevenDayOldSuccessful", "blah", "blah", "blah", policySet1, now.AddDays(-7).LocalDateTime, "C:\\Applications\\Acme.0.0.7", null, true, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.0.0.7.nupkg")); sevenDayOldUnsuccessfulDeployment = new JournalEntry("sevenDayOldUnsuccessful", "blah", "blah", "blah", policySet1, now.AddDays(-7).LocalDateTime, "C:\\Applications\\Acme.0.0.7", null, false, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.0.0.7.nupkg")); // Deployed 6 days prior to 'now' sixDayOldSuccessfulDeployment = new JournalEntry("sixDayOldSuccessful", "blah", "blah", "blah", policySet1, now.AddDays(-6).LocalDateTime, "C:\\Applications\\Acme.0.0.8", null, true, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.0.0.8.nupkg")); // Deployed 5 days prior to 'now' fiveDayOldUnsuccessfulDeployment = new JournalEntry("fiveDayOldUnsuccessful", "blah", "blah", "blah", policySet1, now.AddDays(-5).LocalDateTime, "C:\\Applications\\Acme.0.0.9", null, false, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.0.0.9.nupkg")); // Deployed 4 days prior to 'now' fourDayOldSuccessfulDeployment = new JournalEntry("fourDayOldSuccessful", "blah", "blah", "blah", policySet1, now.AddDays(-4).LocalDateTime, "C:\\Applications\\Acme.1.0.0", null, true, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.1.0.0.nupkg")); // Deployed 4 days prior to 'now' but to the same location as the latest successful deployment fourDayOldSameLocationDeployment = new JournalEntry("fourDayOldSameLocation", "blah", "blah", "blah", policySet1, now.AddDays(-4).LocalDateTime, "C:\\Applications\\Acme.1.2.0", null, true, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.1.2.0.nupkg")); // Deployed 3 days prior to 'now' threeDayOldSuccessfulDeployment = new JournalEntry("threeDayOldSuccessful", "blah", "blah", "blah", policySet1, now.AddDays(-3).LocalDateTime, "C:\\Applications\\Acme.1.1.0", null, true, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.1.1.0.nupkg")); // Deployed 2 days prior to 'now' twoDayOldSuccessfulDeployment = new JournalEntry("twoDayOldSuccessful", "blah", "blah", "blah", policySet1, now.AddDays(-2).LocalDateTime, "C:\\Applications\\Acme.1.2.0", null, true, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.1.2.0.nupkg")); // Deployed (unsuccessfully) 1 day prior to 'now' oneDayOldUnsuccessfulDeployment = new JournalEntry("oneDayOldUnsuccessful", "blah", "blah", "blah", policySet1, now.AddDays(-1).LocalDateTime, "C:\\Applications\\Acme.1.3.0", null, false, new DeployedPackage("blah", "blah", "C:\\packages\\Acme.1.3.0.nupkg")); // Deployed 5 days prior to 'now', but has a different policy-set fiveDayOldNonMatchingDeployment = new JournalEntry("fiveDayOld", "blah", "blah", "blah", policySet2, now.AddDays(-5).LocalDateTime, "C:\\Applications\\Beta.1.0.0", null, true, new DeployedPackage("blah", "blah", "C:\\packages\\Beta.1.0.0.nupkg")); // Step with multiple packages, deployed 4 days prior, and referencing the same source file as the latest successful // deployment from a different step fourDayOldMultiPackageDeployment = new JournalEntry("fourDayOldMultiPackage", "blah", "blah", "blah", policySet3, now.AddDays(-4).LocalDateTime, null, null, true, new[] { new DeployedPackage("blah", "blah", "C:\\packages\\Acme.1.2.0.nupkg"), new DeployedPackage("foo", "blah", "C:\\packages\\Foo.0.0.9.nupkg") }); // Step with multiple packages, deployed 2 days prior twoDayOldMultiPackageDeployment = new JournalEntry("twoDayOldMultiPackage", "blah", "blah", "blah", policySet3, now.AddDays(-2).LocalDateTime, null, null, true, new[] { new DeployedPackage("blah", "blah", "C:\\packages\\Acme.1.2.0.nupkg"), new DeployedPackage("foo", "blah", "C:\\packages\\Foo.1.0.0.nupkg") }); // We may reference packages which are not acquired (e.g. docker containers from script steps). // These will not have a `DeployedFrom` path. twoDayOldDeploymentWithPackageThatWasNotAcquired = new JournalEntry("twoDayOldNotAcquired", "blah", "blah", "blah", policySet4, now.AddDays(-2).LocalDateTime, null, null, true, new[] { new DeployedPackage("blah", "blah", null) }); fiveDayOldDeploymentWithPackageThatWasNotAcquired = new JournalEntry("fiveDayOldNotAcquired", "blah", "blah", "blah", policySet4, now.AddDays(-5).LocalDateTime, null, null, true, new[] { new DeployedPackage("blah", "blah", null) }); var journalEntries = new List<JournalEntry> { sevenDayOldUnsuccessfulDeployment, sevenDayOldSuccessfulDeployment, sixDayOldSuccessfulDeployment, fiveDayOldUnsuccessfulDeployment, fiveDayOldNonMatchingDeployment, fourDayOldSuccessfulDeployment, threeDayOldSuccessfulDeployment, twoDayOldSuccessfulDeployment, oneDayOldUnsuccessfulDeployment, fourDayOldMultiPackageDeployment, twoDayOldMultiPackageDeployment, fiveDayOldDeploymentWithPackageThatWasNotAcquired }; deploymentJournal.GetAllJournalEntries().Returns(journalEntries); foreach (var journalEntry in journalEntries) { if (!string.IsNullOrEmpty(journalEntry.ExtractedTo)) fileSystem.DirectoryExists(journalEntry.ExtractedTo).Returns(true); foreach (var deployedPackage in journalEntry.Packages) fileSystem.FileExists(deployedPackage.DeployedFrom).Returns(true); } Environment.SetEnvironmentVariable("TentacleHome", @"Q:\TentacleHome"); } [Test] public void ShouldNotDeleteDirectoryWhereRetainedDeployedToSame() { var journalEntries = new List<JournalEntry> { fourDayOldSuccessfulDeployment, fourDayOldSameLocationDeployment, twoDayOldSuccessfulDeployment, }; deploymentJournal.GetAllJournalEntries().Returns(journalEntries); fileSystem.FileExists(fourDayOldSameLocationDeployment.Package.DeployedFrom).Returns(true); fileSystem.DirectoryExists(fourDayOldSameLocationDeployment.ExtractedTo).Returns(true); const int days = 3; retentionPolicy.ApplyRetentionPolicy(policySet1, days, null); // Ensure the directories are the same Assert.AreEqual(twoDayOldSuccessfulDeployment.ExtractedTo, fourDayOldSameLocationDeployment.ExtractedTo); // The old directory was not removed... fileSystem.DidNotReceive().DeleteDirectory(Arg.Is<string>(s => s.Equals(fourDayOldSameLocationDeployment.ExtractedTo))); // ...despite being removed from the journal deploymentJournal.Received().RemoveJournalEntries(Arg.Is<IEnumerable<string>>(ids => ids.Contains(fourDayOldSameLocationDeployment.Id))); // and unique directory still removed fileSystem.Received().DeleteDirectory(Arg.Is<string>(s => s.Equals(fourDayOldSuccessfulDeployment.ExtractedTo))); } [Test] public void ShouldKeepDeploymentsForSpecifiedDays() { deploymentJournal.GetAllJournalEntries().Returns(new List<JournalEntry> { fourDayOldSuccessfulDeployment, threeDayOldSuccessfulDeployment, twoDayOldSuccessfulDeployment, oneDayOldUnsuccessfulDeployment, fourDayOldMultiPackageDeployment, twoDayOldMultiPackageDeployment, fiveDayOldDeploymentWithPackageThatWasNotAcquired }); retentionPolicy.ApplyRetentionPolicy(policySet1, 3, null); // The older artifacts should have been removed fileSystem.Received().DeleteDirectory(fourDayOldSuccessfulDeployment.ExtractedTo); // The newer artifacts, and those from the non-matching policy-set, should have been kept // In other words, nothing but the matching deployment should have been removed fileSystem.DidNotReceive().DeleteDirectory(Arg.Is<string>(s => !s.Equals(fourDayOldSuccessfulDeployment.ExtractedTo))); // The older entry should have been removed from the journal deploymentJournal.Received().RemoveJournalEntries(Arg.Is<IEnumerable<string>>(ids => ids.Count() == 1 && ids.Contains(fourDayOldSuccessfulDeployment.Id))); } [Test] public void ShouldKeepSpecifiedNumberOfDeployments() { var deploymentsExpectedToKeep = new List<JournalEntry> { twoDayOldSuccessfulDeployment, sixDayOldSuccessfulDeployment, fiveDayOldNonMatchingDeployment // Non-matching }; var deploymentsExpectedToRemove = new List<JournalEntry> { fiveDayOldUnsuccessfulDeployment, sevenDayOldUnsuccessfulDeployment, sevenDayOldSuccessfulDeployment }; deploymentJournal.GetAllJournalEntries().Returns(deploymentsExpectedToKeep.Concat(deploymentsExpectedToRemove).ToList()); // Keep 1 (+ the current) deployment // This will not count the unsuccessful deployment retentionPolicy.ApplyRetentionPolicy(policySet1, null, 1); foreach (var deployment in deploymentsExpectedToRemove) { fileSystem.Received().DeleteDirectory(deployment.ExtractedTo); } // The newer artifacts, and those from the non-matching policy-set, should have been kept // In other words, nothing but the matching deployment should have been removed foreach (var deployment in deploymentsExpectedToKeep) { fileSystem.DidNotReceive().DeleteDirectory(deployment.ExtractedTo); } // The older entry should have been removed from the journal deploymentJournal.Received().RemoveJournalEntries(Arg.Is<IEnumerable<string>>(ids => ids.All(id => deploymentsExpectedToRemove.Any(d => d.Id == id)))); } [Test] public void ShouldNotDeleteDirectoryWhenItIsPreserved() { var journalEntries = new List<JournalEntry> { twoDayOldSuccessfulDeployment, sevenDayOldUnsuccessfulDeployment, sevenDayOldSuccessfulDeployment }; deploymentJournal.GetAllJournalEntries().Returns(journalEntries); // Keep 1 (+ the current) deployment // This will not count the unsuccessful deployment retentionPolicy.ApplyRetentionPolicy(policySet1, null, 1); fileSystem.DidNotReceive().DeleteDirectory(sevenDayOldUnsuccessfulDeployment.ExtractedTo); deploymentJournal.Received().RemoveJournalEntries(Arg.Is<IEnumerable<string>>(ids => ids.Contains(sevenDayOldUnsuccessfulDeployment.Id))); } [Test] public void ShouldNotDeleteAnythingWhenSpecifiedNumberOfSuccessfulDeploymentsNotMet() { var journalEntries = new List<JournalEntry> { twoDayOldSuccessfulDeployment, oneDayOldUnsuccessfulDeployment, }; deploymentJournal.GetAllJournalEntries().Returns(journalEntries); // Keep 1 (+ the current) deployment // This will not count the unsuccessful deployment retentionPolicy.ApplyRetentionPolicy(policySet1, null, 1); fileSystem.DidNotReceive().DeleteDirectory(Arg.Any<string>()); fileSystem.DidNotReceive().DeleteFile(Arg.Any<string>(), Arg.Any<FailureOptions>()); deploymentJournal.Received().RemoveJournalEntries(Arg.Is<IEnumerable<string>>(ids => !ids.Any())); } [Test] public void ShouldNotExplodeIfPackageWasNotAcquired() { const int days = 3; retentionPolicy.ApplyRetentionPolicy(policySet4, days, null); // The entry should have been removed from the journal deploymentJournal.Received().RemoveJournalEntries(Arg.Is<IEnumerable<string>>(ids => ids.Count() == 1 && ids.Contains(fiveDayOldDeploymentWithPackageThatWasNotAcquired.Id))); } } }<file_sep>using System; namespace Calamari.ConsolidateCalamariPackages { class SourceFile { public string PackageId { get; set; } public string Version { get; set; } public string Platform { get; set; } public string ArchivePath { get; set; } public bool IsNupkg { get; set; } public string FullNameInDestinationArchive { get; set; } public string FullNameInSourceArchive { get; set; } public string Hash { get; set; } } }<file_sep>using Assent; using Assent.Namers; using Calamari.Testing.Helpers; namespace Calamari.Tests.Helpers { public static class AssentConfiguration { public static readonly Configuration Default = new Configuration() .UsingNamer(TestEnvironment.IsCI ? (INamer)new CIAssentNamer() : new SubdirectoryNamer("Approved")) .SetInteractive(!TestEnvironment.IsCI); public static Configuration DefaultWithPostfix(string postfix) => new Configuration() .UsingNamer(TestEnvironment.IsCI ? (INamer)new CIAssentNamer(postfix) : new SubdirectoryNamer("Approved", postfix)) .SetInteractive(!TestEnvironment.IsCI); public static readonly Configuration Json = new Configuration() .UsingNamer(TestEnvironment.IsCI ? (INamer)new CIAssentNamer() : new SubdirectoryNamer("Approved")) .SetInteractive(!TestEnvironment.IsCI) .UsingExtension("json"); public static readonly Configuration Yaml = new Configuration() .UsingNamer(TestEnvironment.IsCI ? (INamer)new CIAssentNamer() : new SubdirectoryNamer("Approved")) .SetInteractive(!TestEnvironment.IsCI) .UsingExtension("yaml"); public static readonly Configuration Xml = new Configuration() .UsingNamer(TestEnvironment.IsCI ? (INamer)new CIAssentNamer() : new SubdirectoryNamer("Approved")) .SetInteractive(!TestEnvironment.IsCI) .UsingExtension("xml"); public static readonly Configuration Properties = new Configuration() .UsingNamer(TestEnvironment.IsCI ? (INamer)new CIAssentNamer() : new SubdirectoryNamer("Approved")) .SetInteractive(!TestEnvironment.IsCI) .UsingExtension("properties"); } }<file_sep>using System; using Calamari.Common.Plumbing.Extensions; using NUnit.Framework; using NUnit.Framework.Interfaces; namespace Calamari.Testing.Requirements { public class RequiresMinimumMonoVersionAttribute : TestAttribute, ITestAction { private readonly int major; private readonly int minor; private readonly int build; public RequiresMinimumMonoVersionAttribute(int major, int minor, int build) { this.major = major; this.minor = minor; this.build = build; } public void BeforeTest(ITest testDetails) { if (ScriptingEnvironment.IsRunningOnMono() && (ScriptingEnvironment.GetMonoVersion() < new Version(major, minor, build))) { Assert.Ignore($"Requires Mono {major}.{minor}.{build} or above"); } } public void AfterTest(ITest testDetails) { } public ActionTargets Targets { get; set; } } }<file_sep>using System; using System.IO; using SharpCompress.Archives; namespace Calamari.Common.Features.Packages.Decorators.ArchiveLimits { /// <summary> /// This decorator prevents extraction of an archive if it would exceed the theoretical limits of current compression algorithms. /// </summary> public class EnforceCompressionRatioDecorator : PackageExtractorDecorator { readonly int maximumCompressionRatio; public EnforceCompressionRatioDecorator(IPackageExtractor concreteExtractor, int maximumCompressionRatio) : base(concreteExtractor) { this.maximumCompressionRatio = maximumCompressionRatio; } public override int Extract(string packageFile, string directory) { if (!TryVerifyCompressionRatio(packageFile, out var archiveLimitException)) throw archiveLimitException!; return base.Extract(packageFile, directory); } bool TryVerifyCompressionRatio(string packageFile, out ArchiveLimitException? exception) { try { if (maximumCompressionRatio >= 1) { var archiveInfo = new FileInfo(packageFile); using (var archive = ArchiveFactory.Open(packageFile)) { var compressedSize = archiveInfo.Length; var uncompressedSize = archive.TotalUncompressSize; var compressionRatio = compressedSize == 0 ? 0 : (double)uncompressedSize / compressedSize; if (compressionRatio > maximumCompressionRatio) { exception = ArchiveLimitException.FromCompressionRatioBreach(compressedSize, uncompressedSize); return false; } } } } catch { // Never fail based on failing to calculate the limits. } exception = null; return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Calamari.Common.Plumbing.Extensions; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using Calamari.Util; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Util { [TestFixture] public class CrossPlatformFixture { [OneTimeSetUp] public void SetEnvironmentVariable() { Environment.SetEnvironmentVariable("MARIO_BROTHER", "LUIGI"); } [OneTimeTearDown] public void ClearEnvironmentVariable() { Environment.SetEnvironmentVariable("MARIO_BROTHER", null); } [Test] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void TildePrefixReplacedWithHome() { // This usage of Environment.GetEnvironmentVariable is fine as it's not accessing a test dependency variable var home = Environment.GetEnvironmentVariable("HOME"); Assert.IsNotNull(home, "Expected $HOME environment variable to be set."); var value = CrossPlatform.ExpandPathEnvironmentVariables("~/blah"); Assert.AreEqual($"{home}/blah", value); } [Test] [TestCase("$MARIO_BROTHER/blah", "LUIGI/blah")] [TestCase("%MARIO_BROTHER%/blah", "LUIGI/blah", Description = "Windows style variables included in Nix")] [TestCase("$MARIO_BROTHERZZ/blah", "/blah", Description = "Variables terminate at last non alpha numeric character")] [TestCase("IMA$MARIO_BROTHER", "IMALUIGI", Description = "Variables begin from dollar character")] [TestCase("\\$MARIO_BROTHER/blah", "\\$MARIO_BROTHER/blah", Description = "Escaped dollar preserved")] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void NixEnvironmentVariableReplaced(string inputValue, string expectedResult) { var value = CrossPlatform.ExpandPathEnvironmentVariables(inputValue); Assert.AreEqual(expectedResult, value); } [Test] [TestCase("$MARIO_BROTHER/blah", "$MARIO_BROTHER/blah", Description = "Nix variable format ignored")] [TestCase("IMA%MARIO_BROTHER%PLUMBER", "IMALUIGIPLUMBER", Description = "Variables demarcated by percent character")] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void WindowsEnvironmentVariableReplaced(string inputValue, string expectedResult) { var value = CrossPlatform.ExpandPathEnvironmentVariables(inputValue); Assert.AreEqual(expectedResult, value); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calamari.Common.Features.Packages { /// <summary> /// Encode illegal filename characters. /// Originally a blanket Uti.EscapeDataString was used but IIS seemed to have problems when the version contained metadata and the "+" turned into a "%2B" in the installed directory location. /// To get around this we will only encode characters that we know are invalid and would have failed anyway. /// </summary> public static class FileNameEscaper { static readonly HashSet<char> InvalidCharacterSet = new HashSet<char> { '%', '<', '>', ':', '"', '/', '\\', '|', '?' }; public static char[] EscapedCharacters => InvalidCharacterSet.ToArray(); /// <summary> /// Encodes invalid Windows filename characters < > : " / \ | ? * /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx /// </summary> /// <returns></returns> public static string Escape(string input) { var sb = new StringBuilder(); foreach (var c in input) if (!InvalidCharacterSet.Contains(c)) sb.Append(c); else sb.Append(Uri.EscapeDataString(c.ToString())); return sb.ToString(); } public static string Unescape(string input) { return Uri.UnescapeDataString(input); } } }<file_sep>using System; using System.IO; using System.Security.Cryptography; namespace Calamari.Common.Plumbing.FileSystem { public class TemporaryFile : IDisposable { readonly ICalamariFileSystem fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); public TemporaryFile(string filePath) { this.FilePath = filePath; } public string DirectoryPath => "file://" + Path.GetDirectoryName(FilePath); public string FilePath { get; } public string Hash { get { using (var file = File.OpenRead(FilePath)) { var hash = SHA1.Create().ComputeHash(file); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } } public long Size { get { using (var file = File.OpenRead(FilePath)) { return file.Length; } } } public void Dispose() { fileSystem.DeleteFile(FilePath, FailureOptions.IgnoreFailure); } } }<file_sep>namespace Calamari.Integration.Nginx { public class WindowsNginxServer : NginxServer { public override string GetConfigRootDirectory() { throw new System.NotImplementedException(); } public override string GetSslRootDirectory() { throw new System.NotImplementedException(); } } } <file_sep>using System; using System.Text.RegularExpressions; namespace Calamari.Common.Plumbing.Extensions { public static class CrossPlatform { public static string ExpandPathEnvironmentVariables(string path) { if (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) { if (path.StartsWith("~")) path = "$HOME" + path.Substring(1, path.Length - 1); path = Regex.Replace(path, @"(?<!\\)\$([a-zA-Z0-9_]+)", "%$1%"); path = Environment.ExpandEnvironmentVariables(path); return Regex.Replace(path, @"(?<!\\)%([a-zA-Z0-9_]+)%", ""); } return Environment.ExpandEnvironmentVariables(path); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Autofac; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.Logging; namespace Calamari.Kubernetes.Commands.Discovery { public class KubernetesDiscovererFactory: IKubernetesDiscovererFactory { readonly IDictionary<string, IKubernetesDiscoverer> discoverers; public KubernetesDiscovererFactory(IEnumerable<IKubernetesDiscoverer> discoverers) { this.discoverers = discoverers.ToDictionary(x => x.Type, x => x); } public bool TryGetKubernetesDiscoverer(string type, out IKubernetesDiscoverer discoverer) { return discoverers.TryGetValue(type, out discoverer); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureResourceGroup { [Command("deploy-azure-resource-group", Description = "Creates a new Azure Resource Group deployment")] public class DeployAzureResourceGroupCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<DeployAzureResourceGroupBehaviour>(); } } }<file_sep>using System; namespace Calamari.Common.Features.FunctionScriptContributions { public class FunctionParameter { public FunctionParameter(ParameterType type, string? dependsOn = null) { Type = type; DependsOn = dependsOn; } public ParameterType Type { get; } public string? DependsOn { get; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.FileSystem; using Newtonsoft.Json.Linq; namespace Calamari.Integration.Nginx { public abstract class NginxServer { private readonly ICalamariFileSystem fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); private readonly List<KeyValuePair<string, string>> serverBindingDirectives = new List<KeyValuePair<string, string>>(); private readonly string TempConfigRootDirectory = "conf"; private readonly string TempSslRootDirectory = "ssl"; public bool UseHostName { get; private set; } public string HostName { get; private set; } public IDictionary<string, string> AdditionalLocations { get; } = new Dictionary<string, string>(); public IDictionary<string, string> SslCerts { get; } = new Dictionary<string, string>(); public string VirtualServerName { get; private set; } public dynamic RootLocation { get; private set; } string virtualServerConfig; public static NginxServer AutoDetect() { if (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) return new NixNginxServer(); return new WindowsNginxServer(); } public NginxServer WithVirtualServerName(string name) { /* * Ensure package ids with chars that are invalid for file names (for example, a GitHub package is in the format * "owner/repository") do not generate unexpected file names. */ VirtualServerName = String.Join("_", name.Split( System.IO.Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries)); return this; } public NginxServer WithServerBindings(IEnumerable<Binding> bindings, IDictionary<string, (string SubjectCommonName, string CertificatePem, string PrivateKeyPem)> certificates, string customSslCertRoot = null) { foreach (var binding in bindings) { if (string.Equals("http", binding.Protocol, StringComparison.OrdinalIgnoreCase)) { AddServerBindingDirective(NginxDirectives.Server.Listen, GetListenValue(binding.IpAddress, binding.Port)); } else { string certificatePath = null; string certificateKeyPath = null; if (string.IsNullOrEmpty(binding.CertificateLocation)) { if (!certificates.TryGetValue(binding.CertificateVariable, out var certificate)) { Log.Warn($"Couldn't find certificate {binding.CertificateVariable}"); continue; } var sanitizedSubjectCommonName = fileSystem.RemoveInvalidFileNameChars(certificate.SubjectCommonName); var certificateFileName = $"{sanitizedSubjectCommonName}.crt"; var certificateKeyFileName = $"{sanitizedSubjectCommonName}.key"; var certificateTempRootPath = Path.Combine(TempSslRootDirectory, sanitizedSubjectCommonName); SslCerts.Add( Path.Combine(certificateTempRootPath, certificateFileName), certificate.CertificatePem); SslCerts.Add( Path.Combine(certificateTempRootPath, certificateKeyFileName), certificate.PrivateKeyPem); var sslRootPath = customSslCertRoot ?? GetSslRootDirectory(); var certificateRootPath = Path.Combine(sslRootPath, sanitizedSubjectCommonName); certificatePath = Path.Combine(certificateRootPath, certificateFileName); certificateKeyPath = Path.Combine(certificateRootPath, certificateKeyFileName); } AddServerBindingDirective(NginxDirectives.Server.Listen, GetListenValue(binding.IpAddress, binding.Port, true)); AddServerBindingDirective(NginxDirectives.Server.Certificate, certificatePath ?? binding.CertificateLocation); AddServerBindingDirective(NginxDirectives.Server.CertificateKey, certificateKeyPath ?? binding.CertificateKeyLocation); var securityProtocols = binding.SecurityProtocols; if (securityProtocols != null && securityProtocols.Any()) { AddServerBindingDirective( NginxDirectives.Server.SecurityProtocols, string.Join(" ", binding.SecurityProtocols)); } // if (!string.IsNullOrWhiteSpace((string) binding.ciphers)) // { // AddServerBindingDirective(NginxDirectives.Server.SslCiphers, string.Join(":", binding.ciphers)); // } } } return this; } public NginxServer WithHostName(string serverHostName) { if (string.IsNullOrWhiteSpace(serverHostName) || serverHostName.Equals("*")) return this; UseHostName = true; HostName = serverHostName; return this; } public NginxServer WithAdditionalLocations(IEnumerable<Location> locations) { if (!locations.Any()) return this; var locationIndex = 0; foreach (var location in locations) { var locationConfig = GetLocationConfig(location); var sanitizedLocationName = SanitizeLocationName(location.Path, locationIndex); var locationConfFile = Path.Combine(TempConfigRootDirectory, $"{VirtualServerName}.conf.d", $"location.{sanitizedLocationName}.conf"); AdditionalLocations.Add(locationConfFile, locationConfig); locationIndex++; } return this; } private string SanitizeLocationName(string locationPath, int index) { /* * The names of the files holding locations are significant as Nginx will process regular expression * locations in the order they are defined or imported. This is from the documentation at * http://nginx.org/en/docs/http/request_processing.html: * * nginx first searches for the most specific prefix location given by literal strings regardless of the * listed order. In the configuration above the only prefix location is “/” and since it matches any request * it will be used as a last resort. * * [THIS IS THE IMPORTANT BIT] * Then nginx checks locations given by regular expression in the order listed in the configuration file. * The first matching expression stops the search and nginx will use this location. * * If no regular expression matches a request, then nginx uses the most specific prefix location * found earlier. * * To accomodate this ordering, we prefix all location paths with the index of the location as it appeared * in the UI. This ensures location file names are unique and processed in the order they were defined. */ var match = Regex.Match(locationPath, "[a-zA-Z0-9/]+"); if (match.Success) { // Remove slashes, as these are not valid for a file name return index + match.Value.Replace("/", "_").Trim('_'); } // Fall back to the index as a file name return index.ToString(); } public NginxServer WithRootLocation(Location location) { RootLocation = location; return this; } public void BuildConfiguration(string customNginxConfigRoot = null) { var nginxConfigRootDirectory = customNginxConfigRoot ?? GetConfigRootDirectory(); virtualServerConfig = $@" server {{ {string.Join(Environment.NewLine, serverBindingDirectives.Select(binding => $" {binding.Key} {binding.Value};"))} {(UseHostName ? $" {NginxDirectives.Server.HostName} {HostName};" : "")} {(AdditionalLocations.Any() ? $" {NginxDirectives.Include} {nginxConfigRootDirectory}/{VirtualServerName}.conf.d/location.*.conf;" : "")} {GetLocationConfig(RootLocation)} }} "; } public void SaveConfiguration(string tempDirectory) { foreach (var sslCert in SslCerts) { var sslCertPath = Path.Combine(tempDirectory, sslCert.Key); fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(sslCertPath)); fileSystem.OverwriteFile(sslCertPath, sslCert.Value); } foreach (var additionalLocation in AdditionalLocations) { var locationConfPath = Path.Combine(tempDirectory, additionalLocation.Key); fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(locationConfPath)); fileSystem.OverwriteFile(locationConfPath, RemoveEmptyLines(additionalLocation.Value)); } var virtualServerConfPath = Path.Combine(tempDirectory, TempConfigRootDirectory, $"{VirtualServerName}.conf"); fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(virtualServerConfPath)); fileSystem.OverwriteFile(virtualServerConfPath, RemoveEmptyLines(virtualServerConfig)); } string RemoveEmptyLines(string text) { return Regex.Replace(text, @"^\s*$\n|\r$", string.Empty, RegexOptions.Multiline).TrimEnd(); } public abstract string GetConfigRootDirectory(); public abstract string GetSslRootDirectory(); private string GetListenValue(string ipAddress, string port, bool isHttps = false) { var sslParameter = isHttps ? " ssl" : ""; var ipAddressParameter = !string.IsNullOrWhiteSpace(ipAddress) && !ipAddress.Equals("*") ? $"{ipAddress}:" : ""; return $"{ipAddressParameter}{port}{sslParameter}"; } private string GetLocationConfig(Location location) { return $@" location {location.Path} {{ {(!string.IsNullOrEmpty(location.ReverseProxyUrl) ? $" {NginxDirectives.Location.Proxy.Url} {location.ReverseProxyUrl};" : "")} {GetLocationDirectives(location.Directives, location.ReverseProxyDirectives)} {GetLocationHeaders(location.Headers, location.ReverseProxyHeaders)} }} "; } private static string GetLocationDirectives(string directivesString, string reverseProxyDirectivesString) { if (string.IsNullOrEmpty(directivesString) && string.IsNullOrEmpty(reverseProxyDirectivesString)) return string.Empty; var directives = ParseJsonArray(directivesString); var reverseProxyDirectives = ParseJson(reverseProxyDirectivesString); var allDirectives = CombineItems(directives.ToList(), reverseProxyDirectives.ToList()); return !allDirectives.Any() ? string.Empty : string.Join(Environment.NewLine, allDirectives.Select(d => $" {d.Name} {d.Value};")); } private static string GetLocationHeaders(string headersString, string reverseProxyHeadersString) { if (string.IsNullOrEmpty(headersString) && string.IsNullOrEmpty(reverseProxyHeadersString)) return string.Empty; var headers = ParseJson(headersString); var reverseProxyHeaders = ParseJson(reverseProxyHeadersString); var allHeaders = CombineItems(headers.ToList(), reverseProxyHeaders.ToList()); return !allHeaders.Any() ? string.Empty : string.Join(Environment.NewLine, allHeaders.Select(h => $" {NginxDirectives.Location.Proxy.SetHeader} {h.Name} {h.Value};")); } private void AddServerBindingDirective(string key, string value) { serverBindingDirectives.Add(new KeyValuePair<string, string>(key, value)); } static List<dynamic> CombineItems(List<dynamic> items1, List<dynamic> items2) { if (!items1.Any()) return items2; foreach (var item in items2) { if (items1.All(i => !string.Equals(i.Name, item.Name, StringComparison.OrdinalIgnoreCase))) { items1.Add(item); } } return items1; } static IEnumerable<dynamic> ParseJsonArray(string json) { try { var result = new List<dynamic>(); var array = JArray.Parse(json); foreach (var o in array.Children<JObject>()) { foreach (var p in o.Properties()) { result.Add(new { p.Name, Value = (string)p.Value }); } } return result; } catch (Exception e) { Console.WriteLine(e.Message); return new List<dynamic>(); } } static IEnumerable<dynamic> ParseJson(string json) { try { IEnumerable<dynamic> items = JObject.Parse(json); return items; } catch { return new List<dynamic>(); } } } public class Binding { public string Protocol { get; set; } public string Port { get; set; } public string IpAddress { get; set; } public string CertificateLocation { get; set; } public string CertificateKeyLocation { get; set; } public string CertificateVariable { get; set; } public IEnumerable<string> SecurityProtocols { get; set; } public bool Enabled { get; set; } } public class Location { public string Path { get; set; } public string ReverseProxyUrl { get; set; } public string Directives { get; set; } public string Headers { get; set; } public string ReverseProxyHeaders { get; set; } public string ReverseProxyDirectives { get; set; } } }<file_sep>using System; using Calamari.Common.Plumbing.FileSystem; using Calamari.Integration.Packages.Download; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; using Octopus.Versioning; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class MavenPackageDownloaderFixture { static readonly string TentacleHome = TestEnvironment.GetTestPath("Fixtures", "PackageDownload"); [OneTimeSetUp] public void TestFixtureSetUp() { Environment.SetEnvironmentVariable("TentacleHome", TentacleHome); } [OneTimeTearDown] public void TestFixtureTearDown() { Environment.SetEnvironmentVariable("TentacleHome", null); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresNonFreeBSDPlatform] public void DownloadMavenPackage() { var downloader = GetDownloader(); var pkg = downloader.DownloadPackage("com.google.guava:guava", VersionFactory.CreateMavenVersion("22.0"), "feed-maven", new Uri("https://repo.maven.apache.org/maven2/"), "", "", true, 3, TimeSpan.FromSeconds(3)); Assert.AreEqual("com.google.guava:guava", pkg.PackageId); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresNonFreeBSDPlatform] public void DownloadMavenSourcePackage() { var downloader = GetDownloader(); var pkg = downloader.DownloadPackage("com.google.guava:guava:jar:sources", VersionFactory.CreateMavenVersion("22.0"), "feed-maven", new Uri("https://repo.maven.apache.org/maven2/"), "", "", true, 3, TimeSpan.FromSeconds(3)); Assert.AreEqual("com.google.guava:guava:jar:sources", pkg.PackageId); } static MavenPackageDownloader GetDownloader() { return new MavenPackageDownloader(CalamariPhysicalFileSystem.GetPhysicalFileSystem()); } } } <file_sep>using Calamari.Tests.Fixtures.Integration.FileSystem; namespace Calamari.Tests.Fixtures.PackageRetention { public class FileSystemThatHasSpace : TestCalamariPhysicalFileSystem { readonly ulong freeBytes; readonly ulong totalBytes; public FileSystemThatHasSpace(ulong freeBytes, ulong totalBytes) { this.freeBytes = freeBytes; this.totalBytes = totalBytes; } public override bool GetDiskFreeSpace(string directoryPath, out ulong totalNumberOfFreeBytes) { totalNumberOfFreeBytes = freeBytes; return true; } public override bool GetDiskTotalSpace(string directoryPath, out ulong totalNumberOfFreeBytes) { totalNumberOfFreeBytes = totalBytes; return true; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; namespace Calamari.Kubernetes.Integration { public class KubeLogin : CommandLineTool { public KubeLogin(ILog log, ICommandLineRunner commandLineRunner, string workingDirectory, Dictionary<string, string> environmentVars) : base(log, commandLineRunner, workingDirectory, environmentVars) { } public bool TrySetKubeLogin() { var result = CalamariEnvironment.IsRunningOnWindows ? ExecuteCommandAndReturnOutput("where", "kubelogin") : ExecuteCommandAndReturnOutput("which", "kubelogin"); var foundExecutable = result.Output.InfoLogs.FirstOrDefault(); if (string.IsNullOrEmpty(foundExecutable)) { log.Verbose("Could not find kubelogin. Make sure kubelogin is on the PATH."); IsConfigured = false; return false; } ExecutableLocation = foundExecutable.Trim(); IsConfigured = true; return true; } public bool IsConfigured { get; set; } public void ConfigureAksKubeLogin(string kubeConfigPath) { var arguments = new List<string>(new[] { "convert-kubeconfig", "-l", "azurecli", "--kubeconfig", $"\"{kubeConfigPath}\"", }); ExecuteCommandAndAssertSuccess(arguments.ToArray()); } public CommandResult ExecuteCommand(params string[] arguments) { var commandInvocation = new CommandLineInvocation(ExecutableLocation, arguments); return ExecuteCommandAndLogOutput(commandInvocation); } void ExecuteCommandAndAssertSuccess(params string[] arguments) { var result = ExecuteCommand(arguments); result.VerifySuccess(); } } } <file_sep>using System; namespace Calamari.Common.Features.Processes.Semaphores { public interface IProcessFinder { bool ProcessIsRunning(int processId, string processName); } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Logging; namespace Calamari.Kubernetes.Integration { public class CommandLineTool { protected readonly ILog log; protected string workingDirectory; protected Dictionary<string, string> environmentVars; readonly ICommandLineRunner commandLineRunner; protected CommandLineTool( ILog log, ICommandLineRunner commandLineRunner, string workingDirectory, Dictionary<string, string> environmentVars) { this.log = log; this.commandLineRunner = commandLineRunner; this.workingDirectory = workingDirectory; this.environmentVars = environmentVars; } public string ExecutableLocation { get; protected set; } protected bool TryExecuteCommandAndLogOutput(string exe, params string[] arguments) { var result = ExecuteCommandAndLogOutput(new CommandLineInvocation(exe, arguments)); return result.ExitCode == 0; } protected CommandResult ExecuteCommandAndLogOutput(CommandLineInvocation invocation) { invocation.EnvironmentVars = environmentVars; invocation.WorkingDirectory = workingDirectory; invocation.OutputAsVerbose = false; invocation.OutputToLog = false; var captureCommandOutput = new CaptureCommandOutput(); invocation.AdditionalInvocationOutputSink = captureCommandOutput; LogCommandText(invocation); var result = commandLineRunner.Execute(invocation); LogCapturedOutput(result, captureCommandOutput); return result; } void LogCommandText(CommandLineInvocation invocation) { log.Verbose(invocation.ToString()); } void LogCapturedOutput(CommandResult result, CaptureCommandOutput captureCommandOutput) { foreach (var message in captureCommandOutput.Messages) { if (result.ExitCode == 0) { log.Verbose(message.Text); continue; } switch (message.Level) { case Level.Info: log.Verbose(message.Text); break; case Level.Error: log.Error(message.Text); break; } } } protected CommandResultWithOutput ExecuteCommandAndReturnOutput(string exe, params string[] arguments) { var captureCommandOutput = new CaptureCommandOutput(); var invocation = new CommandLineInvocation(exe, arguments) { EnvironmentVars = environmentVars, WorkingDirectory = workingDirectory, OutputAsVerbose = false, OutputToLog = false, AdditionalInvocationOutputSink = captureCommandOutput }; var result = commandLineRunner.Execute(invocation); return new CommandResultWithOutput(result, captureCommandOutput); } } public class CommandResultWithOutput { public CommandResultWithOutput(CommandResult result, ICommandOutput output) { Result = result; Output = output; } public CommandResult Result { get; } public ICommandOutput Output { get; set; } } } <file_sep>using System; namespace Calamari.Common.Plumbing.Pipeline { public interface IBeforePackageExtractionBehaviour: IBehaviour { } }<file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json.Linq; using Octostache; namespace Calamari.Deployment.Features { public abstract class IisWebSiteFeature : IFeature { public string Name => "Octopus.Features.IISWebSite"; public abstract string DeploymentStage { get; } public abstract void Execute(RunningDeployment deployment); protected static IEnumerable<dynamic> GetEnabledBindings(IVariables variables) { var bindingString = variables.Get(SpecialVariables.Action.IisWebSite.Bindings); if (string.IsNullOrWhiteSpace(bindingString)) return new List<dynamic>(); IEnumerable<dynamic> bindings; return TryParseJson(bindingString, out bindings) ? bindings.Where(binding => bool.Parse((string)binding.enabled)) : new List<dynamic>(); } static bool TryParseJson(string json, out IEnumerable<dynamic> bindings) { try { bindings = JArray.Parse(json); return true; } catch { bindings = null; return false; } } } }<file_sep>using System; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Calamari.Common.Plumbing.Extensions { public class AesEncryption { const int PasswordSaltIterations = 1000; public const string SaltRaw = "Octopuss"; static readonly byte[] PasswordPaddingSalt = Encoding.UTF8.GetBytes(SaltRaw); static readonly byte[] IvPrefix = Encoding.UTF8.GetBytes("IV__"); static readonly Random RandomGenerator = new Random(); readonly byte[] key; public AesEncryption(string password) { key = GetEncryptionKey(password); } public string Decrypt(byte[] encrypted) { byte[] iv; var aesBytes = ExtractIV(encrypted, out iv); using (var algorithm = GetCryptoProvider(iv)) using (var dec = algorithm.CreateDecryptor()) using (var ms = new MemoryStream(aesBytes)) using (var cs = new CryptoStream(ms, dec, CryptoStreamMode.Read)) using (var sr = new StreamReader(cs, Encoding.UTF8)) { return sr.ReadToEnd(); } } public byte[] Encrypt(string plaintext) { var plainTextBytes = Encoding.UTF8.GetBytes(plaintext); using (var algorithm = GetCryptoProvider()) using (var cryptoTransform = algorithm.CreateEncryptor()) using (var stream = new MemoryStream()) { // The IV is randomly generated each time so safe to append stream.Write(IvPrefix, 0, IvPrefix.Length); stream.Write(algorithm.IV, 0, algorithm.IV.Length); using (var cs = new CryptoStream(stream, cryptoTransform, CryptoStreamMode.Write)) { cs.Write(plainTextBytes, 0, plainTextBytes.Length); } /* For testing purposes var key hex = BitConverter.ToString(algorithm.Key).Replace("-", string.Empty); var iv hex = BitConverter.ToString(algorithm.IV).Replace("-", string.Empty); var enc b64 = Convert.ToBase64String(stream.ToArray()); */ return stream.ToArray(); } } Aes GetCryptoProvider(byte[]? iv = null) { var provider = new AesCryptoServiceProvider { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, KeySize = 128, BlockSize = 128, Key = key }; if (iv != null) provider.IV = iv; return provider; } public static byte[] ExtractIV(byte[] encrypted, out byte[] iv) { var ivLength = 16; iv = new byte[ivLength]; Buffer.BlockCopy(encrypted, IvPrefix.Length, iv, 0, ivLength); var ivDataLength = IvPrefix.Length + ivLength; var aesDataLength = encrypted.Length - ivDataLength; var aesData = new byte[aesDataLength]; Buffer.BlockCopy(encrypted, ivDataLength, aesData, 0, aesDataLength); return aesData; } public static byte[] GetEncryptionKey(string encryptionPassword) { var passwordGenerator = new Rfc2898DeriveBytes(encryptionPassword, PasswordPaddingSalt, PasswordSaltIterations); return passwordGenerator.GetBytes(16); } public static string RandomString(int length) { const string chars = "abcdefghijklmnopqrstuvwxyz0123456789"; return new string( Enumerable.Repeat(chars, length) .Select(s => s[RandomGenerator.Next(s.Length)]) .ToArray()); } } }<file_sep>using System; using System.Collections.Generic; namespace Calamari.Common.Util { public interface ITemplate { string Content { get; } } public interface ITemplateInputs<TInput> { IEnumerable<TInput> Inputs { get; } } public interface ITemplateOutputs<TOutput> { bool HasOutputs { get; } IEnumerable<TOutput> Outputs { get; } } }<file_sep>using System.Collections.Generic; using System.Linq; using YamlDotNet.Serialization; namespace Calamari.Kubernetes.Conventions { public class RawValuesToYamlConverter { /// <summary> /// Converts collections of dot-notation properties into a structured YAM string /// </summary> /// <param name="values"></param> /// <returns></returns> public static string Convert(List<KeyValuePair<string, object>> values) { var structuredObject = new Dictionary<string, object>(); foreach (var v in values.OrderBy(k => k.Key)) { AddEntry(v.Key, v.Value, structuredObject); } return new Serializer().Serialize(structuredObject); } public static string Convert(Dictionary<string, object> values) { return Convert(values.ToList()); } private static void AddEntry(string dotname, object value, Dictionary<string, object> structuredObject) { var keys = dotname.Split('.'); var subDict = structuredObject; for (var i = 0; i < keys.Length; i++) { var key = keys[i]; if (i == keys.Length - 1) // Final dot sub-property, this is where the value lives! { if (!subDict.ContainsKey(key)) { subDict[key] = value; } else { // Another property has come this way before, lets make it a list SetValueAsList(value, key, subDict); } } else { if (!subDict.ContainsKey(key)) { // Another property has come this way before, lets make it an object var innerDict = new Dictionary<string, object>(); subDict[key] = innerDict; subDict = innerDict; } else { subDict = (Dictionary<string, object>) subDict[key]; } } } } private static void SetValueAsList(object value, string key, Dictionary<string, object> structuredObject) { var existing = structuredObject[key]; if (existing.GetType() == typeof(List<object>)) { ((List<object>) existing).Add(value); } else { structuredObject[key] = new List<object>() {existing, value}; } } } }<file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Microsoft.WindowsAzure.Packaging; namespace Calamari.AzureCloudService { public class EnsureCloudServicePackageIsCtpFormatBehaviour : IAfterPackageExtractionBehaviour { readonly ILog log; readonly ICalamariFileSystem fileSystem; public EnsureCloudServicePackageIsCtpFormatBehaviour(ILog log, ICalamariFileSystem fileSystem) { this.log = log; this.fileSystem = fileSystem; } public bool IsEnabled(RunningDeployment context) { return !context.Variables.GetFlag(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled); } public Task Execute(RunningDeployment context) { log.VerboseFormat("Ensuring cloud-service-package is {0} format.", PackageFormats.V20120315.ToString()); var packagePath = context.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath); var packageFormat = PackageConverter.GetFormat(packagePath); switch (packageFormat) { case PackageFormats.Legacy: log.VerboseFormat("Package is Legacy format. Converting to {0} format.", PackageFormats.V20120315.ToString()); ConvertPackage(packagePath); break; case PackageFormats.V20120315: log.VerboseFormat("Package is {0} format.", PackageFormats.V20120315.ToString()); break; default: throw new InvalidOperationException("Unexpected PackageFormat: " + packageFormat); } return this.CompletedTask(); } void ConvertPackage(string packagePath) { var newPackagePath = Path.Combine(Path.GetDirectoryName(packagePath), Path.GetFileNameWithoutExtension(packagePath) + "_new.cspkg"); using (var packageStore = new OpcPackageStore(newPackagePath, FileMode.CreateNew, FileAccess.ReadWrite)) using (var fileStream = fileSystem.OpenFile(packagePath, FileMode.Open)) { PackageConverter.ConvertFromLegacy(fileStream, packageStore); } fileSystem.OverwriteAndDelete(packagePath, newPackagePath); } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public static class DeploymentVariables { public static string Id = "Octopus.Deployment.Id"; public static class Tenant { public static string Id = "Octopus.Deployment.Tenant.Id"; public static string Name = "Octopus.Deployment.Tenant.Name"; } } }<file_sep>using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Calamari.AzureAppService.Azure { public class AzureResource { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("resourceGroup")] public string ResourceGroup { get; set; } [JsonProperty("tags")] public Dictionary<string,string> Tags { get; set; } [JsonIgnore] public bool IsSlot => Type.EndsWith("/slots"); [JsonIgnore] public string SlotName { get { if (!IsSlot) { return null; } var indexOfSlash = Name.LastIndexOf("/", StringComparison.InvariantCulture); return indexOfSlash < 0 ? "" : Name.Substring(indexOfSlash + 1); } } [JsonIgnore] public string ParentName { get { if (!IsSlot) { return null; } var indexOfSlash = Name.LastIndexOf("/", StringComparison.InvariantCulture); return indexOfSlash < 0 ? Name : Name.Substring(0, indexOfSlash); } } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Threading; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; namespace Calamari.Common.Plumbing.FileSystem { public interface ICalamariFileSystem { bool FileExists([NotNullWhen(true)]string? path); bool DirectoryExists(string? path); bool DirectoryIsEmpty(string path); void DeleteFile(string path, FailureOptions options = FailureOptions.ThrowOnFailure); void DeleteDirectory(string path); void DeleteDirectory(string path, FailureOptions options); IEnumerable<string> EnumerateDirectories(string parentDirectoryPath); IEnumerable<string> EnumerateDirectoriesRecursively(string parentDirectoryPath); IEnumerable<string> EnumerateFilesWithGlob(string parentDirectoryPath, GlobMode globMode, params string[] globPatterns); IEnumerable<string> EnumerateFiles(string parentDirectoryPath, params string[] searchPatterns); IEnumerable<string> EnumerateFilesRecursively(string parentDirectoryPath, params string[] searchPatterns); long GetFileSize(string path); string ReadFile(string path); string ReadFile(string path, out Encoding encoding); string ReadAllText(byte[] bytes, out Encoding encoding, ICollection<Encoding> encodingPrecedence); void OverwriteFile(string path, string contents, Encoding? encoding = null); void OverwriteFile(string path, Action<TextWriter> writeToWriter, Encoding? encoding = null); void OverwriteFile(string path, byte[] data); void WriteAllText(string path, string contents, Encoding? encoding = null); void WriteAllText(string path, Action<TextWriter> writeToWriter, Encoding? encoding = null); Stream OpenFile(string path, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read); Stream OpenFile(string path, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read); Stream CreateTemporaryFile(string extension, out string path); string CreateTemporaryDirectory(); void CreateDirectory(string directory); int CopyDirectory(string sourceDirectory, string targetDirectory); int CopyDirectory(string sourceDirectory, string targetDirectory, CancellationToken cancel); void CopyFile(string sourceFile, string destinationFile); void PurgeDirectory(string targetDirectory, FailureOptions options); void PurgeDirectory(string targetDirectory, FailureOptions options, CancellationToken cancel); void PurgeDirectory(string targetDirectory, Predicate<FileSystemInfo> exclude, FailureOptions options); void PurgeDirectory(string targetDirectory, FailureOptions options, GlobMode globMode, params string[] globs); void EnsureDirectoryExists(string directoryPath); bool GetDiskFreeSpace(string directoryPath, out ulong totalNumberOfFreeBytes); bool GetDiskTotalSpace(string directoryPath, out ulong totalNumberOfBytes); string GetFullPath(string relativeOrAbsoluteFilePath); void OverwriteAndDelete(string originalFile, string temporaryReplacement); void WriteAllBytes(string filePath, byte[] data); string RemoveInvalidFileNameChars(string path); void MoveFile(string sourceFile, string destinationFile); string GetRelativePath(string fromFile, string toFile); Stream OpenFileExclusively(string filePath, FileMode fileMode, FileAccess fileAccess); DateTime GetCreationTime(string filePath); string GetFileName(string filePath); string GetDirectoryName(string directoryPath); byte[] ReadAllBytes(string filePath); } }<file_sep>using Autofac; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Caching; using Calamari.Deployment.PackageRetention.Model; using Calamari.Deployment.PackageRetention.Repositories; namespace Calamari.Deployment.PackageRetention { public class PackageRetentionModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<JsonJournalRepository>().As<IJournalRepository>(); builder.RegisterType<VariableJsonJournalPathProvider>().As<IJsonJournalPathProvider>(); builder.RegisterType<PackageJournal>().As<IManagePackageCache>().SingleInstance(); builder.RegisterType<LeastFrequentlyUsedWithAgingSort>().As<ISortJournalEntries>(); builder.RegisterType<PercentFreeDiskSpacePackageCleaner>().As<IRetentionAlgorithm>(); base.Load(builder); } } }<file_sep>namespace Calamari.Kubernetes.ResourceStatus { public enum DeploymentStatus { InProgress, Succeeded, Failed } }<file_sep>using System; using System.Text; namespace Calamari.Common.Plumbing.Extensions { public static class ExceptionExtensions { public static string PrettyPrint(this Exception ex, StringBuilder? sb = null) { sb ??= new StringBuilder(); sb.AppendLine(ex.Message); sb.AppendLine(ex.GetType().FullName); sb.AppendLine(ex.StackTrace); if (ex.InnerException != null) { sb.AppendLine(); sb.AppendLine("--Inner Exception--"); PrettyPrint(ex.InnerException, sb); } return sb.ToString(); } } }<file_sep> using System; Octopus.SetVariable("Password","<PASSWORD>", true); <file_sep>using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureCloudService { public class ChooseCloudServiceConfigurationFileBehaviour : IAfterPackageExtractionBehaviour { static readonly string FallbackFileName = "ServiceConfiguration.Cloud.cscfg"; // Default from Visual Studio static readonly string EnvironmentFallbackFileName = "ServiceConfiguration.{0}.cscfg"; readonly ILog log; readonly ICalamariFileSystem fileSystem; public ChooseCloudServiceConfigurationFileBehaviour(ILog log, ICalamariFileSystem fileSystem) { this.log = log; this.fileSystem = fileSystem; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var configurationFile = ChooseWhichConfigurationFileToUse(context); log.SetOutputVariable(SpecialVariables.Action.Azure.Output.ConfigurationFile, configurationFile, context.Variables); return this.CompletedTask(); } string ChooseWhichConfigurationFileToUse(RunningDeployment deployment) { var configurationFilePath = GetFirstExistingFile(deployment, deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServiceConfigurationFileRelativePath), BuildEnvironmentSpecificFallbackFileName(deployment), FallbackFileName); return configurationFilePath; } string GetFirstExistingFile(RunningDeployment deployment, params string[] fileNames) { foreach (var name in fileNames) { if (string.IsNullOrWhiteSpace(name)) continue; var path = Path.Combine(deployment.CurrentDirectory, name); if (fileSystem.FileExists(path)) { log.Verbose("Found Azure Cloud Service Configuration file: " + path); return path; } log.Verbose("Azure Cloud Service Configuration file (*.cscfg) not found: " + path); } throw new CommandException( "Could not find an Azure Cloud Service Configuration file (*.cscfg) in the package."); } static string BuildEnvironmentSpecificFallbackFileName(RunningDeployment deployment) { return string.Format(EnvironmentFallbackFileName, deployment.Variables.Get(DeploymentEnvironment.Name)); } } }<file_sep>using System; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.Deployment.Journal { public class DeploymentJournalWriter : IDeploymentJournalWriter { readonly ICalamariFileSystem fileSystem; public DeploymentJournalWriter(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } /// <summary> /// Conditionally Write To Journal if there were packages that may need to be cleaned up during retention /// </summary> /// <param name="deployment"></param> /// <param name="wasSuccessful">Was the command successful. Usually ExitCode == 0</param> /// <param name="packageFile">Since package references can still be passed by the command line this needs to be provided here. /// Can remove once we obtain all references through variables</param> public void AddJournalEntry(RunningDeployment deployment, bool wasSuccessful, string? packageFile = null) { if (deployment.SkipJournal) return; var semaphore = SemaphoreFactory.Get(); var journal = new DeploymentJournal(fileSystem, semaphore, deployment.Variables); var hasPackages = !string.IsNullOrWhiteSpace(packageFile) || deployment.Variables.GetIndexes(PackageVariables.PackageCollection).Any(); if (!hasPackages) return; var canWrite = deployment.Variables.Get(TentacleVariables.Agent.JournalPath) != null; if (!canWrite) return; var journalEntry = new JournalEntry(deployment, wasSuccessful); if (string.IsNullOrEmpty(journalEntry.ExtractedTo)) return; journal.AddJournalEntry(new JournalEntry(deployment, wasSuccessful)); } } }<file_sep>#if USE_NUGET_V2_LIBS using System; using System.IO; using NuGet; namespace Calamari.Integration.Packages.Download { public class FixedFilePathResolver : IPackagePathResolver { readonly string packageName; readonly string filePathNameToReturn; public FixedFilePathResolver(string packageName, string filePathNameToReturn) { if (packageName == null) throw new ArgumentNullException("packageName"); if (filePathNameToReturn == null) throw new ArgumentNullException("filePathNameToReturn"); this.packageName = packageName; this.filePathNameToReturn = filePathNameToReturn; } public string GetInstallPath(IPackage package) { EnsureRightPackage(package.Id); return Path.GetDirectoryName(filePathNameToReturn); } public string GetPackageDirectory(IPackage package) { return GetPackageDirectory(package.Id, package.Version); } public string GetPackageFileName(IPackage package) { return GetPackageFileName(package.Id, package.Version); } public string GetPackageDirectory(string packageId, SemanticVersion version) { EnsureRightPackage(packageId); return string.Empty; } public string GetPackageFileName(string packageId, SemanticVersion version) { EnsureRightPackage(packageId); return Path.GetFileName(filePathNameToReturn); } void EnsureRightPackage(string packageId) { var samePackage = string.Equals(packageId, packageName, StringComparison.OrdinalIgnoreCase); if (!samePackage) { throw new ArgumentException(string.Format("Expected to be asked for the path for package {0}, but was instead asked for the path for package {1}", packageName, packageId)); } } } } #endif<file_sep>using System; namespace Calamari.Exceptions { /// <summary> /// Represents an error downloading a maven artifact /// </summary> public class MavenDownloadException : Exception { public MavenDownloadException() { } public MavenDownloadException(string message) : base(message) { } public MavenDownloadException(string message, Exception inner) : base(message, inner) { } } }<file_sep>using Calamari.Common.Plumbing.Extensions; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.FileSystem { [TestFixture] public class PathExtensionsFixture { [TestCase(@"c:\foo", @"c:\foo", true)] [TestCase(@"c:\foo", @"c:\foo\", true)] [TestCase(@"c:\foo\", @"c:\foo", true)] [TestCase(@"c:\foo\bar\", @"c:\foo\", true)] [TestCase(@"c:\foo\bar", @"c:\foo\", true)] [TestCase(@"c:\foo\a.txt", @"c:\foo", true)] [TestCase(@"c:/foo/a.txt", @"c:\foo", true)] [TestCase(@"c:\foobar", @"c:\foo", false)] [TestCase(@"c:\foobar\a.txt", @"c:\foo", false)] [TestCase(@"c:\foobar\a.txt", @"c:\foo\", false)] [TestCase(@"c:\foo\a.txt", @"c:\foobar", false)] [TestCase(@"c:\foo\a.txt", @"c:\foobar\", false)] [TestCase(@"c:\foo\..\bar\baz", @"c:\foo", false)] [TestCase(@"c:\foo\..\bar\baz", @"c:\bar", true)] [TestCase(@"c:\foo\..\bar\baz", @"c:\barr", false)] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void IsChildOfTest(string child, string parent, bool result) { child.IsChildOf(parent).Should().Be(result); } [TestCase(@"c:\FOO\a.txt", @"c:\foo", true)] [TestCase(@"c:\foo\a.txt", @"c:\FOO", true)] [TestCase(@"c:\foo", @"c:", true)] [TestCase(@"c:\foo", @"c:\", true)] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void IsChildOfTestWindows(string child, string parent, bool result) { child.IsChildOf(parent).Should().Be(result); } [TestCase(@"c:\FOO\a.txt", @"c:\foo", false)] [TestCase(@"c:\foo\a.txt", @"c:\FOO", false)] [TestCase(@"/", @"/", true)] [TestCase(@"/foo", @"/", true)] [TestCase(@"/", @"/foo", false)] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void IsChildOfTestUnix(string child, string parent, bool result) { child.IsChildOf(parent).Should().Be(result); } } }<file_sep>import importlib import subprocess import sys def install_package_using_pip(package): printverbose("Did not find dependency, attempting to install {} for the current user using pip".format(package)) exitcode = subprocess.call([sys.executable, "-m", "pip", "install", package, "--user"]) if exitcode != 0: print("Unable to install package {} using pip.".format(package), file=sys.stderr) print("If you do not have pip you can install {} using your favorite python package manager.".format(package), file=sys.stderr) exit(exitcode) def install_missing_dependency(module, package): try: printverbose("Checking for dependency {}".format(package)) importlib.import_module(module) printverbose("{} was found".format(package)) except: install_package_using_pip(package) def printverbose(message): print("##octopus[stdout-verbose]") print(message) print("##octopus[stdout-default]") install_missing_dependency('Crypto.Cipher.AES', 'pycryptodome')<file_sep>using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Variables { [TestFixture] public class ContributeEnvironmentVariablesFixture { [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldAddWindowsEnvironmentVariables() { if (!CalamariEnvironment.IsRunningOnWindows) Assert.Ignore("This test is designed to run on windows"); var variables = AddEnvironmentVariables(); Assert.That(variables.Evaluate("My OS is #{env:OS}"), Does.StartWith("My OS is Windows")); } [Test] [Category(TestCategory.CompatibleOS.OnlyNix)] public void ShouldAddLinuxEnvironmentVariables() { if (!CalamariEnvironment.IsRunningOnNix) Assert.Ignore("This test is designed to run on *nix"); var variables = AddEnvironmentVariables(); Assert.That(variables.Evaluate("My home starts at #{env:HOME}"), Does.StartWith("My home starts at /home/")); } [Test] [Category(TestCategory.CompatibleOS.OnlyMac)] public void ShouldAddMacEnvironmentVariables() { // Mac running in TeamCity agent service does not contain $HOME variable // $PATH is being used since it should be common between service & development // http://askubuntu.com/a/394330 if (!CalamariEnvironment.IsRunningOnMac) Assert.Ignore("This test is designed to run on Mac"); var variables = AddEnvironmentVariables(); Assert.That(variables.Evaluate("My paths are #{env:PATH}"), Does.Contain("/usr/local/bin")); } private IVariables AddEnvironmentVariables() { var variables = new VariablesFactory(CalamariPhysicalFileSystem.GetPhysicalFileSystem()).Create(new CommonOptions("test")); Assert.That(variables.GetNames().Count, Is.GreaterThan(3)); Assert.That(variables.GetRaw(TentacleVariables.Agent.InstanceName), Is.EqualTo("#{env:TentacleInstanceName}")); return variables; } } }<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Calamari.Aws.Deployment; using Calamari.CloudAccounts; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Integration { public class AwsScriptWrapper : IScriptWrapper { readonly ILog log; readonly IVariables variables; public int Priority => ScriptWrapperPriorities.CloudAuthenticationPriority; bool IScriptWrapper.IsEnabled(ScriptSyntax syntax) { var accountType = variables.Get(SpecialVariables.Account.AccountType); var awsAccountVariable = variables.Get(AwsSpecialVariables.Authentication.AwsAccountVariable); var useAwsInstanceRole = variables.Get(AwsSpecialVariables.Authentication.UseInstanceRole); return accountType == "AmazonWebServicesAccount" || !awsAccountVariable.IsNullOrEmpty() || string.Equals(useAwsInstanceRole, bool.TrueString, StringComparison.InvariantCultureIgnoreCase); } public IScriptWrapper NextWrapper { get; set; } public Func<Task<bool>> VerifyAmazonLogin { get; set; } public AwsScriptWrapper(ILog log, IVariables variables) { this.log = log; this.variables = variables; } public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string> environmentVars) { var awsEnvironmentVars = AwsEnvironmentGeneration.Create(log, variables, VerifyAmazonLogin).GetAwaiter().GetResult().EnvironmentVars; awsEnvironmentVars.AddRange(environmentVars); return NextWrapper.ExecuteScript( script, scriptSyntax, commandLineRunner, awsEnvironmentVars); } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; namespace Calamari.Deployment.Conventions { public class SubstituteInFilesConvention : IInstallConvention { readonly SubstituteInFilesBehaviour substituteInFilesBehaviour; public SubstituteInFilesConvention(SubstituteInFilesBehaviour substituteInFilesBehaviour) { this.substituteInFilesBehaviour = substituteInFilesBehaviour; } public void Install(RunningDeployment deployment) { if (substituteInFilesBehaviour.IsEnabled(deployment)) { substituteInFilesBehaviour.Execute(deployment).Wait(); } } } }<file_sep>namespace Calamari.Common.Features.Discovery { public static class KubernetesAuthenticationContextTypes { public const string AzureServicePrincipal = "AzureServicePrincipal"; } }<file_sep>using System; namespace Calamari.Common.Features.Processes.Semaphores { public interface ILockIo { string GetFilePath(string lockName); bool LockExists(string lockFilePath); IFileLock ReadLock(string lockFilePath); bool WriteLock(string lockFilePath, FileLock fileLock); void DeleteLock(string lockFilePath); } }<file_sep>namespace Calamari.Common.Features.Discovery { public interface ITargetDiscoveryAuthenticationDetails { string Type { get; } } } <file_sep>using System; using System.Text.RegularExpressions; using System.Threading.Tasks; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Runtime; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using Calamari.Aws.Integration; using Calamari.Aws.Util; using Calamari.CloudAccounts; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Deployment.Conventions { public class LogAwsUserInfoConvention: IInstallConvention { private readonly AwsEnvironmentGeneration awsEnvironmentGeneration; /// <summary> /// Matches ARNs like arn:aws:iam::123456789:role/AWSTestRole and extracts the name as group 1 /// </summary> private static readonly Regex ArnNameRe = new Regex("^.*?/(.+)$"); public LogAwsUserInfoConvention(AwsEnvironmentGeneration awsEnvironmentGeneration) { this.awsEnvironmentGeneration = awsEnvironmentGeneration; } public void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private async Task InstallAsync(RunningDeployment deployment) { Guard.NotNull(deployment, "deployment can not be null"); Func<IAmazonSecurityTokenService> stsClientFactory = () => ClientHelpers.CreateSecurityTokenServiceClient(awsEnvironmentGeneration); Func<IAmazonIdentityManagementService> identityManagementClientFactory = () => ClientHelpers.CreateIdentityManagementServiceClient(awsEnvironmentGeneration); if (deployment.Variables.IsSet(SpecialVariables.Action.Aws.AssumeRoleARN) || !deployment.Variables.IsSet(SpecialVariables.Action.Aws.AccountId) || !deployment.Variables.IsSet(deployment.Variables.Get(SpecialVariables.Action.Aws.AccountId) + ".AccessKey")) { await WriteRoleInfo(stsClientFactory); } else { await WriteUseInfo(identityManagementClientFactory); } } private async Task WriteUseInfo(Func<IAmazonIdentityManagementService> clientFactory) { try { var result = await clientFactory().GetUserAsync(new GetUserRequest()); Log.Info($"Running the step as the AWS user {result.User.UserName}"); } catch (AmazonServiceException) { // Ignore, we just won't add this to the logs } } private async Task WriteRoleInfo(Func<IAmazonSecurityTokenService> clientFactory) { try { (await clientFactory().GetCallerIdentityAsync(new GetCallerIdentityRequest())) // The response is narrowed to the Aen .Map(response => response.Arn) // Try and match the response to get just the role .Map(arn => ArnNameRe.Match(arn)) // Extract the role name, or a default .Map(match => match.Success ? match.Groups[1].Value : "Unknown") // Log the output .Tee(role => Log.Info($"Running the step as the AWS role {role}")); } catch (AmazonServiceException) { // Ignore, we just won't add this to the logs } } } } <file_sep>using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Calamari.Terraform.Tests")]<file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using Serilog; namespace Calamari.ConsolidateCalamariPackages { class SashimiPackageReference : IPackageReference { private readonly Hasher hasher; private readonly BuildPackageReference packageReference; public SashimiPackageReference(Hasher hasher, BuildPackageReference packageReference) { this.hasher = hasher; this.packageReference = packageReference; } public string Name => packageReference.Name; public string Version => packageReference.Version; public string PackagePath => packageReference.PackagePath; public IReadOnlyList<SourceFile> GetSourceFiles(ILogger log) { var extractPath = $"{Path.GetDirectoryName(PackagePath)}/extract/{Name}"; ZipFile.ExtractToDirectory(PackagePath, extractPath); var toolZipsDir = Path.Combine(extractPath, "tools"); if (!Directory.Exists(toolZipsDir)) { log.Information($"Skipping {Name} as it does not have a tools folder: {toolZipsDir}"); return Array.Empty<SourceFile>(); } var toolZips = Directory.GetFiles(toolZipsDir); if (toolZips.Length == 0) { log.Information($"Skipping {Name} as it does not have any zip files in the tools folder: {toolZipsDir}"); return Array.Empty<SourceFile>(); } return toolZips.SelectMany(toolZipPath => ReadSashimiPackagedZip(toolZipPath)) .ToArray(); } IReadOnlyList<SourceFile> ReadSashimiPackagedZip(string toolZipPath) { using (var zip = ZipFile.OpenRead(toolZipPath)) return zip.Entries .Where(e => !string.IsNullOrEmpty(e.Name)) .Select(entry => { // Sashimi zips have each full Calamari executable in folders according to platform var parts = entry.FullName.Split('/'); return new SourceFile { PackageId = Path.GetFileNameWithoutExtension(toolZipPath), Version = Version, Platform = parts[0], ArchivePath = toolZipPath, IsNupkg = false, FullNameInDestinationArchive = string.Join("/", parts.Skip(1)), FullNameInSourceArchive = entry.FullName, Hash = hasher.Hash(entry) }; }) .ToArray(); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.ConfigurationVariables { public class ConfigurationVariablesReplacer : IConfigurationVariablesReplacer { readonly ILog log; readonly bool ignoreVariableReplacementErrors; public ConfigurationVariablesReplacer(IVariables variables, ILog log) { this.log = log; ignoreVariableReplacementErrors = variables.GetFlag(KnownVariables.Package.IgnoreVariableReplacementErrors); } public void ModifyConfigurationFile(string configurationFilePath, IVariables variables) { try { var doc = ReadXmlDocument(configurationFilePath); var changes = ApplyChanges(doc, variables); if (!changes.Any()) { log.InfoFormat("No matching appSetting, applicationSetting, nor connectionString names were found in: {0}", configurationFilePath); return; } log.InfoFormat("Updating appSettings, applicationSettings, and connectionStrings in: {0}", configurationFilePath); foreach (var change in changes) { log.Verbose(change); } WriteXmlDocument(doc, configurationFilePath); } catch (Exception ex) { if (ignoreVariableReplacementErrors) { log.Warn(ex.Message); log.Warn(ex.StackTrace); } else { log.ErrorFormat("Exception while replacing configuration-variables in: {0}", configurationFilePath); throw; } } } static XDocument ReadXmlDocument(string configurationFilePath) { using (var reader = XmlReader.Create(configurationFilePath, XmlUtils.DtdSafeReaderSettings)) { return XDocument.Load(reader, LoadOptions.PreserveWhitespace); } } static List<string> ApplyChanges(XNode doc, IVariables variables) { var changes = new List<string>(); foreach (var variable in variables.GetNames()) { changes.AddRange( ReplaceAppSettingOrConnectionString(doc, "//*[local-name()='appSettings']/*[local-name()='add']", "key", variable, "value", variables).Concat( ReplaceAppSettingOrConnectionString(doc, "//*[local-name()='connectionStrings']/*[local-name()='add']", "name", variable, "connectionString", variables).Concat( ReplaceStronglyTypeApplicationSetting(doc, "//*[local-name()='applicationSettings']//*[local-name()='setting']", "name", variable, variables)))); } return changes; } static void WriteXmlDocument(XDocument doc, string configurationFilePath) { var xws = new XmlWriterSettings {OmitXmlDeclaration = doc.Declaration == null, Indent = true}; using (var file = new FileStream(configurationFilePath, FileMode.Create, FileAccess.Write)) using (var writer = XmlWriter.Create(file, xws)) { doc.Save(writer); } } static IEnumerable<string> ReplaceAppSettingOrConnectionString(XNode document, string xpath, string keyAttributeName, string keyAttributeValue, string valueAttributeName, IVariables variables) { var changes = new List<string>(); var settings = ( from element in document.XPathSelectElements(xpath) let keyAttribute = element.Attribute(keyAttributeName) where keyAttribute != null where string.Equals(keyAttribute.Value, keyAttributeValue, StringComparison.OrdinalIgnoreCase) select element).ToList(); if (settings.Count == 0) return changes; var value = variables.Get(keyAttributeValue) ?? string.Empty; foreach (var setting in settings) { changes.Add(string.Format("Setting '{0}' = '{1}'", keyAttributeValue, value)); var valueAttribute = setting.Attribute(valueAttributeName); if (valueAttribute == null) { setting.Add(new XAttribute(valueAttributeName, value)); } else { valueAttribute.SetValue(value); } } return changes; } static IEnumerable<string> ReplaceStronglyTypeApplicationSetting(XNode document, string xpath, string keyAttributeName, string keyAttributeValue, IVariables variables) { var changes = new List<string>(); var settings = ( from element in document.XPathSelectElements(xpath) let keyAttribute = element.Attribute(keyAttributeName) where keyAttribute != null where string.Equals(keyAttribute.Value, keyAttributeValue, StringComparison.OrdinalIgnoreCase) select element).ToList(); if (settings.Count == 0) return changes; var value = variables.Get(keyAttributeValue) ?? string.Empty; foreach (var setting in settings) { changes.Add($"Setting '{keyAttributeValue}' = '{value}'"); var valueElement = setting.Elements().FirstOrDefault(e => e.Name.LocalName == "value"); if (valueElement == null) { setting.Add(new XElement("value", value)); } else { valueElement.SetValue(value); } } return changes; } } } <file_sep>using System; namespace Calamari.ConsolidateCalamariPackages { public class BuildPackageReference { public string Name { get; set; } public string Version { get; set; } public string PackagePath { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using Serilog; namespace Calamari.ConsolidateCalamariPackages { public class Consolidate { readonly ILogger log; public Consolidate(ILogger log) { this.log = log; } public string AssemblyVersion { get; set; } = (((AssemblyInformationalVersionAttribute) typeof(Consolidate).Assembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute))!)!).InformationalVersion; public (bool result, string packageFileName) Execute(string outputDirectory, IEnumerable<BuildPackageReference> packageReferences) { using (var hasher = new Hasher()) { if (!Directory.Exists(outputDirectory)) { log.Error($"The output directory {outputDirectory} does not exist"); return (false, null!); } var packages = GetPackages(hasher, packageReferences); var packageHash = hasher.GetPackageCombinationHash(AssemblyVersion, packages); log.Information($"Hash of the package combination is {packageHash}"); var destination = Path.Combine(outputDirectory, $"Calamari.{packageHash}.zip"); if (File.Exists(destination)) { log.Information("Calamari zip with the right package combination hash already exists"); return (true, destination); } log.Information("Scanning Calamari Packages"); var indexEntries = packages.SelectMany(p => p.GetSourceFiles(log)).ToArray(); log.Information("Creating consolidated Calamari package"); var sw = Stopwatch.StartNew(); ConsolidatedPackageCreator.Create(indexEntries, destination); log.Information($"Package creation took {sw.ElapsedMilliseconds:n0}ms"); foreach (var item in indexEntries.Select(i => new {i.PackageId, i.Platform}).Distinct()) log.Information($"Packaged {item.PackageId} for {item.Platform}"); return (true, destination); } } static IReadOnlyList<IPackageReference> GetPackages(Hasher hasher, IEnumerable<BuildPackageReference> packageReferences) { var calamariPackages = packageReferences .Where(p => !MigratedCalamariFlavours.Flavours.Contains(p.Name)) .Where(p => p.Name.StartsWith("Calamari")) .Select(p => new CalamariPackageReference(hasher, p)); var calamariFlavourPackages = packageReferences .Where(p => MigratedCalamariFlavours.Flavours.Contains(p.Name)) .Select(p => new CalamariFlavourPackageReference(hasher, p)); var sashimiPackages = packageReferences .Where(p => p.Name.StartsWith("Sashimi.")) .Select(p => new SashimiPackageReference(hasher, p)); return calamariPackages.Concat<IPackageReference>(sashimiPackages).Concat(calamariFlavourPackages).ToArray(); } } }<file_sep>using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Calamari")] [assembly: InternalsVisibleTo("Calamari.Tests")] [assembly: Guid("2c948d59-4d8c-4c9e-a736-21c82e8a47c4")]<file_sep>using System; using Azure.ResourceManager.AppService.Models; namespace Calamari.AzureAppService.Json { public class ConnectionStringSetting { public string Name { get; set; } public string Value { get; set; } public ConnectionStringType Type { get; set; } public bool SlotSetting { get; set; } internal void Deconstruct(out string name, out string value, out ConnectionStringType type, out bool isSlotSetting) { name = Name; value = Value; type = Type; isSlotSetting = SlotSetting; } public bool Equals(AppSetting other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Name == other.Name && Value == other.Value && SlotSetting == other.SlotSetting; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == this.GetType() && Equals((AppSetting)obj); } public override int GetHashCode() { return new { Name, Value, SlotSetting, Type }.GetHashCode(); } public override string ToString() { return $"\nName: {Name}\nValue: {Value}\nType: {Type}\nIsSlotSetting: {SlotSetting}\n"; } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; namespace Calamari.Common.Features.Scripting { /// <summary> /// This hook is used to wrap the execution of a script with another script. /// </summary> public interface IScriptWrapper { /// <summary> /// The priority of the wrapper. Higher priority scripts are /// run first. /// </summary> int Priority { get; } /// <summary> /// The next wrapper to call. IScriptWrapper objects essentially form /// a linked list through the NextWrapper property, and scipts are /// wrapped up in multiple wrapper as they move through the list. /// </summary> IScriptWrapper? NextWrapper { get; set; } /// <summary> /// true if this wrapper is enabled, and false otherwise. If /// Enabled is false, this wrapper is not used during execution. /// </summary> bool IsEnabled(ScriptSyntax syntax); /// <summary> /// Execute the wrapper. The call to this is usually expected to /// call the NextWrapper.ExecuteScript() method as it's final step. /// </summary> CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars); } }<file_sep>using System; using System.Collections.Generic; using Calamari.AzureServiceFabric.Behaviours; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureServiceFabric.Commands { [Command("deploy-azure-service-fabric-app", Description = "Extracts and installs an Azure Service Fabric Application")] public class DeployAzureServiceFabricAppCommand : PipelineCommand { protected override IEnumerable<IBeforePackageExtractionBehaviour> BeforePackageExtraction(BeforePackageExtractionResolver resolver) { yield return resolver.Create<CheckSdkInstalledBehaviour>(); } protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<SubstituteVariablesInAzureServiceFabricPackageBehaviour>(); yield return resolver.Create<EnsureCertificateInstalledInStoreBehaviour>(); yield return resolver.Create<DeployAzureServiceFabricAppBehaviour>(); } } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Deployment.Journal { public class JournalEntry { public JournalEntry(RunningDeployment deployment, bool wasSuccessful) : this(Guid.NewGuid().ToString(), deployment.Variables.Get(DeploymentEnvironment.Id), deployment.Variables.Get(DeploymentVariables.Tenant.Id), deployment.Variables.Get(ProjectVariables.Id), deployment.Variables.Get(KnownVariables.RetentionPolicySet), DateTime.UtcNow, deployment.Variables.Get(KnownVariables.OriginalPackageDirectoryPath), deployment.Variables.Get(PackageVariables.CustomInstallationDirectory), wasSuccessful, DeployedPackage.GetDeployedPackages(deployment) ) { } public JournalEntry(XElement element) : this( element.Attribute("Id")?.Value, element.Attribute("EnvironmentId")?.Value, element.Attribute("TenantId")?.Value, element.Attribute("ProjectId")?.Value, element.Attribute("RetentionPolicySet")?.Value, ParseDate(element.Attribute("InstalledOn")?.Value), element.Attribute("ExtractedTo")?.Value, element.Attribute("CustomInstallationDirectory")?.Value, ParseBool(element.Attribute("WasSuccessful")?.Value) ?? true, DeployedPackage.FromJournalEntryElement(element) ) { } internal JournalEntry(string? id, string? environmentId, string? tenantId, string? projectId, string? retentionPolicySet, DateTime? installedOn, string? extractedTo, string? customInstallationDirectory, bool wasSuccessful, IEnumerable<DeployedPackage> packages) { Id = id; EnvironmentId = environmentId; TenantId = tenantId; ProjectId = projectId; RetentionPolicySet = retentionPolicySet; InstalledOn = installedOn; ExtractedTo = extractedTo ?? ""; CustomInstallationDirectory = customInstallationDirectory; WasSuccessful = wasSuccessful; Packages = packages?.ToList() ?? new List<DeployedPackage>(); } internal JournalEntry(string id, string environmentId, string tenantId, string projectId, string retentionPolicySet, DateTime installedOn, string extractedTo, string customInstallationDirectory, bool wasSuccessful, DeployedPackage package) : this(id, environmentId, tenantId, projectId, retentionPolicySet, installedOn, extractedTo, customInstallationDirectory, wasSuccessful, package != null ? (IEnumerable<DeployedPackage>)new[] { package } : new List<DeployedPackage>()) { } public string? Id { get; } public string? EnvironmentId { get; } public string? TenantId { get; } public string? ProjectId { get; } public string? RetentionPolicySet { get; } public DateTime? InstalledOn { get; } public string? ExtractedTo { get; } public string? CustomInstallationDirectory { get; } public bool WasSuccessful { get; } public ICollection<DeployedPackage> Packages { get; } // Short-cut for deployments with a single package public DeployedPackage Package => Packages.FirstOrDefault(); public XElement ToXmlElement() { return new XElement("Deployment", new XAttribute("Id", Id), new XAttribute("EnvironmentId", EnvironmentId ?? string.Empty), new XAttribute("TenantId", TenantId ?? string.Empty), new XAttribute("ProjectId", ProjectId ?? string.Empty), new XAttribute("InstalledOn", InstalledOn?.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)), new XAttribute("RetentionPolicySet", RetentionPolicySet ?? string.Empty), new XAttribute("ExtractedTo", ExtractedTo ?? string.Empty), new XAttribute("CustomInstallationDirectory", CustomInstallationDirectory ?? string.Empty), new XAttribute("WasSuccessful", WasSuccessful.ToString()), Packages.Select(pkg => pkg.ToXmlElement()) ); } static DateTime ParseDate(string? s) { DateTime value; if (s != null && (DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out value) || DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentUICulture, DateTimeStyles.AssumeUniversal, out value) || DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal, out value) || DateTime.TryParseExact(s, "yyyy-MM-dd HH.mm.ss", CultureInfo.CurrentUICulture, DateTimeStyles.AssumeUniversal, out value))) return value; throw new Exception(string.Format("Could not parse date from '{0}'", s)); } static bool? ParseBool(string? s) { if (!string.IsNullOrWhiteSpace(s) && bool.TryParse(s, out var b)) return b; return null; } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Amazon.CloudFormation; using Calamari.Aws.Deployment; using Calamari.Aws.Deployment.Conventions; using Calamari.Aws.Integration; using Calamari.Aws.Integration.CloudFormation; using Calamari.Aws.Util; using Calamari.CloudAccounts; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Integration.Processes; namespace Calamari.Aws.Commands { [Command("delete-aws-cloudformation", Description = "Destroy an existing AWS CloudFormation stack")] public class DeleteCloudFormationCommand : Command { readonly ILog log; readonly IVariables variables; private string packageFile; private bool waitForComplete; public DeleteCloudFormationCommand(ILog log, IVariables variables) { this.log = log; this.variables = variables; Options.Add("package=", "Path to the NuGet package to install.", v => packageFile = Path.GetFullPath(v)); Options.Add("waitForCompletion=", "True if the deployment process should wait for the stack to complete, and False otherwise.", v => waitForComplete = !bool.FalseString.Equals(v, StringComparison.OrdinalIgnoreCase)); //True by default } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); var environment = AwsEnvironmentGeneration.Create(log, variables).GetAwaiter().GetResult();; var stackEventLogger = new StackEventLogger(log); IAmazonCloudFormation ClientFactory () => ClientHelpers.CreateCloudFormationClient(environment); StackArn StackProvider (RunningDeployment x) => new StackArn( x.Variables.Get(AwsSpecialVariables.CloudFormation.StackName)); var conventions = new List<IConvention> { new LogAwsUserInfoConvention(environment), new DeleteCloudFormationStackConvention(environment, stackEventLogger, ClientFactory, StackProvider, waitForComplete) }; var deployment = new RunningDeployment(packageFile, variables); var conventionRunner = new ConventionProcessor(deployment, conventions, log); conventionRunner.RunConventions(); return 0; } } }<file_sep>namespace Calamari.Commands.Support { public interface ICommandWithArgs { int Execute(string[] commandLineArguments); } }<file_sep>using System; using System.IO; namespace Calamari.Testing.Helpers { public static class TestEnvironment { public static readonly string AssemblyLocalPath = typeof(TestEnvironment).Assembly.FullLocalPath(); public static readonly string CurrentWorkingDirectory = Path.GetDirectoryName(AssemblyLocalPath); public static readonly bool IsCI = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION")); public static string GetTestPath(params string[] paths) { return Path.Combine(CurrentWorkingDirectory, Path.Combine(paths)); } public static string ConstructRootedPath(params string[] paths) { return Path.Combine(Path.GetPathRoot(CurrentWorkingDirectory), Path.Combine(paths)); } } } <file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Terraform.Tests { public class TerraformCliExecutorFixture { IVariables variables; TerraformCliExecutor cliExecutor; [SetUp] public void Setup() { variables = Substitute.For<IVariables>(); var commandLineRunner = Substitute.For<ICommandLineRunner>(); commandLineRunner.Execute(Arg.Do<CommandLineInvocation>(invocation => invocation.AdditionalInvocationOutputSink.WriteInfo("Terraform v0.15.0"))) .Returns(new CommandResult("foo", 0)); cliExecutor = new TerraformCliExecutor(Substitute.For<ILog>(), Substitute.For<ICalamariFileSystem>(), commandLineRunner, new RunningDeployment("blah", variables), new Dictionary<string, string>()); } [Test] public void TerraformVariableFiles_Null() { variables.Get(TerraformSpecialVariables.Action.Terraform.VarFiles).Returns((string)null); cliExecutor.TerraformVariableFiles.Should().BeNull(); } [Test] public void TerraformVariableFiles_SingleLine() { variables.Get(TerraformSpecialVariables.Action.Terraform.VarFiles).Returns("foo"); cliExecutor.TerraformVariableFiles.Should().Be("-var-file=\"foo\""); } [Test] public void TerraformVariableFiles_MultiLine() { variables.Get(TerraformSpecialVariables.Action.Terraform.VarFiles).Returns("foo\nbar\r\nbaz"); cliExecutor.TerraformVariableFiles.Should().Be("-var-file=\"foo\" -var-file=\"bar\" -var-file=\"baz\""); } } }<file_sep>using System; using System.IO; using System.Reflection; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Extensions; using Octostache.Templates; namespace Calamari.Common.Plumbing.Logging { public class ConsoleFormatter { public static int PrintError(ILog log, Exception ex) { if (ex is CommandException) { log.Error(ex.Message); return ExitStatus.CommandExceptionError; } if (ex is RecursiveDefinitionException) //dont log these - they have already been logged earlier return ExitStatus.RecursiveDefinitionExceptionError; if (ex is ReflectionTypeLoadException) { log.Error(ex.ToString()); foreach (var loaderException in ((ReflectionTypeLoadException)ex).LoaderExceptions) { log.Error(loaderException.ToString()); if (!(loaderException is FileNotFoundException)) continue; var exFileNotFound = loaderException as FileNotFoundException; if (!string.IsNullOrEmpty(exFileNotFound?.FusionLog)) log.Error(exFileNotFound.FusionLog); } return ExitStatus.ReflectionTypeLoadExceptionError; } log.Error(ex.PrettyPrint()); return ExitStatus.OtherError; } } }<file_sep>#!/bin/bash TRUE=0 FALSE=1 SUCCESS=0 # This selector will identify old resources based on the step, environment and tenant ids. This is how # we originally identified resources, but it was not sufficiently unique. However existing # deployments have these labels, and so we retain this query for compatibility. # Note the absence of the Octopus.Kubernetes.SelectionStragegyVersion label identifies this label set # as the V1 set. SELECTOR_V1="!Octopus.Kubernetes.SelectionStrategyVersion,Octopus.Step.Id=#{Octopus.Step.Id},Octopus.Environment.Id=#{Octopus.Environment.Id | ToLower},Octopus.Deployment.Tenant.Id=#{unless Octopus.Deployment.Tenant.Id}untenanted#{/unless}#{if Octopus.Deployment.Tenant.Id}#{Octopus.Deployment.Tenant.Id | ToLower}#{/if},Octopus.Deployment.Id!=#{Octopus.Deployment.Id | ToLower}" # This selector takes the project and action ID into account to address https://github.com/OctopusDeploy/Issues/issues/5185. SELECTOR_V2="Octopus.Kubernetes.SelectionStrategyVersion=SelectionStrategyVersion2,Octopus.Project.Id=#{Octopus.Project.Id | ToLower},Octopus.Step.Id=#{Octopus.Step.Id | ToLower},Octopus.Action.Id=#{Octopus.Action.Id | ToLower},Octopus.Environment.Id=#{Octopus.Environment.Id | ToLower},Octopus.Deployment.Tenant.Id=#{unless Octopus.Deployment.Tenant.Id}untenanted#{/unless}#{if Octopus.Deployment.Tenant.Id}#{Octopus.Deployment.Tenant.Id | ToLower}#{/if},Octopus.Deployment.Id!=#{Octopus.Deployment.Id | ToLower}" # This selector is used when K8S steps are called from runbooks. Note that runbooks don't have an Octopus.Deployment.Id # variable, so we use the Octopus.RunbookRun.Id instead. SELECTOR_RUNBOOK_V2="Octopus.Kubernetes.SelectionStrategyVersion=SelectionStrategyVersion2,Octopus.Project.Id=#{Octopus.Project.Id | ToLower},Octopus.Step.Id=#{Octopus.Step.Id | ToLower},Octopus.Action.Id=#{Octopus.Action.Id | ToLower},Octopus.Environment.Id=#{Octopus.Environment.Id | ToLower},Octopus.Deployment.Tenant.Id=#{unless Octopus.Deployment.Tenant.Id}untenanted#{/unless}#{if Octopus.Deployment.Tenant.Id}#{Octopus.Deployment.Tenant.Id | ToLower}#{/if},Octopus.RunbookRun.Id!=#{Octopus.RunbookRun.Id | ToLower}" RESOURCE_TYPE=`get_octopusvariable "Octopus.Action.KubernetesContainers.DeploymentResourceType"` if [[ -z $RESOURCE_TYPE ]]; then RESOURCE_TYPE="Deployment" fi Kubectl_Exe=`get_octopusvariable "Octopus.Action.Kubernetes.CustomKubectlExecutable"` Deployment_Id=`get_octopusvariable "Octopus.Deployment.Id"` if [[ -z $Kubectl_Exe ]]; then Kubectl_Exe="kubectl" fi function is_bluegreen { Deployment_Style="#{Octopus.Action.KubernetesContainers.DeploymentStyle}" if [[ ${Deployment_Style,,} == "bluegreen" ]]; then return $TRUE else return $FALSE fi } function is_notondelete { Deployment_Style="#{Octopus.Action.KubernetesContainers.DeploymentStyle}" if [[ ${Deployment_Style,,} != "ondelete" ]]; then return $TRUE else return $FALSE fi } function is_waitfordeployment { Deployment_Wait="#{Octopus.Action.KubernetesContainers.DeploymentWait}" if [[ ${Deployment_Wait,,} == "wait" ]]; then return $TRUE else return $FALSE fi } function write_plainerror { defaultIFS=$IFS IFS= echo "##octopus[stdout-error]" for line in $1; do echo "$line" done echo "##octopus[stdout-default]" IFS=$defaultIFS } function write_verbose { defaultIFS=$IFS IFS= echo "##octopus[stdout-verbose]" for line in $1; do echo "$line" done echo "##octopus[stdout-default]" IFS=$defaultIFS } function check_app_exists { command -v $1 > /dev/null 2>&1 if [[ $? -ne 0 ]]; then write_plainerror "The $1 application must be installed" SUCCESS=$FALSE fi } function file_exists { if [[ ! -f $1 ]]; then return $FALSE else FileContents=`cat $1` if [[ -z "$FileContents" ]]; then return $FALSE else return $TRUE fi fi } function deploy_feed_secrets { if [[ $SUCCESS -eq $TRUE ]]; then if file_exists secret.yml; then write_verbose "$(cat secret.yml)" ${Kubectl_Exe} apply -f secret.yml SUCCESS=$? IFS="," read -ra Secrets <<< "#{Octopus.Action.KubernetesContainers.SecretNames}" for Secret in "${Secrets[@]}"; do if [[ ! -z "$Secret" ]]; then set_octopusvariable "Secret(${Secret})" "$(${Kubectl_Exe} get secret ${Secret} -o=json 2> /dev/null)" fi done fi fi } function deploy_configmap { if [[ $SUCCESS -eq $TRUE ]]; then if [[ $(get_octopusvariable "Octopus.Action.KubernetesContainers.KubernetesConfigMapEnabled") == *"True"* ]]; then ConfigMapDataFileArgs=() # Each config map item is in its own file. The file name is stored in a variable: Octopus.Action.KubernetesContainers.ConfigMapData[key].FileName #{each ConfigMapData in Octopus.Action.KubernetesContainers.ConfigMapData } ConfigMapDataFileArgs+=('--from-file=#{ConfigMapData}=#{ConfigMapData.FileName}') #{/each} if [[ ${#ConfigMapDataFileArgs[@]} -gt 0 ]]; then ${Kubectl_Exe} get configmap "#{Octopus.Action.KubernetesContainers.ComputedConfigMapName}" > /dev/null 2>&1 if [[ $? -eq 0 ]]; then write_verbose "${Kubectl_Exe} delete configmap \"#{Octopus.Action.KubernetesContainers.ComputedConfigMapName}\"" ${Kubectl_Exe} delete configmap "#{Octopus.Action.KubernetesContainers.ComputedConfigMapName}" fi write_verbose "${Kubectl_Exe} create configmap \"#{Octopus.Action.KubernetesContainers.ComputedConfigMapName}\" ${ConfigMapDataFileArgs[*]}" printf "%s\n" "${ConfigMapDataFileArgs[@]}" | \ xargs ${Kubectl_Exe} create configmap "#{Octopus.Action.KubernetesContainers.ComputedConfigMapName}" if [[ ! -z "#{Octopus.Action.KubernetesContainers.ComputedLabels}" ]]; then echo $(get_octopusvariable "Octopus.Action.KubernetesContainers.ComputedLabels") | \ jq --arg q '"' -r '. | keys[] as $k | "\($q)\($k)=\(.[$k])\($q) "' | \ xargs $Kubectl_Exe label --overwrite configmap "#{Octopus.Action.KubernetesContainers.ComputedConfigMapName}" fi SUCCESS=$? set_octopusvariable "ConfigMap" $($Kubectl_Exe get configmap "#{Octopus.Action.KubernetesContainers.ComputedConfigMapName}" -o=json) fi fi fi } function deploy_secret { if [[ $SUCCESS -eq $TRUE ]]; then if [[ $(get_octopusvariable "Octopus.Action.KubernetesContainers.KubernetesSecretEnabled") == *"True"* ]]; then SecretDataFileArgs=() # Each secret item is in its own file. The file name is stored in a variable: Octopus.Action.KubernetesContainers.SecretData[key].FileName #{each SecretData in Octopus.Action.KubernetesContainers.SecretData } SecretDataFileArgs+=('--from-file=#{SecretData}=#{SecretData.FileName}') #{/each} if [[ ${#SecretDataFileArgs[@]} -gt 0 ]]; then ${Kubectl_Exe} get secret "#{Octopus.Action.KubernetesContainers.ComputedSecretName}" > /dev/null 2>&1 if [[ $? -eq 0 ]]; then write_verbose "${Kubectl_Exe} delete secret \"#{Octopus.Action.KubernetesContainers.ComputedSecretName}\"" ${Kubectl_Exe} delete secret "#{Octopus.Action.KubernetesContainers.ComputedSecretName}" fi write_verbose "${Kubectl_Exe} create secret generic \"#{Octopus.Action.KubernetesContainers.ComputedSecretName}\" ${SecretDataFileArgs[*]}" printf "%s\n" "${SecretDataFileArgs[@]}" | \ xargs ${Kubectl_Exe} create secret generic "#{Octopus.Action.KubernetesContainers.ComputedSecretName}" if [[ ! -z "#{Octopus.Action.KubernetesContainers.ComputedLabels}" ]]; then echo $(get_octopusvariable "Octopus.Action.KubernetesContainers.ComputedLabels") | \ jq --arg q '"' -r '. | keys[] as $k | "\($q)\($k)=\(.[$k])\($q) "' | \ xargs $Kubectl_Exe label --overwrite secret "#{Octopus.Action.KubernetesContainers.ComputedSecretName}" fi SUCCESS=$? set_octopusvariable "Secret" $($Kubectl_Exe get secret "#{Octopus.Action.KubernetesContainers.ComputedSecretName}" -o=json) fi fi fi } function deploy_customresources { if file_exists "#{Octopus.Action.KubernetesContainers.CustomResourceYamlFileName}"; then if [[ $SUCCESS -eq $TRUE ]]; then write_verbose "$(cat "#{Octopus.Action.KubernetesContainers.CustomResourceYamlFileName}")" newCustomResources=$(${Kubectl_Exe} apply -f "#{Octopus.Action.KubernetesContainers.CustomResourceYamlFileName}" -o json) SUCCESS=$? if [[ $SUCCESS -eq $TRUE ]]; then # kubectl apply will return a list if multiple resources were applied, or a single object. # We can distinguish between the two by the "kind" of the returned value kind=$(jq -r '.kind' <<< $newCustomResources) fi # It is possible kubectl didn't return valid JSON if [[ $SUCCESS -eq $TRUE ]] && [[ $? -eq 0 ]]; then if [[ "$kind" == "List" ]]; then # Get a list of the names and kinds of the created resources newCustomResources=$(jq -r '.items[]? | "\(.metadata.name):\(.kind)"' <<< $newCustomResources) else # There is only 1 created resource newCustomResources=$(jq -r '"\(.metadata.name):\(.kind)"' <<< $newCustomResources) fi IFS= read -ra CustomResources <<< $newCustomResources for CustomResource in "${CustomResources[@]}"; do if [[ ! -z "$CustomResource" ]]; then # Split the text on the colon to create an array customResourceSplit=(${CustomResource//:/ }) # We swallowed the result of kubectl apply, so add some logging to show something happened echo "${customResourceSplit[1]}/${customResourceSplit[0]} created" set_octopusvariable \ "CustomResources(${customResourceSplit[0]})" \ "$(${Kubectl_Exe} get ${customResourceSplit[1]} ${customResourceSplit[0]} -o=json 2> /dev/null)" fi done else write_plainerror "\"kubectl apply -o json\" returned invalid JSON:" write_plainerror "---------------------------" write_plainerror "$newCustomResources" write_plainerror "---------------------------" write_plainerror "This can happen with older versions of kubectl. Please update to a recent version of kubectl." write_plainerror "See https://github.com/kubernetes/kubernetes/issues/58834 for more details." write_plainerror "Custom resources will not be saved as output variables, and will not be automatically cleaned up." fi fi fi } function deploy_deployment { if file_exists deployment.yml; then if [[ $SUCCESS -eq $TRUE ]]; then write_verbose "$(cat deployment.yml)" ${Kubectl_Exe} apply -f deployment.yml # If doing a plain deployment, the success will be judged on the response from the last executable call SUCCESS=$? # When doing a blue/green deployment, the deployment resource created by old steps are deleted once the # new deployment is created and the service is pointed to it. if [[ $RESOURCE_TYPE != "Job" ]] && (is_bluegreen || (is_waitfordeployment && is_notondelete)); then # There can be cases where the rollout command fails when it is executed straight away, # so we need to wait for the deployment to be visible for i in `seq 1 5`; do $Kubectl_Exe get ${RESOURCE_TYPE} "#{Octopus.Action.KubernetesContainers.ComputedDeploymentName}" if [[ $? -eq 0 ]]; then break fi sleep 5 done ${Kubectl_Exe} rollout status "${RESOURCE_TYPE}/#{Octopus.Action.KubernetesContainers.ComputedDeploymentName}" # If doing a blue/green deployment, success is judged by the response of the rollout status SUCCESS=$? if [[ $SUCCESS -ne $TRUE ]]; then write_plainerror "The ${RESOURCE_TYPE} #{Octopus.Action.KubernetesContainers.ComputedDeploymentName} failed." fi fi set_octopusvariable "Deployment" "$(${Kubectl_Exe} get ${RESOURCE_TYPE} "#{Octopus.Action.KubernetesContainers.ComputedDeploymentName}" -o=json 2> /dev/null)" else write_plainerror "The ${RESOURCE_TYPE} was not created or updated." fi fi } function deploy_service { if file_exists service.yml; then if [[ $SUCCESS -eq $TRUE ]]; then write_verbose "$(cat service.yml)" ${Kubectl_Exe} apply -f service.yml SUCCESS=$? else if is_bluegreen; then write_plainerror "The service #{Octopus.Action.KubernetesContainers.ServiceName} was not updated, and does not point to the failed ${RESOURCE_TYPE}, meaning the blue/green swap was not performed." else write_plainerror "The service #{Octopus.Action.KubernetesContainers.ServiceName} was not updated." fi fi set_octopusvariable "Service" "$(${Kubectl_Exe} get service "#{Octopus.Action.KubernetesContainers.ServiceName}" -o=json 2> /dev/null)" fi } function deploy_ingress { if file_exists ingress.yml; then if [[ $SUCCESS -eq $TRUE ]]; then write_verbose "$(cat ingress.yml)" ${Kubectl_Exe} apply -f ingress.yml SUCCESS=$? else write_plainerror "The ingress rules for #{Octopus.Action.KubernetesContainers.IngressName} were not updated." fi set_octopusvariable "Ingress" "$(${Kubectl_Exe} get ingress "#{Octopus.Action.KubernetesContainers.IngressName}" -o=json 2> /dev/null)" fi } # When doing a blue/green deployment, the deployment resource created by old steps are deleted once the # new deployment is created and the service is pointed to it. function clean_deployment { if file_exists deployment.yml; then if [[ $SUCCESS -eq $TRUE ]]; then if is_bluegreen; then echo "Deleting old ${RESOURCE_TYPE}s" if [[ ! -z ${Deployment_Id} ]]; then ${Kubectl_Exe} delete ${RESOURCE_TYPE} -l ${SELECTOR_V1} ${Kubectl_Exe} delete ${RESOURCE_TYPE} -l ${SELECTOR_V2} else ${Kubectl_Exe} delete ${RESOURCE_TYPE} -l ${SELECTOR_RUNBOOK_V2} fi SUCCESS=$? fi else write_plainerror "The previous ${RESOURCE_TYPE}s were not removed." fi fi } # The config map resource created by old steps are deleted once the # new deployment is created and the service is pointed to it. function clean_configmap { if file_exists deployment.yml; then if [[ $SUCCESS -eq $TRUE ]]; then echo "Deleting old ConfigMaps" if [[ ! -z ${Deployment_Id} ]]; then $Kubectl_Exe delete configmap -l ${SELECTOR_V1} $Kubectl_Exe delete configmap -l ${SELECTOR_V2} else $Kubectl_Exe delete configmap -l ${SELECTOR_RUNBOOK_V2} fi SUCCESS=$? else write_plainerror "The previous config maps were not removed." fi fi } # The secret resource created by old steps are deleted once the # new deployment is created and the service is pointed to it. function clean_secret { if file_exists deployment.yml; then if [[ $SUCCESS -eq $TRUE ]]; then echo "Deleting old Secrets" if [[ ! -z ${Deployment_Id} ]]; then $Kubectl_Exe delete secret -l ${SELECTOR_V1} $Kubectl_Exe delete secret -l ${SELECTOR_V2} else $Kubectl_Exe delete secret -l ${SELECTOR_RUNBOOK_V2} fi SUCCESS=$? else write_plainerror "The previous secrets were not removed." fi fi } function clean_customresources { if [[ $SUCCESS -eq $TRUE ]]; then if [[ ! -z $newCustomResources ]]; then if file_exists deployment.yml; then IFS= read -ra CustomResources <<< $newCustomResources for CustomResource in "${CustomResources[@]}"; do if [[ ! -z "${CustomResource}" ]]; then # Split the text on the colon to create an array customResourceSplit=(${CustomResource//:/ }) if [[ ! -z "${customResourceSplit[1]}" ]]; then echo "Deleting old ${customResourceSplit[1]} resources" if [[ ! -z ${Deployment_Id} ]]; then $Kubectl_Exe delete ${customResourceSplit[1]} -l ${SELECTOR_V1} $Kubectl_Exe delete ${customResourceSplit[1]} -l ${SELECTOR_V2} else $Kubectl_Exe delete ${customResourceSplit[1]} -l ${SELECTOR_RUNBOOK_V2} fi if [[ $SUCCESS -eq $TRUE ]]; then SUCCESS=$? fi fi fi done fi fi else write_plainerror "The previous custom resources were not removed." fi } function write_failuremessage { if [[ $SUCCESS -ne $TRUE ]]; then write_plainerror "The deployment process failed. The resources created by this step will be passed to \"kubectl describe\" and logged below." if file_exists deployment.yml; then echo "The Deployment resource description: $Kubectl_Exe describe ${RESOURCE_TYPE} #{Octopus.Action.KubernetesContainers.ComputedDeploymentName}" $Kubectl_Exe describe ${RESOURCE_TYPE} "#{Octopus.Action.KubernetesContainers.ComputedDeploymentName}" # Get the first 10 non-running pods. A deployment could be hundreds of pods, so we don't want to spend time # describing them all. kubectl get replicasets -o json | jq -r '.items[]? | select(.metadata.ownerReferences[]? | select(.name == "#{Octopus.Action.KubernetesContainers.ComputedDeploymentName}" and .kind == "Deployment")) | .metadata.name' | \ xargs -I{} -n 1 sh -c "kubectl get pods -o json | jq -r '.items[]? | select(.metadata.ownerReferences[]? | select(.name == \"{}\" and .kind == \"ReplicaSet\")) | select (.status.phase != \"Running\") | .metadata.name'" | \ head -n 10 | \ xargs -I{} -n 1 sh -c "echo \"The Pod resource description: $Kubectl_Exe describe pod {}\"; $Kubectl_Exe describe pod {}" fi if file_exists service.yml; then echo "The Service resource description: $Kubectl_Exe describe service #{Octopus.Action.KubernetesContainers.ServiceName}" $Kubectl_Exe describe service "#{Octopus.Action.KubernetesContainers.ServiceName}" fi if file_exists ingress.yml; then echo "The Ingress resource description: $Kubectl_Exe describe ingress #{Octopus.Action.KubernetesContainers.IngressName}" $Kubectl_Exe describe ingress "#{Octopus.Action.KubernetesContainers.IngressName}" fi if [[ $(get_octopusvariable "Octopus.Action.KubernetesContainers.KubernetesSecretEnabled") == *"True"* ]]; then echo "The Secret resource description: $Kubectl_Exe describe secret #{Octopus.Action.KubernetesContainers.ComputedSecretName}" $Kubectl_Exe describe secret "#{Octopus.Action.KubernetesContainers.ComputedSecretName}" fi if [[ $(get_octopusvariable "Octopus.Action.KubernetesContainers.KubernetesConfigMapEnabled") == *"True"* ]]; then echo "The ConfigMap resource description: $Kubectl_Exe describe configmap #{Octopus.Action.KubernetesContainers.ComputedConfigMapName}" $Kubectl_Exe describe configmap "#{Octopus.Action.KubernetesContainers.ComputedConfigMapName}" fi if file_exists "#{Octopus.Action.KubernetesContainers.CustomResourceYamlFileName}"; then IFS= read -ra CustomResources <<< $newCustomResources for CustomResource in "${CustomResources[@]}"; do if [[ ! -z "$CustomResource" ]]; then customResourceSplit=(${CustomResource//:/ }) echo "The custom resource description: $Kubectl_Exe describe ${customResourceSplit[1]} ${customResourceSplit[1]}" $Kubectl_Exe describe ${customResourceSplit[1]} ${customResourceSplit[0]} fi done fi exit 1 fi } check_app_exists jq check_app_exists xargs deploy_feed_secrets deploy_configmap deploy_secret deploy_customresources deploy_deployment deploy_service deploy_ingress clean_deployment clean_configmap clean_secret clean_customresources write_failuremessage # Kubectl can return with 1 if an apply results in no change. # https://github.com/kubernetes/kubernetes/issues/58212 # We want a clean exit here though, regardless of the last exit code. exit 0<file_sep>using System; namespace Calamari.Common.Plumbing.Pipeline { public interface IAfterPackageExtractionBehaviour: IBehaviour { } }<file_sep>using System; namespace Calamari.Common.Plumbing.Pipeline { public interface IPostDeployBehaviour: IBehaviour { } }<file_sep>using System; using System.ComponentModel; using System.IO; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.PackageRetention.Model; using Calamari.Deployment.PackageRetention.Repositories; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Integration.FileSystem; using Calamari.Tests.Fixtures.PackageRetention.Repository; using Calamari.Tests.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; using Octopus.Versioning; namespace Calamari.Tests.Fixtures.PackageRetention { [TestFixture] public class JsonJournalRepositoryFixture { readonly string testDir = TestEnvironment.GetTestPath("Fixtures", "JsonJournalRepository"); [SetUp] public void SetUp() { if (!Directory.Exists(testDir)) Directory.CreateDirectory(testDir); } [TearDown] public void TearDown() { if (Directory.Exists(testDir)) Directory.Delete(testDir, true); } static PackageIdentity CreatePackageIdentity(string packageId, string packageVersion) { var version = VersionFactory.CreateSemanticVersion(packageVersion); return new PackageIdentity(new PackageId(packageId), version, new PackagePath($"C:\\{packageId}.{packageVersion}.zip")); } [Test] public void WhenAJournalEntryIsCommittedAndRetrieved_ThenItShouldBeEquivalentToTheOriginal() { var journalPath = Path.Combine(testDir, "PackageRetentionJournal.json"); var thePackage = CreatePackageIdentity("TestPackage", "0.0.1"); var cacheAge = new CacheAge(10); var serverTaskId = new ServerTaskId("TaskID-1"); var journalEntry = new JournalEntry(thePackage, 1); journalEntry.AddLock(serverTaskId, cacheAge); journalEntry.AddUsage(serverTaskId, cacheAge); var writeRepository = new JsonJournalRepository(TestCalamariPhysicalFileSystem.GetPhysicalFileSystem(), new StaticJsonJournalPathProvider(journalPath), Substitute.For<ILog>()); writeRepository.AddJournalEntry(journalEntry); writeRepository.Commit(); var readRepository = new JsonJournalRepository(TestCalamariPhysicalFileSystem.GetPhysicalFileSystem(), new StaticJsonJournalPathProvider(journalPath), Substitute.For<ILog>()); readRepository.Load(); readRepository.TryGetJournalEntry(thePackage, out var retrieved).Should().BeTrue(); retrieved.Package.Should().BeEquivalentTo(journalEntry.Package); retrieved.GetLockDetails().Should().BeEquivalentTo(journalEntry.GetLockDetails()); retrieved.GetUsageDetails().Should().BeEquivalentTo(journalEntry.GetUsageDetails()); } [Test] public void WhenThereIsAnErrorReadingTheJournal_ThenTheJournalIsRenamed() { const string invalidJson = @"[{""a"",}]"; var journalPath = Path.Combine(testDir, "PackageRetentionJournal.json"); File.WriteAllText(journalPath, invalidJson); var variables = new CalamariVariables(); variables.Set(KnownVariables.Calamari.PackageRetentionJournalPath, journalPath); var journal = new JsonJournalRepository(TestCalamariPhysicalFileSystem.GetPhysicalFileSystem(), new StaticJsonJournalPathProvider(journalPath), Substitute.For<ILog>()); journal.Load(); Directory.GetFiles(testDir, "PackageRetentionJournal_*.json").Length.Should().Be(1); } } }<file_sep>#if !NET40 using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Calamari.Common.Plumbing.Logging; using Calamari.Kubernetes.ResourceStatus.Resources; namespace Calamari.Kubernetes.ResourceStatus { public interface IRunningResourceStatusCheck { Task<bool> WaitForCompletionOrTimeout(); Task AddResources(ResourceIdentifier[] newResources); } public class RunningResourceStatusCheck : IRunningResourceStatusCheck { public delegate IRunningResourceStatusCheck Factory( TimeSpan timeout, Options options, IEnumerable<ResourceIdentifier> initialResources); internal const string MessageDeploymentSucceeded = "Resource status check completed successfully because all resources are deployed successfully"; internal const string MessageDeploymentFailed = "Resource status check terminated with errors because some resources have failed"; internal const string MessageInProgressAtTheEndOfTimeout = "Resource status check terminated because the timeout has been reached but some resources are still in progress"; private readonly Func<ResourceStatusCheckTask> statusCheckTaskFactory; private readonly ILog log; private readonly TimeSpan timeout; private readonly Options options; private readonly SemaphoreSlim taskLock = new SemaphoreSlim(1, 1); private readonly HashSet<ResourceIdentifier> resources = new HashSet<ResourceIdentifier>(); private CancellationTokenSource taskCancellationTokenSource; private Task<ResourceStatusCheckTask.Result> statusCheckTask; public RunningResourceStatusCheck( Func<ResourceStatusCheckTask> statusCheckTaskFactory, ILog log, TimeSpan timeout, Options options, IEnumerable<ResourceIdentifier> initialResources) { this.statusCheckTaskFactory = statusCheckTaskFactory; this.log = log; this.timeout = timeout; this.options = options; initialResources = initialResources.ToList(); if (initialResources.Any()) { log.Verbose("Resource Status Check: Performing resource status checks on the following resources:"); log.LogResources(initialResources); } else { log.Verbose("Resource Status Check: Waiting for resources to be applied."); } statusCheckTask = RunNewStatusCheck(initialResources); } public async Task<bool> WaitForCompletionOrTimeout() { await taskLock.WaitAsync(); try { var result = await statusCheckTask; switch (result.DeploymentStatus) { case DeploymentStatus.Succeeded: log.Info(MessageDeploymentSucceeded); return true; case DeploymentStatus.InProgress: LogInProgressResources(result.ResourceStatuses); LogNotCreatedResources(result.DefinedResourceStatuses, result.DefiniedResources); log.Error(MessageInProgressAtTheEndOfTimeout); return false; case DeploymentStatus.Failed: LogFailedResources(result.ResourceStatuses); log.Error(MessageDeploymentFailed); return false; default: return false; } } finally { taskLock.Release(); } } public async Task AddResources(ResourceIdentifier[] newResources) { await taskLock.WaitAsync(); try { taskCancellationTokenSource.Cancel(); await statusCheckTask; statusCheckTask = RunNewStatusCheck(newResources); log.Verbose($"Resource Status Check: {newResources.Length} new resources have been added:"); log.LogResources(newResources); } finally { taskLock.Release(); } } private async Task<ResourceStatusCheckTask.Result> RunNewStatusCheck(IEnumerable<ResourceIdentifier> newResources) { taskCancellationTokenSource = new CancellationTokenSource(); resources.UnionWith(newResources); return await statusCheckTaskFactory() .Run(resources, options, timeout, taskCancellationTokenSource.Token); } private void LogFailedResources(Dictionary<string, Resource> resourceDictionary) { log.Verbose("Resource Status Check: The following resources have failed:"); log.LogResources(resourceDictionary.Values); } private void LogInProgressResources(Dictionary<string, Resource> resourceStatuses) { var inProgress = resourceStatuses.Values .Where(resource => resource.ResourceStatus == Resources.ResourceStatus.InProgress) .ToList(); if (inProgress.Any()) { log.Verbose("Resource Status Check: the following resources are still in progress by the end of the timeout:"); log.LogResources(inProgress); } } private void LogNotCreatedResources(Resource[] definedResourceStatuses, IEnumerable<ResourceIdentifier> definedResources) { var notCreated = definedResources.Where(definedResource => !definedResourceStatuses.Any(resource => resource.Kind == definedResource.Kind && resource.Name == definedResource.Name && resource.Namespace == definedResource.Namespace)).ToList(); if (notCreated.Any()) { log.Verbose("Resource Status Check: the following resource had not been created by the of the timeout:"); log.LogResources(notCreated); } } } } #endif<file_sep>using System; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Microsoft.Azure.Management.WebSites; using Microsoft.Rest; namespace Calamari.AzureAppService.Behaviors { class LegacyAzureAppServiceDeployContainerBehavior : IDeployBehaviour { private ILog Log { get; } public LegacyAzureAppServiceDeployContainerBehavior(ILog log) { Log = log; } public bool IsEnabled(RunningDeployment context) => !FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.IsEnabled(context.Variables); public async Task Execute(RunningDeployment context) { var variables = context.Variables; var principalAccount = ServicePrincipalAccount.CreateFromKnownVariables(variables); var webAppName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); var rgName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName); var targetSite = new AzureTargetSite(principalAccount.SubscriptionNumber, rgName, webAppName, slotName); var image = variables.Get(SpecialVariables.Action.Package.Image); var registryHost = variables.Get(SpecialVariables.Action.Package.Registry); var regUsername = variables.Get(SpecialVariables.Action.Package.Feed.Username); var regPwd = variables.Get(SpecialVariables.Action.Package.Feed.Password); var token = await Auth.GetAuthTokenAsync(principalAccount); var webAppClient = new WebSiteManagementClient(new Uri(principalAccount.ResourceManagementEndpointBaseUri), new TokenCredentials(token)) {SubscriptionId = principalAccount.SubscriptionNumber}; Log.Info($"Updating web app to use image {image} from registry {registryHost}"); Log.Verbose("Retrieving config (this is required to update image)"); var config = await webAppClient.WebApps.GetConfigurationAsync(targetSite); config.LinuxFxVersion = $@"DOCKER|{image}"; Log.Verbose("Retrieving app settings"); var appSettings = await webAppClient.WebApps.ListApplicationSettingsAsync(targetSite); appSettings.Properties["DOCKER_REGISTRY_SERVER_URL"] = "https://" + registryHost; appSettings.Properties["DOCKER_REGISTRY_SERVER_USERNAME"] = regUsername; appSettings.Properties["DOCKER_REGISTRY_SERVER_PASSWORD"] = regPwd; Log.Info("Updating app settings with container registry"); await webAppClient.WebApps.UpdateApplicationSettingsAsync(targetSite, appSettings); Log.Info("Updating configuration with container image"); await webAppClient.WebApps.UpdateConfigurationAsync(targetSite, config); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Text; using Calamari.Common.Commands; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Features.Java.Actions { public class TomcatDeployCertificateAction : JavaAction { public TomcatDeployCertificateAction(JavaRunner runner): base(runner) { } public override void Execute(RunningDeployment deployment) { var variables = deployment.Variables; var tomcatVersion = GetTomcatVersion(variables); Log.Info("Deploying certificate to Tomcat"); runner.Run("com.octopus.calamari.tomcathttps.TomcatHttpsConfig", new Dictionary<string, string>() { {"OctopusEnvironment_Java_Certificate_Variable", variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable)}, {"OctopusEnvironment_Java_Certificate_Password", variables.Get(SpecialVariables.Action.Java.JavaKeystore.Password)}, {"OctopusEnvironment_Java_Certificate_KeystoreFilename", variables.Get(SpecialVariables.Action.Java.JavaKeystore.KeystoreFilename)}, {"OctopusEnvironment_Java_Certificate_KeystoreAlias", variables.Get(SpecialVariables.Action.Java.JavaKeystore.KeystoreAlias)}, {"OctopusEnvironment_Java_Certificate_Private_Key", variables.Get(variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable) + ".PrivateKeyPem")}, {"OctopusEnvironment_Java_Certificate_Public_Key", variables.Get(variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable) + ".CertificatePem")}, {"OctopusEnvironment_Java_Certificate_Public_Key_Subject", variables.Get(variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable) + ".Subject")}, {"OctopusEnvironment_Tomcat_Certificate_Version", tomcatVersion}, {"OctopusEnvironment_Tomcat_Certificate_Default", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.Default)}, {"OctopusEnvironment_Tomcat_Certificate_Hostname", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.Hostname)}, {"OctopusEnvironment_Tomcat_Certificate_CatalinaHome", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.CatalinaHome)}, {"OctopusEnvironment_Tomcat_Certificate_CatalinaBase", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.CatalinaBase)}, {"OctopusEnvironment_Tomcat_Certificate_Port", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.Port)}, {"OctopusEnvironment_Tomcat_Certificate_Service", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.Service)}, {"OctopusEnvironment_Tomcat_Certificate_Implementation", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.Implementation)}, {"OctopusEnvironment_Tomcat_Certificate_PrivateKeyFilename", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.PrivateKeyFilename)}, {"OctopusEnvironment_Tomcat_Certificate_PublicKeyFilename", variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.PublicKeyFilename)}, }); } string GetTomcatVersion(IVariables variables) { var catalinaHome = variables.Get(SpecialVariables.Action.Java.TomcatDeployCertificate.CatalinaHome) ?? Environment.GetEnvironmentVariable("CATALINA_HOME");; var catalinaPath = Path.Combine(catalinaHome, "lib", "catalina.jar"); if (!File.Exists(catalinaPath)) { throw new CommandException("TOMCAT-HTTPS-ERROR-0018: " + $"Failed to find the file {catalinaPath} " + "http://g.octopushq.com/JavaAppDeploy#tomcat-https-error-0018"); } var version = new StringBuilder(); var versionCheck = SilentProcessRunner.ExecuteCommand(JavaRuntime.CmdPath, $"-cp \"{catalinaPath}\" org.apache.catalina.util.ServerInfo", ".", (stdOut) => { Log.Verbose(stdOut); version.AppendLine(stdOut); }, Console.Error.WriteLine); if (versionCheck.ExitCode != 0) { throw new CommandException($"Attempt to obtain tomcat version failed with exit code {versionCheck.ExitCode}."); } return version.ToString(); } } }<file_sep>using System; using Octopus.Versioning; namespace Calamari.Common.Features.Packages { public class PackageFileNameMetadata { public PackageFileNameMetadata(string packageId, IVersion version, IVersion fileVersion, string extension) { PackageId = packageId; Version = version; FileVersion = fileVersion; Extension = extension; } public string PackageId { get; } public IVersion Version { get; } public IVersion FileVersion { get; } public string Extension { get; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Commands.Options; namespace Calamari.Common.Plumbing.Commands { public class CommonOptions { internal CommonOptions(string command) { Command = command; } public string Command { get; } public List<string> RemainingArguments { get; private set; } = new List<string>(); public Variables InputVariables { get; } = new Variables(); public static CommonOptions Parse(string[] args) { if (args.Length == 0) throw new CommandException("No command to run specified as a parameter"); var command = args[0]; if (string.IsNullOrWhiteSpace(command) || command.StartsWith("-")) throw new CommandException($"The command to run '{command}' is not a valid command name"); var options = new CommonOptions(command); var set = new OptionSet() .Add("variables=", "Path to a JSON file containing variables.", v => options.InputVariables.VariablesFile = v) .Add("outputVariables=", "Base64 encoded encrypted JSON file containing output variables.", v => options.InputVariables.OutputVariablesFile = v) .Add("outputVariablesPassword=", "Password used to decrypt output-variables", v => options.InputVariables.OutputVariablesPassword = v) .Add("sensitiveVariables=", "Password protected JSON file containing sensitive-variables.", v => options.InputVariables.SensitiveVariablesFiles.Add(v)) .Add("sensitiveVariablesPassword=", "Password used to decrypt sensitive-variables.", v => options.InputVariables.SensitiveVariablesPassword = v); options.RemainingArguments = set.Parse(args.Skip(1)); return options; } public class Variables { public string? VariablesFile { get; internal set; } public List<string> SensitiveVariablesFiles { get; } = new List<string>(); public string? SensitiveVariablesPassword { get; internal set; } public string? OutputVariablesFile { get; internal set; } public string? OutputVariablesPassword { get; internal set; } } } }<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; using Hyak.Common; using Microsoft.WindowsAzure.Management.Compute; namespace Calamari.AzureCloudService { [Command("health-check", Description = "Run a health check on a DeploymentTargetType")] public class HealthCheckCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<HealthCheckBehaviour>(); } } class HealthCheckBehaviour : IDeployBehaviour { public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment context) { var account = new AzureAccount(context.Variables); var cloudServiceName = context.Variables.Get(SpecialVariables.Action.Azure.CloudServiceName); var certificate = CalamariCertificateStore.GetOrAdd(account.CertificateThumbprint, account.CertificateBytes); using (var azureClient = account.CreateComputeManagementClient(certificate)) { try { await azureClient.HostedServices.GetAsync(cloudServiceName); } catch (CloudException e) { if (e.Error.Code == "ResourceNotFound") { throw new Exception($"Hosted service with name {cloudServiceName} was not found."); } throw; } } } } }<file_sep>using System; using Calamari.Common.Plumbing.Retry; namespace Calamari.AzureWebApp.Util { static class AzureRetryTracker { /// <summary> /// For azure operations, try again after 1s then 2s, 4s etc... /// </summary> static readonly LimitedExponentialRetryInterval RetryIntervalForAzureOperations = new LimitedExponentialRetryInterval(1000, 30000, 2); public static RetryTracker GetDefaultRetryTracker() { return new RetryTracker(maxRetries: 3, timeLimit: TimeSpan.MaxValue, retryInterval: RetryIntervalForAzureOperations); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.DotnetScript { public static class DotnetScriptBootstrapper { static readonly string BootstrapScriptTemplate; static readonly string SensitiveVariablePassword = <PASSWORD>(16); static readonly AesEncryption VariableEncryptor = new AesEncryption(SensitiveVariablePassword); static readonly ICalamariFileSystem CalamariFileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); static DotnetScriptBootstrapper() { BootstrapScriptTemplate = EmbeddedResource.ReadEmbeddedText(typeof(DotnetScriptBootstrapper).Namespace + ".Bootstrap.csx"); } public static string FindExecutable() { if (ScriptingEnvironment.IsNetFramework()) throw new CommandException("dotnet-script requires .NET Core 6 or later"); var exeName = $"dotnet-script.{(CalamariEnvironment.IsRunningOnWindows ? "cmd" : "dll")}"; var myPath = typeof(DotnetScriptExecutor).Assembly.Location; var parent = Path.GetDirectoryName(myPath); var executable = Path.GetFullPath(Path.Combine(parent, "dotnet-script", exeName)); if (File.Exists(executable)) return executable; throw new CommandException(string.Format("dotnet-script was not found at '{0}'", executable)); } public static string FormatCommandArguments(string bootstrapFile, string? scriptParameters) { scriptParameters = RetrieveParameterValues(scriptParameters); var encryptionKey = Convert.ToBase64String(AesEncryption.GetEncryptionKey(SensitiveVariablePassword)); var commandArguments = new StringBuilder(); commandArguments.Append("-s https://api.nuget.org/v3/index.json "); commandArguments.AppendFormat("\"{0}\" -- {1} \"{2}\"", bootstrapFile, scriptParameters, encryptionKey); return commandArguments.ToString(); } [return: NotNullIfNotNull("scriptParameters")] static string? RetrieveParameterValues(string? scriptParameters) { return scriptParameters?.Trim() .TrimStart('-') .Trim(); } public static (string bootstrapFile, string[] temporaryFiles) PrepareBootstrapFile(string scriptFilePath, string configurationFile, string workingDirectory, IVariables variables) { var bootstrapFile = Path.Combine(workingDirectory, "Bootstrap." + Guid.NewGuid().ToString().Substring(10) + "." + Path.GetFileName(scriptFilePath)); var scriptModulePaths = PrepareScriptModules(variables, workingDirectory).ToArray(); using (var file = new FileStream(bootstrapFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.UTF8)) { writer.WriteLine("#load \"" + configurationFile.Replace("\\", "\\\\") + "\""); writer.WriteLine("#load \"" + scriptFilePath.Replace("\\", "\\\\") + "\""); writer.Flush(); } File.SetAttributes(bootstrapFile, FileAttributes.Hidden); return (bootstrapFile, scriptModulePaths); } static IEnumerable<string> PrepareScriptModules(IVariables variables, string workingDirectory) { foreach (var variableName in variables.GetNames().Where(ScriptVariables.IsLibraryScriptModule)) if (ScriptVariables.GetLibraryScriptModuleLanguage(variables, variableName) == ScriptSyntax.CSharp) { var libraryScriptModuleName = ScriptVariables.GetLibraryScriptModuleName(variableName); var name = new string(libraryScriptModuleName.Where(char.IsLetterOrDigit).ToArray()); var moduleFileName = $"{name}.csx"; var moduleFilePath = Path.Combine(workingDirectory, moduleFileName); Log.VerboseFormat("Writing script module '{0}' as c# module {1}. Import this module via `#load \"{1}\"`.", libraryScriptModuleName, moduleFileName, name); var contents = variables.Get(variableName); if (contents == null) throw new InvalidOperationException($"Value for variable {variableName} could not be found."); CalamariFileSystem.OverwriteFile(moduleFilePath, contents, Encoding.UTF8); yield return moduleFileName; } } public static string PrepareConfigurationFile(string workingDirectory, IVariables variables) { var configurationFile = Path.Combine(workingDirectory, "Configure." + Guid.NewGuid().ToString().Substring(10) + ".csx"); var builder = new StringBuilder(BootstrapScriptTemplate); builder.Replace("/*{{VariableDeclarations}}*/", WriteVariableDictionary(variables)); using (var file = new FileStream(configurationFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.UTF8)) { writer.Write(builder.ToString()); writer.Flush(); } File.SetAttributes(configurationFile, FileAttributes.Hidden); return configurationFile; } static string WriteVariableDictionary(IVariables variables) { var builder = new StringBuilder(); foreach (var variable in variables.GetNames()) { var variableValue = EncryptVariable(variables.Get(variable)); builder.Append("\t\t\tthis[").Append(EncodeValue(variable)).Append("] = ").Append(variableValue).AppendLine(";"); } return builder.ToString(); } static string EncodeValue(string value) { if (value == null) return "null;"; var bytes = Encoding.UTF8.GetBytes(value); return $"System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(\"{Convert.ToBase64String(bytes)}\"))"; } static string EncryptVariable(string? value) { if (value == null) return "null;"; var encrypted = VariableEncryptor.Encrypt(value); var rawEncrypted = AesEncryption.ExtractIV(encrypted, out var iv); return $@"DecryptString(""{Convert.ToBase64String(rawEncrypted)}"", ""{Convert.ToBase64String(iv)}"")"; } } }<file_sep>using Newtonsoft.Json; namespace Calamari.Kubernetes.ResourceStatus.Resources { // subset of: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.26/#ingressrule-v1-networking-k8s-io public class IngressRule { [JsonProperty("host")] public string Host { get; set; } } } <file_sep>using System.IO; using System.Runtime.InteropServices; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Tests.Helpers { public class CodeGenerator { public static string GenerateConsoleApplication(string projectName, string destinationFolder) { var projectPath = Directory.CreateDirectory(Path.Combine(destinationFolder, projectName)); CommandLineInvocation CreateCommandLineInvocation(string executable, string arguments) { return new CommandLineInvocation(executable, arguments) { OutputToLog = false, WorkingDirectory = projectPath.FullName }; } var clr = new CommandLineRunner(ConsoleLog.Instance, new CalamariVariables()); File.WriteAllText(Path.Combine(projectPath.FullName, "global.json"), @"{ ""sdk"": { ""version"": ""6.0.10"", ""rollForward"": ""latestFeature"" } }"); var result = clr.Execute(CreateCommandLineInvocation("dotnet", "new console -f net6.0")); result.VerifySuccess(); var programCS = Path.Combine(projectPath.FullName, "Program.cs"); var newProgram = $@"using System; class Program {{ static void Main(string[] args) {{ Console.WriteLine($""Hello from my custom {projectName}!""); Console.Write(String.Join(Environment.NewLine, args)); }} }}"; var architecture = RuntimeInformation.ProcessArchitecture; var rid = "win-x64"; if (CalamariEnvironment.IsRunningOnMac) { rid = "osx-x64"; } else if (CalamariEnvironment.IsRunningOnNix) { rid = "linux-x64"; } if (architecture == Architecture.Arm) { rid = "linux-arm"; } if (architecture == Architecture.Arm64) { rid = "linux-arm64"; } File.WriteAllText(programCS, newProgram); var outputPath = Path.Combine(projectPath.FullName, "output"); result = clr.Execute(CreateCommandLineInvocation("dotnet", $"publish -o {outputPath} -r {rid}")); result.VerifySuccess(); return outputPath; } } }<file_sep>import base64 import os.path import sys import binascii from Crypto.Cipher import AES unpad = lambda s: s[:-s[-1]] def encode(value): return base64.b64encode(value.encode('utf-8')).decode('utf-8') def decode(value): return base64.b64decode(value).decode('utf-8') def decrypt(encrypted, iv): key = sys.argv[len(sys.argv) - 1] key = binascii.unhexlify(key) iv = binascii.unhexlify(iv) cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = unpad(cipher.decrypt(base64.b64decode(encrypted))) return decrypted.decode('utf-8') def get_octopusvariable(key): return octopusvariables.get(key, "") def set_octopusvariable(name, value, sensitive=False): octopusvariables[name] = value name = encode(name) value = encode(value) if sensitive: print("##octopus[setVariable name='{0}' value='{1}' sensitive='{2}']".format(name, value, encode("True"))) else: print("##octopus[setVariable name='{0}' value='{1}']".format(name, value)) def createartifact(path, fileName = None): if fileName is None: fileName = os.path.basename(path) serviceFileName = encode(fileName) length = str(os.stat(path).st_size) if os.path.isfile(path) else "0" length = encode(length) path = os.path.abspath(path) servicepath = encode(path) print("##octopus[stdout-verbose]"); print("Artifact {0} will be collected from {1} after this step completes".format(fileName, path)) print("##octopus[stdout-default]"); print("##octopus[createArtifact path='{0}' name='{1}' length='{2}']".format(servicepath, serviceFileName, length)) def updateprogress(progress, message=None): encodedProgress = encode(str(progress)) encodedMessage = encode(message) print("##octopus[progress percentage='{0}' message='{1}']".format(encodedProgress, encodedMessage)) def failstep(message=None): if message is not None: encodedMessage = encode(message) print("##octopus[resultMessage message='{}']".format(encodedMessage)) exit(-1) def printverbose(message): print("##octopus[stdout-verbose]") print(message) print("##octopus[stdout-default]") def printhighlight(message): print("##octopus[stdout-highlight]") print(message) print("##octopus[stdout-default]") def printwait(message): print("##octopus[stdout-wait]") print(message) print("##octopus[stdout-default]") def printwarning(message): print("##octopus[stdout-warning]") print(message) print("##octopus[stdout-default]") printverbose(sys.version) {{VariableDeclarations}}<file_sep>using System; namespace Calamari.Common.Plumbing.Retry { /// <summary> /// Implements a linear backoff interval as retryCount * retryInterval /// </summary> public class LinearRetryInterval : RetryInterval { readonly TimeSpan retryInterval; public LinearRetryInterval(TimeSpan retryInterval) { this.retryInterval = retryInterval; } public override TimeSpan GetInterval(int retryCount) { return TimeSpan.FromMilliseconds((int)retryInterval.TotalMilliseconds * retryCount); } } }<file_sep>using System; using System.Collections.Generic; using Amazon.Runtime; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.Logging; namespace Calamari.Aws.Kubernetes.Discovery { public class AwsAuthenticationDetails : ITargetDiscoveryAuthenticationDetails { const string DefaultSessionName = "OctopusKubernetesClusterDiscovery"; /// <exception cref="AggregateException"> /// If both InstanceProfile and EnvironmentVariable Credentials fail. /// Contains AmazonClientExceptions for both InstanceProfile and EnvironmentVariable failures</exception> /// <exception cref="AmazonClientException">If Basic (Account) Credentials fail</exception> public bool TryGetCredentials(ILog log, out AWSCredentials credentials) { credentials = null; if (Credentials.Type == "account") { try { credentials = new BasicAWSCredentials(Credentials.Account.AccessKey, Credentials.Account.SecretKey); } // Catching a generic Exception because AWS SDK throws undocumented exceptions. catch (Exception e) { log.Warn("Unable to authorise credentials, see verbose log for details."); log.Verbose($"Unable to authorise credentials for Account: {e}"); return false; } } else { // The sequence of fallbacks trying to log in with credentials exposed by the worker. // This follows the precedence document at https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-precedence if (!(TryGetEnvironmentVariablesAwsCredentials(log, out credentials) || TryGetAssumeRoleWithWebIdentityCredentials(log, out credentials) || TryGetInstanceProfileAwsCredentials(log, out credentials))) { log.Warn("Unable to authorise credentials, see verbose log for details."); return false; } } if (Role.Type == "assumeRole") { credentials = new AssumeRoleAWSCredentials(credentials, Role.Arn, Role.SessionName ?? DefaultSessionName, new AssumeRoleAWSCredentialsOptions { ExternalId = Role.ExternalId, DurationSeconds = Role.SessionDuration }); } return true; } bool TryGetAssumeRoleWithWebIdentityCredentials(ILog log, out AWSCredentials credentials) { try { credentials = AssumeRoleWithWebIdentityCredentials.FromEnvironmentVariables(); return true; } catch(Exception ex) { log.Verbose($"Unable to authorise credentials for web identity: {ex}"); credentials = null; return false; } } bool TryGetEnvironmentVariablesAwsCredentials(ILog log, out AWSCredentials credentials) { try { credentials = new EnvironmentVariablesAWSCredentials(); return true; } catch(Exception ex) { log.Verbose($"Unable to authorise credentials for Environment Variables: {ex}"); credentials = null; return false; } } bool TryGetInstanceProfileAwsCredentials(ILog log, out AWSCredentials credentials) { try { credentials = new InstanceProfileAWSCredentials(); return true; } catch(Exception ex) { log.Verbose($"Unable to authorise credentials for Instance Profile: {ex}"); credentials = null; return false; } } public string Type { get; set; } public AwsCredentials Credentials { get; set; } public AwsAssumedRole Role { get; set; } public IEnumerable<string> Regions { get; set; } } public class AwsAssumedRole { public string Type { get; set; } public string Arn { get; set; } public string SessionName { get; set; } public int? SessionDuration { get; set; } public string ExternalId { get; set; } } public class AwsCredentials { public string Type { get; set; } public string AccountId { get; set; } public AwsAccount Account { get; set; } } public class AwsAccount { public string AccessKey { get; set; } public string SecretKey { get; set; } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.Common.Features.Behaviours { class ExtractBehaviour: IPackageExtractionBehaviour { readonly IExtractPackage extractPackage; public ExtractBehaviour(IExtractPackage extractPackage) { this.extractPackage = extractPackage; } public bool IsEnabled(RunningDeployment context) { return !string.IsNullOrWhiteSpace(context.PackageFilePath); } public Task Execute(RunningDeployment context) { extractPackage.ExtractToStagingDirectory(context.PackageFilePath); return this.CompletedTask(); } } }<file_sep>using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public static class ResourceFactory { public static Resource FromJson(string json, Options options) => FromJObject(JObject.Parse(json), options); public static IEnumerable<Resource> FromListJson(string json, Options options) { var listResponse = JObject.Parse(json); return listResponse.SelectTokens("$.items[*]").Select(item => FromJObject((JObject)item, options)); } public static Resource FromJObject(JObject data, Options options) { var kind = data.SelectToken("$.kind")?.Value<string>(); switch (kind) { case "Pod": return new Pod(data, options); case "ReplicaSet": return new ReplicaSet(data, options); case "Deployment": return new Deployment(data, options); case "StatefulSet": return new StatefulSet(data, options); case "DaemonSet": return new DaemonSet(data, options); case "Job": return new Job(data, options); case "CronJob": return new CronJob(data, options); case "Service": return new Service(data, options); case "Ingress": return new Ingress(data, options); case "EndpointSlice": return new EndpointSlice(data, options); case "ConfigMap": return new ConfigMap(data, options); case "Secret": return new Secret(data, options); case "PersistentVolumeClaim": return new PersistentVolumeClaim(data, options); default: return new Resource(data, options); } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.FSharp { public static class FSharpBootstrapper { static readonly string BootstrapScriptTemplate; static readonly string SensitiveVariablePassword = AesEncryption.RandomString(16); static readonly AesEncryption VariableEncryptor = new AesEncryption(SensitiveVariablePassword); static readonly ICalamariFileSystem CalamariFileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); static FSharpBootstrapper() { BootstrapScriptTemplate = EmbeddedResource.ReadEmbeddedText(typeof(FSharpBootstrapper).Namespace + ".Bootstrap.fsx"); } public static string FindExecutable() { if (!ScriptingEnvironment.IsNet45OrNewer()) throw new CommandException("FSharp scripts require requires .NET framework 4.5"); var myPath = typeof(FSharpExecutor).Assembly.Location; var parent = Path.GetDirectoryName(myPath); var executable = Path.GetFullPath(Path.Combine(parent, "FSharp", "fsi.exe")); if (File.Exists(executable)) return executable; throw new CommandException(string.Format("fsi.exe was not found at '{0}'", executable)); } public static string FormatCommandArguments(string bootstrapFile, string? scriptParameters) { var encryptionKey = Convert.ToBase64String(AesEncryption.GetEncryptionKey(SensitiveVariablePassword)); var commandArguments = new StringBuilder(); commandArguments.AppendFormat("\"{0}\" {1} \"{2}\"", bootstrapFile, scriptParameters, encryptionKey); return commandArguments.ToString(); } public static (string bootstrapFile, string[] temporaryFiles) PrepareBootstrapFile(string scriptFilePath, string configurationFile, string workingDirectory, IVariables variables) { var bootstrapFile = Path.Combine(workingDirectory, "Bootstrap." + Guid.NewGuid().ToString().Substring(10) + "." + Path.GetFileName(scriptFilePath)); var scriptModulePaths = PrepareScriptModules(variables, workingDirectory).ToArray(); using (var file = new FileStream(bootstrapFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.UTF8)) { writer.WriteLine("#load \"" + configurationFile.Replace("\\", "\\\\") + "\""); writer.WriteLine("open Octopus"); writer.WriteLine("Octopus.initializeProxy()"); writer.WriteLine("#load \"" + scriptFilePath.Replace("\\", "\\\\") + "\""); writer.Flush(); } File.SetAttributes(bootstrapFile, FileAttributes.Hidden); return (bootstrapFile, scriptModulePaths); } static IEnumerable<string> PrepareScriptModules(IVariables variables, string workingDirectory) { foreach (var variableName in variables.GetNames().Where(ScriptVariables.IsLibraryScriptModule)) if (ScriptVariables.GetLibraryScriptModuleLanguage(variables, variableName) == ScriptSyntax.FSharp) { var libraryScriptModuleName = ScriptVariables.GetLibraryScriptModuleName(variableName); var name = new string(libraryScriptModuleName.Where(char.IsLetterOrDigit).ToArray()); var moduleFileName = $"{name}.fsx"; var moduleFilePath = Path.Combine(workingDirectory, moduleFileName); Log.VerboseFormat("Writing script module '{0}' as f# module {1}. Import this module via `#load \"{1}\"`.", libraryScriptModuleName, moduleFileName, name); var contents = variables.Get(variableName); if (contents == null) throw new InvalidOperationException($"Value for variable {variableName} could not be found."); CalamariFileSystem.OverwriteFile(moduleFilePath, contents, Encoding.UTF8); yield return moduleFileName; } } public static string PrepareConfigurationFile(string workingDirectory, IVariables variables) { var configurationFile = Path.Combine(workingDirectory, "Configure." + Guid.NewGuid().ToString().Substring(10) + ".fsx"); var builder = new StringBuilder(BootstrapScriptTemplate); builder.Replace("(*{{VariableDeclarations}}*)", WritePatternMatching(variables)); using (var file = new FileStream(configurationFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.UTF8)) { writer.Write(builder.ToString()); writer.Flush(); } File.SetAttributes(configurationFile, FileAttributes.Hidden); return configurationFile; } static string WritePatternMatching(IVariables variables) { var builder = new StringBuilder(); foreach (var variableName in variables.GetNames()) { var variableValue = variables.Get(variableName); if (variableValue == null) builder.AppendFormat(" | \"{0}\" -> Some null", EncodeValue(variableName)); else builder.AppendFormat(" | \"{0}\" -> {1} |> Some", EncodeValue(variableName), EncryptVariable(variableValue)); builder.Append(Environment.NewLine); } builder.Append(" | _ -> None"); return builder.ToString(); } static string EncodeValue(string value) { var bytes = Encoding.UTF8.GetBytes(value); return Convert.ToBase64String(bytes); } static string EncryptVariable(string value) { var encrypted = VariableEncryptor.Encrypt(value); var rawEncrypted = AesEncryption.ExtractIV(encrypted, out var iv); return $@"decryptString ""{Convert.ToBase64String(rawEncrypted)}"" ""{Convert.ToBase64String(iv)}"""; } } }<file_sep>using Calamari.Common.Plumbing.FileSystem; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] public class DeployBilingualPackageFixture : DeployPackageFixture { [SetUp] public override void SetUp() { base.SetUp(); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldOnlyRunPowerShellScriptsOnWindows() { using (var nupkgFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.PackageBilingual", "1.0.0"))) { var result = DeployPackage(nupkgFile.FilePath); result.AssertSuccess(); // PreDeploy result.AssertOutput("hello from PreDeploy.ps1"); result.AssertNoOutput("hello from PreDeploy.sh"); // Deploy result.AssertOutput("hello from Deploy.ps1"); result.AssertNoOutput("hello from Deploy.sh"); // PostDeploy result.AssertOutput("hello from PostDeploy.ps1"); result.AssertNoOutput("hello from PostDeploy.sh"); } } [Test] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void ShouldOnlyRunBashScriptsOnMacOrNix() { using (var tarFile = new TemporaryFile(TarGzBuilder.BuildSamplePackage("Acme.PackageBilingual", "1.0.0", false))) { var result = DeployPackage(tarFile.FilePath); result.AssertSuccess(); // PreDeploy result.AssertOutput("hello from PreDeploy.sh"); result.AssertNoOutput("hello from PreDeploy.ps1"); // Deploy result.AssertOutput("hello from Deploy.sh"); result.AssertNoOutput("hello from Deploy.ps1"); // PostDeploy result.AssertOutput("hello from PostDeploy.sh"); result.AssertNoOutput("hello from PostDeploy.ps1"); } } } } <file_sep>using System; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Proxies; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Proxies { [TestFixture] public abstract class ScriptProxyFixtureBase : CalamariFixture { protected const string BadproxyUrl = "http://proxy-initializer-fixture-bad-proxy:1234"; protected const string ProxyUserName = "some@:/user"; protected const string ProxyPassword = "some@:/password"; #if NET40 const string UrlEncodedProxyUserName = "some%40%3a%2fuser"; const string UrlEncodedProxyPassword = "<PASSWORD>"; #else const string UrlEncodedProxyUserName = "some%40%3A%2Fuser"; const string UrlEncodedProxyPassword = "<PASSWORD>"; #endif protected const string proxyHost = "proxy-initializer-fixture-good-proxy"; protected const int proxyPort = 8888; protected string proxyUrl = $"http://{proxyHost}:{proxyPort}"; protected string authenticatedProxyUrl = $"http://{UrlEncodedProxyUserName}:{UrlEncodedProxyPassword}@{proxyHost}:{proxyPort}"; protected static bool IsRunningOnWindows = CalamariEnvironment.IsRunningOnWindows; [TearDown] public void TearDown() { ResetProxyEnvironmentVariables(); } [Test] public virtual void Initialize_NoSystemProxy_NoProxy() { var result = RunWith(false, "", 80, "", ""); AssertProxyBypassed(result); } [Test] public virtual void Initialize_NoSystemProxy_UseSystemProxy() { var result = RunWith(true, "", 80, "", ""); AssertNoProxyChanges(result); } [Test] public virtual void Initialize_NoSystemProxy_UseSystemProxyWithCredentials() { var result = RunWith(true, "", 80, ProxyUserName, ProxyPassword); AssertNoProxyChanges(result); } [Test] public virtual void Initialize_NoSystemProxy_CustomProxy() { var result = RunWith(false, proxyHost, proxyPort, "", ""); AssertUnauthenticatedProxyUsed(result); } [Test] public virtual void Initialize_NoSystemProxy_CustomProxyWithCredentials() { var result = RunWith(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword); AssertAuthenticatedProxyUsed(result); } protected CalamariResult RunWith( bool useDefaultProxy, string proxyhost, int proxyPort, string proxyUsername, string proxyPassword) { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy, useDefaultProxy.ToString()); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, proxyhost); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, proxyPort.ToString()); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername, proxyUsername); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword, <PASSWORD>Password); return RunScript(); } protected abstract CalamariResult RunScript(); void ResetProxyEnvironmentVariables() { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword, string.Empty); EnvironmentHelper.SetEnvironmentVariable("HTTP_PROXY", string.Empty); EnvironmentHelper.SetEnvironmentVariable("HTTPS_PROXY", string.Empty); EnvironmentHelper.SetEnvironmentVariable("NO_PROXY", string.Empty); } protected virtual void AssertAuthenticatedProxyUsed(CalamariResult output) { output.AssertSuccess(); output.AssertPropertyValue("HTTP_PROXY", authenticatedProxyUrl); output.AssertPropertyValue("HTTPS_PROXY", authenticatedProxyUrl); output.AssertPropertyValue("NO_PROXY", "127.0.0.1,localhost,169.254.169.254"); } protected virtual void AssertUnauthenticatedProxyUsed(CalamariResult output) { output.AssertSuccess(); output.AssertPropertyValue("HTTP_PROXY", proxyUrl); output.AssertPropertyValue("HTTPS_PROXY", proxyUrl); output.AssertPropertyValue("NO_PROXY", "127.0.0.1,localhost,169.254.169.254"); } protected virtual void AssertNoProxyChanges(CalamariResult output) { output.AssertSuccess(); output.AssertPropertyValue("HTTP_PROXY", ""); output.AssertPropertyValue("HTTPS_PROXY", ""); output.AssertPropertyValue("NO_PROXY", ""); } protected virtual void AssertProxyBypassed(CalamariResult output) { output.AssertSuccess(); output.AssertPropertyValue("HTTP_PROXY", ""); output.AssertPropertyValue("HTTPS_PROXY", ""); output.AssertPropertyValue("NO_PROXY", "*"); } } }<file_sep>using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading.Tasks; using Calamari.Common; using Calamari.Common.Plumbing.Logging; namespace Calamari.AzureAppService { public class Program : CalamariFlavourProgramAsync { public Program(ILog log) : base(log) { } public static Task<int> Main(string[] args) { return new Program(ConsoleLog.Instance).Run(args); } } } <file_sep>using Calamari.Common.Commands; namespace Calamari.Deployment.Features { public interface IFeature { string Name { get; } string DeploymentStage { get; } void Execute(RunningDeployment deployment); } }<file_sep>using System; using Calamari.Common.Plumbing.Deployment.PackageRetention; using NUnit.Framework; using Octopus.Versioning; namespace Calamari.Tests.Fixtures.PackageRetention { [TestFixture] public class PackageIdentityFixture { [Test] public void WhenTwoPackagesWithTheSameNameAndVersionAreCompared_ThenTheyAreEqual() { var packageA = CreatePackageIdentity("Package1", "1.0"); var package1 = CreatePackageIdentity("Package1", "1.0"); Assert.AreEqual(package1,packageA); } [Test] public void WhenTwoPackagesWithTheSameNameAndDifferentVersionAreCompared_ThenTheyAreNotEqual() { var package1v1 = CreatePackageIdentity("Package1", "1.0"); var package1v2 = CreatePackageIdentity("Package1", "2.0"); Assert.AreNotEqual(package1v1,package1v2); } [Test] public void WhenTwoPackagesWithADifferentNameAndSameVersionAreCompared_ThenTheyAreNotEqual() { var package1 = CreatePackageIdentity("Package1", "1.0"); var package2 = CreatePackageIdentity("Package2", "1.0"); Assert.AreNotEqual(package1,package2); } static PackageIdentity CreatePackageIdentity(string packageId, string packageVersion) { var version = VersionFactory.CreateSemanticVersion(packageVersion); return new PackageIdentity(new PackageId(packageId), version, new PackagePath($"C:\\{packageId}.{packageVersion}.zip")); } } }<file_sep>using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; namespace Calamari.Deployment.Conventions { public class ConfigurationVariablesConvention : IInstallConvention { readonly ConfigurationVariablesBehaviour configurationVariablesBehaviour; public ConfigurationVariablesConvention(ConfigurationVariablesBehaviour configurationVariablesBehaviour) { this.configurationVariablesBehaviour = configurationVariablesBehaviour; } public void Install(RunningDeployment deployment) { if (configurationVariablesBehaviour.IsEnabled(deployment)) { configurationVariablesBehaviour.Execute(deployment).Wait(); } } } } <file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; using Calamari.Terraform.Behaviours; namespace Calamari.Terraform.Commands { [Command("apply-terraform", Description = "Applies a Terraform template")] public class ApplyCommand : TerraformCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<ApplyBehaviour>(); } } }<file_sep>using System; using System.Security.Cryptography.X509Certificates; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute; namespace Calamari.AzureCloudService { static class AzureAccountExtensions { static SubscriptionCloudCredentials Credentials(this AzureAccount account, X509Certificate2 certificate) { return new CertificateCloudCredentials(account.SubscriptionNumber, certificate); } public static ComputeManagementClient CreateComputeManagementClient(this AzureAccount account, X509Certificate2 certificate) { var credentials = account.Credentials(certificate); return string.IsNullOrWhiteSpace(account.ServiceManagementEndpointBaseUri) ? new ComputeManagementClient(credentials) : new ComputeManagementClient(credentials, new Uri(account.ServiceManagementEndpointBaseUri)); } } }<file_sep>using System.Reflection; using System.Runtime.InteropServices; [assembly: Guid("8a95ea4f-ba70-4ac3-8d61-6031377259e7")] <file_sep>using System; using System.IO; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.Extensions { public class ApplicationDirectory { static readonly ISemaphoreFactory Semaphore = SemaphoreFactory.Get(); /// <summary> /// Returns the directory where the package will be installed. /// Also ensures the directory exists, and that there is free-space on the disk. /// </summary> public static string GetApplicationDirectory(PackageFileNameMetadata packageFileNameMetadata, IVariables variables, ICalamariFileSystem fileSystem) { return EnsureTargetPathExistsAndIsEmpty( Path.Combine(GetEnvironmentApplicationDirectory(fileSystem, variables), FileNameEscaper.Escape(packageFileNameMetadata.PackageId), FileNameEscaper.Escape(packageFileNameMetadata.Version.ToString())), fileSystem); } /// This will be specific to Tenant and/or Environment if these variables are available. static string GetEnvironmentApplicationDirectory(ICalamariFileSystem fileSystem, IVariables variables) { var root = GetApplicationDirectoryRoot(variables); root = AppendTenantNameIfProvided(fileSystem, variables, root); root = AppendEnvironmentNameIfProvided(fileSystem, variables, root); fileSystem.EnsureDirectoryExists(root); new FreeSpaceChecker(fileSystem, variables).EnsureDiskHasEnoughFreeSpace(root); return root; } static string GetApplicationDirectoryRoot(IVariables variables) { const string windowsRoot = "env:SystemDrive"; const string linuxRoot = "env:HOME"; var root = variables.Get(TentacleVariables.Agent.ApplicationDirectoryPath); if (root != null) return root; root = variables.Get(windowsRoot); if (root == null) { root = variables.Get(linuxRoot); if (root == null) throw new Exception(string.Format("Unable to determine the ApplicationRootDirectory. Please provide the {0} variable", TentacleVariables.Agent.ApplicationDirectoryPath)); } return string.Format("{0}{1}Applications", root, Path.DirectorySeparatorChar); } static string AppendEnvironmentNameIfProvided(ICalamariFileSystem fileSystem, IVariables variables, string root) { var environment = variables.Get(DeploymentEnvironment.Name); if (!string.IsNullOrWhiteSpace(environment)) { environment = fileSystem.RemoveInvalidFileNameChars(environment); root = Path.Combine(root, environment); } return root; } static string AppendTenantNameIfProvided(ICalamariFileSystem fileSystem, IVariables variables, string root) { var tenant = variables.Get(DeploymentVariables.Tenant.Name); if (!string.IsNullOrWhiteSpace(tenant)) { tenant = fileSystem.RemoveInvalidFileNameChars(tenant); root = Path.Combine(root, tenant); } return root; } // When a package has been installed once, Octopus gives users the ability to 'force' a redeployment of the package. // This is often useful for example if a deployment partially completes and the installation is in an invalid state // (e.g., corrupt files are left on disk, or the package is only half extracted). We *can't* just uninstall the package // or overwrite the files, since they might be locked by IIS or another process. So instead we create a new unique // directory. static string EnsureTargetPathExistsAndIsEmpty(string desiredTargetPath, ICalamariFileSystem fileSystem) { var target = desiredTargetPath; using (Semaphore.Acquire("Octopus.Calamari.ExtractionDirectory", "Another process is finding an extraction directory, please wait...")) { for (var i = 1; fileSystem.DirectoryExists(target) || fileSystem.FileExists(target); i++) target = desiredTargetPath + "_" + i; fileSystem.EnsureDirectoryExists(target); } return target; } } }<file_sep>using System; namespace Calamari.AzureResourceGroup { public static class AzureAccountVariables { public static readonly string SubscriptionId = "Octopus.Action.Azure.SubscriptionId"; public static readonly string ClientId = "Octopus.Action.Azure.ClientId"; public static readonly string TenantId = "Octopus.Action.Azure.TenantId"; public static readonly string Password = "<PASSWORD>"; public static readonly string ResourceManagementEndPoint = "Octopus.Action.Azure.ResourceManagementEndPoint"; public static readonly string ActiveDirectoryEndPoint = "Octopus.Action.Azure.ActiveDirectoryEndPoint"; } }<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public static class ActionVariables { public const string Name = "Octopus.Action.Name"; public const string AdditionalPaths = "Octopus.Action.AdditionalPaths"; public static readonly string StructuredConfigurationVariablesTargets = "Octopus.Action.Package.JsonConfigurationVariablesTargets"; /* If this flag still exists after 2020.5.0 releases, please reach out to those involved with adding the fallback flag for Structured Configuration in this PR (https://github.com/OctopusDeploy/Calamari/pull/629) so we can assess if the feature has been stable for long enough to tidy up the fallback flag. */ public static readonly string StructuredConfigurationFallbackFlag = "Octopus.Action.StructuredConfigurationFallbackFlag"; public static string GetOutputVariableName(string actionName, string variableName) { return string.Format("Octopus.Action[{0}].Output.{1}", actionName, variableName); } public static string GetMachineIndexedOutputVariableName(string actionName, string machineName, string variableName) { return string.Format("Octopus.Action[{0}].Output[{1}].{2}", actionName, machineName, variableName); } } }<file_sep>using System; using System.Linq; namespace Calamari.Common.Features.Processes { public class CommandResult { readonly string command; readonly string? workingDirectory; public CommandResult(string command, int exitCode, string? additionalErrors = null, string? workingDirectory = null) { this.command = command; ExitCode = exitCode; Errors = additionalErrors; this.workingDirectory = workingDirectory; } public int ExitCode { get; } public string? Errors { get; } public bool HasErrors => !string.IsNullOrWhiteSpace(Errors) && ErrorsExcludeServiceMessages(Errors); public void VerifySuccess() { if (ExitCode != 0) throw new CommandLineException( command, ExitCode, Errors, workingDirectory); } static bool ErrorsExcludeServiceMessages(string s) => s.Split(new[] {Environment.NewLine}, StringSplitOptions.None) .Where(s => !string.IsNullOrWhiteSpace(s)) .Any(s => !s.StartsWith("##octopus")); } }<file_sep>using System.IO; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class DeployVhdFixture : DeployPackageFixture { private const string ServiceName = "Acme.Vhd"; private const string Environment = "Production"; [SetUp] public override void SetUp() { base.SetUp(); } [TearDown] public override void CleanUp() { base.CleanUp(); } [Test] [RequiresAdmin] [RequiresWindowsServer2012OrAbove] public void ShouldDeployAVhd() { Variables[SpecialVariables.Vhd.ApplicationPath] = "ApplicationPath"; Variables["foo"] = "bar"; Variables[PackageVariables.SubstituteInFilesTargets] = "web.config"; Variables[KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles] = "True"; Variables[DeploymentEnvironment.Name] = Environment; Variables[ActionVariables.StructuredConfigurationVariablesTargets] = "appsettings.json"; Variables[KnownVariables.Package.EnabledFeatures] = $"{KnownVariables.Features.StructuredConfigurationVariables},{KnownVariables.Features.SubstituteInFiles}, {KnownVariables.Features.ConfigurationTransforms},Octopus.Features.Vhd"; using (var vhd = new TemporaryFile(VhdBuilder.BuildSampleVhd(ServiceName))) using (var file = new TemporaryFile(PackageBuilder.BuildSimpleZip(ServiceName, "1.0.0", Path.GetDirectoryName(vhd.FilePath)))) { var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutput("Extracting package to: " + Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0")); result.AssertOutput("Extracted 2 files"); // mounts VHD result.AssertOutput($"VHD partition 0 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); // runs predeploy etc result.AssertOutput("Bonjour from PreDeploy.ps1"); // can access mountpoint from predeploy result.AssertOutputMatches(@"VHD is mounted at [A-Z]:\\"); // variable substitution in files result.AssertOutputMatches(@"Performing variable substitution on '[A-Z]:\\ApplicationPath\\web\.config'"); // config transforms result.AssertOutputMatches(@"Transforming '[A-Z]:\\ApplicationPath\\web\.config' using '[A-Z]:\\ApplicationPath\\web\.Production\.config'"); // json substitutions result.AssertOutputMatches("Structured variable replacement succeeded on file [A-Z]:\\\\ApplicationPath\\\\appsettings.json with format Json"); } } [Test] [RequiresAdmin] [RequiresWindowsServer2012OrAbove] public void ShouldDeployAVhdWithTwoPartitions() { Variables[SpecialVariables.Vhd.ApplicationPath] = "ApplicationPath"; Variables["foo"] = "bar"; Variables[PackageVariables.SubstituteInFilesTargets] = "web.config"; Variables[KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles] = "True"; Variables[DeploymentEnvironment.Name] = Environment; Variables[ActionVariables.StructuredConfigurationVariablesTargets] = "appsettings.json"; Variables[KnownVariables.Package.EnabledFeatures] = $"{KnownVariables.Features.StructuredConfigurationVariables},{KnownVariables.Features.SubstituteInFiles}, {KnownVariables.Features.ConfigurationTransforms},Octopus.Features.Vhd"; Variables["OctopusVhdPartitions[1].ApplicationPath"] = "PathThatDoesNotExist"; using (var vhd = new TemporaryFile(VhdBuilder.BuildSampleVhd(ServiceName, twoPartitions: true))) using (var file = new TemporaryFile(PackageBuilder.BuildSimpleZip(ServiceName, "1.0.0", Path.GetDirectoryName(vhd.FilePath)))) { var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutput("Extracting package to: " + Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0")); result.AssertOutput("Extracted 2 files"); // mounts VHD result.AssertOutput($"VHD partition 0 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); result.AssertOutput($"VHD partition 1 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); // handles additionalpaths setting not being valid for all partitions result.AssertOutputMatches(@"[A-Z]:\\PathThatDoesNotExist not found so not added to Calamari processing paths"); // runs predeploy etc result.AssertOutput("Bonjour from PreDeploy.ps1"); // can access mountpoint from predeploy result.AssertOutputMatches(@"VHD is mounted at [A-Z]:\\"); result.AssertOutputMatches(@"VHD partition 0 is mounted at [A-Z]:\\"); result.AssertOutputMatches(@"VHD partition 1 is mounted at [A-Z]:\\"); // variable substitution in files result.AssertOutputMatches(@"Performing variable substitution on '[A-Z]:\\ApplicationPath\\web\.config'"); // config transforms result.AssertOutputMatches(@"Transforming '[A-Z]:\\ApplicationPath\\web\.config' using '[A-Z]:\\ApplicationPath\\web\.Production\.config'"); // json substitutions result.AssertOutputMatches("Structured variable replacement succeeded on file [A-Z]:\\\\ApplicationPath\\\\appsettings.json with format Json"); } } [Test] [RequiresAdmin] [RequiresWindowsServer2012OrAbove] public void ShouldBlockMountAndOverrideAppPath() { Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.Vhd,Octopus.Features.ConfigurationTransforms"; Variables[SpecialVariables.Vhd.ApplicationPath] = "ApplicationPath"; Variables["foo"] = "bar"; Variables[PackageVariables.SubstituteInFilesTargets] = "web.config"; Variables[KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles] = "True"; Variables[DeploymentEnvironment.Name] = Environment; Variables[ActionVariables.StructuredConfigurationVariablesTargets] = "appsettings.json"; Variables[KnownVariables.Package.EnabledFeatures] = $"{KnownVariables.Features.StructuredConfigurationVariables},{KnownVariables.Features.SubstituteInFiles},{KnownVariables.Features.ConfigurationTransforms},Octopus.Features.Vhd"; Variables["OctopusVhdPartitions[0].Mount"] = "false"; Variables["OctopusVhdPartitions[1].ApplicationPath"] = "AlternateApplicationPath"; using (var vhd = new TemporaryFile(VhdBuilder.BuildSampleVhd(ServiceName, twoPartitions: true))) using (var file = new TemporaryFile(PackageBuilder.BuildSimpleZip(ServiceName, "1.0.0", Path.GetDirectoryName(vhd.FilePath)))) { var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutput("Extracting package to: " + Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0")); result.AssertOutput("Extracted 2 files"); // mounts VHD result.AssertNoOutput($"VHD partition 0 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); result.AssertOutput($"VHD partition 1 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); // runs predeploy etc result.AssertOutput("Bonjour from PreDeploy.ps1"); // can access mountpoint from predeploy result.AssertOutputMatches(@"VHD is mounted at [A-Z]:\\"); result.AssertNoOutputMatches(@"VHD partition 0 is mounted at [A-Z]:\\"); result.AssertOutputMatches(@"VHD partition 1 is mounted at [A-Z]:\\"); // variable substitution in files result.AssertOutputMatches(@"Performing variable substitution on '[A-Z]:\\AlternateApplicationPath\\web\.config'"); // config transforms result.AssertOutputMatches(@"Transforming '[A-Z]:\\AlternateApplicationPath\\web\.config' using '[A-Z]:\\AlternateApplicationPath\\web\.Production\.config'"); // json substitutions result.AssertOutputMatches("Structured variable replacement succeeded on file [A-Z]:\\\\AlternateApplicationPath\\\\appsettings.json with format Json"); } } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.FileSystem; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Calamari.Common.Features.Processes.Semaphores { public class LockIo : ILockIo { readonly ICalamariFileSystem fileSystem; public LockIo(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } public string GetFilePath(string lockName) { return Path.Combine(Path.GetTempPath(), lockName + ".lck"); } public bool LockExists(string lockFilePath) { return fileSystem.FileExists(lockFilePath); } public IFileLock ReadLock(string lockFilePath) { try { using (var stream = fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read)) { using (var streamReader = new StreamReader(stream)) { var obj = JObject.Load(new JsonTextReader(streamReader)); var lockContent = new FileLock(obj["ProcessId"].ToObject<long>(), obj["ProcessName"].ToString(), obj["ThreadId"].ToObject<int>(), obj["Timestamp"].ToObject<long>()); if (lockContent.BelongsToCurrentProcessAndThread()) return lockContent; return new OtherProcessOwnsFileLock(lockContent); } } } catch (FileNotFoundException) { return new MissingFileLock(); } catch (IOException) { return new OtherProcessHasExclusiveLockOnFileLock(); } catch (JsonReaderException) { return new UnableToDeserialiseLockFile(fileSystem.GetCreationTime(lockFilePath)); } catch (Exception) //We have no idea what went wrong - reacquire this lock { return new OtherProcessHasExclusiveLockOnFileLock(); } } public bool WriteLock(string lockFilePath, FileLock fileLock) { try { var fileMode = FileMode.CreateNew; if (LockExists(lockFilePath)) { var currentContent = ReadLock(lockFilePath); if (Equals(currentContent, fileLock)) { if ((currentContent as FileLock)?.Timestamp == fileLock.Timestamp) return true; fileMode = FileMode.Create; } else if (currentContent.GetType() == typeof(UnableToDeserialiseLockFile)) { DeleteLock(lockFilePath); } } var obj = new JObject { ["ProcessId"] = fileLock.ProcessId, ["ThreadId"] = fileLock.ThreadId, ["ProcessName"] = fileLock.ProcessName, ["Timestamp"] = fileLock.Timestamp }; using (var stream = fileSystem.OpenFileExclusively(lockFilePath, fileMode, FileAccess.Write)) { using (var streamWriter = new StreamWriter(stream)) { obj.WriteTo(new JsonTextWriter(streamWriter)); } } var writtenContent = ReadLock(lockFilePath); return Equals(writtenContent, fileLock); } catch (Exception) { return false; } } public void DeleteLock(string lockFilePath) { try { fileSystem.DeleteFile(lockFilePath); } catch (Exception) { // ignored - handled in create } } } }<file_sep>// Some of this class was based on code from https://github.com/NuGet/NuGet.Client. // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Calamari.Common.Plumbing.Logging; using SharpCompress.Archives; using SharpCompress.Archives.Zip; using SharpCompress.Common; namespace Calamari.Common.Features.Packages.NuGet { public class NupkgExtractor : IPackageExtractor { const string ExcludeExtension = ".nupkg.sha512"; static readonly string[] ExcludePaths = { "_rels/", "package/services/metadata/", @"_rels\", @"package\services\metadata\", "[Content_Types].xml" }; readonly ILog log; public NupkgExtractor(ILog log) { this.log = log; } public string[] Extensions => new[] { ".nupkg" }; public int Extract(string packageFile, string directory) { var filesExtracted = 0; using (var packageStream = new FileStream(packageFile, FileMode.Open, FileAccess.Read)) using (var archive = ZipArchive.Open(packageStream)) { foreach (var entry in archive.Entries) { var unescapedKey = UnescapePath(entry.Key); if (IsExcludedPath(unescapedKey)) continue; var targetDirectory = Path.Combine(directory, Path.GetDirectoryName(unescapedKey)); if (!Directory.Exists(targetDirectory)) Directory.CreateDirectory(targetDirectory); if (entry.IsDirectory || !IsPackageFile(entry.Key)) continue; var targetFile = Path.Combine(targetDirectory, Path.GetFileName(unescapedKey)); entry.WriteToFile(targetFile, new PackageExtractionOptions(log) { ExtractFullPath = false, PreserveFileTime = false }); SetFileLastModifiedTime(entry, targetFile); filesExtracted++; } return filesExtracted; } } void SetFileLastModifiedTime(IEntry entry, string targetFile) { // Using the SharpCompress PreserveFileTime option caused an exception when unpacking // NuGet packages on Linux. So we set the LastModifiedTime ourselves. if (entry.LastModifiedTime.HasValue && entry.LastModifiedTime.Value != DateTime.MinValue && entry.LastModifiedTime.Value.ToUniversalTime() <= DateTime.UtcNow) try { File.SetLastWriteTimeUtc(targetFile, entry.LastModifiedTime.Value.ToUniversalTime()); } catch (Exception ex) { log.Verbose($"Unable to set LastWriteTime attribute on file '{targetFile}': {ex.Message}"); } } static bool IsPackageFile(string packageFileName) { if (string.IsNullOrEmpty(packageFileName) || string.IsNullOrEmpty(Path.GetFileName(packageFileName))) // This is to ignore archive entries that are not really files return false; if (IsManifest(packageFileName)) return false; return !IsExcludedPath(packageFileName); } static bool IsExcludedPath(string path) { return ExcludePaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)) || path.EndsWith(ExcludeExtension, StringComparison.OrdinalIgnoreCase); } static bool IsManifest(string path) { return Path.GetExtension(path).Equals(".nuspec", StringComparison.OrdinalIgnoreCase); } [return: NotNullIfNotNull("path")] static string? UnescapePath(string? path) { if (path != null && path.IndexOf('%') > -1) try { return Uri.UnescapeDataString(path); } catch (UriFormatException) { // on windows server 2003 we can get UriFormatExceptions when the original unescaped string contained %, just swallow and return path } return path; } } }<file_sep>#!/bin/bash echo $(get_octopusvariable "PreDeployGreeting") "from Deploy.sh"<file_sep> using System; namespace Calamari.AzureAppService.Azure { static class DefaultVariables { public const string ResourceManagementEndpoint = @"https://management.azure.com/"; public const string ActiveDirectoryEndpoint = @"https://login.windows.net/"; } } <file_sep>using System; using System.Diagnostics; using System.Threading; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; namespace Calamari.Common.Features.Processes.Semaphores { public class LockFileBasedSemaphore : ISemaphore { public enum AcquireLockAction { DontAcquireLock, AcquireLock, ForciblyAcquireLock } readonly ILockIo lockIo; readonly IProcessFinder processFinder; readonly ILog log; public LockFileBasedSemaphore(string name, TimeSpan lockTimeout, ILog log) : this(name, lockTimeout, new LockIo(CalamariPhysicalFileSystem.GetPhysicalFileSystem()), new ProcessFinder(), log) { } public LockFileBasedSemaphore(string name, TimeSpan lockTimeout, ILockIo lockIo, IProcessFinder processFinder, ILog log) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name), "name cannot be null or emtpy."); Name = name; LockTimeout = lockTimeout; LockFilePath = lockIo.GetFilePath(name); this.lockIo = lockIo; this.processFinder = processFinder; this.log = log; } TimeSpan LockTimeout { get; } public string Name { get; } string LockFilePath { get; } public AcquireLockAction ShouldAcquireLock(IFileLock fileLock) { if (lockIo.LockExists(LockFilePath)) { //Someone else owns the lock if (fileLock is OtherProcessHasExclusiveLockOnFileLock) //we couldn't read the file as some other process has it open exlusively return AcquireLockAction.DontAcquireLock; if (fileLock is UnableToDeserialiseLockFile nonDeserialisedLockFile) { if ((DateTime.Now - nonDeserialisedLockFile.CreationTime).TotalSeconds > LockTimeout.TotalSeconds) { log.Warn("Lock file existed but was not readable, and has existed for longer than lock timeout. Taking lock."); return AcquireLockAction.AcquireLock; } return AcquireLockAction.DontAcquireLock; } //the file no longer exists if (fileLock is MissingFileLock) return AcquireLockAction.AcquireLock; var concreteFileLock = fileLock as FileLock; if (concreteFileLock == null) return AcquireLockAction.AcquireLock; //This lock belongs to this process - we can reacquire the lock if (concreteFileLock.BelongsToCurrentProcessAndThread()) return AcquireLockAction.AcquireLock; if (!processFinder.ProcessIsRunning((int)concreteFileLock.ProcessId, concreteFileLock.ProcessName ?? "")) { log.Warn($"Process {concreteFileLock.ProcessId}, thread {concreteFileLock.ThreadId} had lock, but appears to have crashed. Taking lock."); return AcquireLockAction.AcquireLock; } var lockWriteTime = new DateTime(concreteFileLock.Timestamp); //The lock has not timed out - we can't acquire it if (!(Math.Abs((DateTime.Now - lockWriteTime).TotalSeconds) > LockTimeout.TotalSeconds)) return AcquireLockAction.DontAcquireLock; log.Warn($"Forcibly taking lock from process {concreteFileLock.ProcessId}, thread {concreteFileLock.ThreadId} as lock has timed out. If this happens regularly, please contact Octopus Support."); return AcquireLockAction.ForciblyAcquireLock; } return AcquireLockAction.AcquireLock; } public bool TryAcquireLock() { var lockContent = lockIo.ReadLock(LockFilePath); var response = ShouldAcquireLock(lockContent); if (response == AcquireLockAction.ForciblyAcquireLock) lockIo.DeleteLock(LockFilePath); if (response == AcquireLockAction.AcquireLock || response == AcquireLockAction.ForciblyAcquireLock) return lockIo.WriteLock(LockFilePath, CreateLockContent()); return false; } public void ReleaseLock() { //Need to own the lock in order to release it (and we can reacquire the lock inside the current process) if (lockIo.LockExists(LockFilePath) && TryAcquireLock()) lockIo.DeleteLock(LockFilePath); } static FileLock CreateLockContent() { var process = Process.GetCurrentProcess(); return new FileLock(process.Id, process.ProcessName, Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks); } public bool WaitOne(int millisecondsToWait) { var stopwatch = new Stopwatch(); stopwatch.Start(); while (true) { if (TryAcquireLock()) return true; if (stopwatch.ElapsedMilliseconds > millisecondsToWait) return false; Thread.Sleep(100); } } public bool WaitOne() { while (true) { if (TryAcquireLock()) return true; Thread.Sleep(100); } } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT namespace Calamari.Integration.Certificates.WindowsNative { internal static class SafeCertContextHandleExtensions { public static bool HasPrivateKey(this SafeCertContextHandle certificateContext) { return certificateContext.HasProperty(WindowsX509Native.CertificateProperty.KeyProviderInfo); } public static bool HasProperty(this SafeCertContextHandle certificateContext, WindowsX509Native.CertificateProperty property) { return CertificatePal.HasProperty(certificateContext.DangerousGetHandle(), property); } /// <summary> /// Get a property of a certificate formatted as a structure /// </summary> public static T GetCertificateProperty<T>(this SafeCertContextHandle certificateContext, WindowsX509Native.CertificateProperty property) where T : struct { return CertificatePal.GetCertificateProperty<T>(certificateContext.DangerousGetHandle(), property); } } } #endif<file_sep>using System; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.StructuredVariables { public interface IFileFormatVariableReplacer { string FileFormatName { get; } bool IsBestReplacerForFileName(string fileName); void ModifyFile(string filePath, IVariables variables); } }<file_sep>using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Calamari.Serialization { /// <summary> /// Support for reading and writing JSON, exposed for convenience of those using JSON.NET. /// </summary> public static class JsonSerialization { /// <summary> /// The serializer settings used by Octopus when reading and writing JSON from the /// Octopus Deploy RESTful API. /// </summary> public static JsonSerializerSettings GetDefaultSerializerSettings() { return new JsonSerializerSettings { Formatting = Formatting.Indented, Converters = new JsonConverterCollection { new StringEnumConverter(), new IsoDateTimeConverter {DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"} } }; } } } <file_sep>using System; namespace Calamari.Common.Plumbing.Retry { public abstract class RetryInterval { public abstract TimeSpan GetInterval(int retryCount); } }<file_sep>using System; namespace Calamari.Common.Features.Scripting { public class Script { public Script(string? file, string? parameters = null) { if (string.IsNullOrEmpty(file)) throw new InvalidScriptException("File can not be null or empty."); File = file; Parameters = parameters; } public string File { get; } public string? Parameters { get; } } }<file_sep>using System; using System.Net; using System.Text.RegularExpressions; using Calamari.Common; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Deployment; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures { public class ProgramFixture { [Test] public void RunScript() { var retCode = RunProgram(); // Expected because we don't pass the required variables Assert.AreEqual(1, retCode); } static int RunProgram() => Program.Main(new[] {"run-script"}); [Test] public void OctopusCalamariWorkingDirectoryEnvironmentVariableIsSet() { EnvironmentHelper.SetEnvironmentVariable("OctopusCalamariWorkingDirectory", null); RunProgram(); // This usage of Environment.GetEnvironmentVariable is fine as it's not accessing a test dependency variable Environment.GetEnvironmentVariable("OctopusCalamariWorkingDirectory").Should().NotBeNullOrWhiteSpace(); } [Test] public void ProxyIsInitialized() { var existingProxy = WebRequest.DefaultWebProxy; try { EnvironmentHelper.SetEnvironmentVariable("TentacleProxyHost", "localhost"); WebRequest.DefaultWebProxy = null; RunProgram(); WebRequest.DefaultWebProxy.Should().NotBeNull(); } finally { WebRequest.DefaultWebProxy = existingProxy; EnvironmentHelper.SetEnvironmentVariable("TentacleProxyHost", null); } } [Test] public void DefaultRegexMatchTimeoutIsSet() { RunProgram(); var regexTimeout = AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT"); regexTimeout.Should().Be(AppDomainConfiguration.DefaultRegexMatchTimeout); } } }<file_sep>using System; using Calamari.Common.Commands; namespace Calamari.Deployment.Conventions { public class ConditionalInstallationConvention<T>: IInstallConvention where T: IInstallConvention { private readonly Func<RunningDeployment, bool> predicate; public ConditionalInstallationConvention(Func<RunningDeployment, bool> predicate, T decorated) { Decorated = decorated; this.predicate = predicate; } protected T Decorated { get; } public void Install(RunningDeployment deployment) { if (predicate(deployment)) { Decorated.Install(deployment); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Commands.Discovery; using Newtonsoft.Json; namespace Calamari.Kubernetes.Commands { [Command(Name, Description = "Discover Kubernetes cluster targets")] public class KubernetesDiscoveryCommand : Command { public const string Name = "kubernetes-target-discovery"; public const string CreateKubernetesTargetServiceMessageName = "create-kubernetestarget"; public const string ContextVariableName = "Octopus.TargetDiscovery.Context"; readonly ILog log; readonly IVariables variables; readonly IKubernetesDiscovererFactory discovererFactory; public KubernetesDiscoveryCommand(ILog log, IVariables variables, IKubernetesDiscovererFactory discovererFactory) { this.log = log; this.variables = variables; this.discovererFactory = discovererFactory; } /// <returns> /// The Discovery Command always returns 0 to indicate success /// because a failure to discover targets should not cause a /// deployment process to fail. The one exception is if the /// json is malformed as this can only occur if there is /// a code issue and not from user misconfiguration. /// </returns> public override int Execute(string[] commandLineArguments) { if (!TryGetDiscoveryContextJson(out var json)) { log.Warn($"Could not find target discovery context in variable {ContextVariableName}."); return ExitStatus.Success; } if (!TryGetAuthenticationContextTypeAndDiscoveryContextScope(json, out var type, out var scope)) return ExitStatus.OtherError; if (!discovererFactory.TryGetKubernetesDiscoverer(type, out var discoverer)) { log.Warn($"Authentication Context type of {type} is not currently supported for discovery."); return ExitStatus.Success; } List<KubernetesCluster> clusters; try { clusters = discoverer.DiscoverClusters(json).ToList(); } catch (Exception e) { log.Warn($"Unable to discover clusters due to '{type}' specific error, see Verbose log for details."); log.Verbose($"Error occured during cluster discovery for {type}: {e}"); return ExitStatus.Success; } log.Verbose($"Found {clusters.Count} candidate clusters."); var discoveredTargetCount = 0; foreach (var cluster in clusters) { var matchResult = scope.Match(cluster.Tags); if (matchResult.IsSuccess) { discoveredTargetCount++; log.Info($"Discovered matching cluster: {cluster.Name}"); WriteTargetCreationServiceMessage(cluster, matchResult, scope); } else { log.Verbose($"Cluster {cluster.Name} does not match target requirements:"); foreach (var reason in matchResult.FailureReasons) { log.Verbose($"- {reason}"); } } } log.Info(discoveredTargetCount > 0 ? $"{discoveredTargetCount} clusters found matching the given scope." : "Could not find any clusters matching the given scope."); return ExitStatus.Success; } void WriteTargetCreationServiceMessage(KubernetesCluster cluster, TargetMatchResult matchResult, TargetDiscoveryScope scope) { var parameters = new Dictionary<string, string> { { "name", cluster.Name }, { "clusterName", cluster.ClusterName }, { "clusterUrl", cluster.Endpoint }, { "clusterResourceGroup", cluster.ResourceGroupName }, { "clusterAdminLogin", null }, { "namespace", null }, { "skipTlsVerification", bool.TrueString }, { "octopusDefaultWorkerPoolIdOrName", cluster.WorkerPool ?? scope.WorkerPoolId }, { "octopusAccountIdOrName", cluster.AccountId }, { "octopusClientCertificateIdOrName", null }, { "octopusServerCertificateIdOrName", null }, { "octopusRoles", matchResult.Role }, { "healthCheckContainerImageFeedIdOrName", scope.HealthCheckContainer?.FeedIdOrName }, { "healthCheckContainerImage", scope.HealthCheckContainer?.ImageNameAndTag }, { "updateIfExisting", bool.TrueString }, { "isDynamic", bool.TrueString }, { "clusterProject", null }, { "clusterRegion", null }, { "clusterZone", null }, { "clusterImpersonateServiceAccount", null }, { "clusterServiceAccountEmails", null }, { "clusterUseVmServiceAccount", null }, { "awsUseWorkerCredentials", cluster.AwsUseWorkerCredentials.ToString() }, { "awsAssumeRole", (cluster.AwsAssumeRole != null).ToString() }, { "awsAssumeRoleArn", cluster.AwsAssumeRole?.Arn }, { "awsAssumeRoleSession", cluster.AwsAssumeRole?.Session }, { "awsAssumeRoleSessionDurationSeconds", cluster.AwsAssumeRole?.SessionDuration?.ToString() }, { "awsAssumeRoleExternalId", cluster.AwsAssumeRole?.ExternalId } }; var serviceMessage = new ServiceMessage( CreateKubernetesTargetServiceMessageName, parameters.Where(p => p.Value != null) .ToDictionary(p => p.Key, p => p.Value)); log.WriteServiceMessage(serviceMessage); } bool TryGetDiscoveryContextJson(out string json) { return (json = variables.Get(ContextVariableName)) != null; } bool TryGetAuthenticationContextTypeAndDiscoveryContextScope( string contextJson, out string type, out TargetDiscoveryScope scope) { type = null; scope = null; try { var discoveryContext = JsonConvert .DeserializeObject<TargetDiscoveryContext<AuthenticationType>>(contextJson); type = discoveryContext?.Authentication?.Type; scope = discoveryContext?.Scope; if (type != null && scope != null) return true; log.Error($"Could not extract Authentication Type or Scope from {ContextVariableName}, the data is in the wrong format."); return false; } catch (JsonException ex) { log.Error($"Could not extract Authentication Type or Scope from {ContextVariableName}, the data is in the wrong format: {ex.Message}"); return false; } } class AuthenticationType : ITargetDiscoveryAuthenticationDetails { public string Type { get; set; } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Autofac; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.StructuredVariables { /// <summary> /// Order matters, so we opt for explicit registration over scanning /// </summary> public class StructuredConfigVariablesModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<JsonFormatVariableReplacer>().As<IFileFormatVariableReplacer>().WithPriority(1); builder.RegisterType<XmlFormatVariableReplacer>().As<IFileFormatVariableReplacer>().WithPriority(2); builder.RegisterType<YamlFormatVariableReplacer>().As<IFileFormatVariableReplacer>().WithPriority(3); builder.RegisterType<PropertiesFormatVariableReplacer>().As<IFileFormatVariableReplacer>().WithPriority(4); builder.RegisterPrioritisedList<IFileFormatVariableReplacer>(); builder.RegisterType<StructuredConfigVariablesService>().As<IStructuredConfigVariablesService>(); } } public interface IStructuredConfigVariablesService { void ReplaceVariables(string currentDirectory); void ReplaceVariables(string currentDirectory, List<string> targets); } public class StructuredConfigVariablesService : IStructuredConfigVariablesService { readonly IFileFormatVariableReplacer jsonReplacer; readonly IFileFormatVariableReplacer[] allReplacers; readonly IVariables variables; readonly ICalamariFileSystem fileSystem; readonly ILog log; public StructuredConfigVariablesService( PrioritisedList<IFileFormatVariableReplacer> replacers, IVariables variables, ICalamariFileSystem fileSystem, ILog log) { this.fileSystem = fileSystem; this.log = log; allReplacers = replacers.ToArray(); this.variables = variables; jsonReplacer = replacers.FirstOrDefault(r => r.FileFormatName == StructuredConfigVariablesFileFormats.Json) ?? throw new Exception("No JSON replacer was supplied. A JSON replacer is required as a fallback."); } public void ReplaceVariables(string currentDirectory) { ReplaceVariables(currentDirectory, variables.GetPaths(ActionVariables.StructuredConfigurationVariablesTargets)); } public void ReplaceVariables(string currentDirectory, List<string> targets) { var onlyPerformJsonReplacement = variables.GetFlag(ActionVariables.StructuredConfigurationFallbackFlag); foreach (var target in targets) { if (fileSystem.DirectoryExists(target)) { log.Warn($"Skipping structured variable replacement on '{target}' because it is a directory."); continue; } var matchingFiles = MatchingFiles(currentDirectory, target); if (!matchingFiles.Any()) { log.Warn($"No files were found that match the replacement target pattern '{target}'"); continue; } foreach (var filePath in matchingFiles) { var replacersToTry = GetReplacersToTryForFile(filePath, onlyPerformJsonReplacement).ToArray(); log.Verbose($"The registered replacers we will try, in order, are: " + string.Join(",", replacersToTry.Select(r => r.GetType().Name))); DoReplacement(filePath, variables, replacersToTry); } } } List<string> MatchingFiles(string currentDirectory, string target) { var globMode = GlobModeRetriever.GetFromVariables(variables); var files = fileSystem.EnumerateFilesWithGlob(currentDirectory, globMode, target).Select(Path.GetFullPath).ToList(); foreach (var path in variables.GetStrings(ActionVariables.AdditionalPaths).Where(s => !string.IsNullOrWhiteSpace(s))) { var pathFiles = fileSystem.EnumerateFilesWithGlob(path, globMode, target).Select(Path.GetFullPath); files.AddRange(pathFiles); } return files; } IEnumerable<IFileFormatVariableReplacer> GetReplacersToTryForFile(string filePath, bool onlyPerformJsonReplacement) { return GetParsersWhenOnlyPerformingJsonReplacement(filePath, onlyPerformJsonReplacement) ?? GetParsersBasedOnFileName(filePath) ?? GetAllParsers(filePath); } IEnumerable<IFileFormatVariableReplacer>? GetParsersWhenOnlyPerformingJsonReplacement(string filePath, bool onlyPerformJsonReplacement) { if (!onlyPerformJsonReplacement) { return null; } log.Verbose($"The {ActionVariables.StructuredConfigurationFallbackFlag} flag is set. The file at " + $"{filePath} will be parsed as JSON."); return new[] { jsonReplacer }; } IEnumerable<IFileFormatVariableReplacer>? GetParsersBasedOnFileName(string filePath) { var guessedParserBasedOnFileName = allReplacers.FirstOrDefault(r => r.IsBestReplacerForFileName(filePath)); if (guessedParserBasedOnFileName == null) { return null; } var guessedParserMessage = $"The file at {filePath} matches a known filename pattern, and will be " + $"treated as {guessedParserBasedOnFileName.FileFormatName}."; if (guessedParserBasedOnFileName == jsonReplacer) { log.Verbose(guessedParserMessage); return new[] { jsonReplacer }; } log.Verbose($"${guessedParserMessage} The file will be tried as {jsonReplacer.FileFormatName} first for backwards compatibility."); return new[] { jsonReplacer, guessedParserBasedOnFileName }; } IEnumerable<IFileFormatVariableReplacer> GetAllParsers(string filePath) { log.Verbose($"The file at {filePath} does not match any known filename patterns. " + "The file will be tried as multiple formats and will be treated as the first format that can be successfully parsed."); // Order so that the json replacer comes first yield return jsonReplacer; foreach (var replacer in allReplacers.Except(new[] { jsonReplacer })) { yield return replacer; } } void DoReplacement(string filePath, IVariables variables, IFileFormatVariableReplacer[] replacersToTry) { for (var r = 0; r < replacersToTry.Length; r++) { var replacer = replacersToTry[r]; var format = replacer.FileFormatName; var isLastParserToTry = r == replacersToTry.Length - 1; try { log.Verbose($"Attempting structured variable replacement on file {filePath} with format {format}"); replacer.ModifyFile(filePath, variables); log.Info($"Structured variable replacement succeeded on file {filePath} with format {format}"); return; } catch (StructuredConfigFileParseException parseException) when (!isLastParserToTry) { log.Verbose($"The file at {filePath} couldn't be parsed as {format}: {parseException.Message}"); } catch (StructuredConfigFileParseException parseException) { var message = $"Structured variable replacement failed on file {filePath}. " + $"The file could not be parsed as {format}: {parseException.Message} " + "See verbose logs for more details."; throw new Exception(message); } } } } }<file_sep>using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Calamari.Tests")] <file_sep>using System; using System.Linq; using System.Text.RegularExpressions; using Assent; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.StructuredVariables { [TestFixture] public class JsonFormatVariableReplacerFixture : VariableReplacerFixture { public JsonFormatVariableReplacerFixture() : base((fs, log) => new JsonFormatVariableReplacer(fs, log)) { } [Test] public void DoesNothingIfThereAreNoVariables() { this.Assent(Replace(new CalamariVariables(), "appsettings.simple.json"), AssentConfiguration.Json); } [Test] public void DoesNothingIfThereAreNoMatchingVariables() { Replace(new CalamariVariables { { "Non-matching", "variable" } }, "appsettings.simple.json"); Log.MessagesInfoFormatted.Should().Contain(StructuredConfigMessages.NoStructuresFound); Log.MessagesVerboseFormatted.Should().NotContain(m => Regex.IsMatch(m, StructuredConfigMessages.StructureFound(".*"))); } [Test] public void ShouldReplaceInSimpleFile() { this.Assent(Replace(new CalamariVariables { { "MyMessage", "Hello world" }, { "EmailSettings:SmtpHost", "localhost" }, { "EmailSettings:SmtpPort", "23" }, { "EmailSettings:DefaultRecipients:To", "<EMAIL>" }, { "EmailSettings:DefaultRecipients:Cc", "<EMAIL>" } }, "appsettings.simple.json"), AssentConfiguration.Json); Log.MessagesVerboseFormatted.Count(m => Regex.IsMatch(m, StructuredConfigMessages.StructureFound(".*"))).Should().Be(5); Log.MessagesVerboseFormatted.Should().Contain(StructuredConfigMessages.StructureFound("EmailSettings:SmtpPort")); Log.MessagesInfoFormatted.Should().NotContain(StructuredConfigMessages.NoStructuresFound); } [Test] public void ShouldIgnoreOctopusPrefix() { this.Assent(Replace(new CalamariVariables { { "MyMessage", "Hello world!" }, { "IThinkOctopusIsGreat", "Yes, I do!" }, { "OctopusRocks", "This is ignored" }, { "Octopus.Rocks", "So is this" }, { "Octopus:Section", "Should work" } }, "appsettings.ignore-octopus.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceVariablesInTopLevelArray() { this.Assent(Replace(new CalamariVariables { { "0:Property", "NewValue" } }, "appsettings.top-level-array.json"), AssentConfiguration.Json); } [Test] public void ShouldKeepExistingValues() { this.Assent(Replace(new CalamariVariables { { "MyMessage", "Hello world!" }, { "EmailSettings:SmtpPort", "24" }, { "EmailSettings:DefaultRecipients:Cc", "<EMAIL>" } }, "appsettings.existing-expected.json"), AssentConfiguration.Json); } [Test] public void ShouldMatchAndReplaceIgnoringCase() { this.Assent(Replace(new CalamariVariables { { "mymessage", "Hello! world!" }, { "EmailSettings:Defaultrecipients:To", "<EMAIL>" }, { "EmailSettings:defaultRecipients:Cc", "<EMAIL>" } }, "appsettings.simple.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceWithAnEmptyString() { this.Assent(Replace(new CalamariVariables { { "MyMessage", "" } }, "appsettings.single.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceWithNull() { this.Assent(Replace(new CalamariVariables { { "MyMessage", null } }, "appsettings.single.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceWithColonInName() { this.Assent(Replace(new CalamariVariables { { "EnvironmentVariables:Hosting:Environment", "Production" } }, "appsettings.colon-in-name.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceWholeObject() { this.Assent(Replace(new CalamariVariables { { "EmailSettings:DefaultRecipients", @"{""To"": ""<EMAIL>"", ""Cc"": ""<EMAIL>""}" } }, "appsettings.simple.json"), AssentConfiguration.Json); } [Test] public void ObjectIsNotModifiedIfTheVariableValueCannotBeParsed() { this.Assent(Replace(new CalamariVariables { { "EmailSettings:DefaultRecipients", @"{<<<<" } }, "appsettings.simple.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceElementInArray() { this.Assent(Replace(new CalamariVariables { { "EmailSettings:DefaultRecipients:1", "<EMAIL>" } }, "appsettings.array.json"), AssentConfiguration.Json); } [Test] public void ShouldReplacePropertyOfAnElementInArray() { this.Assent(Replace(new CalamariVariables { { "EmailSettings:DefaultRecipients:1:Email", "<EMAIL>" } }, "appsettings.object-array.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceEntireArray() { this.Assent(Replace(new CalamariVariables { { "EmailSettings:DefaultRecipients", @"[""<EMAIL>"", ""<EMAIL>""]" } }, "appsettings.array.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceNumber() { this.Assent(Replace(new CalamariVariables { { "EmailSettings:SmtpPort", "8023" } }, "appsettings.array.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceDecimal() { this.Assent(Replace(new CalamariVariables { { "DecimalValue", "50.0" }, { "FloatValue", "456e-5" }, { "StringValue", "60.0" }, { "IntegerValue", "70" } }, "appsettings.decimals.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceBoolean() { this.Assent(Replace(new CalamariVariables { { "EmailSettings:UseProxy", "true" } }, "appsettings.array.json"), AssentConfiguration.Json); } [Test] public void ShouldReplaceStructures() { this.Assent(Replace(new CalamariVariables { {"mapping2mapping", "{\"this\": \"is\", \"new\": \"mapping\"}"}, {"sequence2sequence", "[ \"another\", \"sequence\", \"altogether\" ]"}, {"mapping2sequence", "[\"a\",\"sequence\"]"}, {"sequence2mapping", "{ \"this\": \"now\", \"has\": \"keys\" }"}, {"mapping2string", "\"no longer a mapping\""}, {"sequence2string", "\"no longer a sequence\""}, }, "structures.json"), AssentConfiguration.Json); } [Test] public void ShouldFallBackToStringIfTypePreservationFails() { this.Assent(Replace(new CalamariVariables { { "null2num", "33" }, { "null2str", "bananas" }, { "null2obj", @"{""x"": 1}" }, { "null2arr", "[3, 2]" }, { "bool2null", "null" }, { "bool2num", "52" }, { "num2null", "null" }, { "num2bool", "true" }, { "num2arr", "[1]" }, { "str2bool", "false" } }, "types-fall-back.json"), AssentConfiguration.Json); } [Test] public void ShouldExpandOctopusVariableReferences() { this.Assent(Replace(new CalamariVariables { { "Smtp.Host", "mail.example.com" }, { "EmailSettings:SmtpHost", "#{Smtp.Host}" } }, "appsettings.simple.json"), AssentConfiguration.Json); } [Test] public void ShouldPreserveEncodingUtf8DosBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf8-dos-bom.json"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingUtf8UnixNoBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf8-unix-nobom.json"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingUtf16DosBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf16-dos-bom.json"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingWindows1252DosNoBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-windows1252-dos-nobom.json"), AssentConfiguration.Default); } [Test] public void ShouldUpgradeEncodingIfNecessaryToAccomodateVariables() { this.Assent(ReplaceToHex(new CalamariVariables{{"dagger", "\uFFE6"}}, "enc-windows1252-dos-nobom.json"), AssentConfiguration.Default); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Microsoft.Azure.Management.WebSites; namespace Calamari.AzureWebApp { class LogAzureWebAppDetailsBehaviour : IDeployBehaviour { readonly ILog log; Dictionary<string, string> portalLinks = new Dictionary<string, string> { { "AzureGlobalCloud", "portal.azure.com" }, { "AzureChinaCloud", "portal.azure.cn" }, { "AzureUSGovernment", "portal.azure.us" }, { "AzureGermanCloud", "portal.microsoftazure.de" } }; public LogAzureWebAppDetailsBehaviour(ILog log) { this.log = log; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment deployment) { try { var variables = deployment.Variables; var resourceGroupName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName, string.Empty); var siteAndSlotName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var azureEnvironment = variables.Get(SpecialVariables.Action.Azure.Environment); var account = new AzureServicePrincipalAccount(variables); var client = await account.CreateWebSiteManagementClient(); var site = await client.WebApps.GetAsync(resourceGroupName, siteAndSlotName); if (site != null) { var portalUrl = GetAzurePortalUrl(azureEnvironment); log.Info($"Default Host Name: {site.DefaultHostName}"); log.Info($"Application state: {site.State}"); log.Info("Links:"); log.Info(log.FormatLink($"https://{site.DefaultHostName}")); if (!site.HttpsOnly.HasValue || site.HttpsOnly == false) { log.Info(log.FormatLink($"http://{site.DefaultHostName}")); } var portalUri = $"https://{portalUrl}/#@/resource{site.Id}"; log.Info(log.FormatLink(portalUri, "View in Azure Portal")); } } catch { // do nothing } } string GetAzurePortalUrl(string environment) { if (!string.IsNullOrEmpty(environment) && portalLinks.ContainsKey(environment)) { return portalLinks[environment]; } return portalLinks["AzureGlobalCloud"]; } } }<file_sep>using System; namespace Calamari.Common.Plumbing.FileSystem { public enum FailureOptions { ThrowOnFailure = 1, IgnoreFailure = 2 } }<file_sep>using System; using System.Collections.Generic; namespace Calamari.Common.Plumbing.Extensions { public static class DictionaryExtensions { public static void AddRange(this IDictionary<string, string> collection, IDictionary<string, string> items) { if (items == null) return; foreach (var obj in items) collection[obj.Key] = obj.Value; } } }<file_sep>using System; using System.IO; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.FileSystem; using Calamari.Integration.Processes; namespace Calamari.Commands { [Command("apply-delta", Description = "Applies a delta file to a package to create a new version of the package")] public class ApplyDeltaCommand : Command { string? basisFileName; string? fileHash; string? deltaFileName; string? newFileName; bool showProgress; bool skipVerification; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; readonly ILog log; public ApplyDeltaCommand(ILog log, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner) { this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; this.log = log; Options.Add("basisFileName=", "The file that the delta was created for.", v => basisFileName = v); Options.Add("fileHash=", "", v => fileHash = v); Options.Add("deltaFileName=", "The delta to apply to the basis file", v => deltaFileName = v); Options.Add("newFileName=", "The file to write the result to.", v => newFileName = v); Options.Add("progress", "Whether progress should be written to stdout", v => showProgress = true); Options.Add("skipVerification", "Skip checking whether the basis file is the same as the file used to produce the signature that created the delta.", v => skipVerification = true); } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); string deltaFilePath; string newFilePath; string basisFilePath; try { ValidateParameters(out basisFilePath, out deltaFilePath, out newFilePath); var tempNewFilePath = newFilePath + ".partial"; #if USE_OCTODIFF_EXE var factory = new OctoDiffCommandLineRunner(commandLineRunner); #else var factory = new OctoDiffLibraryCallRunner(); #endif var octoDiff = factory.OctoDiff .Action("patch") .PositionalArgument(basisFilePath) .PositionalArgument(deltaFilePath) .PositionalArgument(tempNewFilePath); if(skipVerification) octoDiff.Flag("skip-verification"); if(showProgress) octoDiff.Flag("progress"); log.InfoFormat("Applying delta to {0} with hash {1} and storing as {2}", basisFilePath, fileHash ?? string.Empty, newFilePath); var result = factory.Execute(); if (result.ExitCode != 0) { fileSystem.DeleteFile(tempNewFilePath, FailureOptions.ThrowOnFailure); throw new CommandLineException("OctoDiff", result.ExitCode, result.Errors); } fileSystem.MoveFile(tempNewFilePath, newFilePath); if (!File.Exists(newFilePath)) throw new CommandException($"Failed to apply delta file {deltaFilePath} to {basisFilePath}"); } catch (Exception e) when (e is CommandLineException || e is CommandException) { log.DeltaVerificationError(e.Message); return 0; } var package = PackagePhysicalFileMetadata.Build(newFilePath); if (package == null) return 0; log.DeltaVerification(newFilePath, package.Hash, package.Size); return 0; } void ValidateParameters(out string basisFilePath, out string deltaFilePath, out string newFilePath) { Guard.NotNullOrWhiteSpace(basisFileName, "No basis file was specified. Please pass --basisFileName MyPackage.1.0.0.0.nupkg"); Guard.NotNullOrWhiteSpace(fileHash, "No file hash was specified. Please pass --fileHash MyFileHash"); Guard.NotNullOrWhiteSpace(deltaFileName, "No delta file was specified. Please pass --deltaFileName MyPackage.1.0.0.0_to_1.0.0.1.octodelta"); Guard.NotNullOrWhiteSpace(newFileName, "No new file name was specified. Please pass --newFileName MyPackage.1.0.0.1.nupkg"); basisFilePath = basisFileName; if (!File.Exists(basisFileName)) { basisFilePath = Path.GetFullPath(basisFileName); if (!File.Exists(basisFilePath)) throw new CommandException("Could not find basis file: " + basisFileName); } deltaFilePath = deltaFileName; if (!File.Exists(deltaFileName)) { deltaFilePath = Path.GetFullPath(deltaFileName); if (!File.Exists(deltaFilePath)) throw new CommandException("Could not find delta file: " + deltaFileName); } // Probably dont need to do this since the server appends a guid in the name... maybe it was originall put here in the name of safety? var newPackageDetails = PackageName.FromFile(newFileName); newFilePath = Path.Combine(PackageStore.GetPackagesDirectory(), PackageName.ToCachedFileName(newPackageDetails.PackageId, newPackageDetails.Version, newPackageDetails.Extension)); var hash = HashCalculator.Hash(basisFileName); if (hash != fileHash) { throw new CommandException($"Basis file hash `{hash}` does not match the file hash specified `{fileHash}`"); } } } }<file_sep>using System; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Newtonsoft.Json; namespace Calamari.Deployment.PackageRetention.Model { public class PackageCache { [JsonProperty] public CacheAge CacheAge { get; private set; } public PackageCache(int cacheAge) { CacheAge = new CacheAge(cacheAge); } [JsonConstructor] public PackageCache(CacheAge cacheAge) { CacheAge = cacheAge; } public void IncrementCacheAge() { CacheAge.IncrementAge(); } } }<file_sep>using System; using Calamari.Common.Plumbing.Commands.Options; namespace Calamari.Common.Plumbing.Commands { public static class CommandLineArgumentsExtensions { public static void ParseArgument(this string[] commandLineArguments, string argumentName, Action<string> action) { var customOptions = new OptionSet(); customOptions.Add($"{argumentName}=",$"", action); customOptions.Parse(commandLineArguments); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus { [TestFixture] public class ResourceRetrieverTests { [Test] public void ReturnsCorrectObjectHierarchyForDeployments() { var deploymentUid = Guid.NewGuid().ToString(); var replicaSetUid = Guid.NewGuid().ToString(); var nginxDeployment = new ResourceResponseBuilder() .WithKind("Deployment") .WithName("nginx") .WithUid(deploymentUid) .Build(); var nginxReplicaSet = new ResourceResponseBuilder() .WithKind("ReplicaSet") .WithName("nginx-replicaset") .WithUid(replicaSetUid) .WithOwnerUid(deploymentUid) .Build(); var pod1 = new ResourceResponseBuilder() .WithKind("Pod") .WithName("nginx-pod-1") .WithOwnerUid(replicaSetUid) .Build(); var pod2 = new ResourceResponseBuilder() .WithKind("Pod") .WithName("nginx-pod-2") .WithOwnerUid(replicaSetUid) .Build(); var kubectlGet = new MockKubectlGet(); var resourceRetriever = new ResourceRetriever(kubectlGet); kubectlGet.SetResource("nginx", nginxDeployment); kubectlGet.SetAllResources("ReplicaSet", nginxReplicaSet); kubectlGet.SetAllResources("Pod", pod1, pod2); var got = resourceRetriever.GetAllOwnedResources( new List<ResourceIdentifier> { new ResourceIdentifier("Deployment", "nginx", "octopus") }, null, new Options()); got.Should().BeEquivalentTo(new object[] { new { Kind = "Deployment", Name = "nginx", Children = new object[] { new { Kind = "ReplicaSet", Name = "nginx-replicaset", Children = new object[] { new { Kind = "Pod", Name = "nginx-pod-1"}, new { Kind = "Pod", Name = "nginx-pod-2"}, } } } } }); } [Test] public void ReturnsCorrectObjectHierarchyForMultipleResources() { var deployment1Uid = Guid.NewGuid().ToString(); var deployment2Uid = Guid.NewGuid().ToString(); var deployment1 = new ResourceResponseBuilder() .WithKind("Deployment") .WithName("deployment-1") .WithUid(deployment1Uid) .Build(); var replicaSet1 = new ResourceResponseBuilder() .WithKind("ReplicaSet") .WithName("replicaset-1") .WithOwnerUid(deployment1Uid) .Build(); var deployment2 = new ResourceResponseBuilder() .WithKind("Deployment") .WithName("deployment-2") .WithUid(deployment2Uid) .Build(); var replicaSet2 = new ResourceResponseBuilder() .WithKind("ReplicaSet") .WithName("replicaset-2") .WithOwnerUid(deployment2Uid) .Build(); var kubectlGet = new MockKubectlGet(); var resourceRetriever = new ResourceRetriever(kubectlGet); kubectlGet.SetResource("deployment-1", deployment1); kubectlGet.SetResource("deployment-2", deployment2); kubectlGet.SetAllResources("ReplicaSet", replicaSet1, replicaSet2); kubectlGet.SetAllResources("Pod"); var got = resourceRetriever.GetAllOwnedResources( new List<ResourceIdentifier> { new ResourceIdentifier("Deployment", "deployment-1", "octopus"), new ResourceIdentifier("Deployment", "deployment-2", "octopus") }, null, new Options()); got.Should().BeEquivalentTo(new object[] { new { Kind = "Deployment", Name = "deployment-1", Children = new object[] { new { Kind = "ReplicaSet", Name = "replicaset-1", } } }, new { Kind = "Deployment", Name = "deployment-2", Children = new object[] { new { Kind = "ReplicaSet", Name = "replicaset-2", } } } }); } [Test] public void IgnoresIrrelevantResources() { var replicaSetUid = Guid.NewGuid().ToString(); var replicaSet = new ResourceResponseBuilder() .WithKind("ReplicaSet") .WithName("rs") .WithUid(replicaSetUid) .Build(); var childPod = new ResourceResponseBuilder() .WithKind("Pod") .WithName("pod-1") .WithOwnerUid(replicaSetUid) .Build(); var irrelevantPod = new ResourceResponseBuilder() .WithKind("Pod") .WithName("pod-x") .Build(); var kubectlGet = new MockKubectlGet(); var resourceRetriever = new ResourceRetriever(kubectlGet); kubectlGet.SetResource("rs", replicaSet); kubectlGet.SetAllResources("Pod", childPod, irrelevantPod); var got = resourceRetriever.GetAllOwnedResources( new List<ResourceIdentifier> { new ResourceIdentifier("ReplicaSet", "rs", "octopus"), }, null, new Options()); got.Should().BeEquivalentTo(new object[] { new { Kind = "ReplicaSet", Name = "rs", Children = new object[] { new { Kind = "Pod", Name = "pod-1" } } } }); } } public class MockKubectlGet : IKubectlGet { private readonly Dictionary<string, string> resourceEntries = new Dictionary<string, string>(); private readonly Dictionary<string, string> resourcesByKind = new Dictionary<string, string>(); public void SetResource(string name, string data) { resourceEntries.Add(name, data); } public void SetAllResources(string kind, params string[] data) { resourcesByKind.Add(kind, $"{{items: [{string.Join(",", data)}]}}"); } public string Resource(string kind, string name, string @namespace, IKubectl kubectl) { return resourceEntries[name]; } public string AllResources(string kind, string @namespace, IKubectl kubectl) { return resourcesByKind[kind]; } } public class ResourceResponseBuilder { private static string template = @" {{ ""kind"": ""{0}"", ""metadata"": {{ ""name"": ""{1}"", ""uid"": ""{2}"", ""ownerReferences"": [ {{ ""uid"": ""{3}"" }} ] }} }}"; private string kind = ""; private string name = ""; private string uid = Guid.NewGuid().ToString(); private string ownerUid = Guid.NewGuid().ToString(); public ResourceResponseBuilder WithKind(string kind) { this.kind = kind; return this; } public ResourceResponseBuilder WithName(string name) { this.name = name; return this; } public ResourceResponseBuilder WithUid(string uid) { this.uid = uid; return this; } public ResourceResponseBuilder WithOwnerUid(string ownerUid) { this.ownerUid = ownerUid; return this; } public string Build() => string.Format(template, kind, name, uid, ownerUid); } }<file_sep>#nullable enable using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Azure.ResourceManager; using Azure.ResourceManager.AppService.Models; using Calamari.AzureAppService.Azure; using Calamari.AzureAppService.Json; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Newtonsoft.Json; namespace Calamari.AzureAppService.Behaviors { class AzureAppServiceSettingsBehaviour : IDeployBehaviour { private ILog Log { get; } public AzureAppServiceSettingsBehaviour(ILog log) { Log = log; } public bool IsEnabled(RunningDeployment context) { return FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.IsEnabled(context.Variables) && (!string.IsNullOrWhiteSpace(context.Variables.Get(SpecialVariables.Action.Azure.AppSettings)) || !string.IsNullOrWhiteSpace(context.Variables.Get(SpecialVariables.Action.Azure.ConnectionStrings))); } public async Task Execute(RunningDeployment context) { // Read/Validate variables Log.Verbose("Starting App Settings Deploy"); var variables = context.Variables; var principalAccount = ServicePrincipalAccount.CreateFromKnownVariables(variables); var webAppName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); if (webAppName == null) throw new Exception("Web App Name must be specified"); var resourceGroupName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName); if (resourceGroupName == null) throw new Exception("resource group name must be specified"); var targetSite = new AzureTargetSite(principalAccount.SubscriptionNumber, resourceGroupName, webAppName, slotName); var armClient = principalAccount.CreateArmClient(); // If app settings are specified if (variables.GetNames().Contains(SpecialVariables.Action.Azure.AppSettings) && !string.IsNullOrWhiteSpace(variables[SpecialVariables.Action.Azure.AppSettings])) { var appSettingsJson = variables.Get(SpecialVariables.Action.Azure.AppSettings, ""); Log.Verbose($"Updating application settings:\n{appSettingsJson}"); var appSettings = JsonConvert.DeserializeObject<AppSetting[]>(appSettingsJson); await PublishAppSettings(armClient, principalAccount, targetSite, appSettings); Log.Info("Updated application settings"); } // If connection strings are specified if (variables.GetNames().Contains(SpecialVariables.Action.Azure.ConnectionStrings) && !string.IsNullOrWhiteSpace(variables[SpecialVariables.Action.Azure.ConnectionStrings])) { var connectionStringsJson = variables.Get(SpecialVariables.Action.Azure.ConnectionStrings, ""); Log.Verbose($"Updating connection strings:\n{connectionStringsJson}"); var connectionStrings = JsonConvert.DeserializeObject<ConnectionStringSetting[]>(connectionStringsJson); await PublishConnectionStrings(armClient, targetSite, connectionStrings); Log.Info("Updated connection strings"); } } /// <summary> /// combines and publishes app and slot settings /// </summary> /// <param name="armClient"></param> /// <param name="targetSite"></param> /// <param name="appSettings"></param> /// <param name="authToken"></param> /// <returns></returns> private async Task PublishAppSettings(ArmClient armClient, ServicePrincipalAccount principalAccount, AzureTargetSite targetSite, AppSetting[] appSettings) { var settingsDict = new AppServiceConfigurationDictionary(); var existingSlotSettings = new List<string>(); // for each app setting found on the web app (existing app setting) update it value and add if is a slot setting, add foreach (var (name, value, slotSetting) in await armClient.GetAppSettingsListAsync(targetSite)) { settingsDict.Properties[name] = value; if (slotSetting) existingSlotSettings.Add(name); } // for each app setting defined by the user foreach (var setting in appSettings) { // add/update the settings value settingsDict.Properties[setting.Name] = setting.Value; // if the user indicates a settings should no longer be a slot setting if (existingSlotSettings.Contains(setting.Name) && !setting.SlotSetting) { Log.Verbose($"Removing {setting.Name} from the list of slot settings"); existingSlotSettings.Remove(setting.Name); } } await armClient.UpdateAppSettingsAsync(targetSite, settingsDict); var slotSettings = appSettings .Where(setting => setting.SlotSetting) .Select(setting => setting.Name) .ToArray(); if (!slotSettings.Any()) return; await armClient.UpdateSlotSettingsAsync(targetSite, slotSettings.Union(existingSlotSettings)); } private async Task PublishConnectionStrings(ArmClient armClient, AzureTargetSite targetSite, ConnectionStringSetting[] newConStrings) { var conStrings = await armClient.GetConnectionStringsAsync(targetSite); foreach (var connectionStringSetting in newConStrings) { conStrings.Properties[connectionStringSetting.Name] = new ConnStringValueTypePair(connectionStringSetting.Value, connectionStringSetting.Type); } await armClient.UpdateConnectionStringsAsync(targetSite, conStrings); } } } #nullable restore<file_sep>#if !NET40 using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Commands.Executors; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus; namespace Calamari.Kubernetes.Commands { [Command(Name, Description = "Apply Raw Yaml to Kubernetes Cluster")] public class KubernetesApplyRawYamlCommand : KubernetesDeploymentCommandBase { public const string Name = "kubernetes-apply-raw-yaml"; private readonly IVariables variables; private readonly IResourceStatusReportExecutor statusReporter; private readonly IGatherAndApplyRawYamlExecutor gatherAndApplyRawYamlExecutor; public KubernetesApplyRawYamlCommand( ILog log, IDeploymentJournalWriter deploymentJournalWriter, IVariables variables, ICalamariFileSystem fileSystem, IExtractPackage extractPackage, ISubstituteInFiles substituteInFiles, IStructuredConfigVariablesService structuredConfigVariablesService, IGatherAndApplyRawYamlExecutor gatherAndApplyRawYamlExecutor, IResourceStatusReportExecutor statusReporter, Kubectl kubectl) : base(log, deploymentJournalWriter, variables, fileSystem, extractPackage, substituteInFiles, structuredConfigVariablesService, kubectl) { this.variables = variables; this.statusReporter = statusReporter; this.gatherAndApplyRawYamlExecutor = gatherAndApplyRawYamlExecutor; } protected override async Task<bool> ExecuteCommand(RunningDeployment runningDeployment) { if (!variables.GetFlag(SpecialVariables.ResourceStatusCheck)) { return await gatherAndApplyRawYamlExecutor.Execute(runningDeployment); } var timeoutSeconds = variables.GetInt32(SpecialVariables.Timeout) ?? 0; var waitForJobs = variables.GetFlag(SpecialVariables.WaitForJobs); var statusCheck = statusReporter.Start(timeoutSeconds, waitForJobs); return await gatherAndApplyRawYamlExecutor.Execute(runningDeployment, statusCheck.AddResources) && await statusCheck.WaitForCompletionOrTimeout(); } } } #endif<file_sep>using System; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using JavaPropertiesParser; using JavaPropertiesParser.Expressions; using JavaPropertiesParser.Utils; namespace Calamari.Common.Features.StructuredVariables { public class PropertiesFormatVariableReplacer : IFileFormatVariableReplacer { readonly ICalamariFileSystem fileSystem; readonly ILog log; public PropertiesFormatVariableReplacer(ICalamariFileSystem fileSystem, ILog log) { this.fileSystem = fileSystem; this.log = log; } public string FileFormatName => StructuredConfigVariablesFileFormats.Properties; public bool IsBestReplacerForFileName(string fileName) { return fileName.EndsWith(".properties", StringComparison.InvariantCultureIgnoreCase); } public void ModifyFile(string filePath, IVariables variables) { try { var fileText = fileSystem.ReadFile(filePath, out var encoding); var parsed = Parser.Parse(fileText); var replaced = 0; var updated = parsed.Mutate(expr => { var newExpr = TryReplaceValue(expr, variables); if (!ReferenceEquals(newExpr, expr)) replaced++; return newExpr; }); if (replaced == 0) log.Info(StructuredConfigMessages.NoStructuresFound); var serialized = updated.ToString(); fileSystem.OverwriteFile(filePath, serialized, encoding); } catch (Sprache.ParseException e) { throw new StructuredConfigFileParseException(e.Message, e); } } bool IsOctopusVariableName(string variableName) { return variableName.StartsWith("Octopus", StringComparison.OrdinalIgnoreCase); } ITopLevelExpression TryReplaceValue(ITopLevelExpression expr, IVariables variables) { switch (expr) { case KeyValuePairExpression pair: var logicalName = pair.Key?.Text?.LogicalValue ?? ""; if (!IsOctopusVariableName(logicalName) && variables.IsSet(logicalName)) { log.Verbose(StructuredConfigMessages.StructureFound(logicalName)); var logicalValue = variables.Get(logicalName); var encodedValue = Encode.Value(logicalValue); var newValueExpr = new ValueExpression(new StringValue(logicalValue, encodedValue)); // In cases where a key was specified with neither separator nor value // we have to add a separator, otherwise the value becomes part of the key. var separator = pair.Separator ?? new SeparatorExpression(":"); return new KeyValuePairExpression(pair.Key, separator, newValueExpr); } else { return expr; } default: return expr; } } } } <file_sep># Calamari.Tests.Fixtures.PackageDownload.NuGetFeedSupport This package exists purely to support Integration Tests of Calamari's NuGet package download functionality.<file_sep>using System.Collections.Generic; namespace Calamari.Aws.Integration.S3 { public interface IProvideS3TargetOptions { IEnumerable<S3TargetPropertiesBase> GetOptions(S3TargetMode mode); } }<file_sep>using System; using System.Collections.Generic; using Calamari.Aws.Deployment.Conventions; using Calamari.Aws.Integration.S3; using Calamari.Serialization; namespace Calamari.Aws.Serialization { public class FileSelectionsConverter : InheritedClassConverter<S3FileSelectionProperties, S3FileSelectionTypes> { static readonly IDictionary<S3FileSelectionTypes, Type> SelectionTypeMappings = new Dictionary<S3FileSelectionTypes, Type> { {S3FileSelectionTypes.SingleFile, typeof(S3SingleFileSelectionProperties)}, {S3FileSelectionTypes.MultipleFiles, typeof(S3MultiFileSelectionProperties)} }; protected override IDictionary<S3FileSelectionTypes, Type> DerivedTypeMappings => SelectionTypeMappings; protected override string TypeDesignatingPropertyName { get; } = "Type"; } }<file_sep>namespace Calamari.Util { public static class HelmVersionParser { //versionString from "helm version --client --short" public static HelmVersion? ParseVersion(string versionString) { //eg of output for helm 2: Client: v2.16.1+gbbdfe5e //eg of output for helm 3: v3.0.1+g7c22ef9 var indexOfVersionIdentifier = versionString.IndexOf('v'); if (indexOfVersionIdentifier == -1) return null; var indexOfVersionNumber = indexOfVersionIdentifier + 1; if (indexOfVersionNumber >= versionString.Length) return null; var version = versionString[indexOfVersionNumber]; switch (version) { case '3': return HelmVersion.V3; case '2': return HelmVersion.V2; default: return null; } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Calamari.Common.Plumbing.Extensions { public static class StringExtensions { public enum LineEnding { Unix, Dos } static readonly Regex NewlinesPattern = new Regex(@"(\r)?\n", RegexOptions.Compiled); public static bool ContainsIgnoreCase(this string originalString, string value) { return originalString.IndexOf(value, StringComparison.OrdinalIgnoreCase) != -1; } public static string EscapeSingleQuotedString(this string str) { return str.Replace("'", "''"); } public static byte[] EncodeInUtf8Bom(this string source) { return Encoding.UTF8.GetPreamble().Concat(source.EncodeInUtf8NoBom()).ToArray(); } public static byte[] EncodeInUtf8NoBom(this string source) { return Encoding.UTF8.GetBytes(source); } public static string AsRelativePathFrom(this string source, string baseDirectory) { // Adapted from https://stackoverflow.com/a/340454 var uri = new Uri(source); if (!baseDirectory.EndsWith(Path.DirectorySeparatorChar.ToString())) baseDirectory += Path.DirectorySeparatorChar.ToString(); var baseUri = new Uri(baseDirectory); var relativeUri = baseUri.MakeRelativeUri(uri); var relativePath = Uri.UnescapeDataString(relativeUri.ToString()); return relativePath; } public static bool IsValidUrl(this string value) { if (string.IsNullOrWhiteSpace(value)) return false; return Uri.TryCreate(value, UriKind.Absolute, out _); } public static string Join(this IEnumerable<string> values, string separator) { return string.Join(separator, values); } public static LineEnding GetMostCommonLineEnding(this string text) { return NewlinesPattern.Matches(text) .Cast<Match>() .Select(m => m.Groups[1].Success ? LineEnding.Dos : LineEnding.Unix) .GroupBy(lineEnding => lineEnding) .OrderByDescending(group => group.Count()) .FirstOrDefault() ?.Key ?? LineEnding.Dos; } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public static class DeploymentEnvironment { public static readonly string Id = "Octopus.Environment.Id"; public static readonly string Name = "Octopus.Environment.Name"; } }<file_sep>using Calamari.Aws.Deployment.Conventions; namespace Calamari.Aws.Integration.S3 { public class S3FileSelectionProperties : S3TargetPropertiesBase { public S3FileSelectionTypes Type { get; set; } } }<file_sep>namespace Calamari.Aws.Integration.S3 { public enum S3FileSelectionTypes { SingleFile, MultipleFiles } }<file_sep>using System; using System.Net; using Octopus.CoreUtilities; namespace Calamari.Common.Plumbing.Proxies { public static class ProxyInitializer { public static void InitializeDefaultProxy() { var proxy = ProxySettingsInitializer.GetProxySettingsFromEnvironment().CreateProxy(); if (proxy.Some()) WebRequest.DefaultWebProxy = proxy.Value; } } }<file_sep>using Calamari.Util; using NUnit.Framework; using System.Collections.Generic; using System.Linq; namespace Calamari.Tests.Fixtures.Util { [TestFixture] public class RelativeGlobFixture { [Test] public void HasCorrectRelativePathsForRootGlobAll() { var files = new List<string>{ @"c:\staging\content\first.txt", @"c:\staging\content\nested\two.txt" }; var matches = new RelativeGlobber((@base, pattern) => files, @"c:\staging").EnumerateFilesWithGlob("**/*").ToList(); Assert.AreEqual(@"content/first.txt", matches[0].MappedRelativePath); Assert.AreEqual( @"content/nested/two.txt", matches[1].MappedRelativePath); } [Test] public void HasCorrectRelativePathsForFolderGlob() { var files = new List<string>{ @"c:\staging\content\first.txt", @"c:\staging\content\nested\two.txt" }; var matches = new RelativeGlobber((@base, pattern) => files, @"c:\staging").EnumerateFilesWithGlob("content/**/*").ToList(); Assert.AreEqual(@"first.txt", matches[0].MappedRelativePath); Assert.AreEqual(@"nested/two.txt", matches[1].MappedRelativePath); } [Test] public void HasCorrectRelativePathsForRootGlobAllAndOverride() { var files = new List<string>{ @"c:\staging\content\first.txt", @"c:\staging\content\nested\two.txt" }; var matches = new RelativeGlobber((@base, pattern) => files, @"c:\staging").EnumerateFilesWithGlob("**/* => bob").ToList(); Assert.AreEqual(@"bob/content/first.txt", matches[0].MappedRelativePath); Assert.AreEqual(@"bob/content/nested/two.txt", matches[1].MappedRelativePath); } [Test] public void HasCorrectRelativePathsForFolderGlobAndOverride() { var files = new List<string>{ @"c:\staging\content\first.txt", @"c:\staging\content\nested\two.txt" }; var matches = new RelativeGlobber((@base, pattern) => files, @"c:\staging").EnumerateFilesWithGlob("content/**/* => bob").ToList(); Assert.AreEqual(@"bob/first.txt", matches[0].MappedRelativePath); Assert.AreEqual(@"bob/nested/two.txt", matches[1].MappedRelativePath); } [Test] public void CanFlattenUsingOverride() { var files = new List<string>{ @"c:\staging\content\first.txt", @"c:\staging\content\nested\two.txt" }; var matches = new RelativeGlobber((@base, pattern) => files, @"c:\staging").EnumerateFilesWithGlob("content/**/* => bob/*").ToList(); Assert.AreEqual(@"bob/first.txt", matches[0].MappedRelativePath); Assert.AreEqual(@"bob/two.txt", matches[1].MappedRelativePath); } [Test] public void DropsAllBaseFoldersForOverride() { var files = new List<string>{ @"c:\staging\content\nested\deep\first.txt", @"c:\staging\content\nested\deep\deeper\two.txt" }; var matches = new RelativeGlobber((@base, pattern) => files, @"c:\staging").EnumerateFilesWithGlob("content/nested/**/* => bob").ToList(); Assert.AreEqual(@"bob/deep/first.txt", matches[0].MappedRelativePath); Assert.AreEqual(@"bob/deep/deeper/two.txt", matches[1].MappedRelativePath); } } }<file_sep>using System; using System.Linq; using System.Text.RegularExpressions; using Assent; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Variables; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.StructuredVariables { [TestFixture] public class YamlVariableReplacerFixture : VariableReplacerFixture { public YamlVariableReplacerFixture() : base((fs, log) => new YamlFormatVariableReplacer(fs, log)) { } [Test] public void DoesNothingIfThereAreNoVariables() { this.Assent(Replace(new CalamariVariables(), "application.yaml"), AssentConfiguration.Yaml); } [Test] public void DoesNothingIfThereAreNoMatchingVariables() { Replace(new CalamariVariables { { "Non-matching", "variable" } }, "application.yaml"); Log.MessagesInfoFormatted.Should().Contain(StructuredConfigMessages.NoStructuresFound); Log.MessagesVerboseFormatted.Should().NotContain(m => Regex.IsMatch(m, StructuredConfigMessages.StructureFound(".*"))); } [Test] public void CanReplaceStringWithString() { this.Assent(Replace(new CalamariVariables { { "server:ports:0", "8080" }, { "spring:datasource:url", "" }, { "spring:h2:console:enabled", "false" }, { "spring:loggers:1:name", "rolling-file" }, { "environment", "production" } }, "application.yaml"), AssentConfiguration.Yaml); Log.MessagesVerboseFormatted.Count(m => Regex.IsMatch(m, StructuredConfigMessages.StructureFound(".*"))).Should().Be(5); Log.MessagesVerboseFormatted.Should().Contain(StructuredConfigMessages.StructureFound("spring:h2:console:enabled")); Log.MessagesInfoFormatted.Should().NotContain(StructuredConfigMessages.NoStructuresFound); } [Test] public void ShouldMatchAndReplaceIgnoringCase() { this.Assent(Replace(new CalamariVariables { { "Spring:h2:Console:enabled", "false" } }, "application.mixed-case.yaml"), AssentConfiguration.Yaml); } [Test] public void CanReplaceMappingWithString() { this.Assent(Replace(new CalamariVariables { { "server", "local" }, { "spring:datasource", "none" } }, "application.yaml"), AssentConfiguration.Yaml); } [Test] public void CanReplaceSequenceWithString() { this.Assent(Replace(new CalamariVariables { { "server:ports", "none" } }, "application.yaml"), AssentConfiguration.Yaml); } [Test] public void CanReplaceMappingDespiteReplacementInsideMapping() { this.Assent(Replace(new CalamariVariables { { "spring:datasource:dbcp2", "none" }, { "spring:datasource", "none" } }, "application.yaml"), AssentConfiguration.Yaml); } [Test] public void TypesAreInfluencedByThePositionInTheInputDocument() { this.Assent(Replace(new CalamariVariables { { "null1", "~" }, { "null2", "null" }, { "bool1", "true" }, { "bool2", "no" }, { "int1", "99" }, { "float1", "1.99" }, { "str1", "true" }, { "str2", "~" }, { "str3", "true" }, { "str3", "aye" }, { "str4", "cats.com" }, { "obj1", $"fruit: apple{Environment.NewLine}animal: sloth" }, { "seq1", $"- scissors{Environment.NewLine}- paper{Environment.NewLine}- rock" }, { "seq2:0", "Orange" } }, "types.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldReplaceVariablesInTopLevelSequence() { this.Assent(Replace(new CalamariVariables { { "1", "zwei" } }, "application.top-level-sequence.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldReplaceWithNull() { this.Assent(Replace(new CalamariVariables { // Note: although these replacements are unquoted in the output to match input style, // YAML strings do not require quotes, so they still string-equal to our variables. { "bool1", "null" }, { "int1", "~" }, { "float1", "null" }, { "str1", null }, { "obj1", "~" }, { "seq1", "null" }, { "seq2:0", "~" } }, "types.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldReplaceWithEmpty() { this.Assent(Replace(new CalamariVariables { { "obj1", "{}" }, { "seq1", "[]" } }, "types.yaml"), AssentConfiguration.Yaml); } [Test] public void CanReplaceStructuresWithBlank() { this.Assent(Replace(new CalamariVariables { { "obj1", "" }, { "seq1", null }, { "seq2", "" } }, "types.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldIgnoreOctopusPrefix() { this.Assent(Replace(new CalamariVariables { { "MyMessage", "Hello world!" }, { "IThinkOctopusIsGreat", "Yes, I do!" }, { "Octopus", "Foo: Bar" }, { "OctopusRocks", "This is ignored" }, { "Octopus.Rocks", "So is this" }, { "Octopus:Section", "Should work" } }, "application.ignore-octopus.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldExpandOctopusVariableReferences() { this.Assent(Replace(new CalamariVariables { { "Server.Port", "8080" }, { "Server:Ports:0", "#{Server.Port}" } }, "application.yaml"), AssentConfiguration.Yaml); } [Test] public void OutputShouldBeStringEqualToVariableWhenInputTypeDoesNotMatch() { this.Assent(Replace(new CalamariVariables { // Note: although these replacements are unquoted in the output to match input style, // YAML strings do not require quotes, so they still string-equal to our variables. { "null2num", "33" }, { "null2str", "bananas" }, { "null2obj", @"{""x"": 1}" }, { "null2arr", "[3, 2]" }, { "bool2null", "null" }, { "bool2num", "52" }, { "num2null", "null" }, { "num2bool", "true" }, { "num2arr", "[1]" }, { "str2bool", "false" } }, "types-fall-back.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldReplaceWithColonInName() { this.Assent(Replace(new CalamariVariables { { "spring:h2:console:enabled", "false" } }, "application.colon-in-name.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldPreserveDirectives() { // Note: because YamlDotNet outputs the default directives alongside any custom ones, they have been // included in the input file here to avoid implying we require them to be added. this.Assent(Replace(new CalamariVariables { { "spring:h2:console:enabled", "true" } }, "application.directives.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldPreserveComments() { this.Assent(Replace(new CalamariVariables { { "environment:matrix:2:DVersion", "stable" } }, "comments.yml"), AssentConfiguration.Yaml); } [Test] public void ParsingErrorPositionIsReportedToUser() { var message = ""; try { Replace(new CalamariVariables(), "broken.yaml"); } catch (StructuredConfigFileParseException ex) { message = ex.Message; } message.Should().MatchRegex(@"(?i)\bLine\W+4\b"); message.Should().MatchRegex(@"(?i)\bCol\w*\W+1\b"); } [Test] public void ShouldPreserveFlowAndBlockStyles() { this.Assent(Replace(new CalamariVariables(), "flow-and-block-styles.yaml"), AssentConfiguration.Yaml); } [Test] public void CanReplaceNestedList() { var nl = Environment.NewLine; this.Assent(Replace(new CalamariVariables { { "pets-config:pets", $"- name: Susan{nl} species: Cuttlefish{nl}- name: Craig{nl} species: Manta Ray" } }, "pets.yaml"), AssentConfiguration.Yaml); } [Test] public void CanReplaceStructures() { var nl = Environment.NewLine; this.Assent(Replace(new CalamariVariables { {"mapping2mapping", $"this: is{nl}new: mapping"}, {"sequence2sequence", $"- another{nl}- sequence{nl}- altogether"}, {"mapping2sequence", $"- a{nl}- sequence"}, {"sequence2mapping", $" this: now{nl} has: keys"}, {"mapping2string", "no longer a mapping"}, {"sequence2string", "no longer a sequence"}, }, "structures.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldPreserveMostCommonIndent() { this.Assent(Replace(new CalamariVariables { { "bbb:this:is", "much more" } }, "indenting.yaml"), AssentConfiguration.Yaml); } [Test] public void ShouldPreserveEncodingUtf8DosBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf8-dos-bom.yaml"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingUtf8UnixNoBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf8-unix-nobom.yaml"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingUtf16DosBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf16-dos-bom.yaml"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingWindows1252DosNoBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-windows1252-dos-nobom.yaml"), AssentConfiguration.Default); } [Test] public void ShouldUpgradeEncodingIfNecessaryToAccomodateVariables() { this.Assent(ReplaceToHex(new CalamariVariables{{"dagger", "\uFFE6"}}, "enc-windows1252-dos-nobom.yaml"), AssentConfiguration.Default); } } }<file_sep>#!/bin/bash echo "HTTP_PROXY:$HTTP_PROXY" echo "HTTPS_PROXY:$HTTPS_PROXY" echo "NO_PROXY:$NO_PROXY"<file_sep>using System.IO; namespace Calamari.Tests.Helpers { public static class DirectoryEx { public static void Copy(string sourcePath, string destPath) { if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); } foreach (var file in Directory.EnumerateFiles(sourcePath)) { var dest = Path.Combine(destPath, Path.GetFileName(file)); File.Copy(file, dest); } foreach (var folder in Directory.EnumerateDirectories(sourcePath)) { var dest = Path.Combine(destPath, Path.GetFileName(folder)); Copy(folder, dest); } } } }<file_sep>namespace Calamari.Testing.Requirements { public class RequiresMonoVersion423OrAboveAttribute : RequiresMinimumMonoVersionAttribute { public RequiresMonoVersion423OrAboveAttribute() : base(4, 2, 3) { } } }<file_sep>using System; using System.IO; using System.Text; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.NuGet; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; using SharpCompress.Common; using SharpCompress.Writers; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class PackageExtractorFixture : CalamariFixture { private const string PackageId = "Acme.Core"; private const string PackageVersion = "1.0.0.0-bugfix"; [Test] [TestCase(typeof(TarGzipPackageExtractor), "tar.gz", true)] [TestCase(typeof(TarPackageExtractor), "tar", true)] [TestCase(typeof(TarBzipPackageExtractor), "tar.bz2", true)] [TestCase(typeof(ZipPackageExtractor), "zip", true)] [TestCase(typeof(NupkgExtractor), "nupkg", false)] public void ExtractPumpsFilesToFilesystem(Type extractorType, string extension, bool preservesTimestamp) { var fileName = GetFileName(extension); var timeBeforeExtraction = DateTime.Now.AddSeconds(-1); var extractor = (IPackageExtractor) Activator.CreateInstance(extractorType, ConsoleLog.Instance); var targetDir = GetTargetDir(extractorType, fileName); var filesExtracted = extractor.Extract(fileName, targetDir); var textFileName = Path.Combine(targetDir, "my resource.txt"); var text = File.ReadAllText(textFileName); var fileInfo = new FileInfo(textFileName); if (preservesTimestamp) { Assert.Less(fileInfo.LastWriteTime, timeBeforeExtraction); } Assert.AreEqual(9, filesExtracted, "Mismatch in the number of files extracted"); //If you edit the nupkg file with Nuget Package Explorer it will add a _._ file to EmptyFolder and you'll get 5 here. Assert.AreEqual("Im in a package!", text.TrimEnd('\n'), "The contents of the extractd file do not match the expected value"); } [Test] [TestCase(typeof(TarGzipPackageExtractor), "tar.gz", true)] [TestCase(typeof(TarPackageExtractor), "tar", true)] [TestCase(typeof(TarBzipPackageExtractor), "tar.bz2", true)] [TestCase(typeof(ZipPackageExtractor), "zip", true)] [TestCase(typeof(NupkgExtractor), "nupkg", false)] public void ExtractCanHandleNestedPackage(Type extractorType, string extension, bool preservesTimestamp) { var fileName = GetFileName(extension); var extractor = (IPackageExtractor) Activator.CreateInstance(extractorType, ConsoleLog.Instance); var targetDir = GetTargetDir(extractorType, fileName); extractor.Extract(fileName, targetDir); var textFileName = Path.Combine(targetDir, "file-from-child-archive.txt"); Assert.That(File.Exists(textFileName), Is.False, $"The file '{Path.GetFileName(textFileName)}' should not have been extracted."); var childArchiveName = Path.Combine(targetDir, "child-archive." + extension); Assert.That(File.Exists(childArchiveName), Is.True, $"Expected nested archive '{Path.GetFileName(childArchiveName)}' to have been extracted"); } [Test] [TestCase(typeof(TarGzipPackageExtractor), "tar.gz", true)] [TestCase(typeof(TarPackageExtractor), "tar", true)] [TestCase(typeof(TarBzipPackageExtractor), "tar.bz2", true)] [TestCase(typeof(ZipPackageExtractor), "zip", true)] [TestCase(typeof(NupkgExtractor), "nupkg", false)] public void ExtractCanHandleNestedFolders(Type extractorType, string extension, bool preservesTimestamp) { var fileName = GetFileName(extension); var extractor = (IPackageExtractor) Activator.CreateInstance(extractorType, ConsoleLog.Instance); var targetDir = GetTargetDir(extractorType, fileName); extractor.Extract(fileName, targetDir); var textFileName = Path.Combine(targetDir, "ChildFolder", "file-in-child-folder.txt"); Assert.That(File.Exists(textFileName), Is.True, $"The file '{Path.GetFileName(textFileName)}' should have been extracted."); //nupkg should not ignore files in the package folder unless they are in package/services/metadata var packageFolderFileName = Path.Combine(targetDir, "package", "file-in-the-package-folder.txt"); Assert.That(File.Exists(packageFolderFileName), Is.True, $"The file '{Path.GetFileName(textFileName)}' should have been extracted."); } [Test] [TestCase(typeof(NupkgExtractor), "nupkg", false)] public void NupkgExtractDoesNotExtractMetadata(Type extractorType, string extension, bool preservesTimestamp) { var fileName = GetFileName(extension); var extractor = (IPackageExtractor) Activator.CreateInstance(extractorType, ConsoleLog.Instance); var targetDir = GetTargetDir(extractorType, fileName); extractor.Extract(fileName, targetDir); var textFileName = Path.Combine(targetDir, "package", "services", "metadata", "core-properties", "8e89f0a759d94c1aaab0626891f7b81f.psmdcp"); Assert.That(File.Exists(textFileName), Is.False, $"The file '{Path.GetFileName(textFileName)}' should not have been extracted."); } [Test] [TestCase(typeof(TarGzipPackageExtractor), "tar.gz", true)] [TestCase(typeof(TarPackageExtractor), "tar", true)] [TestCase(typeof(TarBzipPackageExtractor), "tar.bz2", true)] [TestCase(typeof(ZipPackageExtractor), "zip", true)] [TestCase(typeof(NupkgExtractor), "nupkg", false)] public void ExtractCanHandleEmptyFolders(Type extractorType, string extension, bool preservesTimestamp) { var fileName = GetFileName(extension); var extractor = (IPackageExtractor) Activator.CreateInstance(extractorType, ConsoleLog.Instance); var targetDir = GetTargetDir(extractorType, fileName); extractor.Extract(fileName, targetDir); var folderName = Path.Combine(targetDir, "EmptyFolder"); Assert.That(Directory.Exists(folderName), Is.True, $"The empty folder '{Path.GetFileName(folderName)}' should have been extracted."); } [Test] [TestCase(typeof(TarGzipPackageExtractor), "tar.gz", ArchiveType.Tar, CompressionType.GZip)] [TestCase(typeof(TarPackageExtractor), "tar", ArchiveType.Tar, CompressionType.None)] [TestCase(typeof(TarBzipPackageExtractor), "tar.bz2", ArchiveType.Tar, CompressionType.BZip2)] [TestCase(typeof(ZipPackageExtractor), "zip", ArchiveType.Zip, CompressionType.Deflate)] public void ExtractTakesIntoAccountEncoding(Type extractorType, string extension, ArchiveType archiveType, CompressionType compressionType) { const string characterSetToTest = "âçÿú¢ŤṵﻝﺕﻻⱩῠᾌ"; var memoryStream = new MemoryStream(); memoryStream.WriteByte(1); using (var tempFolder = TemporaryDirectory.Create()) { var fileName = Path.Combine(tempFolder.DirectoryPath, $"package.{extension}"); using (Stream stream = File.OpenWrite(fileName)) using (var writer = WriterFactory.Open(stream, archiveType, new WriterOptions(compressionType) { ArchiveEncoding = new ArchiveEncoding {Default = Encoding.UTF8} })) { foreach (var c in characterSetToTest) { memoryStream.Position = 0; writer.Write($"{c}", memoryStream); } } var extractor = (IPackageExtractor) Activator.CreateInstance(extractorType, ConsoleLog.Instance); var targetDir = GetTargetDir(extractorType, fileName); extractor.Extract(fileName, targetDir); foreach (var c in characterSetToTest) { File.Exists(Path.Combine(targetDir, c.ToString())).Should().BeTrue(); } } } [Test] //Latest version of SharpCompress throws an exception if a symbolic link is encountered and we haven't provided a handler for it. public void ExtractIgnoresSymbolicLinks() { var log = new InMemoryLog(); var fileName = GetFixtureResource("Samples", string.Format("{0}.{1}.{2}", PackageId, "1.0.0.0-symlink", "tar.gz")); var extractor = new TarGzipPackageExtractor(log); var targetDir = GetTargetDir(typeof(TarGzipPackageExtractor), fileName); extractor.Extract(fileName, targetDir); //If we get this far and an exception hasn't been thrown, the test has served it's purpose' //If the symbolic link actually exists, someone has implimented it but hasn't updated/deleted this test var symlink = Path.Combine(targetDir, "octopus-sample", "link-to-sample"); Assert.That(File.Exists(symlink), Is.False, $"Symbolic link exists, please update this test."); log.StandardOut.Should().ContainMatch("Cannot create symbolic link*"); } private string GetFileName(string extension) { return GetFixtureResource("Samples", string.Format("{0}.{1}.{2}", PackageId, PackageVersion, extension)); } private string GetTargetDir(Type extractorType, string fileName) { var targetDir = Path.Combine(Path.GetDirectoryName(fileName), extractorType.Name); if (Directory.Exists(targetDir)) { Directory.Delete(targetDir, true); } Directory.CreateDirectory(targetDir); return targetDir; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Nginx; using Newtonsoft.Json; namespace Calamari.Deployment.Features { public class NginxFeature : IFeature { static readonly string[] RootLocations = { "= /", "/" }; public string Name => "Octopus.Features.Nginx"; public string DeploymentStage => DeploymentStages.AfterDeploy; readonly NginxServer nginxServer; readonly ICalamariFileSystem fileSystem; public NginxFeature(NginxServer nginxServer, ICalamariFileSystem fileSystem) { this.nginxServer = nginxServer; this.fileSystem = fileSystem; } public void Execute(RunningDeployment deployment) { var variables = deployment.Variables; var (rootLocation, additionalLocations) = GetLocations(variables); if (rootLocation == null) throw new NginxMissingRootLocationException(); var enabledBindings = GetEnabledBindings(variables).ToList(); var sslCertificates = GetSslCertificates(enabledBindings, variables); var customNginxSslRoot = variables.Get(SpecialVariables.Action.Nginx.SslRoot); /* * Previous versions of the NGINX step did not expose the ability to define the file names of the configuration * files, and instead used the Package ID. This meant that multi-tenanted deployments that shared the same * package would overwrite each other when deployed to the same machine. * * To retain compatibility with existing deployments, the Package ID is still used as a default file name. * But if the config name setting has been defined, that is used instead. * * See https://github.com/OctopusDeploy/Issues/issues/6216 */ var virtualServerName = string.IsNullOrWhiteSpace(variables.Get(SpecialVariables.Action.Nginx.Server.ConfigName)) ? variables.Get(PackageVariables.PackageId) : variables.Get(SpecialVariables.Action.Nginx.Server.ConfigName); nginxServer .WithVirtualServerName(virtualServerName) .WithHostName(variables.Get(SpecialVariables.Action.Nginx.Server.HostName)) .WithServerBindings(enabledBindings, sslCertificates, customNginxSslRoot) .WithRootLocation(rootLocation) .WithAdditionalLocations(additionalLocations); Log.Verbose("Building nginx configuration"); var customNginxConfRoot = variables.Get(SpecialVariables.Action.Nginx.ConfigRoot); nginxServer.BuildConfiguration(customNginxConfRoot); Log.Verbose("Saving nginx configuration"); var tempDirectory = fileSystem.CreateTemporaryDirectory(); variables.Set("OctopusNginxFeatureTempDirectory", tempDirectory); nginxServer.SaveConfiguration(tempDirectory); } IDictionary<string, (string SubjectCommonName, string CertificatePem, string PrivateKeyPem)> GetSslCertificates(IEnumerable<Binding> enabledBindings, IVariables variables) { var sslCertsForEnabledBindings = new Dictionary<string, (string, string, string)>(); foreach (var httpsBinding in enabledBindings.Where(b => string.Equals("https", b.Protocol, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(b.CertificateVariable) )) { var certificateVariable = httpsBinding.CertificateVariable; var subjectCommonName = variables.Get($"{certificateVariable}.SubjectCommonName"); var certificatePem = variables.Get($"{certificateVariable}.CertificatePem"); var privateKeyPem = variables.Get($"{certificateVariable}.PrivateKeyPem"); sslCertsForEnabledBindings.Add(certificateVariable, (subjectCommonName, certificatePem, privateKeyPem)); } return sslCertsForEnabledBindings; } static IEnumerable<Binding> GetEnabledBindings(IVariables variables) { var bindingsString = variables.Get(SpecialVariables.Action.Nginx.Server.Bindings); if (string.IsNullOrWhiteSpace(bindingsString)) return new List<Binding>(); return TryParseJson<Binding>(bindingsString, out var bindings) ? bindings.Where(b => b.Enabled) : new List<Binding>(); } static (Location rootLocation, IEnumerable<Location> additionalLocations) GetLocations(IVariables variables) { var locationsString = variables.Get(SpecialVariables.Action.Nginx.Server.Locations); if(string.IsNullOrWhiteSpace(locationsString)) return (null, new List<Location>()); if (!TryParseJson<Location>(locationsString, out var locations)) throw new NginxMissingRootLocationException(); var rootLocation = locations.FirstOrDefault(l => RootLocations.Contains(l.Path)); if (rootLocation == null) throw new NginxMissingRootLocationException(); return (rootLocation, locations.Where(l => !string.Equals(rootLocation.Path, l.Path))); } static bool TryParseJson<T>(string json, out IEnumerable<T> items) { try { items = JsonConvert.DeserializeObject<IEnumerable<T>>(json); return true; } catch { items = null; return false; } } } } <file_sep>using System; using Calamari.Common.Plumbing.Commands; namespace Calamari.Common.Plumbing.Logging { public class LogCommandInvocationOutputSink : ICommandInvocationOutputSink { readonly ILog log; readonly bool outputAsVerbose; public LogCommandInvocationOutputSink(ILog log, bool outputAsVerbose) { this.log = log; this.outputAsVerbose = outputAsVerbose; } public void WriteInfo(string line) { if (outputAsVerbose) log.Verbose(line); else log.Info(line); } public void WriteError(string line) { log.Error(line); } } }<file_sep>using Calamari.Util; using NUnit.Framework; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using FluentAssertions; using NSubstitute; namespace Calamari.Tests.Fixtures.Util { [TestFixture] public class InputSubstitutionFixture { [Test] [TestCase("#{Octopus.Action.Package[package].ExtractedPath}", "Octopus.Action.Package[package].ExtractedPath=C:\\OctopusTest\\Api Test\\1\\Octopus-Primary\\Work\\20210804020317-7-11\\package", "C:\\\\OctopusTest\\\\Api Test\\\\1\\\\Octopus-Primary\\\\Work\\\\20210804020317-7-11\\\\package")] [TestCase("#{MyPassword[#{UserName}]}", "MyPassword[username]=C:\\OctopusTest;UserName=username", "C:\\\\OctopusTest")] [TestCase("#{if BoolVariable}#{TestVariable}#{/if}", "BoolVariable=True;TestVariable=C:\\OctopusTest", "C:\\\\OctopusTest")] [TestCase("#{if BoolVariable}#{TestVariable}#{else}#{OtherVariable}#{/if}", "BoolVariable=False;TestVariable=C:\\OctopusTest;OtherVariable=D:\\TestFolder", "D:\\\\TestFolder")] [TestCase("#{if Octopus.Environment.Name == \"Production\"}#{TestVariable}#{/if}", "Octopus.Environment.Name=Production;TestVariable=C:\\OctopusTest", "C:\\\\OctopusTest")] [TestCase("#{each w in MyWidgets}'#{w.Value.WidgetId}': #{if w.Value.WidgetId == WidgetIdSelector}This is my Widget!#{else}No widget matched :(#{/if}#{/each}", "WidgetIdSelector=Widget-2;MyWidgets={\"One\":{\"WidgetId\":\"Widget-1\",\"Name\":\"Widget-One\"},\"Two\":{\"WidgetId\":\"Widget-2\",\"Name\":\"Widget-Two\"}}", @"'Widget-1': No widget matched :('Widget-2': This is my Widget!")] [TestCase("#{each endpoint in Endpoints}#{endpoint},#{/each}", "Endpoints=C:\\A,D:\\B", "C:\\\\A,D:\\\\B,")] [TestCase("#{FilterVariable | ToUpper}", "FilterVariable=C:\\somelowercase", "C:\\\\SOMELOWERCASE")] [TestCase("#{MyVar | Match \"a b\"}", "MyVar=a b c", "true")] [TestCase("#{MyVar | StartsWith \"Ab\"}", "MyVar=Abc", "true")] [TestCase("#{MyVar | Match #{pattern}}", "MyVar=a b c;pattern=a b", "true")] [TestCase("#{MyVar | Substring \"8\" \"6\"}", "MyVar=Octopus Deploy", "Deploy")] public void CommonExpressionsAreEvaluated(string expression, string variables, string expectedResult) { var variableDictionary = ParseVariables(variables); string jsonInputs = "{\"testValue\":\"" + expression + "\"}"; var log = Substitute.For<ILog>(); string evaluatedInputs = InputSubstitution.SubstituteAndEscapeAllVariablesInJson(jsonInputs, variableDictionary, log); string expectedEvaluatedInputs = "{\"testValue\":\"" + expectedResult + "\"}"; Assert.AreEqual(expectedEvaluatedInputs, evaluatedInputs); log.DidNotReceive().Warn(Arg.Any<string>()); } [Test] public void SimpleExpressionsAreEvaluated() { var variableDictionary = new CalamariVariables(); string jsonInputs = "{\"testValue\":\"#{ | NowDateUtc}\"}"; var log = Substitute.For<ILog>(); string evaluatedInputs = InputSubstitution.SubstituteAndEscapeAllVariablesInJson(jsonInputs, variableDictionary, log); evaluatedInputs.Should().NotBeEmpty(); evaluatedInputs.Should().NotBeEquivalentTo(jsonInputs); log.DidNotReceive().Warn(Arg.Any<string>()); } [Test] public void VariablesInJsonInputsShouldBeEvaluated() { var variables = new CalamariVariables { { "Octopus.Action.Package[package].ExtractedPath", "C:\\OctopusTest\\Api Test\\1\\Octopus-Primary\\Work\\20210804020317-7-11\\package" }, }; string jsonInputs = "{\"containerNameOverride\":\"payload\",\"package\":{\"extractedToPath\":\"#{Octopus.Action.Package[package].ExtractedPath}\"},\"target\":{\"files\":[{\"path\":\"azure-blob-container-target.0.0.0.zip\",\"fileName\":{\"type\":\"original file name\"}}]}}"; string evaluatedInputs = InputSubstitution.SubstituteAndEscapeAllVariablesInJson(jsonInputs, variables, Substitute.For<ILog>()); string expectedEvaluatedInputs = "{\"containerNameOverride\":\"payload\",\"package\":{\"extractedToPath\":\"C:\\\\OctopusTest\\\\Api Test\\\\1\\\\Octopus-Primary\\\\Work\\\\20210804020317-7-11\\\\package\"},\"target\":{\"files\":[{\"path\":\"azure-blob-container-target.0.0.0.zip\",\"fileName\":{\"type\":\"original file name\"}}]}}"; Assert.AreEqual(expectedEvaluatedInputs, evaluatedInputs); } [Test] public void MissingVariableValue_LogsAWarning() { var variables = new CalamariVariables { }; string jsonInputs = "{\"containerNameOverride\":\"payload\",\"package\":{\"extractedToPath\":\"#{Octopus.Action.Package[package].ExtractedPath}\"},\"target\":{\"files\":[]}}"; var log = Substitute.For<ILog>(); InputSubstitution.SubstituteAndEscapeAllVariablesInJson(jsonInputs, variables, log); log.Received().Warn(Arg.Any<string>()); } [Test] public void InvalidVariableExpressionFails() { var variables = new CalamariVariables { }; string jsonInputs = "{\"package\":{\"extractedToPath\":\"#{Octopus.Action.Package[package]...ExtractedPath}\"}}"; Assert.Throws<CommandException>(() => InputSubstitution.SubstituteAndEscapeAllVariablesInJson(jsonInputs, variables, Substitute.For<ILog>())); } CalamariVariables ParseVariables(string variableDefinitions) { var variables = new CalamariVariables(); var items = variableDefinitions.Split(';'); foreach (var item in items) { var pair = item.Split('='); var key = pair.First(); var value = pair.Last(); variables[key] = value; } return variables; } } }<file_sep>using System.IO; using Calamari.Testing.Helpers; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus { public static class TestFileLoader { public static string Load(string filename) { var filePath = TestEnvironment.GetTestPath("KubernetesFixtures", "ResourceStatus", "assets", filename); return File.ReadAllText(filePath); } } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Calamari.AzureCloudService.CloudServicePackage.ManifestSchema { public class AzurePackageMetadata { public static readonly XName ElementName = PackageDefinition.AzureNamespace + "PackageMetaData"; static readonly XName KeyValuePairElementName = PackageDefinition.AzureNamespace + "KeyValuePair"; static readonly XName KeyElementName = PackageDefinition.AzureNamespace + "Key"; static readonly XName ValueElementName = PackageDefinition.AzureNamespace + "Value"; const string AzureVersionKey = "http://schemas.microsoft.com/windowsazure/ProductVersion/"; public AzurePackageMetadata() { Data = new Dictionary<string, string>(); } public AzurePackageMetadata(XElement element) { Data = element.Elements(KeyValuePairElementName) .ToDictionary(x => x.Element(KeyElementName).Value, x => x.Element(ValueElementName).Value); } public IDictionary<string, string> Data { get; private set; } public string AzureVersion { get { string version; return Data.TryGetValue(AzureVersionKey, out version) ? version : null; } set { Data[AzureVersionKey] = value; } } public XElement ToXml() { return new XElement(ElementName, Data.Select(kv => new XElement(KeyValuePairElementName, new XElement(KeyElementName, kv.Key), new XElement(ValueElementName, kv.Value))).ToArray()); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; namespace Calamari.Common.Features.ConfigurationTransforms { public interface ITransformFileLocator { IEnumerable<string> DetermineTransformFileNames(string sourceFile, XmlConfigTransformDefinition transformation, bool diagnosticLoggingEnabled, string currentDirectory); } }<file_sep>using System; using Calamari.Common.Features.Scripts; namespace Calamari.Scripting { static class SpecialVariables { public static class Packages { public static string ExtractedPath(string key) { return $"Octopus.Action.Package[{key}].ExtractedPath"; } public static string PackageFileName(string key) { return $"Octopus.Action.Package[{key}].PackageFileName"; } public static string PackageFilePath(string key) { return $"Octopus.Action.Package[{key}].PackageFilePath"; } } public static class Action { public const string SkipRemainingConventions = "Octopus.Action.SkipRemainingConventions"; public const string FailScriptOnErrorOutput = "Octopus.Action.FailScriptOnErrorOutput"; public static class Script { public static readonly string ScriptParameters = "Octopus.Action.Script.ScriptParameters"; public static readonly string ScriptSource = "Octopus.Action.Script.ScriptSource"; public static readonly string ExitCode = "Octopus.Action.Script.ExitCode"; public static string ScriptBodyBySyntax(ScriptSyntax syntax) { return $"Octopus.Action.Script.ScriptBody[{syntax.ToString()}]"; } } } } }<file_sep>using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class DeployWindowsServiceWithCustomServiceNameFixture : DeployWindowsServiceAbstractFixture { protected override string ServiceName => @"[f`o]o$b'[a]r"; [Test] public void ShouldEscapeBackslashesAndDollarSignsInArgumentsPassedToScExe() { Variables[SpecialVariables.Action.WindowsService.Arguments] = @"""c:\foo $dr bar\"" ArgumentWithoutSpace"; Variables["Octopus.Action.WindowsService.DisplayName"] = @"""c:\foo $dr bar\"" ArgumentWithoutSpace"; Variables["Octopus.Action.WindowsService.Description"] = @"""c:\foo $dr bar\"" ArgumentWithoutSpace"; RunDeployment(); } [Test] public void ShouldUpdateExistingServiceWithFunnyCharactersInServiceName() { RunDeployment(); //Simulate an update RunDeployment(); } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; namespace Calamari.Common.Features.ConfigurationTransforms { public class TransformFileLocator : ITransformFileLocator { readonly ICalamariFileSystem fileSystem; readonly ILog log; public TransformFileLocator(ICalamariFileSystem fileSystem, ILog log) { this.fileSystem = fileSystem; this.log = log; } public IEnumerable<string> DetermineTransformFileNames(string sourceFile, XmlConfigTransformDefinition transformation, bool diagnosticLoggingEnabled, string currentDirectory) { var defaultTransformFileName = DetermineTransformFileName(sourceFile, transformation, true); var transformFileName = DetermineTransformFileName(sourceFile, transformation, false); string fullTransformDirectoryPath; if (Path.IsPathRooted(transformFileName)) { fullTransformDirectoryPath = Path.GetFullPath(GetDirectoryName(transformFileName)); } else { var relativeTransformPath = fileSystem.GetRelativePath(sourceFile, transformFileName); fullTransformDirectoryPath = Path.GetFullPath(Path.Combine(GetDirectoryName(sourceFile), GetDirectoryName(relativeTransformPath))); } if (!fileSystem.DirectoryExists(fullTransformDirectoryPath)) { if (diagnosticLoggingEnabled) log.Verbose($" - Skipping as transform folder \'{fullTransformDirectoryPath}\' does not exist"); yield break; } // The reason we use fileSystem.EnumerateFiles here is to get the actual file-names from the physical file-system. // This prevents any issues with mis-matched casing in transform specifications. var enumerateFiles = fileSystem.EnumerateFiles(fullTransformDirectoryPath, GetFileName(defaultTransformFileName), GetFileName(transformFileName)).Distinct().ToArray(); if (enumerateFiles.Any()) { foreach (var transformFile in enumerateFiles) { var sourceFileName = GetSourceFileName(sourceFile, transformation, transformFileName, transformFile, currentDirectory); if (transformation.Advanced && !transformation.IsSourceWildcard && !string.Equals(transformation.SourcePattern, sourceFileName, StringComparison.OrdinalIgnoreCase)) { if (diagnosticLoggingEnabled) log.Verbose($" - Skipping as file name \'{sourceFileName}\' does not match the target pattern \'{transformation.SourcePattern}\'"); continue; } if (transformation.Advanced && transformation.IsSourceWildcard && !DoesFileMatchWildcardPattern(sourceFileName, transformation.SourcePattern)) { if (diagnosticLoggingEnabled) log.Verbose($" - Skipping as file name \'{sourceFileName}\' does not match the wildcard target pattern \'{transformation.SourcePattern}\'"); continue; } if (!fileSystem.FileExists(transformFile)) { if (diagnosticLoggingEnabled) log.Verbose($" - Skipping as transform \'{transformFile}\' does not exist"); continue; } if (string.Equals(sourceFile, transformFile, StringComparison.OrdinalIgnoreCase)) { if (diagnosticLoggingEnabled) log.Verbose($" - Skipping as target \'{sourceFile}\' is the same as transform \'{transformFile}\'"); continue; } yield return transformFile; } } else if (diagnosticLoggingEnabled) { if (GetFileName(defaultTransformFileName) == GetFileName(transformFileName)) log.Verbose($" - skipping as transform \'{GetFileName(defaultTransformFileName)}\' could not be found in \'{fullTransformDirectoryPath}\'"); else log.Verbose($" - skipping as neither transform \'{GetFileName(defaultTransformFileName)}\' nor transform \'{GetFileName(transformFileName)}\' could be found in \'{fullTransformDirectoryPath}\'"); } } private string GetSourceFileName(string sourceFile, XmlConfigTransformDefinition transformation, string transformFileName, string transformFile, string currentDirectory) { var sourcePattern = transformation.SourcePattern ?? ""; if (Path.IsPathRooted(transformFileName) && sourcePattern.StartsWith("." + Path.DirectorySeparatorChar)) { var path = fileSystem.GetRelativePath(currentDirectory, sourceFile); return "." + path.Substring(path.IndexOf(Path.DirectorySeparatorChar)); } if (sourcePattern.Contains(Path.DirectorySeparatorChar)) return fileSystem.GetRelativePath(transformFile, sourceFile) .TrimStart('.', Path.DirectorySeparatorChar); return GetFileName(sourceFile); } private static string DetermineTransformFileName(string sourceFile, XmlConfigTransformDefinition transformation, bool defaultExtension) { var tp = transformation.TransformPattern; if (defaultExtension && !tp.EndsWith(".config")) tp += ".config"; if (transformation.Advanced && transformation.IsTransformWildcard && transformation.IsSourceWildcard) { return DetermineWildcardTransformFileName(sourceFile, transformation, tp); } if (transformation.Advanced && transformation.IsTransformWildcard && !transformation.IsSourceWildcard) { var transformDirectory = GetTransformationFileDirectory(sourceFile, transformation); return Path.Combine(transformDirectory, GetDirectoryName(tp), "*." + GetFileName(tp).TrimStart('.')); } if (transformation.Advanced && !transformation.IsTransformWildcard) { var transformDirectory = GetTransformationFileDirectory(sourceFile, transformation); return Path.Combine(transformDirectory, tp); } return Path.ChangeExtension(sourceFile, tp); } static string DetermineWildcardTransformFileName(string sourceFile, XmlConfigTransformDefinition transformation, string transformPattern) { var sourcePatternWithoutPrefix = GetFileName(transformation.SourcePattern); if (transformation.SourcePattern != null && transformation.SourcePattern.StartsWith(".")) { sourcePatternWithoutPrefix = transformation.SourcePattern.Remove(0, 1); } var transformDirectory = GetTransformationFileDirectory(sourceFile, transformation); var baseFileName = transformation.IsSourceWildcard ? GetFileName(sourceFile).Replace(sourcePatternWithoutPrefix, "") : GetFileName(sourceFile); var baseTransformPath = Path.Combine(transformDirectory, GetDirectoryName(transformPattern), baseFileName); return Path.ChangeExtension(baseTransformPath, GetFileName(transformPattern)); } static bool DoesFileMatchWildcardPattern(string fileName, string? pattern) { var patternDirectory = GetDirectoryName(pattern); var regexBuilder = new StringBuilder(); regexBuilder.Append(Regex.Escape(patternDirectory)) .Append(string.IsNullOrEmpty(patternDirectory) ? string.Empty : Regex.Escape(Path.DirectorySeparatorChar.ToString())) .Append(".*?").Append(Regex.Escape(".")) .Append(Regex.Escape(Path.GetFileName(pattern)?.TrimStart('.') ?? string.Empty)); return Regex.IsMatch(fileName, regexBuilder.ToString(), RegexOptions.IgnoreCase); } [return: NotNullIfNotNull("path")] static string? GetDirectoryName(string? path) { return Path.GetDirectoryName(path); } [return: NotNullIfNotNull("path")] static string? GetFileName(string? path) { return Path.GetFileName(path); } static string GetTransformationFileDirectory(string sourceFile, XmlConfigTransformDefinition transformation) { var sourceDirectory = GetDirectoryName(sourceFile); if (transformation.SourcePattern == null || !transformation.SourcePattern.Contains(Path.DirectorySeparatorChar)) return sourceDirectory; var sourcePattern = transformation.SourcePattern; var sourcePatternPath = sourcePattern.Substring(0, sourcePattern.LastIndexOf(Path.DirectorySeparatorChar)); if (sourceDirectory.EndsWith(sourcePatternPath, StringComparison.OrdinalIgnoreCase)) return sourceDirectory.Substring(0, sourceDirectory.Length - sourcePatternPath.Length); return sourceDirectory; } } }<file_sep>using System; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using Calamari.AzureAppService.Azure; using Microsoft.Azure.Management.AppService.Fluent; using Microsoft.Azure.Management.AppService.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Rest; namespace Calamari.AzureAppService { internal class PublishingProfile { public string Site { get; set; } public string Password { get; set; } public string Username { get; set; } public string PublishUrl { get; set; } public string GetBasicAuthCredentials() => Convert.ToBase64String(Encoding.ASCII.GetBytes($"{Username}:{Password}")); public static async Task<PublishingProfile> GetPublishingProfile(AzureTargetSite targetSite, ServicePrincipalAccount account) { string mgmtEndpoint = account.ResourceManagementEndpointBaseUri; var token = new TokenCredentials(await Auth.GetAuthTokenAsync(account)); var azureCredentials = new AzureCredentials( token, token, account.TenantId, new AzureKnownEnvironment(account.AzureEnvironment).AsAzureSDKEnvironment()) .WithDefaultSubscription(account.SubscriptionNumber); var restClient = RestClient .Configure() .WithBaseUri(mgmtEndpoint) .WithEnvironment(new AzureKnownEnvironment(account.AzureEnvironment).AsAzureSDKEnvironment()) .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .WithCredentials(azureCredentials) .Build(); var webAppClient = new WebSiteManagementClient(restClient) {SubscriptionId = account.SubscriptionNumber}; var options = new CsmPublishingProfileOptions {Format = PublishingProfileFormat.WebDeploy}; await webAppClient.WebApps.GetWithHttpMessagesAsync(targetSite.ResourceGroupName, targetSite.Site); using var publishProfileStream = targetSite.HasSlot ? await webAppClient.WebApps.ListPublishingProfileXmlWithSecretsSlotAsync(targetSite.ResourceGroupName, targetSite.Site, options, targetSite.Slot) : await webAppClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(targetSite.ResourceGroupName, targetSite.Site, options); return await ParseXml(publishProfileStream); } public static async Task<PublishingProfile> ParseXml(Stream publishingProfileXmlStream) { using var streamReader = new StreamReader(publishingProfileXmlStream); var document = XDocument.Parse(await streamReader.ReadToEndAsync()); var profile = (from el in document.Descendants("publishProfile") where string.Compare(el.Attribute("publishMethod")?.Value, "MSDeploy", StringComparison.OrdinalIgnoreCase) == 0 select new PublishingProfile { PublishUrl = $"https://{el.Attribute("publishUrl")?.Value}", Username = el.Attribute("userName")?.Value, Password = el.Attribute("<PASSWORD>")?.Value, Site = el.Attribute("msdeploySite")?.Value }).FirstOrDefault(); if (profile == null) throw new Exception("Failed to retrieve publishing profile."); return profile; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Xml.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Hyak.Common; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Calamari.AzureCloudService { class ConfigureAzureCloudServiceBehaviour : IPreDeployBehaviour { readonly ILog log; readonly AzureAccount account; readonly ICalamariFileSystem fileSystem; public ConfigureAzureCloudServiceBehaviour(ILog log, AzureAccount account, ICalamariFileSystem fileSystem) { this.log = log; this.account = account; this.fileSystem = fileSystem; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment context) { // Validate we actually have a real path to the real config file since this value is potentially passed via variable or a previous convention var configurationFilePath = context.Variables.Get(SpecialVariables.Action.Azure.Output.ConfigurationFile); if (!fileSystem.FileExists(configurationFilePath)) throw new CommandException("Could not find the Azure Cloud Service Configuration file: " + configurationFilePath); var configuration = XDocument.Parse(fileSystem.ReadFile(configurationFilePath)); await UpdateConfigurationWithCurrentInstanceCount(configuration, configurationFilePath, context.Variables); UpdateConfigurationSettings(configuration, context.Variables); SaveConfigurationFile(configuration, configurationFilePath); } async Task<XDocument> GetConfiguration(string serviceName, DeploymentSlot slot) { using var client = account.CreateComputeManagementClient(CalamariCertificateStore.GetOrAdd(account.CertificateThumbprint, account.CertificateBytes)); try { var response = await client.Deployments.GetBySlotAsync(serviceName, slot); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"Getting deployment by slot returned HTTP Status Code: {response.StatusCode}"); } return string.IsNullOrEmpty(response.Configuration) ? null : XDocument.Parse(response.Configuration); } catch (CloudException exception) { log.VerboseFormat("Getting deployments for service '{0}', slot {1}, returned:\n{2}", serviceName, slot.ToString(), exception.Message); return null; } } void SaveConfigurationFile(XDocument document, string configurationFilePath) { fileSystem.OverwriteFile(configurationFilePath, document.ToString()); } void UpdateConfigurationSettings(XContainer configurationFile, IVariables variables) { log.Verbose("Updating configuration settings..."); var foundSettings = false; WithConfigurationSettings(configurationFile, (roleName, settingName, settingValueAttribute) => { var setting = variables.Get(roleName + "/" + settingName) ?? variables.Get(roleName + "\\" + settingName) ?? variables.Get(settingName) ?? (variables.GetNames().Contains(settingName) ? "" : null); if (setting != null) { foundSettings = true; log.InfoFormat("Updating setting for role {0}: {1} = {2}", roleName, settingName, setting); settingValueAttribute.Value = setting; } }); if (!foundSettings) { log.Info("No settings that match provided variables were found."); } } async Task UpdateConfigurationWithCurrentInstanceCount(XContainer localConfigurationFile, string configurationFileName, IVariables variables) { if (!variables.GetFlag(SpecialVariables.Action.Azure.UseCurrentInstanceCount)) return; var serviceName = variables.Get(SpecialVariables.Action.Azure.CloudServiceName); var slot = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), variables.Get(SpecialVariables.Action.Azure.Slot)); var remoteConfigurationFile = await GetConfiguration(serviceName, slot); if (remoteConfigurationFile == null) { log.InfoFormat("There is no current deployment of service '{0}' in slot '{1}', so existing instance counts will not be imported.", serviceName, slot); return; } var rolesByCount = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); log.Verbose("Local instance counts (from " + Path.GetFileName(configurationFileName) + "): "); WithInstanceCounts(localConfigurationFile, (roleName, attribute) => { log.Verbose(" - " + roleName + " = " + attribute.Value); string value; if (rolesByCount.TryGetValue(roleName, out value)) { attribute.SetValue(value); } }); log.Verbose("Remote instance counts: "); WithInstanceCounts(remoteConfigurationFile, (roleName, attribute) => { rolesByCount[roleName] = attribute.Value; log.Verbose(" - " + roleName + " = " + attribute.Value); }); log.Verbose("Replacing local instance count settings with remote settings: "); WithInstanceCounts(localConfigurationFile, (roleName, attribute) => { string value; if (!rolesByCount.TryGetValue(roleName, out value)) return; attribute.SetValue(value); log.Verbose(" - " + roleName + " = " + attribute.Value); }); } static void WithInstanceCounts(XContainer configuration, Action<string, XAttribute> roleAndCountAttributeCallback) { foreach (var roleElement in configuration.Elements() .SelectMany(e => e.Elements()) .Where(e => e.Name.LocalName == "Role")) { var roleNameAttribute = roleElement.Attributes().FirstOrDefault(x => x.Name.LocalName == "name"); if (roleNameAttribute == null) continue; var instancesElement = roleElement.Elements().FirstOrDefault(e => e.Name.LocalName == "Instances"); if (instancesElement == null) continue; var countAttribute = instancesElement.Attributes().FirstOrDefault(x => x.Name.LocalName == "count"); if (countAttribute == null) continue; roleAndCountAttributeCallback(roleNameAttribute.Value, countAttribute); } } static void WithConfigurationSettings(XContainer configuration, Action<string, string, XAttribute> roleSettingNameAndValueAttributeCallback) { foreach (var roleElement in configuration.Elements() .SelectMany(e => e.Elements()) .Where(e => e.Name.LocalName == "Role")) { var roleNameAttribute = roleElement.Attributes().FirstOrDefault(x => x.Name.LocalName == "name"); if (roleNameAttribute == null) continue; var configSettingsElement = roleElement.Elements().FirstOrDefault(e => e.Name.LocalName == "ConfigurationSettings"); if (configSettingsElement == null) continue; foreach (var settingElement in configSettingsElement.Elements().Where(e => e.Name.LocalName == "Setting")) { var nameAttribute = settingElement.Attributes().FirstOrDefault(x => x.Name.LocalName == "name"); if (nameAttribute == null) continue; var valueAttribute = settingElement.Attributes().FirstOrDefault(x => x.Name.LocalName == "value"); if (valueAttribute == null) continue; roleSettingNameAndValueAttributeCallback(roleNameAttribute.Value, nameAttribute.Value, valueAttribute); } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Runtime; using Calamari.Aws.Exceptions; using Calamari.Aws.Integration.CloudFormation; using Calamari.Aws.Integration.CloudFormation.Templates; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Variables; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Deployment.Conventions { public class CreateCloudFormationChangeSetConvention : CloudFormationInstallationConventionBase { readonly Func<IAmazonCloudFormation> clientFactory; readonly Func<RunningDeployment, StackArn> stackProvider; readonly Func<ICloudFormationRequestBuilder> templateFactory; public CreateCloudFormationChangeSetConvention(Func<IAmazonCloudFormation> clientFactory, StackEventLogger logger, Func<RunningDeployment, StackArn> stackProvider, Func<ICloudFormationRequestBuilder> templateFactory ) : base(logger) { Guard.NotNull(stackProvider, "Stack provider should not be null"); Guard.NotNull(clientFactory, "Client factory should not be null"); Guard.NotNull(templateFactory, "Template factory should not be null"); this.clientFactory = clientFactory; this.stackProvider = stackProvider; this.templateFactory = templateFactory; } public override void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private async Task InstallAsync(RunningDeployment deployment) { var stack = stackProvider(deployment); Guard.NotNull(stack, "The provided stack may not be null"); var name = deployment.Variables[AwsSpecialVariables.CloudFormation.Changesets.Name]; Guard.NotNullOrWhiteSpace(name, "The changeset name must be provided."); var template = templateFactory(); Guard.NotNull(template, "CloudFormation template should not be null."); try { var changeset = await CreateChangeSet(await template.BuildChangesetRequest()); await WaitForChangesetCompletion(changeset); ApplyVariables(deployment.Variables)(changeset); } catch (AmazonServiceException exception) { LogAmazonServiceException(exception); throw; } } private Task WaitForChangesetCompletion(RunningChangeSet result) { return clientFactory.WaitForChangeSetCompletion(CloudFormationDefaults.StatusWaitPeriod, result); } private Action<RunningChangeSet> ApplyVariables(IVariables variables) { return result => { SetOutputVariable(variables, "ChangesetId", result.ChangeSet.Value); SetOutputVariable(variables, "StackId", result.Stack.Value); variables.Set(AwsSpecialVariables.CloudFormation.Changesets.Arn, result.ChangeSet.Value); }; } private async Task<RunningChangeSet> CreateChangeSet(CreateChangeSetRequest request) { try { return (await clientFactory.CreateChangeSetAsync(request)) .Map(x => new RunningChangeSet(new StackArn(x.StackId), new ChangeSetArn(x.Id))); } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "AccessDenied") { throw new PermissionException( @"The AWS account used to perform the operation does not have the required permissions to create the change set.\n" + "Please ensure the current user has the cloudformation:CreateChangeSet permission.\n" + ex.Message + "\n", ex); } } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.Common.Commands; namespace Calamari.Common.Plumbing.Pipeline { public interface IBehaviour { public bool IsEnabled(RunningDeployment context); public Task Execute(RunningDeployment context); } }<file_sep>using System; using Calamari.Common.Plumbing.Logging; namespace Calamari.Common.Features.Processes.Semaphores { //Originally based on https://github.com/markedup-mobi/file-lock (MIT license) public class FileBasedSempahoreManager : ISemaphoreFactory { readonly ILog log; readonly ICreateSemaphores semaphoreCreator; readonly int initialWaitBeforeShowingLogMessage; public FileBasedSempahoreManager() { log = ConsoleLog.Instance; initialWaitBeforeShowingLogMessage = (int)TimeSpan.FromSeconds(3).TotalMilliseconds; semaphoreCreator = new LockFileBasedSemaphoreCreator(log); } public FileBasedSempahoreManager(ILog log, TimeSpan initialWaitBeforeShowingLogMessage, ICreateSemaphores semaphoreCreator) { this.log = log; this.semaphoreCreator = semaphoreCreator; this.initialWaitBeforeShowingLogMessage = (int)initialWaitBeforeShowingLogMessage.TotalMilliseconds; } public IDisposable Acquire(string name, string waitMessage) { var semaphore = semaphoreCreator.Create(name, TimeSpan.FromMinutes(2)); if (!semaphore.WaitOne(initialWaitBeforeShowingLogMessage)) { log.Verbose(waitMessage); semaphore.WaitOne(); } return new LockFileBasedSemaphoreReleaser(semaphore); } class LockFileBasedSemaphoreReleaser : IDisposable { readonly ISemaphore semaphore; public LockFileBasedSemaphoreReleaser(ISemaphore semaphore) { this.semaphore = semaphore; } public void Dispose() { semaphore.ReleaseLock(); } } } }<file_sep>#if NETFX using NUnit.Framework; using System; using System.IO; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.Helpers; namespace Calamari.Tests.Fixtures.Commands { [TestFixture] public class CommandFromModuleTest { private string Script = GetFixtureResource("Scripts", "awsscript.ps1"); private static string GetFixtureResource(params string[] paths) { var type = typeof(CommandFromModuleTest); return GetFixtureResource(type, paths); } private static string GetFixtureResource(Type type, params string[] paths) { var path = type.Namespace.Replace("Calamari.Tests.", String.Empty); path = path.Replace('.', Path.DirectorySeparatorChar); return Path.Combine(TestEnvironment.CurrentWorkingDirectory, path, Path.Combine(paths)); } private CalamariVariables BuildVariables() { var variables = new CalamariVariables(); variables.Set("Octopus.Action.AwsAccount.Variable", "AwsAccount"); variables.Set("Octopus.Action.Aws.Region", "us-east-1"); variables.Set("AWSAccount.AccessKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey)); variables.Set("AWSAccount.SecretKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); variables.Set("Octopus.Action.Aws.AssumeRole", "False"); variables.Set("Octopus.Action.Aws.AssumedRoleArn", ""); variables.Set("Octopus.Action.Aws.AssumedRoleSession", ""); variables.Set("Octopus.Account.AccountType", "AzureServicePrincipal"); variables.Set("Octopus.Action.Azure.TenantId", "2a881dca-3230-4e01-abcb-a1fd235c0981"); variables.Set("Octopus.Action.Azure.ClientId", ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId)); variables.Set("Octopus.Action.Azure.Password", ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword)); variables.Set("Octopus.Action.Azure.SubscriptionId", "cf21dc34-73dc-4d7d-bd86-041884e0bc75"); return variables; } [SetUp] public void SetUp() { ExternalVariables.LogMissingVariables(); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void RunScript() { Assert.IsTrue(File.Exists(Script), Script + " must exist as a file"); using (var temp = new TemporaryFile(Path.GetTempFileName())) { BuildVariables().Save(temp.FilePath); var args = new[] { "run-test-script", "--script=" + Script, "--variables=" + temp.FilePath }; ScriptHookMock.WasCalled = false; var retCode = TestProgramWrapper.Main(args); Assert.AreEqual(0, retCode); // TestModule should have been loaded because we are treating the // Calamari.Test dll as an extension. This means ScriptHookMock and // EnvironmentVariableHook have been placed in the container, and because // it is enabled they must have been called. Assert.IsTrue(ScriptHookMock.WasCalled); } } } } #endif<file_sep>using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; using Octostache; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] public class TransferPackageFixture : CalamariFixture { TemporaryFile nupkgFile; [OneTimeSetUp] public void Init() { nupkgFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0")); } protected string StagingDirectory { get; private set; } protected string CustomDirectory { get; private set; } [SetUp] public void SetUp() { var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); // Ensure staging directory exists and is empty StagingDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestStaging"); CustomDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestCustom"); fileSystem.EnsureDirectoryExists(StagingDirectory); fileSystem.PurgeDirectory(StagingDirectory, FailureOptions.ThrowOnFailure); Environment.SetEnvironmentVariable("TentacleJournal", Path.Combine(StagingDirectory, "DeploymentJournal.xml")); } [Test] public void ShouldPreserveFileInStagingDirectory() { var result = TransferPackage(); result.AssertSuccess(); Assert.IsTrue(File.Exists(nupkgFile.FilePath)); } [Test] public void ShouldCopyFileToTransferPath() { var result = TransferPackage(); result.AssertSuccess(); var outputResult = Path.Combine(CustomDirectory, Path.GetFileName(nupkgFile.FilePath)); Assert.IsTrue(File.Exists(outputResult)); } [Test] public void ShouldProvideOutputVaribles() { var result = TransferPackage(); result.AssertSuccess(); var outputResult = Path.Combine(CustomDirectory, Path.GetFileName(nupkgFile.FilePath)); result.AssertOutputVariable(PackageVariables.Output.DirectoryPath, Is.EqualTo(CustomDirectory)); result.AssertOutputVariable(PackageVariables.Output.FileName,Is.EqualTo(Path.GetFileName(nupkgFile.FilePath))); result.AssertOutputVariable(PackageVariables.Output.FilePath, Is.EqualTo(outputResult)); } [Test] public void ShouldOutputMessageToLogs() { var result = TransferPackage(); result.AssertSuccess(); result.AssertOutput( $"Copied package '{Path.GetFileName(nupkgFile.FilePath)}' to directory '{CustomDirectory}'"); } protected CalamariResult TransferPackage() { var variables = new VariableDictionary { [PackageVariables.TransferPath] = CustomDirectory, [PackageVariables.OriginalFileName] = Path.GetFileName(nupkgFile.FilePath), [TentacleVariables.CurrentDeployment.PackageFilePath] = nupkgFile.FilePath, [ActionVariables.Name] = "MyAction", [MachineVariables.Name] = "MyMachine" }; using (var variablesFile = new TemporaryFile(Path.GetTempFileName())) { variables.Save(variablesFile.FilePath); return Invoke(Calamari() .Action("transfer-package") .Argument("variables", variablesFile.FilePath)); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; /* * JSON format * "properties":{ * "appSettingNames":[ * "string1", * "string2" * ] *} * */ namespace Calamari.AzureAppService.Json { public class appSettingNamesRoot { public string name { get; set; } public string type => "Microsoft.Web/sites"; public properties properties { get; set; } } public class properties { public IEnumerable<string> appSettingNames { get; set; } public IEnumerable<string> connectionStringNames { get; set; } } } <file_sep>using System; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.ServiceMessages { /// <summary> /// Parses command-output for service-messages /// </summary> public class ServiceMessageCommandInvocationOutputSink : ICommandInvocationOutputSink { readonly IVariables variables; readonly ServiceMessageParser serviceMessageParser; public ServiceMessageCommandInvocationOutputSink(IVariables variables) { this.variables = variables; serviceMessageParser = new ServiceMessageParser(ProcessServiceMessage); } public void WriteInfo(string line) { serviceMessageParser.Parse(line); } public void WriteError(string line) { } void ProcessServiceMessage(ServiceMessage message) { switch (message.Name) { case ServiceMessageNames.SetVariable.Name: var variableName = message.GetValue(ServiceMessageNames.SetVariable.NameAttribute); var variableValue = message.GetValue(ServiceMessageNames.SetVariable.ValueAttribute); if (!string.IsNullOrWhiteSpace(variableName)) variables.SetOutputVariable(variableName, variableValue); break; } } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Security; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.WindowsPowerShell { public class PowerShellScriptExecutor : ScriptExecutor { protected override IEnumerable<ScriptExecution> PrepareExecution(Script script, IVariables variables, Dictionary<string, string>? environmentVars = null) { var powerShellBootstrapper = GetPowerShellBootstrapper(variables); var (bootstrapFile, otherTemporaryFiles) = powerShellBootstrapper.PrepareBootstrapFile(script, variables); var debuggingBootstrapFile = powerShellBootstrapper.PrepareDebuggingBootstrapFile(script); var executable = powerShellBootstrapper.PathToPowerShellExecutable(variables); var arguments = powerShellBootstrapper.FormatCommandArguments(bootstrapFile, debuggingBootstrapFile, variables); var invocation = new CommandLineInvocation(executable, arguments) { EnvironmentVars = environmentVars, WorkingDirectory = Path.GetDirectoryName(script.File), UserName = powerShellBootstrapper.AllowImpersonation() ? variables.Get(PowerShellVariables.UserName) : null, Password = powerShellBootstrapper.AllowImpersonation() ? ToSecureString(variables.Get(PowerShellVariables.Password)) : null }; return new[] { new ScriptExecution( invocation, otherTemporaryFiles.Concat(new[] { bootstrapFile, debuggingBootstrapFile }) ) }; } PowerShellBootstrapper GetPowerShellBootstrapper(IVariables variables) { if (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) return new UnixLikePowerShellCoreBootstrapper(); var specifiedEdition = variables[PowerShellVariables.Edition]; if (string.IsNullOrEmpty(specifiedEdition)) return new WindowsPowerShellBootstrapper(); if (specifiedEdition.Equals("Core", StringComparison.OrdinalIgnoreCase)) return new WindowsPowerShellCoreBootstrapper(CalamariPhysicalFileSystem.GetPhysicalFileSystem()); if (specifiedEdition.Equals("Desktop", StringComparison.OrdinalIgnoreCase)) return new WindowsPowerShellBootstrapper(); throw new PowerShellEditionNotFoundException(specifiedEdition); } [return: NotNullIfNotNull("unsecureString")] static SecureString? ToSecureString(string? unsecureString) { if (string.IsNullOrEmpty(unsecureString)) return null; return unsecureString.Aggregate(new SecureString(), (s, c) => { s.AppendChar(c); return s; }); } } public class PowerShellEditionNotFoundException : CommandException { public PowerShellEditionNotFoundException(string specifiedEdition) : base($"Attempted to use '{specifiedEdition}' edition of PowerShell, but this edition could not be found. Possible editions: Core, Desktop") { } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Deployment; using Calamari.Deployment.Conventions; namespace Calamari.Commands { public class DelegateInstallConvention : IInstallConvention { readonly Action<RunningDeployment> convention; public DelegateInstallConvention(Action<RunningDeployment> convention) { this.convention = convention; } public void Install(RunningDeployment deployment) => convention(deployment); } } <file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Model; using Calamari.Deployment.PackageRetention.Repositories; namespace Calamari.Tests.Fixtures.PackageRetention.Repository { public class InMemoryJournalRepository : JournalRepositoryBase { public InMemoryJournalRepository(Dictionary<PackageIdentity, JournalEntry> journalEntries) { this.journalEntries = journalEntries; Cache = new PackageCache(0); } public InMemoryJournalRepository() : this(new Dictionary<PackageIdentity, JournalEntry>()) { } public bool HasLock(PackageIdentity package) { return TryGetJournalEntry(package, out var entry) && entry.HasLock(); } public PackageUsages GetUsage(PackageIdentity package) { return TryGetJournalEntry(package, out var entry) ? entry.GetUsageDetails() : new PackageUsages(); } public override void Load() { } public override void Commit() { //This does nothing in the in-memory implementation } } }<file_sep>using System; using Calamari.Serialization; using Newtonsoft.Json; namespace Calamari.LaunchTools { public interface ILaunchTool { int Execute(string instructions); } public abstract class LaunchTool<T> : ILaunchTool where T: class { public int Execute(string instructions) { var toolSpecificInstructions = JsonConvert.DeserializeObject<T>(instructions, JsonSerialization.GetDefaultSerializerSettings()); return ExecuteInternal(toolSpecificInstructions); } protected abstract int ExecuteInternal(T instructions); } }<file_sep>using System; namespace Calamari.Common.Features.Processes { public class LibraryCallInvocation { public LibraryCallInvocation(Func<string[], int> func, string[] v) { Executable = func; Arguments = v; } public Func<string[], int> Executable { get; } public string[] Arguments { get; } } }<file_sep>namespace Calamari.Common.Features.Packages.Decorators { /// <summary> /// A base Decorator which allows addition to the behaviour of an IPackageExtractor /// </summary> public class PackageExtractorDecorator : IPackageExtractor { readonly IPackageExtractor concreteExtractor; protected PackageExtractorDecorator(IPackageExtractor concreteExtractor) { this.concreteExtractor = concreteExtractor; } public string[] Extensions => concreteExtractor.Extensions; public virtual int Extract(string packageFile, string directory) { return concreteExtractor.Extract(packageFile, directory); } } } <file_sep>namespace Calamari.Aws.Integration.S3 { public enum BucketKeyBehaviourType { Custom = 0, Filename = 1, FilenameWithContentHash = 2, } }<file_sep>using System.Xml; namespace Calamari.AzureCloudService.CloudServicePackage { public static class XmlUtils { const int MaxCharactersInDocument = (1024*1024*1024); // Max 1GB public static XmlReaderSettings DtdSafeReaderSettings { get { return new XmlReaderSettings() { //DtdProcessing = DtdProcessing.Parse, //Bug in netcore causes this to not build at 1/9/2016 DtdProcessing = (DtdProcessing)2, MaxCharactersInDocument = MaxCharactersInDocument }; } } } }<file_sep>using System; using System.IO; namespace Calamari.Common.Plumbing.FileSystem { public class TemporaryDirectory : IDisposable { public readonly string DirectoryPath; readonly ICalamariFileSystem fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); public TemporaryDirectory(string directoryPath) { DirectoryPath = directoryPath; } public void Dispose() { fileSystem.DeleteDirectory(DirectoryPath, FailureOptions.IgnoreFailure); } public static TemporaryDirectory Create() { var dir = Path.Combine(Path.GetTempPath(), "Test_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir); return new TemporaryDirectory(dir); } } }<file_sep>using System; using System.IO; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; namespace Calamari.Common.Features.Packages.Java { public static class JavaRuntime { static string ExecutingDirectory => Path.GetDirectoryName(typeof(JavaRuntime).Assembly.Location); public static string CmdPath { get { var javaHome = Environment.GetEnvironmentVariable("JAVA_HOME"); return string.IsNullOrEmpty(javaHome) ? "java" : Path.Combine(javaHome, "bin", "java"); } } public static void VerifyExists() { const string minimumJavaVersion = "1.8"; var jarFile = Path.Combine(ExecutingDirectory, "javatest.jar"); try { var silentProcessResult = SilentProcessRunner.ExecuteCommand(CmdPath, $"-jar \"{jarFile}\" {minimumJavaVersion}", ".", Console.WriteLine, i => Console.Error.WriteLine(i)); if (silentProcessResult.ExitCode == 0) return; } catch (Exception e) { Console.WriteLine(e); } throw new CommandException( $"Failed to run {CmdPath}. You must have Java {minimumJavaVersion} or later installed on the target machine, " + "and have the java executable on the path or have the JAVA_HOME environment variable defined"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Octopus.Versioning; using Octopus.Versioning.Semver; using YamlDotNet.RepresentationModel; namespace Calamari.Integration.Packages.Download.Helm { public static class HelmIndexYamlReader { public static IEnumerable<(string PackageId, IEnumerable<ChartData> Versions)> Read(YamlStream yaml) { var mapping = (YamlMappingNode)yaml.Documents[0].RootNode; var apiVersion = ((YamlScalarNode)mapping.Children[new YamlScalarNode("apiVersion")]).Value; if (apiVersion != "v1") throw new InvalidOperationException($"Octopus Deploy only supports the Helm repository api version 'v1'.\r\nThe version returned by this endpoint was '{apiVersion}'"); var entries = (YamlMappingNode)mapping.Children[new YamlScalarNode("entries")]; foreach (var node in entries) { var packageId = (YamlScalarNode)node.Key; if (packageId.Value == null) throw new InvalidOperationException($"PackageId was null"); yield return (packageId.Value, Foo((YamlSequenceNode)node.Value)); } } static IEnumerable<ChartData> Foo(YamlSequenceNode packageVersions) { foreach (var yamlNode in packageVersions) { var node = ChartData.FromNode((YamlMappingNode)yamlNode); if (node != null) { yield return node; } } } public class ChartData { readonly YamlMappingNode yamlNode; ChartData(YamlMappingNode yamlNode, IVersion version) { this.yamlNode = yamlNode; Version = version; } public static ChartData? FromNode(YamlMappingNode yamlNode) { var value = ((YamlScalarNode)yamlNode.Children[new YamlScalarNode("version")]).Value; if (value == null) return null; var version = SemVerFactory.TryCreateVersion(value); if (version == null) return null; if (yamlNode.Children.TryGetValue(new YamlScalarNode("deprecated"), out var deprecatedNode) && bool.TryParse(((YamlScalarNode)deprecatedNode).Value, out var isDeprecated) && isDeprecated) return null; return new ChartData(yamlNode, version); } public IVersion Version { get; } public string? Description => yamlNode.Children.TryGetValue(new YamlScalarNode("description"), out var descriptionNode) ? ((YamlScalarNode) descriptionNode).Value : null; public string? Name => ((YamlScalarNode) yamlNode.Children[new YamlScalarNode("name")]).Value; public DateTimeOffset? Published { get { if (yamlNode.Children.TryGetValue(new YamlScalarNode("created"), out var createdNode) && DateTimeOffset.TryParse(((YamlScalarNode) createdNode).Value, out var created)) { return created; } return null; } } public IEnumerable<string> Urls { get { return ((YamlSequenceNode) yamlNode.Children[new YamlScalarNode("urls")]).Children.Select(t => ((YamlScalarNode) t).Value).Where(x => x != null)!; } } } } }<file_sep>#!/bin/bash if [ "$(get_octopusvariable "ShouldFail")" == "yes" ]; then echo "You want me to fail" exit 1 fi echo "$(get_octopusvariable "PreDeployGreeting")" "from PreDeploy.sh" <file_sep>using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class StatefulSet: Resource { public override string ChildKind => "Pod"; public string Ready { get; } public StatefulSet(JObject json, Options options) : base(json, options) { var readyReplicas = FieldOrDefault("$.status.readyReplicas", 0); var replicas = FieldOrDefault("$.status.replicas", 0); Ready = $"{readyReplicas}/{replicas}"; ResourceStatus = readyReplicas == replicas ? ResourceStatus.Successful : ResourceStatus.InProgress; } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<StatefulSet>(lastStatus); return last.Ready != Ready; } } } <file_sep>using System; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.ConfigurationVariables { public interface IConfigurationVariablesReplacer { void ModifyConfigurationFile(string configurationFilePath, IVariables variables); } }<file_sep>using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.ResourceStatus.Resources; namespace Calamari.Kubernetes.ResourceStatus { public class ResourceFinder { private readonly IVariables variables; private readonly ICalamariFileSystem fileSystem; public ResourceFinder(IVariables variables, ICalamariFileSystem fileSystem) { this.variables = variables; this.fileSystem = fileSystem; } public IEnumerable<ResourceIdentifier> FindResources(string workingDirectory) { var defaultNamespace = variables.Get(SpecialVariables.Namespace, "default"); // When the namespace on a target was set and then cleared, it's going to be "" instead of null if (string.IsNullOrEmpty(defaultNamespace)) { defaultNamespace = "default"; } var manifests = ReadManifestFiles(workingDirectory).ToList(); var definedResources = KubernetesYaml.GetDefinedResources(manifests, defaultNamespace).ToList(); var secret = GetSecret(defaultNamespace); if (secret.HasValue) { definedResources.Add(secret.Value); } var configMap = GetConfigMap(defaultNamespace); if (configMap.HasValue) { definedResources.Add(configMap.Value); } return definedResources; } private IEnumerable<string> ReadManifestFiles(string workingDirectory) { var groupedFiles = GetGroupedYamlDirectories(workingDirectory).ToList(); if (groupedFiles.Any()) { return from file in groupedFiles where fileSystem.FileExists(file) select fileSystem.ReadFile(file); } return from file in GetManifestFileNames(workingDirectory) where fileSystem.FileExists(file) select fileSystem.ReadFile(file); } private IEnumerable<string> GetManifestFileNames(string workingDirectory) { var customResourceFileName = variables.Get(SpecialVariables.CustomResourceYamlFileName) ?? "customresource.yml"; return new[] { "secret.yml", customResourceFileName, "deployment.yml", "service.yml", "ingress.yml", }.Select(p => Path.Combine(workingDirectory, p)); } private IEnumerable<string> GetGroupedYamlDirectories(string workingDirectory) { var groupedDirectories = variables.Get(SpecialVariables.GroupedYamlDirectories); return groupedDirectories != null ? groupedDirectories.Split(';').SelectMany(d => fileSystem.EnumerateFilesRecursively(Path.Combine(workingDirectory, d))) : Enumerable.Empty<string>(); } private ResourceIdentifier? GetConfigMap(string defaultNamespace) { if (!variables.GetFlag("Octopus.Action.KubernetesContainers.KubernetesConfigMapEnabled")) { return null; } // Skip it if the user did not input configmap data if (!variables.GetIndexes("Octopus.Action.KubernetesContainers.ConfigMapData").Any()) { return null; } var configMapName = variables.Get("Octopus.Action.KubernetesContainers.ComputedConfigMapName"); return string.IsNullOrEmpty(configMapName) ? (ResourceIdentifier?)null : new ResourceIdentifier("ConfigMap", configMapName, defaultNamespace); } private ResourceIdentifier? GetSecret(string defaultNamespace) { if (!variables.GetFlag("Octopus.Action.KubernetesContainers.KubernetesSecretEnabled")) { return null; } // Skip it if the user did not input secret data if (!variables.GetIndexes("Octopus.Action.KubernetesContainers.SecretData").Any()) { return null; } var secretName = variables.Get("Octopus.Action.KubernetesContainers.ComputedSecretName"); return string.IsNullOrEmpty(secretName) ? (ResourceIdentifier?)null : new ResourceIdentifier("Secret", secretName, defaultNamespace); } } }<file_sep>using System; using System.Runtime.InteropServices; namespace Calamari.Common.Plumbing.FileSystem { public class WindowsPhysicalFileSystem : CalamariPhysicalFileSystem { public WindowsPhysicalFileSystem() { #if USE_ALPHAFS_FOR_LONG_FILE_PATH_SUPPORT File = new LongPathsFile(); Directory = new LongPathsDirectory(); #endif } [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); public override bool GetDiskFreeSpace(string directoryPath, out ulong totalNumberOfFreeBytes) { ulong freeBytesAvailable; ulong totalNumberOfBytes; return GetDiskFreeSpaceEx(directoryPath, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes); } public override bool GetDiskTotalSpace(string directoryPath, out ulong totalNumberOfBytes) { ulong freeBytesAvailable; ulong totalNumberOfFreeBytes; return GetDiskFreeSpaceEx(directoryPath, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes); } } }<file_sep>using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureWebApp { class AzureServicePrincipalAccount { public AzureServicePrincipalAccount(IVariables variables) { SubscriptionNumber = variables.Get(AzureAccountVariables.SubscriptionId); ClientId = variables.Get(AzureAccountVariables.ClientId); TenantId = variables.Get(AzureAccountVariables.TenantId); Password = variables.Get(AzureAccountVariables.Password); AzureEnvironment = variables.Get(AzureAccountVariables.Environment); ResourceManagementEndpointBaseUri = variables.Get(AzureAccountVariables.ResourceManagementEndPoint, DefaultVariables.ResourceManagementEndpoint); ActiveDirectoryEndpointBaseUri = variables.Get(AzureAccountVariables.ActiveDirectoryEndPoint, DefaultVariables.ActiveDirectoryEndpoint); } public string WhereHasMyStringGone { get; set; } public string SubscriptionNumber { get; set; } public string ClientId { get; set; } public string TenantId { get; set; } public string Password { get; set; } public string AzureEnvironment { get; set; } public string ResourceManagementEndpointBaseUri { get; set; } public string ActiveDirectoryEndpointBaseUri { get; set; } } }<file_sep>using System; namespace Calamari.AzureWebApp.Integration.Websites.Publishing { class SitePublishProfile { public SitePublishProfile(string userName, string password, Uri uri) { UserName = userName; Password = <PASSWORD>; Uri = uri; } public string UserName { get; } public string Password { get; } public Uri Uri { get; } } }<file_sep>#nullable enable using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Calamari.AzureAppService.Json; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.Rest; using Newtonsoft.Json; namespace Calamari.AzureAppService.Behaviors { class LegacyAzureAppServiceSettingsBehaviour : IDeployBehaviour { private ILog Log { get; } public LegacyAzureAppServiceSettingsBehaviour(ILog log) { Log = log; } public bool IsEnabled(RunningDeployment context) { return !FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.IsEnabled(context.Variables) && (!string.IsNullOrWhiteSpace(context.Variables.Get(SpecialVariables.Action.Azure.AppSettings)) || !string.IsNullOrWhiteSpace(context.Variables.Get(SpecialVariables.Action.Azure.ConnectionStrings))); } public async Task Execute(RunningDeployment context) { // Read/Validate variables Log.Verbose("Starting App Settings Deploy"); var variables = context.Variables; var principalAccount = ServicePrincipalAccount.CreateFromKnownVariables(variables); var webAppName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); if (webAppName == null) throw new Exception("Web App Name must be specified"); var resourceGroupName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName); if (resourceGroupName == null) throw new Exception("resource group name must be specified"); var targetSite = new AzureTargetSite(principalAccount.SubscriptionNumber, resourceGroupName, webAppName, slotName); string token = await Auth.GetAuthTokenAsync(principalAccount); var webAppClient = new WebSiteManagementClient(new Uri(principalAccount.ResourceManagementEndpointBaseUri), new TokenCredentials(token)) { SubscriptionId = principalAccount.SubscriptionNumber, HttpClient = { BaseAddress = new Uri(principalAccount.ResourceManagementEndpointBaseUri) } }; // If app settings are specified if (variables.GetNames().Contains(SpecialVariables.Action.Azure.AppSettings) && !string.IsNullOrWhiteSpace(variables[SpecialVariables.Action.Azure.AppSettings])) { var appSettingsJson = variables.Get(SpecialVariables.Action.Azure.AppSettings, ""); Log.Verbose($"Updating application settings:\n{appSettingsJson}"); var appSettings = JsonConvert.DeserializeObject<AppSetting[]>(appSettingsJson); await PublishAppSettings(webAppClient, targetSite, appSettings, token); Log.Info("Updated application settings"); } // If connection strings are specified if (variables.GetNames().Contains(SpecialVariables.Action.Azure.ConnectionStrings) && !string.IsNullOrWhiteSpace(variables[SpecialVariables.Action.Azure.ConnectionStrings])) { var connectionStringsJson = variables.Get(SpecialVariables.Action.Azure.ConnectionStrings, ""); Log.Verbose($"Updating connection strings:\n{connectionStringsJson}"); var connectionStrings = JsonConvert.DeserializeObject<LegacyConnectionStringSetting[]>(connectionStringsJson); await PublishConnectionStrings(webAppClient, targetSite, connectionStrings); Log.Info("Updated connection strings"); } } /// <summary> /// combines and publishes app and slot settings /// </summary> /// <param name="webAppClient"></param> /// <param name="targetSite"></param> /// <param name="appSettings"></param> /// <param name="authToken"></param> /// <returns></returns> private async Task PublishAppSettings(WebSiteManagementClient webAppClient, AzureTargetSite targetSite, AppSetting[] appSettings, string authToken) { var settingsDict = new StringDictionary { Properties = new Dictionary<string, string>() }; var existingSlotSettings = new List<string>(); // for each app setting found on the web app (existing app setting) update it value and add if is a slot setting, add foreach (var (name, value, SlotSetting) in (await AppSettingsManagement.GetAppSettingsAsync(webAppClient, authToken, targetSite)).ToList()) { settingsDict.Properties[name] = value; if (SlotSetting) existingSlotSettings.Add(name); } // for each app setting defined by the user foreach (var setting in appSettings) { // add/update the settings value settingsDict.Properties[setting.Name] = setting.Value; // if the user indicates a settings should no longer be a slot setting if (existingSlotSettings.Contains(setting.Name) && !setting.SlotSetting) { Log.Verbose($"Removing {setting.Name} from the list of slot settings"); existingSlotSettings.Remove(setting.Name); } } await AppSettingsManagement.PutAppSettingsAsync(webAppClient, settingsDict, targetSite); var slotSettings = appSettings .Where(setting => setting.SlotSetting) .Select(setting => setting.Name) .ToArray(); if (!slotSettings.Any()) return; await AppSettingsManagement.PutSlotSettingsListAsync(webAppClient, targetSite, slotSettings.Union(existingSlotSettings), authToken); } private async Task PublishConnectionStrings(WebSiteManagementClient webAppClient, AzureTargetSite targetSite, LegacyConnectionStringSetting[] newConStrings) { var conStrings = await AppSettingsManagement.GetConnectionStringsAsync(webAppClient, targetSite); foreach (var connectionStringSetting in newConStrings) { conStrings.Properties[connectionStringSetting.Name] = new ConnStringValueTypePair(connectionStringSetting.Value, connectionStringSetting.Type); } await webAppClient.WebApps.UpdateConnectionStringsAsync(targetSite, conStrings); } } }<file_sep>using System; namespace Calamari.Common.Features.ConfigurationTransforms { public interface IConfigurationTransformer { void PerformTransform(string configFile, string transformFile, string destinationFile); } }<file_sep>using System; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Octopus.Versioning; namespace Calamari.Commands { [Command("register-package", Description = "Register the use of a package in the package journal")] public class RegisterPackageUseCommand : Command { PackageId packageId; VersionFormat versionFormat; string rawVersionString; IVersion packageVersion; PackagePath packagePath; ServerTaskId taskId; readonly ILog log; readonly IManagePackageCache journal; readonly ICalamariFileSystem fileSystem; public RegisterPackageUseCommand(ILog log, IManagePackageCache journal, ICalamariFileSystem fileSystem) { this.log = log; this.journal = journal; this.fileSystem = fileSystem; Options.Add("packageId=", "Package ID of the used package", v => packageId = new PackageId(v)); Options.Add("packageVersionFormat=", $"[Optional] Format of version. Options {string.Join(", ", Enum.GetNames(typeof(VersionFormat)))}. Defaults to `{VersionFormat.Semver}`.", v => { if (!Enum.TryParse(v, out VersionFormat format)) { throw new CommandException($"The provided version format `{format}` is not recognised."); } versionFormat = format; }); Options.Add("packageVersion=", "Package version of the used package", v => rawVersionString = v); Options.Add("packagePath=", "Path to the package", v => packagePath = new PackagePath(v)); Options.Add("taskId=", "Id of the task that is using the package", v => taskId = new ServerTaskId(v)); } public override int Execute(string[] commandLineArguments) { try { Options.Parse(commandLineArguments); packageVersion = VersionFactory.TryCreateVersion(rawVersionString, versionFormat); RegisterPackageUse(); } catch (Exception ex) { log.Info($"Unable to register package use.{Environment.NewLine}{ex.ToString()}"); return ConsoleFormatter.PrintError(log, ex); } return 0; } void RegisterPackageUse() { var package = new PackageIdentity(packageId, packageVersion, packagePath); var size = fileSystem.GetFileSize(package.Path.Value); journal.RegisterPackageUse(package, taskId, (ulong)size); } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public static class PackageVariables { public static readonly string TransferPath = "Octopus.Action.Package.TransferPath"; public static readonly string OriginalFileName = "Octopus.Action.Package.OriginalFileName"; public static readonly string CustomInstallationDirectory = "Octopus.Action.Package.CustomInstallationDirectory"; public static readonly string CustomPackageFileName = "Octopus.Action.Package.CustomPackageFileName"; public static readonly string JavaArchiveCompression = "Octopus.Action.Package.JavaArchiveCompression"; public static readonly string CustomInstallationDirectoryShouldBePurgedBeforeDeployment = "Octopus.Action.Package.CustomInstallationDirectoryShouldBePurgedBeforeDeployment"; public static readonly string CustomInstallationDirectoryPurgeExclusions = "Octopus.Action.Package.CustomInstallationDirectoryPurgeExclusions"; public static readonly string EnableNoMatchWarning = "Octopus.Action.SubstituteInFiles.EnableNoMatchWarning"; public static readonly string SubstituteInFilesOutputEncoding = "Octopus.Action.SubstituteInFiles.OutputEncoding"; public static readonly string SubstituteInFilesTargets = "Octopus.Action.SubstituteInFiles.TargetFiles"; public static readonly string PackageCollection = "Octopus.Action.Package"; public static string PackageId => IndexedPackageId(string.Empty); public static string PackageVersion => IndexedPackageVersion(string.Empty); public static string IndexedPackageId(string packageReferenceName) => $"Octopus.Action.Package[{packageReferenceName}].PackageId"; public static string IndexedPackageVersion(string packageReferenceName) => $"Octopus.Action.Package[{packageReferenceName}].PackageVersion"; public static string IndexedOriginalPath(string packageReferenceName) { return $"Octopus.Action.Package[{packageReferenceName}].OriginalPath"; } public static string IndexedExtract(string packageReferenceName) { return $"Octopus.Action.Package[{packageReferenceName}].Extract"; } public class Output { public static readonly string DeprecatedInstallationDirectoryPath = "Package.InstallationDirectoryPath"; public static readonly string InstallationDirectoryPath = "Octopus.Action.Package.InstallationDirectoryPath"; public static readonly string InstallationPackagePath = "Octopus.Action.Package.InstallationPackagePath"; public static readonly string ExtractedFileCount = "Package.ExtractedFileCount"; public static readonly string CopiedFileCount = "Package.CopiedFileCount"; public static readonly string DirectoryPath = "Package.DirectoryPath"; public static readonly string FileName = "Package.FileName"; public static readonly string FilePath = "Package.FilePath"; } } }<file_sep>using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.ConfigurationTransforms { [TestFixture] public class VerboseTransformLoggerFixture { InMemoryLog log; [SetUp] public void SetUp() { log = new InMemoryLog(); } [Test] [TestCase(TransformLoggingOptions.None, InMemoryLog.Level.Warn)] [TestCase(TransformLoggingOptions.LogWarningsAsErrors, InMemoryLog.Level.Error)] [TestCase(TransformLoggingOptions.LogWarningsAsInfo, InMemoryLog.Level.Info)] public void ShouldLogWarningsToConfiguredLevel(TransformLoggingOptions options, InMemoryLog.Level expectedLevel) { var target = new VerboseTransformLogger(options, log); const string message = "This is a warning"; target.LogWarning(message); log.Messages.Should().Contain(m => m.Level == expectedLevel, message); } [Test] [TestCase(TransformLoggingOptions.None, InMemoryLog.Level.Error)] [TestCase(TransformLoggingOptions.LogExceptionsAsWarnings, InMemoryLog.Level.Warn)] public void ShouldLogErrorsToConfiguredLevel(TransformLoggingOptions options, InMemoryLog.Level expectedLevel) { var target = new VerboseTransformLogger(options, log); const string message = "This is an error"; target.LogError(message); log.Messages.Should().Contain(m => m.Level == expectedLevel, message); } } }<file_sep>using Calamari.Common.Commands; namespace Calamari.Deployment.Features.Java.Actions { public abstract class JavaAction { protected readonly JavaRunner runner; public JavaAction(JavaRunner runner) { this.runner = runner; } public abstract void Execute(RunningDeployment deployment); } }<file_sep>using System; using System.Collections.Generic; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Deployment.Features.Java; using Calamari.Deployment.Features.Java.Actions; namespace Calamari.Deployment.Conventions { public class JavaStepConvention : IInstallConvention { readonly string actionType; readonly JavaRunner javaRunner; public JavaStepConvention(string actionType, JavaRunner javaRunner) { this.actionType = actionType; this.javaRunner = javaRunner; } readonly Dictionary<string, Type> javaStepTypes = new Dictionary<string, Type>() { {SpecialVariables.Action.Java.JavaKeystore.CertificateActionTypeName, typeof(JavaKeystoreAction)}, {SpecialVariables.Action.Java.WildFly.CertificateActionTypeName, typeof(WildflyDeployCertificateAction)}, {SpecialVariables.Action.Java.Tomcat.StateActionTypeName, typeof(TomcatStateAction)}, {SpecialVariables.Action.Java.WildFly.StateActionTypeName, typeof(WildFlyStateAction)}, {SpecialVariables.Action.Java.TomcatDeployCertificate.CertificateActionTypeName, typeof(TomcatDeployCertificateAction)} }; public void Install(RunningDeployment deployment) { if (javaStepTypes.TryGetValue(actionType, out var stepType)) { var javaStep = (JavaAction)Activator.CreateInstance(stepType, new object[] {javaRunner}); javaStep.Execute(deployment); } else { throw new CommandException($"Unknown step type `{actionType}`"); } } } }<file_sep>using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class EndpointSlice : Resource { public string AddressType { get; } public IEnumerable<string> Ports { get; } public IEnumerable<string> Endpoints { get; } public EndpointSlice(JObject json, Options options) : base(json, options) { AddressType = Field("$.addressType"); var ports = data.SelectToken("$.ports") ?.ToObject<ServicePort[]>() ?? new ServicePort[] { }; Ports = ports.Select(port => port.Port.ToString()); var endpoints = data.SelectToken("$.endpoints") ?.ToObject<Endpoint[]>() ?? new Endpoint[] { }; Endpoints = FormatEndpoints(endpoints); } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<EndpointSlice>(lastStatus); return last.AddressType != AddressType || !last.Ports.SequenceEqual(Ports) || !last.Endpoints.SequenceEqual(Endpoints); } private static IEnumerable<string> FormatEndpoints(IEnumerable<Endpoint> endpoints) { return endpoints.SelectMany(endpoint => endpoint.Addresses); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Runtime; using Calamari.Aws.Exceptions; using Calamari.Aws.Integration.CloudFormation; using Calamari.Aws.Integration.CloudFormation.Templates; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Integration.Processes; using Octopus.CoreUtilities; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Deployment.Conventions { public class CloudFormationOutputsAsVariablesConvention : CloudFormationInstallationConventionBase { private readonly Func<IAmazonCloudFormation> clientFactory; private readonly Func<RunningDeployment, StackArn> stackProvider; public CloudFormationOutputsAsVariablesConvention( Func<IAmazonCloudFormation> clientFactory, StackEventLogger logger, Func<RunningDeployment, StackArn> stackProvider): base(logger) { Guard.NotNull(clientFactory, "Client factory must not be null"); Guard.NotNull(stackProvider, "Stack provider must not be null"); this.clientFactory = clientFactory; this.stackProvider = stackProvider; } public override void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private Task InstallAsync(RunningDeployment deployment) { Guard.NotNull(deployment, "Deployment must not be null"); var stack = stackProvider(deployment); Guard.NotNull(stack, "The provided stack may not be null."); return GetAndPipeOutputVariablesWithRetry(() => WithAmazonServiceExceptionHandling(async () => (await QueryStackAsync(clientFactory, stack)).ToMaybe()), deployment.Variables, true, CloudFormationDefaults.RetryCount, CloudFormationDefaults.StatusWaitPeriod); } public async Task<(IReadOnlyList<VariableOutput> result, bool success)> GetOutputVariables( Func<Task<Maybe<Stack>>> query) { Guard.NotNull(query, "Query for stack may not be null"); List<VariableOutput> ConvertStackOutputs(Stack stack) => stack.Outputs.Select(p => new VariableOutput(p.OutputKey, p.OutputValue)).ToList(); return (await query()).Select(ConvertStackOutputs) .Map(result => (result: result.SomeOr(new List<VariableOutput>()), success: true)); } public void PipeOutputs(IEnumerable<VariableOutput> outputs, IVariables variables, string name = "AwsOutputs") { Guard.NotNull(variables, "Variables may not be null"); foreach (var output in outputs) { SetOutputVariable(variables, output.Name, output.Value ); } } public async Task GetAndPipeOutputVariablesWithRetry(Func<Task<Maybe<Stack>>> query, IVariables variables, bool wait, int retryCount, TimeSpan waitPeriod) { for (var retry = 0; retry < retryCount; ++retry) { var (result, success) = await GetOutputVariables(query); if (success || !wait) { PipeOutputs(result, variables); break; } // Wait for a bit for and try again await Task.Delay(waitPeriod); } } } }<file_sep>using System; using Autofac; namespace Calamari.Common.Plumbing.Pipeline { public class DeployResolver: Resolver<IDeployBehaviour> { public DeployResolver(ILifetimeScope lifetimeScope) : base(lifetimeScope) { } } }<file_sep>using System.Xml.Linq; namespace Calamari.AzureCloudService.CloudServicePackage.ManifestSchema { public class FileDefinition { public static readonly XName ElementName = PackageDefinition.AzureNamespace + "FileDefinition"; static readonly XName FilePathElementName = PackageDefinition.AzureNamespace + "FilePath"; public FileDefinition() { } public FileDefinition(XElement element) { FilePath = element.Element(FilePathElementName).Value; Description = new FileDescription(element.Element(FileDescription.ElementName)); } public string FilePath { get; set; } public FileDescription Description { get; set; } public XElement ToXml() { return new XElement(ElementName, new XElement(FilePathElementName, FilePath), Description.ToXml()); } } }<file_sep>using System; using Calamari.Common.Features.Processes; namespace Calamari.Integration.Processes { public class LibraryCallRunner { public CommandResult Execute(LibraryCallInvocation invocation) { try { var exitCode = invocation.Executable(invocation.Arguments); return new CommandResult(invocation.ToString(), exitCode, null); } catch (Exception ex) { Console.Error.WriteLine(ex); Console.Error.WriteLine("The command that caused the exception was: " + invocation); return new CommandResult(invocation.ToString(), -1, ex.ToString()); } } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Principal; // Needed for dotnetcore namespace Calamari.Common.Plumbing.Extensions /* This is in the 'Environments' namespace to avoid collisions with CrossPlatformExtensions */ { public static class EnvironmentHelper { public static string[] SafelyGetEnvironmentInformation() { var envVars = GetEnvironmentVars() .Concat(GetPathVars()) .Concat(GetProcessVars()); return envVars.ToArray(); } public static void SetEnvironmentVariable(string name, string value) { Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.Process); } static string SafelyGet(Func<string> thingToGet) { try { return thingToGet.Invoke(); } catch (Exception) { return "Unable to retrieve environment information."; } } static IEnumerable<string> GetEnvironmentVars() { yield return SafelyGet(() => $"OperatingSystem: {Environment.OSVersion}"); yield return SafelyGet(() => $"OsBitVersion: {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}"); yield return SafelyGet(() => $"Is64BitProcess: {Environment.Is64BitProcess}"); if (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) yield return SafelyGet(() => $"Running on Mono: {CalamariEnvironment.IsRunningOnMono}"); if (CalamariEnvironment.IsRunningOnWindows) yield return SafelyGet(() => $"CurrentUser: {WindowsIdentity.GetCurrent().Name}"); else yield return SafelyGet(() => $"CurrentUser: {Environment.UserName}"); yield return SafelyGet(() => $"MachineName: {Environment.MachineName}"); yield return SafelyGet(() => $"ProcessorCount: {Environment.ProcessorCount}"); } static IEnumerable<string> GetPathVars() { yield return SafelyGet(() => $"CurrentDirectory: {Directory.GetCurrentDirectory()}"); yield return SafelyGet(() => $"TempDirectory: {Path.GetTempPath()}"); } static IEnumerable<string> GetProcessVars() { yield return SafelyGet(() => { var process = Process.GetCurrentProcess(); return $"HostProcess: {process.ProcessName} ({process.Id})"; }); } } }<file_sep>using Calamari.Common.Plumbing.Extensions; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace Calamari.Testing.Requirements { public class RequiresDotNetFrameworkAttribute: NUnitAttribute, IApplyToTest { public void ApplyToTest(Test test) { if (!ScriptingEnvironment.IsNetFramework()) { test.RunState = RunState.Skipped; test.Properties.Set(PropertyNames.SkipReason, "Requires dotnet Framework"); } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using Calamari.Util; using Newtonsoft.Json; namespace Calamari.Kubernetes.Conventions { public class HelmUpgradeConvention : IInstallConvention { readonly ILog log; readonly IScriptEngine scriptEngine; readonly ICommandLineRunner commandLineRunner; readonly ICalamariFileSystem fileSystem; public HelmUpgradeConvention(ILog log, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner, ICalamariFileSystem fileSystem) { this.log = log; this.scriptEngine = scriptEngine; this.commandLineRunner = commandLineRunner; this.fileSystem = fileSystem; } public void Install(RunningDeployment deployment) { ScriptSyntax syntax = ScriptSyntaxHelper.GetPreferredScriptSyntaxForEnvironment(); var cmd = BuildHelmCommand(deployment, syntax); var fileName = SyntaxSpecificFileName(deployment, syntax); using (new TemporaryFile(fileName)) { fileSystem.OverwriteFile(fileName, cmd); var result = scriptEngine.Execute(new Script(fileName), deployment.Variables, commandLineRunner); if (result.ExitCode != 0) { throw new CommandException( $"Helm Upgrade returned non-zero exit code: {result.ExitCode}. Deployment terminated."); } if (result.HasErrors && deployment.Variables.GetFlag(Deployment.SpecialVariables.Action.FailScriptOnErrorOutput, false)) { throw new CommandException( "Helm Upgrade returned zero exit code but had error output. Deployment terminated."); } } } string BuildHelmCommand(RunningDeployment deployment, ScriptSyntax syntax) { var releaseName = GetReleaseName(deployment.Variables); var packagePath = GetChartLocation(deployment); var customHelmExecutable = CustomHelmExecutableFullPath(deployment.Variables, deployment.CurrentDirectory); var helmVersion = GetVersion(deployment.Variables); CheckHelmToolVersion(customHelmExecutable, helmVersion); var sb = new StringBuilder(); SetExecutable(sb, syntax, customHelmExecutable); sb.Append($" upgrade --install"); SetNamespaceParameter(deployment, sb); SetResetValuesParameter(deployment, sb); if (helmVersion == HelmVersion.V2) { SetTillerTimeoutParameter(deployment, sb); SetTillerNamespaceParameter(deployment, sb); } SetTimeoutParameter(deployment, sb); SetValuesParameters(deployment, sb); SetAdditionalArguments(deployment, sb); sb.Append($" \"{releaseName}\" \"{packagePath}\""); log.Verbose(sb.ToString()); return sb.ToString(); } HelmVersion GetVersion(IVariables variables) { var clientVersionText = variables.Get(SpecialVariables.Helm.ClientVersion); if (Enum.TryParse(clientVersionText, out HelmVersion version)) return version; throw new CommandException($"Unrecognized Helm version: '{clientVersionText}'"); } void SetExecutable(StringBuilder sb, ScriptSyntax syntax, string customHelmExecutable) { if (customHelmExecutable != null) { // With PowerShell we need to invoke custom executables sb.Append(syntax == ScriptSyntax.PowerShell ? ". " : $"chmod +x \"{customHelmExecutable}\"\n"); sb.Append($"\"{customHelmExecutable}\""); } else { sb.Append("helm"); } } string CustomHelmExecutableFullPath(IVariables variables, string workingDirectory) { var helmExecutable = variables.Get(SpecialVariables.Helm.CustomHelmExecutable); if (!string.IsNullOrWhiteSpace(helmExecutable)) { if (variables.GetIndexes(PackageVariables.PackageCollection) .Contains(SpecialVariables.Helm.Packages.CustomHelmExePackageKey) && !Path.IsPathRooted(helmExecutable)) { var fullPath = Path.GetFullPath(Path.Combine(workingDirectory, SpecialVariables.Helm.Packages.CustomHelmExePackageKey, helmExecutable)); log.Info( $"Using custom helm executable at {helmExecutable} from inside package. Full path at {fullPath}"); return fullPath; } else { log.Info($"Using custom helm executable at {helmExecutable}"); return helmExecutable; } } return null; } static void SetNamespaceParameter(RunningDeployment deployment, StringBuilder sb) { var @namespace = deployment.Variables.Get(SpecialVariables.Helm.Namespace); if (!string.IsNullOrWhiteSpace(@namespace)) { sb.Append($" --namespace \"{@namespace}\""); } } static void SetResetValuesParameter(RunningDeployment deployment, StringBuilder sb) { if (deployment.Variables.GetFlag(SpecialVariables.Helm.ResetValues, true)) { sb.Append(" --reset-values"); } } void SetValuesParameters(RunningDeployment deployment, StringBuilder sb) { foreach (var additionalValuesFile in AdditionalValuesFiles(deployment)) { sb.Append($" --values \"{additionalValuesFile}\""); } if (TryAddRawValuesYaml(deployment, out var rawValuesFile)) { sb.Append($" --values \"{rawValuesFile}\""); } if (TryGenerateVariablesFile(deployment, out var valuesFile)) { sb.Append($" --values \"{valuesFile}\""); } } void SetAdditionalArguments(RunningDeployment deployment, StringBuilder sb) { var additionalArguments = deployment.Variables.Get(SpecialVariables.Helm.AdditionalArguments); if (!string.IsNullOrWhiteSpace(additionalArguments)) { sb.Append($" {additionalArguments}"); } } static void SetTillerNamespaceParameter(RunningDeployment deployment, StringBuilder sb) { if (deployment.Variables.IsSet(SpecialVariables.Helm.TillerNamespace)) { sb.Append($" --tiller-namespace \"{deployment.Variables.Get(SpecialVariables.Helm.TillerNamespace)}\""); } } static void SetTimeoutParameter(RunningDeployment deployment, StringBuilder sb) { if (!deployment.Variables.IsSet(SpecialVariables.Helm.Timeout)) return; var timeout = deployment.Variables.Get(SpecialVariables.Helm.Timeout); if (!GoDurationParser.ValidateTimeout(timeout)) { throw new CommandException($"Timeout period is not a valid duration: {timeout}"); } sb.Append($" --timeout \"{timeout}\""); } static void SetTillerTimeoutParameter(RunningDeployment deployment, StringBuilder sb) { if (!deployment.Variables.IsSet(SpecialVariables.Helm.TillerTimeout)) return; var tillerTimeout = deployment.Variables.Get(SpecialVariables.Helm.TillerTimeout); if (!int.TryParse(tillerTimeout, out _)) { throw new CommandException($"Tiller timeout period is not a valid integer: {tillerTimeout}"); } sb.Append($" --tiller-connection-timeout \"{tillerTimeout}\""); } string SyntaxSpecificFileName(RunningDeployment deployment, ScriptSyntax syntax) { return Path.Combine(deployment.CurrentDirectory, syntax == ScriptSyntax.PowerShell ? "Calamari.HelmUpgrade.ps1" : "Calamari.HelmUpgrade.sh"); } string GetReleaseName(IVariables variables) { var validChars = new Regex("[^a-zA-Z0-9-]"); var releaseName = variables.Get(SpecialVariables.Helm.ReleaseName)?.ToLower(); if (string.IsNullOrWhiteSpace(releaseName)) { releaseName = $"{variables.Get(ActionVariables.Name)}-{variables.Get(DeploymentEnvironment.Name)}"; releaseName = validChars.Replace(releaseName, "").ToLowerInvariant(); } log.SetOutputVariable("ReleaseName", releaseName, variables); log.Info($"Using Release Name {releaseName}"); return releaseName; } IEnumerable<string> AdditionalValuesFiles(RunningDeployment deployment) { var variables = deployment.Variables; var packageReferenceNames = variables.GetIndexes(PackageVariables.PackageCollection); foreach (var packageReferenceName in packageReferenceNames) { var sanitizedPackageReferenceName = fileSystem.RemoveInvalidFileNameChars(packageReferenceName); var paths = variables.GetPaths(SpecialVariables.Helm.Packages.ValuesFilePath(packageReferenceName)); foreach (var providedPath in paths) { var packageId = variables.Get(PackageVariables.IndexedPackageId(packageReferenceName)); var version = variables.Get(PackageVariables.IndexedPackageVersion(packageReferenceName)); var relativePath = Path.Combine(sanitizedPackageReferenceName, providedPath); var globMode = GlobModeRetriever.GetFromVariables(variables); var files = fileSystem.EnumerateFilesWithGlob(deployment.CurrentDirectory, globMode, relativePath).ToList(); if (!files.Any() && string.IsNullOrEmpty(packageReferenceName)) // Chart archives have chart name root directory { log.Verbose($"Unable to find values files at path `{providedPath}`. " + $"Chart package contains root directory with chart name, so looking for values in there."); var chartRelativePath = Path.Combine(fileSystem.RemoveInvalidFileNameChars(packageId), relativePath); files = fileSystem.EnumerateFilesWithGlob(deployment.CurrentDirectory, globMode, chartRelativePath).ToList(); } if (!files.Any()) { throw new CommandException($"Unable to find file `{providedPath}` for package {packageId} v{version}"); } foreach (var file in files) { var relative = file.Substring(Path.Combine(deployment.CurrentDirectory, sanitizedPackageReferenceName).Length); log.Info($"Including values file `{relative}` from package {packageId} v{version}"); yield return Path.GetFullPath(file); } } } } string GetChartLocation(RunningDeployment deployment) { var installDir = deployment.Variables.Get(PackageVariables.Output.InstallationDirectoryPath); var packageId = deployment.Variables.Get(PackageVariables.IndexedPackageId(string.Empty)); // Try the root directory if (fileSystem.FileExists(Path.Combine(installDir, "Chart.yaml"))) { return Path.Combine(installDir, "Chart.yaml"); } // Try the directory that matches the package id var packageIdPath = Path.Combine(installDir, packageId); if (fileSystem.DirectoryExists(packageIdPath) && fileSystem.FileExists(Path.Combine(packageIdPath, "Chart.yaml"))) { return packageIdPath; } /* * Although conventions suggests that the directory inside the helm archive matches the package ID, this * can not be assumed. If the standard locations above failed to locate the Chart.yaml file, loop over * all subdirectories to try and find the file. */ foreach (var dir in fileSystem.EnumerateDirectories(installDir)) { if (fileSystem.FileExists(Path.Combine(dir, "Chart.yaml"))) { return dir; } } // Nothing worked throw new CommandException($"Unexpected error. Chart.yaml was not found in {packageIdPath}"); } static bool TryAddRawValuesYaml(RunningDeployment deployment, out string fileName) { fileName = null; var yaml = deployment.Variables.Get(SpecialVariables.Helm.YamlValues); if (!string.IsNullOrWhiteSpace(yaml)) { fileName = Path.Combine(deployment.CurrentDirectory, "rawYamlValues.yaml"); File.WriteAllText(fileName, yaml); return true; } return false; } static bool TryGenerateVariablesFile(RunningDeployment deployment, out string fileName) { fileName = null; var variables = deployment.Variables.Get(SpecialVariables.Helm.KeyValues, "{}"); var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(variables); if (!values.Any()) { return false; } fileName = Path.Combine(deployment.CurrentDirectory, "explicitVariableValues.yaml"); File.WriteAllText(fileName, RawValuesToYamlConverter.Convert(values)); return true; } void CheckHelmToolVersion(string customHelmExecutable, HelmVersion selectedVersion) { log.Verbose($"Helm version selected: {selectedVersion}"); StringBuilder stdout = new StringBuilder(); var result = SilentProcessRunner.ExecuteCommand(customHelmExecutable ?? "helm", "version --client --short", Environment.CurrentDirectory, output => stdout.Append(output), error => { }); if (result.ExitCode != 0) log.Warn("Unable to retrieve the Helm tool version"); var toolVersion = HelmVersionParser.ParseVersion(stdout.ToString()); if (!toolVersion.HasValue) log.Warn("Unable to parse the Helm tool version text: " + stdout); if (toolVersion.Value != selectedVersion) log.Warn($"The Helm tool version '{toolVersion.Value}' ('{stdout}') doesn't match the Helm version selected '{selectedVersion}'"); } } } <file_sep>using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; namespace Calamari.Deployment.Features.Java.Actions { public class WildFlyStateAction : JavaAction { public WildFlyStateAction(JavaRunner runner): base(runner) { } public override void Execute(RunningDeployment deployment) { var variables = deployment.Variables; Log.Info("Updating WildFly state"); runner.Run("com.octopus.calamari.wildfly.WildflyState", new Dictionary<string, string>() { {"OctopusEnvironment_WildFly_Deploy_Name", variables.Get(SpecialVariables.Action.Java.WildFly.DeployName)}, {"OctopusEnvironment_WildFly_Deploy_Controller", variables.Get(SpecialVariables.Action.Java.WildFly.Controller)}, {"OctopusEnvironment_WildFly_Deploy_Port", variables.Get(SpecialVariables.Action.Java.WildFly.Port)}, {"OctopusEnvironment_WildFly_Deploy_Protocol", variables.Get(SpecialVariables.Action.Java.WildFly.Protocol)}, {"OctopusEnvironment_WildFly_Deploy_User", variables.Get(SpecialVariables.Action.Java.WildFly.User)}, {"OctopusEnvironment_WildFly_Deploy_Password", variables.Get(SpecialVariables.Action.Java.WildFly.Password)}, {"OctopusEnvironment_WildFly_Deploy_Enabled", variables.Get(SpecialVariables.Action.Java.WildFly.Enabled)}, {"OctopusEnvironment_WildFly_Deploy_EnabledServerGroup", variables.Get(SpecialVariables.Action.Java.WildFly.EnabledServerGroup)}, {"OctopusEnvironment_WildFly_Deploy_DisabledServerGroup", variables.Get(SpecialVariables.Action.Java.WildFly.DisabledServerGroup)}, {"OctopusEnvironment_WildFly_Deploy_ServerType", variables.Get(SpecialVariables.Action.Java.WildFly.ServerType)}, }); } } }<file_sep>using System; using System.Diagnostics; namespace Calamari.Terraform.Helpers { public static class VersionExtensions { public static bool IsLessThan(this Version value, string compareTo) { return value.CompareTo(new Version(compareTo)) < 0; } } } <file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus.Resources; namespace Calamari.Kubernetes.ResourceStatus { /// <summary> /// Retrieves resources information from a kubernetes cluster /// </summary> public interface IResourceRetriever { /// <summary> /// Gets the resources identified by the resourceIdentifiers and all their owned resources /// </summary> IEnumerable<Resource> GetAllOwnedResources(IEnumerable<ResourceIdentifier> resourceIdentifiers, IKubectl kubectl, Options options); } public class ResourceRetriever : IResourceRetriever { private readonly IKubectlGet kubectlGet; public ResourceRetriever(IKubectlGet kubectlGet) { this.kubectlGet = kubectlGet; } /// <inheritdoc /> public IEnumerable<Resource> GetAllOwnedResources(IEnumerable<ResourceIdentifier> resourceIdentifiers, IKubectl kubectl, Options options) { var resources = resourceIdentifiers .Select(identifier => GetResource(identifier, kubectl, options)) .Where(resource => resource != null) .ToList(); foreach (var resource in resources) { resource.UpdateChildren(GetChildrenResources(resource, kubectl, options)); } return resources; } private Resource GetResource(ResourceIdentifier resourceIdentifier, IKubectl kubectl, Options options) { var result = kubectlGet.Resource(resourceIdentifier.Kind, resourceIdentifier.Name, resourceIdentifier.Namespace, kubectl); return string.IsNullOrEmpty(result) ? null : ResourceFactory.FromJson(result, options); } private IEnumerable<Resource> GetChildrenResources(Resource parentResource, IKubectl kubectl, Options options) { var childKind = parentResource.ChildKind; if (string.IsNullOrEmpty(childKind)) { return Enumerable.Empty<Resource>(); } var result = kubectlGet.AllResources(childKind, parentResource.Namespace, kubectl); var resources = ResourceFactory.FromListJson(result, options); return resources.Where(resource => resource.OwnerUids.Contains(parentResource.Uid)) .Select(child => { child.UpdateChildren(GetChildrenResources(child, kubectl, options)); return child; }).ToList(); } } }<file_sep>using Newtonsoft.Json; namespace Calamari.Aws.Integration.S3 { public class S3MultiFileSelectionProperties : S3FileSelectionProperties { public string BucketKeyPrefix { get; set; } public string Pattern { get; set; } public string VariableSubstitutionPatterns { get; set; } public string StructuredVariableSubstitutionPatterns { get; set; } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public static class JavaVariables { public static readonly string JavaLibraryEnvVar = "JavaIntegrationLibraryPackagePath"; } }<file_sep>using System; using System.Net; using System.Net.Http; using Azure.Core; using Azure.Core.Pipeline; using Azure.Identity; using Azure.ResourceManager; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; namespace Calamari.AzureAppService.Azure { internal static class AzureClient { public static IAzure CreateAzureClient(this ServicePrincipalAccount servicePrincipal) { var environment = new AzureKnownEnvironment(servicePrincipal.AzureEnvironment).AsAzureSDKEnvironment(); var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(servicePrincipal.ClientId, servicePrincipal.Password, servicePrincipal.TenantId, environment ); // Note: This is a tactical fix to ensure this Sashimi uses the appropriate web proxy #pragma warning disable DE0003 var client = new HttpClient(new HttpClientHandler {Proxy = WebRequest.DefaultWebProxy}); #pragma warning restore DE0003 return Microsoft.Azure.Management.Fluent.Azure.Configure() .WithHttpClient(client) .Authenticate(credentials) .WithSubscription(servicePrincipal.SubscriptionNumber); } /// <summary> /// Creates an ArmClient for the new Azure SDK, which replaces the older fluent libraries. /// We should migrate to this SDK once it stabilises. /// </summary> /// <param name="servicePrincipal">Service Principal Account to use when connecting to Azure</param> /// <returns></returns> public static ArmClient CreateArmClient(this ServicePrincipalAccount servicePrincipal, Action<RetryOptions> retryOptionsSetter = null) { var (armClientOptions, tokenCredentialOptions) = GetArmClientOptions(servicePrincipal, retryOptionsSetter); var credential = new ClientSecretCredential(servicePrincipal.TenantId, servicePrincipal.ClientId, servicePrincipal.Password, tokenCredentialOptions); return new ArmClient(credential, defaultSubscriptionId: servicePrincipal.SubscriptionNumber, armClientOptions); } public static (ArmClientOptions, TokenCredentialOptions) GetArmClientOptions(this ServicePrincipalAccount servicePrincipalAccount, Action<RetryOptions> retryOptionsSetter = null) { var azureKnownEnvironment = new AzureKnownEnvironment(servicePrincipalAccount.AzureEnvironment); // Configure a specific transport that will pick up the proxy settings set by Calamari #pragma warning disable DE0003 var httpClientTransport = new HttpClientTransport(new HttpClientHandler { Proxy = WebRequest.DefaultWebProxy }); #pragma warning restore DE0003 // Specifically tell the new Azure SDK which authentication endpoint to use var authorityHost = string.IsNullOrEmpty(servicePrincipalAccount.ActiveDirectoryEndpointBaseUri) ? azureKnownEnvironment.GetAzureAuthorityHost() // if the user has specified a custom authentication endpoint, use that value : new Uri(servicePrincipalAccount.ActiveDirectoryEndpointBaseUri); var tokenCredentialOptions = new TokenCredentialOptions { Transport = httpClientTransport, AuthorityHost = authorityHost }; // The new Azure SDK uses a different representation of Environments var armEnvironment = string.IsNullOrEmpty(servicePrincipalAccount.ResourceManagementEndpointBaseUri) ? azureKnownEnvironment.AsAzureArmEnvironment() // if the user has specified a custom resource management endpoint, define a custom environment using that value : new ArmEnvironment(new Uri(servicePrincipalAccount.ResourceManagementEndpointBaseUri, UriKind.Absolute), servicePrincipalAccount.ResourceManagementEndpointBaseUri); var armClientOptions = new ArmClientOptions { Transport = httpClientTransport, Environment = armEnvironment }; retryOptionsSetter?.Invoke(armClientOptions.Retry); // there is a bug in the slotconfignames call due to it not passing back an ID, so this is needed to fix that // see https://github.com/Azure/azure-sdk-for-net/issues/33384 armClientOptions.AddPolicy(new SlotConfigNamesInvalidIdFilterPolicy(), HttpPipelinePosition.PerRetry); return (armClientOptions, tokenCredentialOptions); } } } <file_sep>using System; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Retry; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.FileSystem; using Calamari.Integration.Packages.Download; using Octopus.Versioning; namespace Calamari.Integration.Packages.NuGet { public class InternalNuGetPackageDownloader { readonly ICalamariFileSystem fileSystem; readonly IVariables variables; public InternalNuGetPackageDownloader(ICalamariFileSystem fileSystem, IVariables variables) { this.fileSystem = fileSystem; this.variables = variables; } public void DownloadPackage(string packageId, IVersion version, Uri feedUri, ICredentials feedCredentials, string targetFilePath, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { DownloadPackage(packageId, version, feedUri, feedCredentials, targetFilePath, maxDownloadAttempts, downloadAttemptBackoff, DownloadPackageAction); } public void DownloadPackage( string packageId, IVersion version, Uri feedUri, ICredentials feedCredentials, string targetFilePath, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff, Action<string, IVersion, Uri, ICredentials, string> action) { if (maxDownloadAttempts <= 0) throw new ArgumentException($"The number of download attempts should be greater than zero, but was {maxDownloadAttempts}", nameof(maxDownloadAttempts)); var tempTargetFilePath = targetFilePath + NuGetPackageDownloader.DownloadingExtension; // The RetryTracker is a bit finicky to set up... var numberOfRetriesOnFailure = maxDownloadAttempts-1; var retry = new RetryTracker(numberOfRetriesOnFailure, timeLimit: null, retryInterval: new LinearRetryInterval(downloadAttemptBackoff)); while (retry.Try()) { Log.Verbose($"Downloading package (attempt {retry.CurrentTry} of {maxDownloadAttempts})"); try { action(packageId, version, feedUri, feedCredentials, tempTargetFilePath); fileSystem.MoveFile(tempTargetFilePath, targetFilePath); return; } catch (Exception ex) { if (ex is WebException webException && webException.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.Unauthorized) { throw new Exception($"Unable to download package: {webException.Message}", ex); } Log.Verbose($"Attempt {retry.CurrentTry} of {maxDownloadAttempts}: {ex.Message}"); fileSystem.DeleteFile(tempTargetFilePath, FailureOptions.IgnoreFailure); fileSystem.DeleteFile(targetFilePath, FailureOptions.IgnoreFailure); if (retry.CanRetry()) { var wait = retry.Sleep(); Log.Verbose($"Going to wait {wait.TotalSeconds}s before attempting the download from the external feed again."); Thread.Sleep(wait); } else { var helpfulFailure = $"The package {packageId} version {version} could not be downloaded from the external feed '{feedUri}' after making {maxDownloadAttempts} attempts over a total of {Math.Floor(retry.TotalElapsed.TotalSeconds)}s. Make sure the package is pushed to the external feed and try the deployment again. For a detailed troubleshooting guide go to http://g.octopushq.com/TroubleshootMissingPackages"; helpfulFailure += $"{Environment.NewLine}{ex}"; throw new Exception(helpfulFailure, ex); } } } } private void DownloadPackageAction(string packageId, IVersion version, Uri feedUri, ICredentials feedCredentials, string targetFilePath) { // FileSystem feed if (feedUri.IsFile) { NuGetFileSystemDownloader.DownloadPackage(packageId, version, feedUri, targetFilePath); return; } #if USE_NUGET_V2_LIBS var timeout = GetHttpTimeout(); if (IsHttp(feedUri.ToString())) { if (NuGetV3Downloader.CanHandle(feedUri, feedCredentials, timeout)) { NuGetV3Downloader.DownloadPackage(packageId, version, feedUri, feedCredentials, targetFilePath, timeout); } else { WarnIfHttpTimeoutHasBeenSet(); NuGetV2Downloader.DownloadPackage(packageId, version.ToString(), feedUri, feedCredentials, targetFilePath); } } #else else { WarnIfHttpTimeoutHasBeenSet(); NuGetV3LibDownloader.DownloadPackage(packageId, version, feedUri, feedCredentials, targetFilePath); } #endif } #if USE_NUGET_V2_LIBS TimeSpan GetHttpTimeout() { const string expectedTimespanFormat = "c"; // Equal to Timeout.InfiniteTimeSpan, which isn't available in net40 var defaultTimeout = new TimeSpan(0, 0, 0, 0, -1); var rawTimeout = variables.Get(KnownVariables.NugetHttpTimeout); if (string.IsNullOrWhiteSpace(rawTimeout)) { return defaultTimeout; } if (TimeSpan.TryParseExact(rawTimeout, expectedTimespanFormat, null, out var parsedTimeout)) { return parsedTimeout; } var exampleTimespan = new TimeSpan(0, 0, 1, 0).ToString(expectedTimespanFormat); var message = $"The variable {KnownVariables.NugetHttpTimeout} couldn't be parsed as a timespan. " + $"Expected a value like '{exampleTimespan}' but received '{rawTimeout}'. " + $"Defaulting to '{defaultTimeout.ToString(expectedTimespanFormat)}'."; Log.Warn(message); return defaultTimeout; } #endif void WarnIfHttpTimeoutHasBeenSet() { if (variables.IsSet(KnownVariables.NugetHttpTimeout)) { Log.Warn( $"A Nuget HTTP timeout was set via the '{KnownVariables.NugetHttpTimeout}' variable. " + "This variable is only supported when running on .NET Framework." ); } } bool IsHttp(string uri) { return uri.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || uri.StartsWith("https://", StringComparison.OrdinalIgnoreCase); } } } <file_sep>using System; using Autofac; namespace Calamari.Common.Plumbing.Pipeline { public class PostDeployResolver: Resolver<IPostDeployBehaviour> { public PostDeployResolver(ILifetimeScope lifetimeScope) : base(lifetimeScope) { } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Xml; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Integration.Iis; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] public class DeployWebPackageFixture : DeployPackageFixture { // Fixture Depedencies TemporaryFile nupkgFile; TemporaryFile tarFile; [SetUp] public override void SetUp() { base.SetUp(); } [OneTimeSetUp] public void Init() { nupkgFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0")); tarFile = new TemporaryFile(TarGzBuilder.BuildSamplePackage("Acme.Web", "1.0.0")); } [OneTimeTearDown] public void Dispose() { nupkgFile.Dispose(); tarFile.Dispose(); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldDeployPackageOnWindows() { var result = DeployPackage(); result.AssertSuccess(); result.AssertOutput("Extracting package to: " + Path.Combine(StagingDirectory, "Acme.Web", "1.0.0")); result.AssertOutput("Extracted 11 files"); result.AssertOutput("Hello from Deploy.ps1"); } [Test] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void ShouldDeployPackageOnMacOrNix() { if (!CalamariEnvironment.IsRunningOnMac && !CalamariEnvironment.IsRunningOnNix) Assert.Inconclusive("This test is designed to run on *Nix or Mac."); var result = DeployPackage(); result.AssertSuccess(); result.AssertOutput("Hello from Deploy.sh"); } [Test] public void ShouldSetExtractionVariable() { var result = DeployPackage(); result.AssertSuccess(); result.AssertOutputVariable(PackageVariables.Output.InstallationDirectoryPath, Is.EqualTo(Path.Combine(StagingDirectory, "Acme.Web", "1.0.0"))); } [Test] public void ShouldCopyToCustomDirectoryExtractionVariable() { Variables[PackageVariables.CustomInstallationDirectory] = CustomDirectory; var result = DeployPackage(); result.AssertSuccess(); result.AssertOutput("Copying package contents to"); result.AssertOutputVariable(PackageVariables.Output.InstallationDirectoryPath, Is.EqualTo(CustomDirectory)); } [Test] public void ShouldSubstituteVariablesInFiles() { Variables.Set("foo", "bar"); // Enable file substitution and configure the target Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.SubstituteInFiles); Variables.Set(PackageVariables.SubstituteInFilesTargets, "web.config"); DeployPackage(); // The #{foo} variable in web.config should have been replaced by 'bar' AssertXmlNodeValue(Path.Combine(StagingDirectory, "Acme.Web", "1.0.0", "web.config"), "configuration/appSettings/add[@key='foo']/@value", "bar"); } [Test] public void ShouldSubstituteVariablesInRelativePathFiles() { Variables.Set("foo", "bar"); var path = Path.Combine("assets", "README.txt"); // Enable file substitution and configure the target Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.SubstituteInFiles); Variables.Set(PackageVariables.SubstituteInFilesTargets, path); DeployPackage(); // The #{foo} variable in assets\README.txt should have been replaced by 'bar' string actual = FileSystem.ReadFile(Path.Combine(StagingDirectory, "Acme.Web", "1.0.0", "assets", "README.txt")); Assert.AreEqual("bar", actual); } [Test] [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 public void ShouldTransformConfig() { // Set the environment, and the flag to automatically run config transforms Variables.Set(DeploymentEnvironment.Name, "Production"); Variables.Set(KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles, true.ToString()); Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationTransforms); var result = DeployPackage(); // The environment app-setting value should have been transformed to 'Production' AssertXmlNodeValue(Path.Combine(StagingDirectory, "Production", "Acme.Web", "1.0.0", "web.config"), "configuration/appSettings/add[@key='environment']/@value", "Production"); } [Test] [Category(TestCategory.ScriptingSupport.FSharp)] [Category(TestCategory.ScriptingSupport.DotnetScript)] [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 public void ShouldInvokeDeployFailedOnError() { Variables.Set("ShouldFail", "yes"); var result = DeployPackage(); if (ScriptingEnvironment.IsRunningOnMono()) result.AssertOutput("I have failed! DeployFailed.sh"); else result.AssertOutput("I have failed! DeployFailed.ps1"); result.AssertNoOutput("I have failed! DeployFailed.fsx"); result.AssertNoOutput("I have failed! DeployFailed.csx"); } [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426 public void ShouldNotInvokeDeployFailedWhenNoError() { var result = DeployPackage(); result.AssertNoOutput("I have failed! DeployFailed.ps1"); result.AssertNoOutput("I have failed! DeployFailed.sh"); result.AssertNoOutput("I have failed! DeployFailed.fsx"); result.AssertNoOutput("I have failed! DeployFailed.csx"); } [Test] [TestCase(DeploymentType.Nupkg)] [TestCase(DeploymentType.Tar)] public void ShouldCopyFilesToCustomInstallationDirectory(DeploymentType deploymentType) { // Set-up a custom installation directory string customInstallDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestInstall"); FileSystem.EnsureDirectoryExists(customInstallDirectory); // Ensure the directory is empty before we start FileSystem.PurgeDirectory(customInstallDirectory, FailureOptions.ThrowOnFailure); Variables.Set(PackageVariables.CustomInstallationDirectory, customInstallDirectory ); var result = DeployPackage(deploymentType); // Assert content was copied to custom-installation directory Assert.IsTrue(FileSystem.FileExists(Path.Combine(customInstallDirectory, "assets", "styles.css"))); } [Test] [TestCase(DeploymentType.Nupkg)] [TestCase(DeploymentType.Tar)] public void ShouldExecuteFeatureScripts(DeploymentType deploymentType) { Variables.Set(KnownVariables.Package.EnabledFeatures, "Octopus.Features.HelloWorld"); var result = DeployPackage(deploymentType); result.AssertOutput("Hello World!"); } #if IIS_SUPPORT [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldModifyIisWebsiteRoot() { // If the 'UpdateIisWebsite' variable is set, the website root will be updated // Create the website var originalWebRootPath = Path.Combine(Path.GetTempPath(), "CalamariTestIisSite"); FileSystem.EnsureDirectoryExists(originalWebRootPath); var webServer = WebServerSupport.AutoDetect(); var siteName = "CalamariTest-" + Guid.NewGuid(); webServer.CreateWebSiteOrVirtualDirectory(siteName, "/", originalWebRootPath, 1081); Variables.Set(SpecialVariables.Package.UpdateIisWebsite, true.ToString()); Variables.Set(SpecialVariables.Package.UpdateIisWebsiteName, siteName); var result = DeployPackage(); Assert.AreEqual( Path.Combine(StagingDirectory, "Acme.Web\\1.0.0"), webServer.GetHomeDirectory(siteName, "/")); // And remove the website webServer.DeleteWebSite(siteName); FileSystem.DeleteDirectory(originalWebRootPath); } #endif [Test] public void ShouldRunConfiguredScripts() { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts); if (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) { Variables.Set(ConfiguredScriptConvention.GetScriptName(DeploymentStages.Deploy, ScriptSyntax.Bash), "echo 'The wheels on the bus go round...'"); } else { Variables.Set(ConfiguredScriptConvention.GetScriptName(DeploymentStages.Deploy, ScriptSyntax.PowerShell), "Write-Host 'The wheels on the bus go round...'"); } var result = DeployPackage(); result.AssertOutput("The wheels on the bus go round..."); } [Test] public void ShouldAddJournalEntry() { var result = DeployPackage(); result.AssertOutput("Adding journal entry"); } [Test] [TestCase(DeploymentType.Nupkg)] [TestCase(DeploymentType.Tar)] public void ShouldSkipIfAlreadyInstalled(DeploymentType deploymentType) { Variables.Set(KnownVariables.Package.SkipIfAlreadyInstalled, true.ToString()); Variables.Set(KnownVariables.RetentionPolicySet, "a/b/c/d"); Variables.Set(PackageVariables.PackageId, "Acme.Web"); Variables.Set(PackageVariables.PackageVersion, "1.0.0"); var result = DeployPackage(deploymentType); result.AssertSuccess(); result.AssertOutput("The package has been installed to"); result = DeployPackage(deploymentType); result.AssertSuccess(); result.AssertOutput("The package has already been installed on this machine"); } [Test] public void ShouldSkipIfAlreadyInstalledWithDifferentPackageType() { Variables.Set(KnownVariables.Package.SkipIfAlreadyInstalled, true.ToString()); Variables.Set(KnownVariables.RetentionPolicySet, "a/b/c/d"); Variables.Set(PackageVariables.PackageId, "Acme.Web"); Variables.Set(PackageVariables.PackageVersion, "1.0.0"); var result = DeployPackage(DeploymentType.Tar); result.AssertSuccess(); result.AssertOutput("The package has been installed to"); result = DeployPackage(DeploymentType.Nupkg); result.AssertSuccess(); result.AssertOutput("The package has already been installed on this machine"); } [Test] public void ShouldDeployInParallel() { var locker = new object(); var extractionDirectories = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var errors = new List<Exception>(); var threads = Enumerable.Range(0, 4).Select(i => new Thread(new ThreadStart(delegate { try { CalamariResult result; using (var variablesFile = new TemporaryFile(Path.GetTempFileName())) { lock (locker) // this save method isn't thread safe { Variables.Save(variablesFile.FilePath); } result = Invoke(Calamari() .Action("deploy-package") .Argument("package", nupkgFile.FilePath) .Argument("variables", variablesFile.FilePath)); } result.AssertSuccess(); var extracted = result.GetOutputForLineContaining("Extracting package to: "); result.AssertOutput("Extracted 11 files"); lock (locker) { if (!extractionDirectories.Contains(extracted)) { extractionDirectories.Add(extracted); } else { Assert.Fail("The same installation directory was used twice: " + extracted); } } } catch (Exception ex) { errors.Add(ex); } }))).ToList(); foreach (var thread in threads) thread.Start(); foreach (var thread in threads) thread.Join(); var allErrors = string.Join(Environment.NewLine, errors.Select(e => e.ToString())); Assert.That(allErrors, Is.EqualTo(""), allErrors); } CalamariResult DeployPackage(DeploymentType deploymentType = DeploymentType.Nupkg) { var packageName = deploymentType == DeploymentType.Nupkg ? nupkgFile.FilePath : tarFile.FilePath; return DeployPackage(packageName); } [TearDown] public override void CleanUp() { base.CleanUp(); } private void AssertXmlNodeValue(string xmlFile, string nodeXPath, string value) { var configXml = new XmlDocument(); configXml.LoadXml( FileSystem.ReadFile(xmlFile)); var node = configXml.SelectSingleNode(nodeXPath); Assert.AreEqual(value, node.Value); } public enum DeploymentType { Tar, Nupkg } } } <file_sep>// // Options.cs // // Authors: // <NAME> <<EMAIL>> // // Copyright (C) 2008 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace Calamari.Common.Plumbing.Commands.Options { public abstract class Option { static readonly char[] NameTerminator = { '=', ':' }; protected Option(string? prototype, string? description, int maxValueCount = 1) { if (prototype == null) throw new ArgumentNullException("prototype"); if (prototype.Length == 0) throw new ArgumentException("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException("maxValueCount"); Prototype = prototype; Names = prototype.Split('|'); Description = description; MaxValueCount = maxValueCount; OptionValueType = ParsePrototype(); if (MaxValueCount == 0 && OptionValueType != OptionValueType.None) throw new ArgumentException( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (OptionValueType == OptionValueType.None && maxValueCount > 1) throw new ArgumentException( string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf(Names, "<>") >= 0 && (Names.Length == 1 && OptionValueType != OptionValueType.None || Names.Length > 1 && MaxValueCount > 1)) throw new ArgumentException( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype { get; } public string? Description { get; } public OptionValueType OptionValueType { get; } public int MaxValueCount { get; } internal string[] Names { get; } internal string[]? ValueSeparators { get; set; } public string[] GetNames() { return (string[])Names.Clone(); } public string[] GetValueSeparators() { if (ValueSeparators == null) return new string[0]; return (string[])ValueSeparators.Clone(); } [return: NotNullIfNotNull("value"), MaybeNull] protected static T Parse<T>(string? value, OptionContext c) { var conv = TypeDescriptor.GetConverter(typeof(T)); var t = default(T); try { if (value != null) t = (T)conv.ConvertFromString(value); } catch (Exception e) { throw new OptionException( string.Format( "Could not convert string `{0}' to type {1} for option `{2}'.", value, typeof(T).Name, c.OptionName), c.OptionName ?? "UnknownOptionName", e); } return t; } OptionValueType ParsePrototype() { var c = '\0'; var seps = new List<string>(); for (var i = 0; i < Names.Length; ++i) { var name = Names[i]; if (name.Length == 0) throw new ArgumentException("Empty option names are not supported."); var end = name.IndexOfAny(NameTerminator); if (end == -1) continue; Names[i] = name.Substring(0, end); if (c == '\0' || c == name[end]) c = name[end]; else throw new ArgumentException( string.Format("Conflicting option types: '{0}' vs. '{1}'.", c, name[end])); AddSeparators(name, end, seps); } if (c == '\0') return OptionValueType.None; if (MaxValueCount <= 1 && seps.Count != 0) throw new ArgumentException( string.Format("Cannot provide key/value separators for Options taking {0} value(s).", MaxValueCount)); if (MaxValueCount > 1) { if (seps.Count == 0) ValueSeparators = new[] { ":", "=" }; else if (seps.Count == 1 && seps[0].Length == 0) ValueSeparators = null; else ValueSeparators = seps.ToArray(); } return c == '=' ? OptionValueType.Required : OptionValueType.Optional; } static void AddSeparators(string name, int end, ICollection<string> seps) { var start = -1; for (var i = end + 1; i < name.Length; ++i) switch (name[i]) { case '{': if (start != -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name)); start = i + 1; break; case '}': if (start == -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name)); seps.Add(name.Substring(start, i - start)); start = -1; break; default: if (start == -1) seps.Add(name[i].ToString()); break; } if (start != -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name)); } public void Invoke(OptionContext c) { OnParseComplete(c); c.OptionName = null; c.Option = null; c.OptionValues.Clear(); } protected abstract void OnParseComplete(OptionContext c); public override string ToString() { return Prototype; } } }<file_sep>using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Amazon; using Amazon.Runtime; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; namespace Calamari.CloudAccounts { /// <summary> /// This service is used to generate the appropriate environment variables required to authentication /// custom scripts and the C# AWS SDK code exposed as Calamari commands that interact with AWS. /// </summary> public class AwsEnvironmentGeneration { const string TokenUri = "http://169.254.169.254/latest/api/token"; const string RoleUri = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"; const string MetadataHeaderToken = "X-aws-ec2-metadata-token"; const string MetadataHeaderTTL = "X-aws-ec2-metadata-token-ttl-seconds"; readonly ILog log; readonly Func<Task<bool>> verifyLogin; readonly string region; readonly string accessKey; readonly string secretKey; readonly string assumeRole; readonly string assumeRoleArn; readonly string assumeRoleExternalId; readonly string assumeRoleSession; readonly string assumeRoleDurationSeconds; public static async Task<AwsEnvironmentGeneration> Create(ILog log, IVariables variables, Func<Task<bool>> verifyLogin = null) { var environmentGeneration = new AwsEnvironmentGeneration(log, variables, verifyLogin); await environmentGeneration.Initialise(); return environmentGeneration; } async Task Initialise() { PopulateCommonSettings(); if (!await PopulateSuppliedKeys()) { if (!await LoginFallback()) { throw new Exception("AWS-LOGIN-ERROR-0006: " + "Failed to login via external credentials assigned to the worker. " + $"For more information visit {log.FormatLink("https://oc.to/t9nRNg")}"); } } await AssumeRole(); } /// <summary> /// This method represents the sequence of login fallbacks. AWS has an ever increasing /// assortment of processes for embedding credentials onto VMs and containers, see /// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-precedence /// for a breakdown of the precedence used by the AWS CLI tool. /// </summary> /// <returns>true if the login was successful, false otherwise</returns> async Task<bool> LoginFallback() { // Inherit role from web auth tokens return await PopulateKeysFromWebRole() // Inherit the role via the IMDS web endpoint exposed by VMs || await PopulateKeysFromInstanceRole(); } public Dictionary<string, string> EnvironmentVars { get; } = new Dictionary<string, string>(); internal AwsEnvironmentGeneration(ILog log, IVariables variables, Func<Task<bool>> verifyLogin = null) { this.log = log; this.verifyLogin = verifyLogin ?? VerifyLogin; var account = variables.Get("Octopus.Action.AwsAccount.Variable")?.Trim(); region = variables.Get("Octopus.Action.Aws.Region")?.Trim(); // When building the context for an AWS step, there will be a variable expanded with the keys accessKey = variables.Get(account + ".AccessKey")?.Trim() ?? // When building a context with an account associated with a target, the keys are under Octopus.Action.Amazon. // The lack of any keys means we rely on an EC2 instance role. variables.Get("Octopus.Action.Amazon.AccessKey")?.Trim(); secretKey = variables.Get(account + ".SecretKey")?.Trim() ?? variables.Get("Octopus.Action.Amazon.SecretKey")?.Trim(); assumeRole = variables.Get("Octopus.Action.Aws.AssumeRole")?.Trim(); assumeRoleArn = variables.Get("Octopus.Action.Aws.AssumedRoleArn")?.Trim(); assumeRoleExternalId = variables.Get("Octopus.Action.Aws.AssumeRoleExternalId")?.Trim(); assumeRoleSession = variables.Get("Octopus.Action.Aws.AssumedRoleSession")?.Trim(); assumeRoleDurationSeconds = variables.Get("Octopus.Action.Aws.AssumeRoleSessionDurationSeconds")?.Trim(); } /// <summary> /// Depending on how we logged in, we might be using a session or basic credentials /// </summary> /// <returns>AWS Credentials that can be used by the AWS API</returns> public AWSCredentials AwsCredentials { get { if (EnvironmentVars.ContainsKey("AWS_SESSION_TOKEN")) { return new SessionAWSCredentials( EnvironmentVars["AWS_ACCESS_KEY_ID"], EnvironmentVars["AWS_SECRET_ACCESS_KEY"], EnvironmentVars["AWS_SESSION_TOKEN"]); } return new BasicAWSCredentials( EnvironmentVars["AWS_ACCESS_KEY_ID"], EnvironmentVars["AWS_SECRET_ACCESS_KEY"]); } } public RegionEndpoint AwsRegion => RegionEndpoint.GetBySystemName(EnvironmentVars["AWS_REGION"]); /// <summary> /// Verify that we can login with the supplied credentials /// </summary> /// <returns>true if login succeeds, false otherwise</returns> async Task<bool> VerifyLogin() { try { await new AmazonSecurityTokenServiceClient(AwsCredentials).GetCallerIdentityAsync(new GetCallerIdentityRequest()); return true; } catch (AmazonServiceException ex) { log.Error("Error occured while verifying login"); log.Error(ex.Message); log.Error(ex.StackTrace); // Any exception is considered to be a failed login return false; } } /// <summary> /// We always set these variables, regardless of the kind of login /// </summary> void PopulateCommonSettings() { EnvironmentVars["AWS_DEFAULT_REGION"] = region; EnvironmentVars["AWS_REGION"] = region; } /// <summary> /// If the keys were explicitly supplied, use them directly /// </summary> /// <exception cref="Exception">The supplied keys were not valid</exception> async Task<bool> PopulateSuppliedKeys() { if (!String.IsNullOrEmpty(accessKey)) { EnvironmentVars["AWS_ACCESS_KEY_ID"] = accessKey; EnvironmentVars["AWS_SECRET_ACCESS_KEY"] = secretKey; if (!await verifyLogin()) { throw new Exception("AWS-LOGIN-ERROR-0005: Failed to verify the credentials. " + "Please check the keys assigned to the Amazon Web Services Account associated with this step. " + $"For more information visit {log.FormatLink("https://oc.to/U4WA8x")}"); } return true; } return false; } /// <summary> /// If no keys were supplied, we must be using the instance role /// </summary> async Task<bool> PopulateKeysFromInstanceRole() { if (String.IsNullOrEmpty(accessKey)) { try { string payload; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add(MetadataHeaderToken, await GetIMDSv2Token()); var instanceRole = await client.GetStringAsync(RoleUri); payload = await client.GetStringAsync($"{RoleUri}{instanceRole}"); } dynamic instanceRoleKeys = JsonConvert.DeserializeObject(payload); EnvironmentVars["AWS_ACCESS_KEY_ID"] = instanceRoleKeys.AccessKeyId; EnvironmentVars["AWS_SECRET_ACCESS_KEY"] = instanceRoleKeys.SecretAccessKey; EnvironmentVars["AWS_SESSION_TOKEN"] = instanceRoleKeys.Token; return true; } catch { // catch the exception and fallback to returning false } } return false; } /// <summary> /// This method reads the AWS_WEB_IDENTITY_TOKEN_FILE environment variable, loads the token /// from the associated file, and then assumes the role. This is used when a tentacle is /// running in an EKS cluster. The docs at https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html /// have more details. /// </summary> async Task<bool> PopulateKeysFromWebRole() { if (String.IsNullOrEmpty(accessKey)) { try { var credentials = await AssumeRoleWithWebIdentityCredentials .FromEnvironmentVariables() .GetCredentialsAsync(); EnvironmentVars["AWS_ACCESS_KEY_ID"] = credentials.AccessKey; EnvironmentVars["AWS_SECRET_ACCESS_KEY"] = credentials.SecretKey; EnvironmentVars["AWS_SESSION_TOKEN"] = credentials.Token; return true; } catch { // catch the exception and fallback to returning false } } return false; } /// <summary> /// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html /// </summary> /// <returns>A token to be used with any IMDS request</returns> async Task<string> GetIMDSv2Token() { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add(MetadataHeaderTTL, "60"); var body = await client.PutAsync(TokenUri, null); return await body.Content.ReadAsStringAsync(); } } /// <summary> /// If we assume a secondary role, do it here /// </summary> async Task AssumeRole() { if ("True".Equals(assumeRole, StringComparison.OrdinalIgnoreCase)) { var client = new AmazonSecurityTokenServiceClient(AwsCredentials); var credentials = (await client.AssumeRoleAsync(GetAssumeRoleRequest())).Credentials; EnvironmentVars["AWS_ACCESS_KEY_ID"] = credentials.AccessKeyId; EnvironmentVars["AWS_SECRET_ACCESS_KEY"] = credentials.SecretAccessKey; EnvironmentVars["AWS_SESSION_TOKEN"] = credentials.SessionToken; } } public AssumeRoleRequest GetAssumeRoleRequest() { var request = new AssumeRoleRequest { RoleArn = assumeRoleArn, RoleSessionName = assumeRoleSession, ExternalId = string.IsNullOrWhiteSpace(assumeRoleExternalId) ? null : assumeRoleExternalId }; if (int.TryParse(assumeRoleDurationSeconds, out var durationSeconds)) request.DurationSeconds = durationSeconds; return request; } } }<file_sep>namespace Calamari.Common.Plumbing.Logging { public static class ExitStatus { public const int Success = 0; public const int CommandExceptionError = 1; public const int RecursiveDefinitionExceptionError = 101; public const int ReflectionTypeLoadExceptionError = 43; public const int OtherError = 100; } }<file_sep>using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text.RegularExpressions; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Certificates; using Calamari.Integration.Iis; namespace Calamari.Deployment.Features { public class IisWebSiteAfterPostDeployFeature : IisWebSiteFeature { public override string DeploymentStage => DeploymentStages.AfterPostDeploy; public override void Execute(RunningDeployment deployment) { var variables = deployment.Variables; if (variables.GetFlag(SpecialVariables.Action.IisWebSite.DeployAsWebSite, false)) { #if WINDOWS_CERTIFICATE_STORE_SUPPORT // For any bindings using certificate variables, the application pool account // must have access to the private-key. EnsureApplicationPoolHasCertificatePrivateKeyAccess(variables); #endif } } #if WINDOWS_CERTIFICATE_STORE_SUPPORT static void EnsureApplicationPoolHasCertificatePrivateKeyAccess(IVariables variables) { foreach (var binding in GetEnabledBindings(variables)) { string certificateVariable = binding.certificateVariable; if (string.IsNullOrWhiteSpace(certificateVariable)) continue; var thumbprint = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Thumbprint}"); var privateKeyAccess = CreatePrivateKeyAccessForApplicationPoolAccount(variables); // The store-name variable was set by IisWebSiteBeforePostDeploy var storeName = variables.Get(SpecialVariables.Action.IisWebSite.Output.CertificateStoreName); WindowsX509CertificateStore.AddPrivateKeyAccessRules(thumbprint, StoreLocation.LocalMachine, storeName, new List<PrivateKeyAccessRule> {privateKeyAccess}); } } static PrivateKeyAccessRule CreatePrivateKeyAccessForApplicationPoolAccount(IVariables variables) { var applicationPoolIdentityTypeValue = variables.Get(SpecialVariables.Action.IisWebSite.ApplicationPoolIdentityType); ApplicationPoolIdentityType appPoolIdentityType; if(!Enum.TryParse(applicationPoolIdentityTypeValue, out appPoolIdentityType)) { throw new CommandException($"Unexpected value for '{SpecialVariables.Action.IisWebSite.ApplicationPoolIdentityType}': '{applicationPoolIdentityTypeValue}'"); } return new PrivateKeyAccessRule( GetIdentityForApplicationPoolIdentity(appPoolIdentityType, variables), PrivateKeyAccess.FullControl); } static IdentityReference GetIdentityForApplicationPoolIdentity(ApplicationPoolIdentityType applicationPoolIdentityType, IVariables variables) { switch (applicationPoolIdentityType) { case ApplicationPoolIdentityType.ApplicationPoolIdentity: return new NTAccount("IIS AppPool\\" + variables.Get(SpecialVariables.Action.IisWebSite.ApplicationPoolName)); case ApplicationPoolIdentityType.LocalService: return new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null); case ApplicationPoolIdentityType.LocalSystem: return new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null); case ApplicationPoolIdentityType.NetworkService: return new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); case ApplicationPoolIdentityType.SpecificUser: return new NTAccount(StripLocalAccountIdentifierFromUsername(variables.Get(SpecialVariables.Action.IisWebSite.ApplicationPoolUserName))); default: throw new ArgumentOutOfRangeException(nameof(applicationPoolIdentityType), applicationPoolIdentityType, null); } } static string StripLocalAccountIdentifierFromUsername(string username) { //The NTAccount class doesnt work with local accounts represented in the format of .\username //an exception is thrown when attempting to call NTAccount.Translate(). //The following expression is to remove .\ from the beginning of usernames, we still allow for usernames in the format of machine\user or domain\user return Regex.Replace(username, "\\.\\\\(.*)", "$1", RegexOptions.None); } #endif } }<file_sep>using System; namespace Calamari.Testing.Helpers { public static class TestCategory { public static class ScriptingSupport { public const string FSharp = "fsharp"; public const string DotnetScript = "dotnet-script"; } public static class CompatibleOS { public const string OnlyNix = "Nix"; public const string OnlyWindows = "Windows"; public const string OnlyMac = "macOS"; public const string OnlyNixOrMac = "nixMacOS"; } public const string PlatformAgnostic = "PlatformAgnostic"; public const string RunOnceOnWindowsAndLinux = "RunOnceOnWindowsAndLinux"; } }<file_sep>#if NETCORE using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Assent; using Calamari.Aws.Kubernetes.Discovery; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Kubernetes.Commands; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Tests.AWS; using Calamari.Tests.Helpers; using FluentAssertions; using Newtonsoft.Json.Linq; using NUnit.Framework; using SharpCompress.Archives.Zip; using SharpCompress.Common; using File = System.IO.File; using KubernetesSpecialVariables = Calamari.Kubernetes.SpecialVariables; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] [Category(TestCategory.RunOnceOnWindowsAndLinux)] public class KubernetesContextScriptWrapperLiveFixtureEks: KubernetesContextScriptWrapperLiveFixture { private const string ResourcePackageFileName = "package.1.0.0.zip"; private const string DeploymentFileName = "customresource.yml"; private const string DeploymentFileName2 = "myapp-deployment.yml"; private const string ServiceFileName = "myapp-service.yml"; private const string ConfigMapFileName = "myapp-configmap1.yml"; private const string ConfigMapFileName2 = "myapp-configmap2.yml"; private const string SimpleDeploymentResourceType = "Deployment"; private const string SimpleDeploymentResourceName = "nginx-deployment"; private const string SimpleDeploymentResource = "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: nginx-deployment\nspec:\n selector:\n matchLabels:\n app: nginx\n replicas: 3\n template:\n metadata:\n labels:\n app: nginx\n spec:\n containers:\n - name: nginx\n image: nginx:1.14.2\n ports:\n - containerPort: 80"; private const string SimpleDeployment2ResourceName = "nginx-deployment"; private const string SimpleDeploymentResource2 = "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: nginx-deployment2\nspec:\n selector:\n matchLabels:\n app: nginx2\n replicas: 1\n template:\n metadata:\n labels:\n app: nginx2\n spec:\n containers:\n - name: nginx2\n image: nginx:1.14.2\n ports:\n - containerPort: 81\n"; private const string InvalidDeploymentResource = "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: nginx-deployment\nspec:\nbad text here\n selector:\n matchLabels:\n app: nginx\n replicas: 3\n template:\n metadata:\n labels:\n app: nginx\n spec:\n containers:\n - name: nginx\n image: nginx:1.14.2\n ports:\n - containerPort: 80\n"; private const string FailToDeploymentResource = "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: nginx-deployment\nspec:\n selector:\n matchLabels:\n app: nginx\n replicas: 3\n template:\n metadata:\n labels:\n app: nginx\n spec:\n containers:\n - name: nginx\n image: nginx-bad-container-name:1.14.2\n ports:\n - containerPort: 80\n"; private const string SimpleServiceResourceName = "nginx-service"; private const string SimpleService = "apiVersion: v1\nkind: Service\nmetadata:\n name: nginx-service\nspec:\n selector:\n app.kubernetes.io/name: nginx\n ports:\n - protocol: TCP\n port: 80\n targetPort: 9376"; private const string SimpleConfigMapResourceName = "game-demo"; private const string SimpleConfigMap = "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: game-demo\ndata:\n player_initial_lives: '3'\n ui_properties_file_name: 'user-interface.properties'\n game.properties: |\n enemy.types=aliens,monsters\n player.maximum-lives=5\n user-interface.properties: |\n color.good=purple\n color.bad=yellow\n allow.textmode=true"; private const string SimpleConfigMap2ResourceName = "game-demo2"; private const string SimpleConfigMap2 = "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: game-demo2\ndata:\n player_initial_lives: '1'\n ui_properties_file_name: 'user-interface.properties'\n game.properties: |\n enemy.types=blobs,foxes\n player.maximum-lives=10\n user-interface.properties: |\n color.good=orange\n color.bad=pink\n allow.textmode=false"; string eksClientID; string eksSecretKey; string eksClusterEndpoint; string eksClusterCaCertificate; string eksClusterName; string awsVpcID; string awsSubnetID; string awsIamInstanceProfileName; string region; string eksClusterArn; string eksIamRolArn; protected override string KubernetesCloudProvider => "EKS"; protected override async Task PreInitialise() { region = RegionRandomiser.GetARegion(); await TestContext.Progress.WriteLineAsync($"Aws Region chosen: {region}"); } protected override async Task InstallOptionalTools(InstallTools tools) { await tools.InstallAwsAuthenticator(); await tools.InstallAwsCli(); } protected override IEnumerable<string> ToolsToAddToPath(InstallTools tools) { return new List<string> { tools.AwsAuthenticatorExecutable, tools.AwsCliExecutable }; } protected override void ExtractVariablesFromTerraformOutput(JObject jsonOutput) { eksClientID = jsonOutput["eks_client_id"]["value"].Value<string>(); eksSecretKey = jsonOutput["eks_secret_key"]["value"].Value<string>(); eksClusterEndpoint = jsonOutput["eks_cluster_endpoint"]["value"].Value<string>(); eksClusterCaCertificate = jsonOutput["eks_cluster_ca_certificate"]["value"].Value<string>(); eksClusterName = jsonOutput["eks_cluster_name"]["value"].Value<string>(); eksClusterArn = jsonOutput["eks_cluster_arn"]["value"].Value<string>(); eksIamRolArn = jsonOutput["eks_iam_role_arn"]["value"].Value<string>(); awsVpcID = jsonOutput["aws_vpc_id"]["value"].Value<string>(); awsSubnetID = jsonOutput["aws_subnet_id"]["value"].Value<string>(); awsIamInstanceProfileName = jsonOutput["aws_iam_instance_profile_name"]["value"].Value<string>(); } protected override Dictionary<string, string> GetEnvironmentVars() { return new Dictionary<string, string> { { "AWS_ACCESS_KEY_ID", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey) }, { "AWS_SECRET_ACCESS_KEY", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey) }, { "AWS_DEFAULT_REGION", region }, { "TF_VAR_tests_source_dir", testFolder } }; } [Test] [TestCase(true, true)] [TestCase(true, false)] [TestCase(false, true)] [TestCase(false, false)] public void DeployRawYaml_WithRawYamlDeploymentScriptOrCommand_OutputShouldIndicateSuccessfulDeployment(bool runAsScript, bool usePackage) { SetupAndRunKubernetesRawYamlDeployment(runAsScript, usePackage, SimpleDeploymentResource); var rawLogs = Log.Messages.Select(m => m.FormattedMessage).ToArray(); var scrubbedJson = AssertResourceCreatedAndGetJson(SimpleDeploymentResourceName); this.Assent(scrubbedJson, configuration: AssentConfiguration.Default); AssertObjectStatusMonitoringStarted(runAsScript, rawLogs, (SimpleDeploymentResourceType, SimpleDeploymentResourceName)); var objectStatusUpdates = Log.Messages.GetServiceMessagesOfType("k8s-status"); objectStatusUpdates.Where(m => m.Properties["status"] == "Successful").Should().HaveCount(5); rawLogs.Should().ContainSingle(m => m.Contains("Resource status check completed successfully because all resources are deployed successfully")); } private static void AssertObjectStatusMonitoringStarted(bool runAsScript, string[] rawLogs, params (string Type, string Name)[] resources) { var resourceStatusCheckLog = runAsScript ? "Resource Status Check: Performing resource status checks on the following resources:" : "Resource Status Check: 1 new resources have been added:"; var idx = Array.IndexOf(rawLogs, resourceStatusCheckLog); foreach (var (i, type, name) in resources.Select((t, i) => (i, t.Type, t.Name))) { rawLogs[idx + i + 1].Should().Be($" - {type}/{name} in namespace calamari-testing"); } } private string AssertResourceCreatedAndGetJson(string resourceName) { var variableMessages = Log.Messages.GetServiceMessagesOfType("setVariable"); var variableMessage = variableMessages.Should().ContainSingle(m => m.Properties["name"] == $"CustomResources({resourceName})") .Subject; return KubernetesJsonResourceScrubber.ScrubRawJson(variableMessage.Properties["value"], p => p.Name.Contains("Time") || p.Name == "annotations" || p.Name == "uid" || p.Name == "conditions" || p.Name == "resourceVersion" || p.Name == "status" || p.Name == "generation" || p.Name.StartsWith("clusterIP")); } [Test] [TestCase(true, true)] [TestCase(true, false)] [TestCase(false, true)] [TestCase(false, false)] public void DeployRawYaml_WithInvalidYaml_OutputShouldIndicateFailure(bool runAsScript, bool usePackage) { SetupAndRunKubernetesRawYamlDeployment(runAsScript, usePackage, InvalidDeploymentResource, shouldSucceed: false); var rawLogs = Log.Messages.Select(m => m.FormattedMessage).Where(m => !m.StartsWith("##octopus") && m != string.Empty).ToArray(); var fileName = usePackage ? $"deployments{Path.DirectorySeparatorChar}{DeploymentFileName}" : DeploymentFileName; var initialErrorMessage = $"error: error parsing {fileName}: error converting YAML to JSON: yaml: line 7: could not find expected ':'"; rawLogs.Should() .ContainSingle(l => l == initialErrorMessage); var index = Array.IndexOf(rawLogs, initialErrorMessage); var logsToCompare = new List<string>(rawLogs); // We'll check the rest of the logs after the one above // as they should be the same for all cases (except those // filtered out or adjusted below). logsToCompare.RemoveRange(0, index+1); logsToCompare = logsToCompare.Select(l => { // This log line is slightly different in the new command because // we apply the yaml in batches (even if there is only one file). return l.Replace("\"kubectl apply -o json\" returned invalid JSON:", "\"kubectl apply -o json\" returned invalid JSON for Batch #1:"); }) .Select(l => { // There was actually no clean-up process for custom resources // so the log line produced by the deployment script doesn't // make sense. The new command does not have that part of the // log line. return l.Replace( "Custom resources will not be saved as output variables, and will not be automatically cleaned up.", "Custom resources will not be saved as output variables."); }) .Where(l => { // These log lines are in the old deployment script but the script // doesn't actually do the things that the logs describe and so they // aren't in the new command. return l != "The previous custom resources were not removed." && l != "The deployment process failed. The resources created by this step will be passed to \"kubectl describe\" and logged below."; }) .Where(l => { // These logs are printed after an error is caught but only for the new command return l != "Adding journal entry:" && !l.StartsWith("<Deployment Id="); }) .ToList(); this.Assent(string.Join('\n', logsToCompare), configuration: AssentConfiguration.Default); } [Test] [TestCase(true, true)] [TestCase(true, false)] [TestCase(false, true)] [TestCase(false, false)] public void DeployRawYaml_WithYamlThatWillNotSucceed_OutputShouldIndicateFailure(bool runAsScript, bool usePackage) { SetupAndRunKubernetesRawYamlDeployment(runAsScript, usePackage, FailToDeploymentResource, shouldSucceed: false); var rawLogs = Log.Messages.Select(m => m.FormattedMessage).ToArray(); var scrubbedJson = AssertResourceCreatedAndGetJson(SimpleDeploymentResourceName); this.Assent(scrubbedJson, configuration: AssentConfiguration.Default); AssertObjectStatusMonitoringStarted(runAsScript, rawLogs, (SimpleDeploymentResourceType, SimpleDeploymentResourceName)); rawLogs.Should().ContainSingle(l => l == "Resource status check terminated because the timeout has been reached but some resources are still in progress"); } [Test] public void DeployRawYaml_WithMultipleYamlFilesSpecifiedByGlobPatterns_YamlFilesAreAppliedInCorrectBatches() { SetVariablesToAuthoriseWithAmazonAccount(); SetVariablesForKubernetesResourceStatusCheck(30); SetVariablesForRawYamlCommand($@"deployments/**/* services/{ServiceFileName} configmaps/*.yml"); string CreatePackageWithMultipleYamlFiles(string directory) { var packageToPackage = CreatePackageWithFiles(ResourcePackageFileName, directory, ("deployments", DeploymentFileName, SimpleDeploymentResource), (Path.Combine("deployments", "subfolder"), DeploymentFileName2, SimpleDeploymentResource2), ("services", ServiceFileName, SimpleService), ("services", "EmptyYamlFile.yml", ""), ("configmaps", ConfigMapFileName, SimpleConfigMap), ("configmaps", ConfigMapFileName2, SimpleConfigMap2), (Path.Combine("configmaps","subfolder"), "InvalidJSONNotUsed.yml", InvalidDeploymentResource)); return packageToPackage; } ExecuteCommandAndVerifyResult(KubernetesApplyRawYamlCommand.Name, CreatePackageWithMultipleYamlFiles); var rawLogs = Log.Messages.Select(m => m.FormattedMessage).Where(l => !l.StartsWith("##octopus")).ToArray(); // We take the logs starting from when Calamari starts applying batches // to when the last k8s resource is created and compare them in an assent test. var startIndex = Array.FindIndex(rawLogs, l => l.StartsWith("Applying Batch #1")); var endIndex = Array.FindLastIndex(rawLogs, l => l == "Resource Status Check: 2 new resources have been added:") + 2; var assentLogs = rawLogs.Skip(startIndex) .Take(endIndex + 1 - startIndex) .Where(l => !l.StartsWith("##octopus")).ToArray(); var batch3Index = Array.FindIndex(assentLogs, l => l.StartsWith("Applying Batch #3")); // In this case the two config maps have been loaded in reverse order // This can happen as Directory.EnumerateFiles() does not behave the // same on all platforms. // We'll flip them back the right way before performing the Assent Test. if (assentLogs[batch3Index + 1].Contains("myapp-configmap1.yml")) { var configMap1Idx = batch3Index + 1; var configMap2Idx = Array.FindIndex(assentLogs, l => l.Contains("myapp-configmap2.yml")); var endIdx = Array.FindLastIndex(assentLogs, l => l == "Created Resources:") - 1; InPlaceSwap(assentLogs, configMap1Idx, configMap2Idx, endIdx); } // We need to replace the backslash with forward slash because // the slash comes out differently on windows machines. var assentString = string.Join('\n', assentLogs).Replace("\\", "/"); this.Assent(assentString, configuration: AssentConfiguration.DefaultWithPostfix("ApplyingBatches")); var resources = new[] { (Name: SimpleDeploymentResourceName, Label: "Deployment1"), (Name: SimpleDeployment2ResourceName,Label: "Deployment2"), (Name: SimpleServiceResourceName, Label: "Service1"), (Name: SimpleConfigMapResourceName, Label: "ConfigMap1"), (Name: SimpleConfigMap2ResourceName, Label: "ConfigMap3") }; var statusMessages = Log.Messages.GetServiceMessagesOfType("k8s-status"); foreach (var (name, label) in resources) { // Check that each resource was created and the appropriate setvariable service message was created. var resource = AssertResourceCreatedAndGetJson(name); this.Assent(resource, configuration: AssentConfiguration.DefaultWithPostfix(label)); // Check that each deployed resource has a "Successful" status reported. statusMessages.Should().Contain(m => m.Properties["name"] == name && m.Properties["status"] == "Successful"); } rawLogs.Should().ContainSingle(m => m.Contains("Resource status check completed successfully because all resources are deployed successfully")); } [Test] [TestCase(true)] [TestCase(false)] public void AuthorisingWithAmazonAccount(bool runAsScript) { SetVariablesToAuthoriseWithAmazonAccount(); if (runAsScript) { DeployWithKubectlTestScriptAndVerifyResult(); } else { ExecuteCommandAndVerifyResult(TestableKubernetesDeploymentCommand.Name); } } [Test] public void UnreachableK8Cluster_ShouldExecuteTargetScript() { const string account = "eks_account"; const string certificateAuthority = "myauthority"; const string unreachableClusterEndpoint = "https://example.kubernetes.com"; variables.Set(SpecialVariables.Account.AccountType, "AmazonWebServicesAccount"); variables.Set(KubernetesSpecialVariables.ClusterUrl, unreachableClusterEndpoint); variables.Set(KubernetesSpecialVariables.EksClusterName, eksClusterName); variables.Set("Octopus.Action.Aws.Region", region); variables.Set("Octopus.Action.AwsAccount.Variable", account); variables.Set($"{account}.AccessKey", eksClientID); variables.Set($"{account}.SecretKey", eksSecretKey); variables.Set("Octopus.Action.Kubernetes.CertificateAuthority", certificateAuthority); variables.Set($"{certificateAuthority}.CertificatePem", eksClusterCaCertificate); DeployWithNonKubectlTestScriptAndVerifyResult(); } [Test] public void UsingEc2Instance() { var terraformWorkingFolder = InitialiseTerraformWorkingFolder("terraform_working/EC2", "KubernetesFixtures/Terraform/EC2"); var env = new Dictionary<string, string> { { "TF_VAR_iam_role_arn", eksIamRolArn }, { "TF_VAR_cluster_name", eksClusterName }, { "TF_VAR_aws_vpc_id", awsVpcID }, { "TF_VAR_aws_subnet_id", awsSubnetID }, { "TF_VAR_aws_iam_instance_profile_name", awsIamInstanceProfileName }, { "TF_VAR_aws_region", region } }; RunTerraformInternal(terraformWorkingFolder, env, "init"); try { // The actual tests are run via EC2/test.sh which executes the tests in // KubernetesContextScriptWrapperLiveFixtureForAmazon.cs RunTerraformInternal(terraformWorkingFolder, env, "apply", "-auto-approve"); } finally { RunTerraformDestroy(terraformWorkingFolder, env); } } [Test] public void DiscoverKubernetesClusterWithEnvironmentVariableCredentialsAndIamRole() { const string accessKeyEnvVar = "AWS_ACCESS_KEY_ID"; const string secretKeyEnvVar = "AWS_SECRET_ACCESS_KEY"; var originalAccessKey = Environment.GetEnvironmentVariable(accessKeyEnvVar); var originalSecretKey = Environment.GetEnvironmentVariable(secretKeyEnvVar); try { Environment.SetEnvironmentVariable(accessKeyEnvVar, eksClientID); Environment.SetEnvironmentVariable(secretKeyEnvVar, eksSecretKey); var authenticationDetails = new AwsAuthenticationDetails { Type = "Aws", Credentials = new AwsCredentials { Type = "worker" }, Role = new AwsAssumedRole { Type = "assumeRole", Arn = eksIamRolArn }, Regions = new []{region} }; var serviceMessageProperties = new Dictionary<string, string> { { "name", eksClusterArn }, { "clusterName", eksClusterName }, { "clusterUrl", eksClusterEndpoint }, { "skipTlsVerification", bool.TrueString }, { "octopusDefaultWorkerPoolIdOrName", "WorkerPools-1" }, { "octopusRoles", "discovery-role" }, { "updateIfExisting", bool.TrueString }, { "isDynamic", bool.TrueString }, { "awsUseWorkerCredentials", bool.TrueString }, { "awsAssumeRole", bool.TrueString }, { "awsAssumeRoleArn", eksIamRolArn }, }; DoDiscoveryAndAssertReceivedServiceMessageWithMatchingProperties(authenticationDetails, serviceMessageProperties); } finally { Environment.SetEnvironmentVariable(accessKeyEnvVar, originalAccessKey); Environment.SetEnvironmentVariable(secretKeyEnvVar, originalSecretKey); } } [Test] public void DiscoverKubernetesClusterWithEnvironmentVariableCredentialsAndNoIamRole() { const string accessKeyEnvVar = "AWS_ACCESS_KEY_ID"; const string secretKeyEnvVar = "AWS_SECRET_ACCESS_KEY"; var originalAccessKey = Environment.GetEnvironmentVariable(accessKeyEnvVar); var originalSecretKey = Environment.GetEnvironmentVariable(secretKeyEnvVar); try { Environment.SetEnvironmentVariable(accessKeyEnvVar, eksClientID); Environment.SetEnvironmentVariable(secretKeyEnvVar, eksSecretKey); var authenticationDetails = new AwsAuthenticationDetails { Type = "Aws", Credentials = new AwsCredentials { Type = "worker" }, Role = new AwsAssumedRole { Type = "noAssumedRole" }, Regions = new []{region} }; var serviceMessageProperties = new Dictionary<string, string> { { "name", eksClusterArn }, { "clusterName", eksClusterName }, { "clusterUrl", eksClusterEndpoint }, { "skipTlsVerification", bool.TrueString }, { "octopusDefaultWorkerPoolIdOrName", "WorkerPools-1" }, { "octopusRoles", "discovery-role" }, { "updateIfExisting", bool.TrueString }, { "isDynamic", bool.TrueString }, { "awsUseWorkerCredentials", bool.TrueString }, { "awsAssumeRole", bool.FalseString } }; DoDiscoveryAndAssertReceivedServiceMessageWithMatchingProperties(authenticationDetails, serviceMessageProperties); } finally { Environment.SetEnvironmentVariable(accessKeyEnvVar, originalAccessKey); Environment.SetEnvironmentVariable(secretKeyEnvVar, originalSecretKey); } } [Test] public void DiscoverKubernetesClusterWithAwsAccountCredentialsAndNoIamRole() { var authenticationDetails = new AwsAuthenticationDetails { Type = "Aws", Credentials = new AwsCredentials { Account = new AwsAccount { AccessKey = eksClientID, SecretKey = eksSecretKey }, AccountId = "Accounts-1", Type = "account" }, Role = new AwsAssumedRole { Type = "noAssumedRole" }, Regions = new []{region} }; var serviceMessageProperties = new Dictionary<string, string> { { "name", eksClusterArn }, { "clusterName", eksClusterName }, { "clusterUrl", eksClusterEndpoint }, { "skipTlsVerification", bool.TrueString }, { "octopusDefaultWorkerPoolIdOrName", "WorkerPools-1" }, { "octopusAccountIdOrName", "Accounts-1" }, { "octopusRoles", "discovery-role" }, { "updateIfExisting", bool.TrueString }, { "isDynamic", bool.TrueString }, { "awsUseWorkerCredentials", bool.FalseString }, { "awsAssumeRole", bool.FalseString } }; DoDiscoveryAndAssertReceivedServiceMessageWithMatchingProperties(authenticationDetails, serviceMessageProperties); } [Test] public void DiscoverKubernetesClusterWithAwsAccountCredentialsAndIamRole() { const int sessionDuration = 900; var authenticationDetails = new AwsAuthenticationDetails { Type = "Aws", Credentials = new AwsCredentials { Account = new AwsAccount { AccessKey = eksClientID, SecretKey = eksSecretKey }, AccountId = "Accounts-1", Type = "account" }, Role = new AwsAssumedRole { Type = "assumeRole", Arn = eksIamRolArn, SessionName = "ThisIsASessionName", SessionDuration = sessionDuration }, Regions = new []{region} }; var serviceMessageProperties = new Dictionary<string, string> { { "name", eksClusterArn }, { "clusterName", eksClusterName }, { "clusterUrl", eksClusterEndpoint }, { "skipTlsVerification", bool.TrueString }, { "octopusDefaultWorkerPoolIdOrName", "WorkerPools-1" }, { "octopusAccountIdOrName", "Accounts-1" }, { "octopusRoles", "discovery-role" }, { "updateIfExisting", bool.TrueString }, { "isDynamic", bool.TrueString }, { "awsUseWorkerCredentials", bool.FalseString }, { "awsAssumeRole", bool.TrueString }, { "awsAssumeRoleArn", eksIamRolArn }, { "awsAssumeRoleSession", "ThisIsASessionName" }, { "awsAssumeRoleSessionDurationSeconds", sessionDuration.ToString() } }; DoDiscoveryAndAssertReceivedServiceMessageWithMatchingProperties(authenticationDetails, serviceMessageProperties); } [Test] public void DiscoverKubernetesClusterWithNoValidCredentials() { const string accessKeyEnvVar = "AWS_ACCESS_KEY_ID"; const string secretKeyEnvVar = "AWS_SECRET_ACCESS_KEY"; var originalAccessKey = Environment.GetEnvironmentVariable(accessKeyEnvVar); var originalSecretKey = Environment.GetEnvironmentVariable(secretKeyEnvVar); try { Environment.SetEnvironmentVariable(accessKeyEnvVar, null); Environment.SetEnvironmentVariable(secretKeyEnvVar, null); var authenticationDetails = new AwsAuthenticationDetails { Type = "Aws", Credentials = new AwsCredentials { Type = "worker" }, Role = new AwsAssumedRole { Type = "noAssumedRole" }, Regions = new []{region} }; DoDiscovery(authenticationDetails); Log.ServiceMessages.Should().NotContain(m => m.Name == KubernetesDiscoveryCommand.CreateKubernetesTargetServiceMessageName); Log.Messages.Should().NotContain(m => m.Level == InMemoryLog.Level.Error); Log.StandardError.Should().BeEmpty(); Log.Messages.Should() .ContainSingle(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == "Unable to authorise credentials, see verbose log for details."); } finally { Environment.SetEnvironmentVariable(accessKeyEnvVar, originalAccessKey); Environment.SetEnvironmentVariable(secretKeyEnvVar, originalSecretKey); } } [Test] public void DiscoverKubernetesClusterWithInvalidAccountCredentials() { var authenticationDetails = new AwsAuthenticationDetails { Type = "Aws", Credentials = new AwsCredentials { Account = new AwsAccount { AccessKey = "abcdefg", SecretKey = null }, AccountId = "Accounts-1", Type = "account" }, Role = new AwsAssumedRole { Type = "noAssumedRole" }, Regions = new []{region} }; DoDiscovery(authenticationDetails); Log.ServiceMessages.Should().NotContain(m => m.Name == KubernetesDiscoveryCommand.CreateKubernetesTargetServiceMessageName); Log.MessagesErrorFormatted.Should().BeEmpty(); Log.StandardError.Should().BeEmpty(); Log.Messages.Should() .ContainSingle(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == "Unable to authorise credentials, see verbose log for details."); } private void SetupAndRunKubernetesRawYamlDeployment(bool runAsScript, bool usePackage, string resource, bool shouldSucceed = true) { SetVariablesToAuthoriseWithAmazonAccount(); SetVariablesForKubernetesResourceStatusCheck(shouldSucceed ? 30 : 5); SetVariablesForRawYamlCommand(runAsScript ? null : "**/*.{yml,yaml}"); if (runAsScript) { DeployWithDeploymentScriptAndVerifyResult(usePackage ? CreateAddPackageFunc(resource) : CreateAddCustomResourceFileFunc(resource), shouldSucceed); } else { ExecuteCommandAndVerifyResult(KubernetesApplyRawYamlCommand.Name, usePackage ? CreateAddPackageFunc(resource) : CreateAddCustomResourceFileFunc(resource), shouldSucceed); } } private void SetVariablesToAuthoriseWithAmazonAccount() { const string account = "eks_account"; const string certificateAuthority = "myauthority"; variables.Set(SpecialVariables.Account.AccountType, "AmazonWebServicesAccount"); variables.Set(KubernetesSpecialVariables.ClusterUrl, eksClusterEndpoint); variables.Set(KubernetesSpecialVariables.EksClusterName, eksClusterName); variables.Set("Octopus.Action.Aws.Region", region); variables.Set("Octopus.Action.AwsAccount.Variable", account); variables.Set($"{account}.AccessKey", eksClientID); variables.Set($"{account}.SecretKey", eksSecretKey); variables.Set("Octopus.Action.Kubernetes.CertificateAuthority", certificateAuthority); variables.Set($"{certificateAuthority}.CertificatePem", eksClusterCaCertificate); } private void SetVariablesForRawYamlCommand(string globPaths = null) { variables.Set("Octopus.Action.KubernetesContainers.Namespace", "nginx"); variables.Set(KnownVariables.Package.JsonConfigurationVariablesTargets, globPaths ?? "**/*.{yml,yaml}"); if (globPaths != null) { variables.Set(KubernetesSpecialVariables.CustomResourceYamlFileName, globPaths); } } private void SetVariablesForKubernetesResourceStatusCheck(int timeout) { variables.Set("Octopus.Action.Kubernetes.ResourceStatusCheck", "True"); variables.Set("Octopus.Action.KubernetesContainers.DeploymentWait", "NoWait"); variables.Set("Octopus.Action.Kubernetes.DeploymentTimeout", timeout.ToString()); } private static string CreateResourceYamlFile(string directory, string fileName, string content) { var pathToCustomResource = Path.Combine(directory, fileName); File.WriteAllText(pathToCustomResource, content); return pathToCustomResource; } private Func<string,string> CreateAddCustomResourceFileFunc(string yamlContent) { return directory => { CreateResourceYamlFile(directory, DeploymentFileName, yamlContent); if (!variables.IsSet(KubernetesSpecialVariables.CustomResourceYamlFileName)) { variables.Set(KubernetesSpecialVariables.CustomResourceYamlFileName, DeploymentFileName); } return null; }; } private Func<string,string> CreateAddPackageFunc(string yamlContent) { return directory => { var pathInPackage = Path.Combine("deployments", DeploymentFileName); var pathToPackage = CreatePackageWithFiles(ResourcePackageFileName, directory, ("deployments", DeploymentFileName, yamlContent)); if (!variables.IsSet(KubernetesSpecialVariables.CustomResourceYamlFileName)) { variables.Set(KubernetesSpecialVariables.CustomResourceYamlFileName, pathInPackage); } return pathToPackage; }; } private string CreatePackageWithFiles(string packageFileName, string currentDirectory, params (string directory, string fileName, string content)[] files) { var pathToPackage = Path.Combine(currentDirectory, packageFileName); using (var archive = ZipArchive.Create()) { var readStreams = new List<IDisposable>(); foreach (var (directory, fileName, content) in files) { var pathInPackage = Path.Combine(directory, fileName); var readStream = new MemoryStream(Encoding.UTF8.GetBytes(content)); readStreams.Add(readStream); archive.AddEntry(pathInPackage, readStream); } using (var writeStream = File.OpenWrite(pathToPackage)) { archive.SaveTo(writeStream, CompressionType.Deflate); } foreach (var readStream in readStreams) { readStream.Dispose(); } } return pathToPackage; } private void InPlaceSwap(string[] array, int section1StartIndex, int section2StartIndex, int endIndex) { var length = endIndex + 1 - section1StartIndex; var section2TempIndex = section2StartIndex - section1StartIndex; var temp = new string[length]; Array.Copy(array, section1StartIndex, temp, 0, length); Array.Copy(temp, section2TempIndex, array, section1StartIndex, temp.Length - section2TempIndex); Array.Copy(temp, 0, array, section1StartIndex + temp.Length - section2TempIndex, section2TempIndex); } } } #endif<file_sep>using System; namespace Calamari.Integration.Time { public interface IClock { DateTimeOffset GetUtcTime(); DateTimeOffset GetLocalTime(); } }<file_sep>using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using Assent; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Substitutions { [TestFixture] public class SubstitutionsFixture : CalamariFixture { static readonly CalamariPhysicalFileSystem FileSystem = CalamariEnvironment.IsRunningOnWindows ? (CalamariPhysicalFileSystem)new WindowsPhysicalFileSystem() : new NixCalamariPhysicalFileSystem(); static readonly Encoding AnsiEncoding; static SubstitutionsFixture() { #if NETCORE Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Required to use code pages in .NET Standard #endif AnsiEncoding = Encoding.GetEncoding("windows-1252", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); } [Test] public void ShouldSubstitute() { var variables = new CalamariVariables { ["ServerEndpoints[FOREXUAT01].Name"] = "forexuat01.local", ["ServerEndpoints[FOREXUAT01].Port"] = "1566", ["ServerEndpoints[FOREXUAT02].Name"] = "forexuat02.local", ["ServerEndpoints[FOREXUAT02].Port"] = "1566" }; var text = PerformTest(GetFixtureResource("Samples", "Servers.json"), variables).text; Assert.That(Regex.Replace(text, "\\s+", ""), Is.EqualTo(@"{""Servers"":[{""Name"":""forexuat01.local"",""Port"":1566},{""Name"":""forexuat02.local"",""Port"":1566}]}")); } [Test] public void ShouldApplyFiltersDuringSubstitution() { var variables = new CalamariVariables { ["var"] = "=:'\"\\\r\n\t <>\uFFE6" }; var textAfterReplacement = PerformTest(GetFixtureResource("Samples", "Filters.txt"), variables).text; this.Assent(textAfterReplacement, AssentConfiguration.Default); } [Test] public void ShouldIgnoreParserErrors() { var variables = new CalamariVariables { ["fox"] = "replaced fox" }; var text = PerformTest(GetFixtureResource("Samples", "ParserErrors.txt"), variables).text; // Environment.Newline returning \r\n when running tests on mono, but \n on dotnet core, just replace Assert.AreEqual("the quick brown replaced fox jumps over the lazy #{dog\nthe quick brown replaced fox jumps over the lazy #{dog #{", text.Replace("\r\n", "\n")); } [Test] public void ShouldRetainEncodingIfNoneSet() { var filePath = GetFixtureResource("Samples", "UTF16LE.ini"); var variables = new CalamariVariables { ["LocalCacheFolderName"] = "SpongeBob" }; var result = PerformTest(filePath, variables); var input = FileSystem.ReadFile(filePath, out var inputEncoding); Assert.AreEqual("utf-16", inputEncoding.WebName); Assert.AreEqual("utf-16", result.encoding.WebName); Assert.AreEqual(2, result.encoding.GetPreamble().Length); // BOM detected result.text.Should().Contain("banknames.ora"); result.text.Should().MatchRegex(@"\r\n"); // DOS CRLF result.text.Should().Be(input.Replace("#{LocalCacheFolderName}", "SpongeBob")); } [Test] public void ShouldOverrideEncodingIfProvided() { var filePath = GetFixtureResource("Samples", "UTF16LE.ini"); var variables = new CalamariVariables { ["LocalCacheFolderName"] = "SpongeBob", [PackageVariables.SubstituteInFilesOutputEncoding] = "utf-8" }; var result = PerformTest(filePath, variables); var input = FileSystem.ReadFile(filePath, out var inputEncoding); Assert.AreEqual("utf-16", inputEncoding.WebName); Assert.AreEqual("utf-8", result.encoding.WebName); Assert.AreEqual(3, result.encoding.GetPreamble().Length); // BOM detected result.text.Should().Contain("banknames.ora"); result.text.Should().MatchRegex(@"\r\n"); // DOS CRLF result.text.Should().Be(input.Replace("#{LocalCacheFolderName}", "SpongeBob")); } [Test] public void ShouldRevertToExistingEncodingIfInvalid() { var filePath = GetFixtureResource("Samples", "UTF16LE.ini"); var variables = new CalamariVariables { [PackageVariables.SubstituteInFilesOutputEncoding] = "utf-666" }; var result = PerformTest(filePath, variables); FileSystem.ReadFile(filePath, out var inputEncoding); Assert.AreEqual("utf-16", inputEncoding.WebName); Assert.AreEqual("utf-16", result.encoding.WebName); result.text.Should().MatchRegex(@"\bFile1=banknames.ora\b"); } [Test] public void ShouldDetectUtf8WithNoBom() { var filePath = GetFixtureResource("Samples", "UTF8.txt"); var text = FileSystem.ReadFile(filePath, out var encoding); Assert.AreEqual(0, encoding.GetPreamble().Length); // No BOM detected Assert.AreEqual("utf-8", encoding.WebName); text.Should().Contain("\u03C0"); // Pi } [Test] public void ShouldDetectUtf8WithBom() { var filePath = GetFixtureResource("Samples", "UTF8BOM.txt"); var text = FileSystem.ReadFile(filePath, out var encoding); Assert.AreEqual(3, encoding.GetPreamble().Length); // BOM detected Assert.AreEqual("utf-8", encoding.WebName); text.Should().Contain("\u03C0"); // Pi } [Test] public void RetainAnsi() { var filePath = GetFixtureResource("Samples", "ANSI.txt"); var variables = new CalamariVariables { ["LocalCacheFolderName"] = "SpongeBob" }; var result = PerformTest(filePath, variables, AnsiEncoding); var input = File.ReadAllText(filePath, AnsiEncoding); result.text.Should().Contain("\u00F7"); // Division sign result.text.Should().MatchRegex(@"\r\n"); // DOS CRLF result.text.Should().Be(input.Replace("#{LocalCacheFolderName}", "SpongeBob")); } [Test] public void RetainAscii() { var filePath = GetFixtureResource("Samples", "ASCII.txt"); var variables = new CalamariVariables { ["LocalCacheFolderName"] = "SpongeBob" }; var result = PerformTest(filePath, variables, Encoding.ASCII); var input = File.ReadAllText(filePath, Encoding.ASCII); result.text.Should().Contain(@"plain old ASCII"); result.text.Should().MatchRegex(@"\r\n"); // DOS CRLF result.text.Should().Be(input.Replace("#{LocalCacheFolderName}", "SpongeBob")); } [Test] public void RetainUtf8() { var filePath = GetFixtureResource("Samples", "UTF8.txt"); var variables = new CalamariVariables { ["LocalCacheFolderName"] = "SpongeBob" }; var result = PerformTest(filePath, variables); var input = File.ReadAllText(filePath, Encoding.UTF8); Assert.AreEqual(0, result.encoding.GetPreamble().Length); // No BOM detected Assert.AreEqual("utf-8", result.encoding.WebName); result.text.Should().Contain("\u03C0"); // Pi result.text.Should().MatchRegex(@"[^\r]\n"); // Unix LF result.text.Should().Be(input.Replace("#{LocalCacheFolderName}", "SpongeBob")); } [Test] public void RetainUtf8Bom() { var filePath = GetFixtureResource("Samples", "UTF8BOM.txt"); var variables = new CalamariVariables { ["LocalCacheFolderName"] = "SpongeBob" }; var result = PerformTest(filePath, variables); var input = File.ReadAllText(filePath, Encoding.UTF8); Assert.AreEqual(3, result.encoding.GetPreamble().Length); // BOM detected Assert.AreEqual("utf-8", result.encoding.WebName); result.text.Should().Contain("\u03C0"); // Pi result.text.Should().MatchRegex(@"\r\n"); // DOS CRLF result.text.Should().Be(input.Replace("#{LocalCacheFolderName}", "SpongeBob")); } [Test] public void AmbiguouslyEncodedInputRetainsUnicodeVariables() { var filePath = GetFixtureResource("Samples", "ASCII.txt"); var variables = new CalamariVariables { ["LocalCacheFolderName"] = "SpöngeBöb" }; var result = PerformTest(filePath, variables); var input = File.ReadAllText(filePath, Encoding.ASCII); Assert.AreEqual(0, result.encoding.GetPreamble().Length); // No BOM detected Assert.AreEqual("utf-8", result.encoding.WebName); result.text.Should().Contain(@"plain old ASCII"); result.text.Should().MatchRegex(@"\r\n"); // DOS CRLF result.text.Should().Be(input.Replace("#{LocalCacheFolderName}", "Sp\u00F6ngeB\u00F6b")); } [Test] public void WhenAnsiCannotRepresentOutputUtf8IsUsed() { var filePath = GetFixtureResource("Samples", "ANSI.txt"); var variables = new CalamariVariables { ["LocalCacheFolderName"] = "SpőngeBőb" }; var result = PerformTest(filePath, variables); var input = File.ReadAllText(filePath, AnsiEncoding); Assert.AreEqual(0, result.encoding.GetPreamble().Length); // No BOM detected Assert.AreEqual("utf-8", result.encoding.WebName); result.text.Should().Contain("\u00F7"); // Division sign result.text.Should().MatchRegex(@"\r\n"); // DOS CRLF result.text.Should().Be(input.Replace("#{LocalCacheFolderName}", "Sp\u0151ngeB\u0151b")); } (string text, Encoding encoding) PerformTest(string sampleFile, IVariables variables, Encoding expectedResultEncoding = null) { var temp = Path.GetTempFileName(); using (new TemporaryFile(temp)) { var substituter = new FileSubstituter(new InMemoryLog(), FileSystem); substituter.PerformSubstitution(sampleFile, variables, temp); using (var reader = new StreamReader(temp, expectedResultEncoding ?? new UTF8Encoding(false, true), expectedResultEncoding == null)) { return (reader.ReadToEnd(), reader.CurrentEncoding); } } } } }<file_sep>//Taken from https://github.com/Microsoft/referencesource/blob/d925d870f3cb3f6acdb14e71522ece7054e2233b/System/compmod/system/codedom/compiler/IndentTextWriter.cs // as this isn't available in .NET Core at this point. //------------------------------------------------------------------------------ //The MIT License(MIT) //Copyright(c) Microsoft Corporation //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. ////------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace Calamari.Common.Plumbing { /// <devdoc> /// <para>Provides a text writer that can indent new lines by a tabString token.</para> /// </devdoc> public class IndentedTextWriter : TextWriter { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const string DefaultTabString = " "; int indentLevel; bool tabsPending; /// <devdoc> /// <para> /// Initializes a new instance of <see cref='System.CodeDom.Compiler.IndentedTextWriter' /> using the specified /// text writer and default tab string. /// </para> /// </devdoc> public IndentedTextWriter(TextWriter writer) : this(writer, DefaultTabString) { } /// <devdoc> /// <para> /// Initializes a new instance of <see cref='System.CodeDom.Compiler.IndentedTextWriter' /> using the specified /// text writer and tab string. /// </para> /// </devdoc> public IndentedTextWriter(TextWriter writer, string tabString) : base(CultureInfo.InvariantCulture) { InnerWriter = writer; TabString = tabString; indentLevel = 0; tabsPending = false; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override Encoding Encoding => InnerWriter.Encoding; /// <devdoc> /// <para> /// Gets or sets the new line character to use. /// </para> /// </devdoc> public override string NewLine { get => InnerWriter.NewLine; set => InnerWriter.NewLine = value; } /// <devdoc> /// <para> /// Gets or sets the number of spaces to indent. /// </para> /// </devdoc> public int Indent { get => indentLevel; set { Debug.Assert(value >= 0, "Bogus Indent... probably caused by mismatched Indent++ and Indent--"); if (value < 0) value = 0; indentLevel = value; } } /// <devdoc> /// <para> /// Gets or sets the TextWriter to use. /// </para> /// </devdoc> public TextWriter InnerWriter { get; } internal string TabString { get; } /// <devdoc> /// <para> /// Closes the document being written to. /// </para> /// </devdoc> public override void Close() { InnerWriter.Close(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void Flush() { InnerWriter.Flush(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected virtual void OutputTabs() { if (tabsPending) { for (var i = 0; i < indentLevel; i++) InnerWriter.Write(TabString); tabsPending = false; } } /// <devdoc> /// <para> /// Writes a string /// to the text stream. /// </para> /// </devdoc> public override void Write(string s) { OutputTabs(); InnerWriter.Write(s); } /// <devdoc> /// <para> /// Writes the text representation of a Boolean value to the text stream. /// </para> /// </devdoc> public override void Write(bool value) { OutputTabs(); InnerWriter.Write(value); } /// <devdoc> /// <para> /// Writes a character to the text stream. /// </para> /// </devdoc> public override void Write(char value) { OutputTabs(); InnerWriter.Write(value); } /// <devdoc> /// <para> /// Writes a /// character array to the text stream. /// </para> /// </devdoc> public override void Write(char[] buffer) { OutputTabs(); InnerWriter.Write(buffer); } /// <devdoc> /// <para> /// Writes a subarray /// of characters to the text stream. /// </para> /// </devdoc> public override void Write(char[] buffer, int index, int count) { OutputTabs(); InnerWriter.Write(buffer, index, count); } /// <devdoc> /// <para> /// Writes the text representation of a Double to the text stream. /// </para> /// </devdoc> public override void Write(double value) { OutputTabs(); InnerWriter.Write(value); } /// <devdoc> /// <para> /// Writes the text representation of /// a Single to the text /// stream. /// </para> /// </devdoc> public override void Write(float value) { OutputTabs(); InnerWriter.Write(value); } /// <devdoc> /// <para> /// Writes the text representation of an integer to the text stream. /// </para> /// </devdoc> public override void Write(int value) { OutputTabs(); InnerWriter.Write(value); } /// <devdoc> /// <para> /// Writes the text representation of an 8-byte integer to the text stream. /// </para> /// </devdoc> public override void Write(long value) { OutputTabs(); InnerWriter.Write(value); } /// <devdoc> /// <para> /// Writes the text representation of an object /// to the text stream. /// </para> /// </devdoc> public override void Write(object value) { OutputTabs(); InnerWriter.Write(value); } /// <devdoc> /// <para> /// Writes out a formatted string, using the same semantics as specified. /// </para> /// </devdoc> public override void Write(string format, object arg0) { OutputTabs(); InnerWriter.Write(format, arg0); } /// <devdoc> /// <para> /// Writes out a formatted string, /// using the same semantics as specified. /// </para> /// </devdoc> public override void Write(string format, object arg0, object arg1) { OutputTabs(); InnerWriter.Write(format, arg0, arg1); } /// <devdoc> /// <para> /// Writes out a formatted string, /// using the same semantics as specified. /// </para> /// </devdoc> public override void Write(string format, params object[] arg) { OutputTabs(); InnerWriter.Write(format, arg); } /// <devdoc> /// <para> /// Writes the specified /// string to a line without tabs. /// </para> /// </devdoc> public void WriteLineNoTabs(string s) { InnerWriter.WriteLine(s); } /// <devdoc> /// <para> /// Writes the specified string followed by /// a line terminator to the text stream. /// </para> /// </devdoc> public override void WriteLine(string s) { OutputTabs(); InnerWriter.WriteLine(s); tabsPending = true; } /// <devdoc> /// <para> /// Writes a line terminator. /// </para> /// </devdoc> public override void WriteLine() { OutputTabs(); InnerWriter.WriteLine(); tabsPending = true; } /// <devdoc> /// <para> /// Writes the text representation of a Boolean followed by a line terminator to /// the text stream. /// </para> /// </devdoc> public override void WriteLine(bool value) { OutputTabs(); InnerWriter.WriteLine(value); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(char value) { OutputTabs(); InnerWriter.WriteLine(value); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(char[] buffer) { OutputTabs(); InnerWriter.WriteLine(buffer); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(char[] buffer, int index, int count) { OutputTabs(); InnerWriter.WriteLine(buffer, index, count); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(double value) { OutputTabs(); InnerWriter.WriteLine(value); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(float value) { OutputTabs(); InnerWriter.WriteLine(value); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(int value) { OutputTabs(); InnerWriter.WriteLine(value); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(long value) { OutputTabs(); InnerWriter.WriteLine(value); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(object value) { OutputTabs(); InnerWriter.WriteLine(value); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(string format, object arg0) { OutputTabs(); InnerWriter.WriteLine(format, arg0); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(string format, object arg0, object arg1) { OutputTabs(); InnerWriter.WriteLine(format, arg0, arg1); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(string format, params object[] arg) { OutputTabs(); InnerWriter.WriteLine(format, arg); tabsPending = true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteLine(uint value) { OutputTabs(); InnerWriter.WriteLine(value); tabsPending = true; } internal void InternalOutputTabs() { for (var i = 0; i < indentLevel; i++) InnerWriter.Write(TabString); } } class Indentation { readonly IndentedTextWriter writer; readonly int indent; string? s; internal Indentation(IndentedTextWriter writer, int indent) { this.writer = writer; this.indent = indent; } internal string IndentationString { get { if (s == null) { var tabString = writer.TabString; var sb = new StringBuilder(indent * tabString.Length); for (var i = 0; i < indent; i++) sb.Append(tabString); s = sb.ToString(); } return s; } } } }<file_sep>using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class ConfigMap : Resource { public int Data { get; } public ConfigMap(JObject json, Options options) : base(json, options) { Data = (data.SelectToken("$.data") ?.ToObject<Dictionary<string, string>>() ?? new Dictionary<string, string>()) .Count; } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<ConfigMap>(lastStatus); return last.Data != Data; } } }<file_sep>#!/bin/bash echo "Hello from PostDeploy.sh"<file_sep>using System.Collections.Generic; using Newtonsoft.Json; namespace Calamari.Kubernetes.ResourceStatus.Resources { // Subset of: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.26/#loadbalancerstatus-v1-core public class LoadBalancerStatus { [JsonProperty("ingress")] public IEnumerable<LoadBalancerIngress> Ingress { get; set; } } public class LoadBalancerIngress { [JsonProperty("hostname")] public string Hostname { get; set; } [JsonProperty("ip")] public string Ip { get; set; } [JsonProperty("ports")] public IEnumerable<PortStatus> Ports { get; set; } } } <file_sep>using System; using System.Threading; using Calamari.Common.Features.Processes.Semaphores; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { [TestFixture] public class FileLockFixture { [Test] [TestCase(123, 456, "ProcessName", 123, 456, "ProcessName", true)] [TestCase(123, 456, "ProcessName", 789, 456, "ProcessName", false)] [TestCase(123, 456, "ProcessName", 123, 789, "ProcessName", false)] [TestCase(123, 456, "ProcessName", 123, 456, "DiffProcessName", false)] [TestCase(123, 456, "ProcessName", 789, 246, "ProcessName", false)] [TestCase(123, 456, "ProcessName", 123, 246, "DiffProcessName", false)] [TestCase(123, 456, "ProcessName", 789, 456, "ProcessName", false)] [TestCase(123, 456, "ProcessName", 789, 246, "DiffProcessName", false)] public void EqualsComparesCorrectly(int processIdA, int threadIdA, string processNameA, int processIdB, int threadIdB, string processNameB, bool expectedResult) { var objectA = new FileLock(processIdA, processNameA, threadIdA, DateTime.Now.Ticks); var objectB = new FileLock(processIdB, processNameB, threadIdB, DateTime.Now.Ticks); Assert.That(Equals(objectA, objectB), Is.EqualTo(expectedResult)); } [Test] public void EqualsIgnoresTimestamp() { var objectA = new FileLock(123, "ProcessName", 456, DateTime.Now.Ticks); var objectB = new FileLock(123, "ProcessName", 456, DateTime.Now.Ticks + 5); Assert.That(Equals(objectA, objectB), Is.True); } [Test] public void EqualsReturnsFalseIfOtherObjectIsNull() { var fileLock = new FileLock(123, "ProcessName", 456, DateTime.Now.Ticks); Assert.That(fileLock.Equals(null), Is.False); } [Test] public void EqualsReturnsFalseIfOtherObjectIsDifferentType() { var fileLock = new FileLock(123, "ProcessName", 456, DateTime.Now.Ticks); Assert.That(fileLock.Equals(new object()), Is.False); } [Test] public void EqualsReturnsTrueIfSameObject() { var fileLock = new FileLock(123, "ProcessName", 456, DateTime.Now.Ticks); // ReSharper disable once EqualExpressionComparison Assert.That(fileLock.Equals(fileLock), Is.True); } [Test] public void BelongsToCurrentProcessAndThreadMatchesOnCurrentProcessAndThread() { var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var fileLock = new FileLock( currentProcess.Id, currentProcess.ProcessName, Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks ); Assert.That(fileLock.BelongsToCurrentProcessAndThread(), Is.True); } [Test] public void BelongsToCurrentProcessAndThreadReturnsFalseIfIncorrectProcessId() { var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var fileLockWithIncorrectProcessId = new FileLock( -100, currentProcess.ProcessName, Thread.CurrentThread.ManagedThreadId, DateTime.Now.Ticks ); Assert.That(fileLockWithIncorrectProcessId.BelongsToCurrentProcessAndThread(), Is.False); } [Test] public void BelongsToCurrentProcessAndThreadReturnsFalseIfIncorrectThreadId() { var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var fileLockWithIncorrectThreadId = new FileLock( currentProcess.Id, currentProcess.ProcessName, -200, DateTime.Now.Ticks ); Assert.That(fileLockWithIncorrectThreadId.BelongsToCurrentProcessAndThread(), Is.False); } } } <file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Variables; namespace Calamari.Commands { [Command("substitute-variables-in-files")] public class SubstituteVariablesInFilesCommand : Command<SubstituteVariablesInFilesCommandInputs> { readonly IVariables variables; readonly ISubstituteInFiles substituteInFiles; public SubstituteVariablesInFilesCommand(IVariables variables, ISubstituteInFiles substituteInFiles) { this.variables = variables; this.substituteInFiles = substituteInFiles; } protected override void Execute(SubstituteVariablesInFilesCommandInputs inputs) { var runningDeployment = new RunningDeployment(variables); var targetPath = runningDeployment.CurrentDirectory; substituteInFiles.Substitute(targetPath, inputs.FilesToTarget.Split(new []{'\n', '\r', ';'}, StringSplitOptions.RemoveEmptyEntries)); } } public class SubstituteVariablesInFilesCommandInputs { public string FilesToTarget { get; set; } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using SharpCompress.Archives; namespace Calamari.Common.Features.Packages.Decorators.Logging { public class LogArchiveMetricsDecorator : PackageExtractorDecorator { readonly ILog log; public LogArchiveMetricsDecorator(IPackageExtractor concreteExtractor, ILog log) : base(concreteExtractor) { this.log = log; } public override int Extract(string packageFile, string directory) { using (var timer = log.BeginTimedOperation($"Extract package")) { LogArchiveMetrics(packageFile, timer.OperationId); var result = base.Extract(packageFile, directory); timer.Complete(); return result; } } void LogArchiveMetrics(string archivePath, string operationId) { try { var archiveInfo = new FileInfo(archivePath); using (var archive = ArchiveFactory.Open(archivePath)) { var compressedSize = archiveInfo.Length; var uncompressedSize = archive.TotalUncompressSize; var compressionRatio = compressedSize == 0 ? 0 : (double)uncompressedSize / compressedSize; log.LogMetric("DeploymentPackageCompressedSize", compressedSize, operationId); log.LogMetric("DeploymentPackageUncompressedSize", archive.TotalUncompressSize, operationId); log.LogMetric("DeploymentPackageCompressionRatio", compressionRatio, operationId); } } catch { log.Verbose("Could not collect archive metrics"); } } } } <file_sep>using System; using System.Threading; using System.Threading.Tasks; namespace Calamari.Testing.Helpers { public static class EventuallyStrategyExtensionMethods { public static async Task ShouldEventually(this EventuallyStrategy strategy, Action action, CancellationToken cancellationToken) { Task WrappedAction(CancellationToken ct) => Task.Run(action, ct).WithCancellationToken(ct); await strategy.ShouldEventually(WrappedAction, cancellationToken); } public static async Task ShouldEventually(this EventuallyStrategy strategy, Func<Task> action, CancellationToken cancellationToken) { Task WrappedAction(CancellationToken ct) => Task.Run(action, ct).WithCancellationToken(ct); await strategy.ShouldEventually(WrappedAction, cancellationToken); } } } <file_sep>using System; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Packages.Java { /// <summary> /// Wrapper class for invoking the Java Archive Tool http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jar.html /// </summary> public class JarTool { readonly ICommandLineRunner commandLineRunner; readonly ILog log; readonly string toolsPath; public JarTool(ICommandLineRunner commandLineRunner, ILog log, IVariables variables) { this.commandLineRunner = commandLineRunner; this.log = log; /* The precondition script will also set the location of the java library files */ toolsPath = Path.Combine( variables?.Get(JavaVariables.JavaLibraryEnvVar, "") ?? "", "contentFiles", "any", "any", "tools.jar"); } public void CreateJar(string contentsDirectory, string targetJarPath, bool enableCompression) { var compressionFlag = enableCompression ? "" : "0"; var manifestPath = Path.Combine(contentsDirectory, "META-INF", "MANIFEST.MF"); var args = File.Exists(manifestPath) ? $"-cp \"{toolsPath}\" sun.tools.jar.Main cvmf{compressionFlag} \"{manifestPath}\" \"{targetJarPath}\" -C \"{contentsDirectory}\" ." : $"-cp \"{toolsPath}\" sun.tools.jar.Main cvf{compressionFlag} \"{targetJarPath}\" -C \"{contentsDirectory}\" ."; var createJarCommand = new CommandLineInvocation(JavaRuntime.CmdPath, args) { WorkingDirectory = contentsDirectory, OutputAsVerbose = true }; log.Verbose($"Invoking '{createJarCommand}' to create '{targetJarPath}'"); var result = commandLineRunner.Execute(createJarCommand); result.VerifySuccess(); } /// <summary> /// Extracts a Java archive file (.jar, .war, .ear) to the target directory /// </summary> /// <returns>Count of files extracted</returns> public int ExtractJar(string jarPath, string targetDirectory) { try { /* Start by verifying the archive is valid. */ var tfCommand = new CommandLineInvocation( JavaRuntime.CmdPath, $"-cp \"{toolsPath}\" sun.tools.jar.Main tf \"{jarPath}\"" ) { WorkingDirectory = targetDirectory, OutputAsVerbose = true }; commandLineRunner.Execute(tfCommand).VerifySuccess(); /* If it is valid, go ahead an extract it */ var extractJarCommand = new CommandLineInvocation( JavaRuntime.CmdPath, $"-cp \"{toolsPath}\" sun.tools.jar.Main xf \"{jarPath}\"" ) { WorkingDirectory = targetDirectory, OutputAsVerbose = true }; log.Verbose($"Invoking '{extractJarCommand}' to extract '{jarPath}'"); var result = commandLineRunner.Execute(extractJarCommand); result.VerifySuccess(); } catch (Exception ex) { log.Error($"Exception thrown while extracting a Java archive. {ex}"); throw; } var count = -1; try { count = Directory.EnumerateFiles(targetDirectory, "*", SearchOption.AllDirectories).Count(); } catch (Exception ex) { log.Verbose( $"Unable to return extracted file count. Error while enumerating '{targetDirectory}':\n{ex.Message}"); } return count; } } }<file_sep>using System; using System.Dynamic; using YamlDotNet.Core.Tokens; namespace Calamari.Deployment.PackageRetention { //TODO: At some point, replace this basic tiny types implementation with the Octopus one. The blocking issue is Net40 atm. public abstract class TinyType<T> where T : IComparable { public readonly T Value; protected TinyType(T value) { this.Value = value; } static object Create(Type type, T value) { return Activator.CreateInstance(type, value); } public static U Create<U>(T value) where U : TinyType<T> { return (U)Create(typeof(U), value); } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; var other = (TinyType<T>)obj; return this.Value.Equals(other.Value); } public override int GetHashCode() { return GetType().GetHashCode() ^ (Value != null ? Value.GetHashCode() : 0); } public static bool operator == (TinyType<T>? first, TinyType<T>? second) { if (first is null || second is null) return false; return first.Equals(second); } public static bool operator !=(TinyType<T> first, TinyType<T> second) { return !(first == second); } public override string ToString() { return Value?.ToString() ?? ""; } } }<file_sep>using System; using System.IO; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures; using Calamari.Tests.Helpers; using Calamari.Util; using FluentAssertions; using NUnit.Framework; using Octopus.Versioning.Semver; namespace Calamari.Tests.KubernetesFixtures { public abstract class HelmUpgradeFixture : CalamariFixture { static readonly string ServerUrl = ExternalVariables.Get(ExternalVariable.KubernetesClusterUrl); static readonly string ClusterToken = ExternalVariables.Get(ExternalVariable.KubernetesClusterToken); ICalamariFileSystem FileSystem { get; set; } protected IVariables Variables { get; set; } string StagingDirectory { get; set; } protected static readonly string ReleaseName = "calamaritest-" + Guid.NewGuid().ToString("N").Substring(0, 6); protected static readonly string ConfigMapName = "mychart-configmap-" + ReleaseName; protected const string Namespace = "calamari-testing"; static string HelmOsPlatform => CalamariEnvironment.IsRunningOnWindows ? "windows-amd64" : "linux-amd64"; HelmVersion? helmVersion; TemporaryDirectory explicitVersionTempDirectory; [OneTimeSetUp] public async Task OneTimeSetUp() { if (ExplicitExeVersion != null) { await DownloadExplicitHelmExecutable(); helmVersion = new SemanticVersion(ExplicitExeVersion).Major == 2 ? HelmVersion.V2 : HelmVersion.V3; } else { helmVersion = GetVersion(); } async Task DownloadExplicitHelmExecutable() { explicitVersionTempDirectory = TemporaryDirectory.Create(); var fileName = Path.GetFullPath(Path.Combine(explicitVersionTempDirectory.DirectoryPath, $"helm-v{ExplicitExeVersion}-{HelmOsPlatform}.tgz")); using (new TemporaryFile(fileName)) { await DownloadHelmPackage(ExplicitExeVersion, fileName); new TarGzipPackageExtractor(ConsoleLog.Instance).Extract(fileName, explicitVersionTempDirectory.DirectoryPath); } } } [OneTimeTearDown] public void OneTimeTearDown() { explicitVersionTempDirectory?.Dispose(); } [SetUp] public virtual void SetUp() { FileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); // Ensure staging directory exists and is empty StagingDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestStaging"); FileSystem.EnsureDirectoryExists(StagingDirectory); FileSystem.PurgeDirectory(StagingDirectory, FailureOptions.ThrowOnFailure); Environment.SetEnvironmentVariable("TentacleJournal", Path.Combine(StagingDirectory, "DeploymentJournal.xml")); Variables = new VariablesFactory(FileSystem).Create(new CommonOptions("test")); Variables.Set(TentacleVariables.Agent.ApplicationDirectoryPath, StagingDirectory); //Chart Package Variables.Set(PackageVariables.PackageId, "mychart"); Variables.Set(PackageVariables.PackageVersion, "0.3.7"); //Helm Options Variables.Set(Kubernetes.SpecialVariables.Helm.ReleaseName, ReleaseName); Variables.Set(Kubernetes.SpecialVariables.Helm.ClientVersion, helmVersion.ToString()); //K8S Auth Variables.Set(Kubernetes.SpecialVariables.ClusterUrl, ServerUrl); Variables.Set(Kubernetes.SpecialVariables.SkipTlsVerification, "True"); Variables.Set(Kubernetes.SpecialVariables.Namespace, Namespace); Variables.Set(SpecialVariables.Account.AccountType, "Token"); Variables.Set(SpecialVariables.Account.Token, ClusterToken); if (ExplicitExeVersion != null) Variables.Set(Kubernetes.SpecialVariables.Helm.CustomHelmExecutable, HelmExePath); AddPostDeployMessageCheckAndCleanup(); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void NoValues_EmbeddedValuesUsed() { var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello Embedded Variables", result.CapturedOutput.OutputVariables["Message"]); } [Test(Description = "Test the case where the package ID does not match the directory inside the helm archive.")] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void MismatchPackageIDAndHelmArchivePathWorks() { var packageName = $"{Variables.Get(PackageVariables.PackageId)}-{Variables.Get(PackageVariables.PackageVersion)}.tgz"; Variables.Set(PackageVariables.PackageId, "thisisnotamatch"); Variables.Set(PackageVariables.PackageVersion, "0.3.7"); var result = DeployPackage(packageName); result.AssertSuccess(); Assert.AreEqual("Hello Embedded Variables", result.CapturedOutput.OutputVariables["Message"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void ExplicitValues_NewValuesUsed() { //Helm Config Variables.Set(Kubernetes.SpecialVariables.Helm.KeyValues, "{\"SpecialMessage\": \"FooBar\"}"); var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello FooBar", result.CapturedOutput.OutputVariables["Message"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void ValuesFromPackage_NewValuesUsed() { //Additional Package Variables.Set(PackageVariables.IndexedPackageId("Pack-1"), "CustomValues"); Variables.Set(PackageVariables.IndexedPackageVersion("Pack-1"), "2.0.0"); Variables.Set(PackageVariables.IndexedOriginalPath("Pack-1"), GetFixtureResource("Charts", "CustomValues.2.0.0.zip")); Variables.Set(Kubernetes.SpecialVariables.Helm.Packages.ValuesFilePath("Pack-1"), "values.yaml"); //Variable that will replace packaged value in package Variables.Set("MySecretMessage", "Variable Replaced In Package"); var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello Variable Replaced In Package", result.CapturedOutput.OutputVariables["Message"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void ValuesFromChartPackage_NewValuesUsed() { //Additional Package Variables.Set(Kubernetes.SpecialVariables.Helm.Packages.ValuesFilePath(""), Path.Combine("mychart", "secondary.Development.yaml")); var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello I am in a secondary", result.CapturedOutput.OutputVariables["Message"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void ValuesFromChartPackage_GetSubstituted() { Variables.Set(PackageVariables.PackageVersion, "0.3.8"); Variables.Set("SpecialMessage", "octostache is working"); var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello octostache is working", result.CapturedOutput.OutputVariables["Message"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void ValuesFromChartPackageWithoutSubDirectory_NewValuesUsed() { //Additional Package Variables.Set(Kubernetes.SpecialVariables.Helm.Packages.ValuesFilePath(""), "secondary.Development.yaml"); var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello I am in a secondary", result.CapturedOutput.OutputVariables["Message"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void ValuesFromPackageAndExplicit_ExplicitTakesPrecedence() { //Helm Config (lets make sure Explicit values take precedence Variables.Set(Kubernetes.SpecialVariables.Helm.KeyValues, "{\"SpecialMessage\": \"FooBar\"}"); //Additional Package Variables.Set(PackageVariables.IndexedPackageId("Pack-1"), "CustomValues"); Variables.Set(PackageVariables.IndexedPackageVersion("Pack-1"), "2.0.0"); Variables.Set(PackageVariables.IndexedOriginalPath("Pack-1"), GetFixtureResource("Charts", "CustomValues.2.0.0.zip")); Variables.Set(Kubernetes.SpecialVariables.Helm.Packages.ValuesFilePath("Pack-1"), "values.yaml"); //Variable that will replace packaged value in package Variables.Set("MySecretMessage", "From A Variable Replaced In Package"); var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello FooBar", result.CapturedOutput.OutputVariables["Message"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void ValuesFromRawYaml_ValuesAdded() { Variables.Set(Kubernetes.SpecialVariables.Helm.YamlValues, "\"SpecialMessage\": \"YAML\""); var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello YAML", result.CapturedOutput.OutputVariables["Message"]); } protected async Task TestCustomHelmExeInPackage_RelativePath(string version) { var fileName = Path.Combine(Path.GetTempPath(), $"helm-v{version}-{HelmOsPlatform}.tgz"); using (new TemporaryFile(fileName)) { await DownloadHelmPackage(version, fileName); var customHelmExePackageId = Kubernetes.SpecialVariables.Helm.Packages.CustomHelmExePackageKey; Variables.Set(PackageVariables.IndexedOriginalPath(customHelmExePackageId), fileName); Variables.Set(PackageVariables.IndexedExtract(customHelmExePackageId), "True"); Variables.Set(PackageVariables.IndexedPackageId(customHelmExePackageId), "helmexe"); Variables.Set(PackageVariables.IndexedPackageVersion(customHelmExePackageId), version); // If package is provided then it should be treated as a relative path var customLocation = HelmOsPlatform + Path.DirectorySeparatorChar + "helm"; Variables.Set(Kubernetes.SpecialVariables.Helm.CustomHelmExecutable, customLocation); AddPostDeployMessageCheckAndCleanup(); var result = DeployPackage(); result.AssertSuccess(); result.AssertOutput($"Using custom helm executable at {HelmOsPlatform}\\helm from inside package. Full path at"); } } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void Namespace_Override_Used() { const string @namespace = "calamari-testing-foo"; Variables.Set(Kubernetes.SpecialVariables.Helm.Namespace, @namespace); AddPostDeployMessageCheckAndCleanup(@namespace); var result = DeployPackage(); result.AssertSuccess(); Assert.AreEqual("Hello Embedded Variables", result.CapturedOutput.OutputVariables["Message"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void AdditionalArgumentsPassed() { Variables.Set(Kubernetes.SpecialVariables.Helm.AdditionalArguments, "--dry-run"); AddPostDeployMessageCheckAndCleanup(explicitNamespace: null, dryRun: true); var result = DeployPackage(); result.AssertSuccess(); result.AssertOutputMatches("[helm|\\\\helm\"] upgrade (.*) --dry-run"); } protected abstract string ExplicitExeVersion { get; } protected string HelmExePath => ExplicitExeVersion == null ? "helm" : Path.Combine(explicitVersionTempDirectory.DirectoryPath, HelmOsPlatform, "helm"); void AddPostDeployMessageCheckAndCleanup(string explicitNamespace = null, bool dryRun = false) { if (dryRun) { // If it's a dry-run we can't fetch the ConfigMap and there's nothing to clean-up Variables.Set(KnownVariables.Package.EnabledFeatures, ""); return; } var @namespace = explicitNamespace ?? Namespace; var kubectlCmd = "kubectl get configmaps " + ConfigMapName + " --namespace " + @namespace +" -o jsonpath=\"{.data.myvalue}\""; var syntax = ScriptSyntax.Bash; var deleteCommand = DeleteCommand(@namespace, ReleaseName); var script = "set_octopusvariable Message \"$("+ kubectlCmd +$")\"\n{HelmExePath} " + deleteCommand; if (CalamariEnvironment.IsRunningOnWindows) { syntax = ScriptSyntax.PowerShell; script = $"Set-OctopusVariable -name Message -Value $({kubectlCmd})\r\n{HelmExePath} " + deleteCommand; } Variables.Set(SpecialVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.PostDeploy, syntax), script); Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts); } string DeleteCommand(string @namespace, string releaseName) { switch (helmVersion) { case HelmVersion.V2: return $"delete {releaseName} --purge"; case HelmVersion.V3: return $"uninstall {releaseName} --namespace {@namespace}"; default: throw new ArgumentOutOfRangeException(nameof(helmVersion), helmVersion, "Unrecognized Helm version"); } } protected CalamariResult DeployPackage(string packageName = null) { using (var variablesFile = new TemporaryFile(Path.GetTempFileName())) { if (packageName == null) { packageName = $"{Variables.Get(PackageVariables.PackageId)}-{Variables.Get(PackageVariables.PackageVersion)}.tgz"; } var pkg = GetFixtureResource("Charts", packageName); Variables.Save(variablesFile.FilePath); return InvokeInProcess(Calamari() .Action("helm-upgrade") .Argument("package", pkg) .Argument("variables", variablesFile.FilePath)); } } static async Task DownloadHelmPackage(string version, string fileName) { using (var client = new HttpClient()) { using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) using (var stream = await client.GetStreamAsync($"https://get.helm.sh/helm-v{version}-{HelmOsPlatform}.tar.gz")) { await stream.CopyToAsync(fileStream); } } } static HelmVersion GetVersion() { StringBuilder stdout = new StringBuilder(); var result = SilentProcessRunner.ExecuteCommand("helm", "version --client --short", Environment.CurrentDirectory, output => stdout.AppendLine(output), error => { }); result.ExitCode.Should().Be(0, $"Failed to retrieve version from Helm (Exit code {result.ExitCode}). Error output: \r\n{result.ErrorOutput}"); return ParseVersion(stdout.ToString()); } //versionString from "helm version --client --short" static HelmVersion ParseVersion(string versionString) { //eg of output for helm 2: Client: v2.16.1+gbbdfe5e //eg of output for helm 3: v3.0.1+g7c22ef9 var indexOfVersionIdentifier = versionString.IndexOf('v'); if (indexOfVersionIdentifier == -1) throw new FormatException($"Failed to find version identifier from '{versionString}'."); var indexOfVersionNumber = indexOfVersionIdentifier + 1; if (indexOfVersionNumber >= versionString.Length) throw new FormatException($"Failed to find version number from '{versionString}'."); var version = versionString[indexOfVersionNumber]; switch (version) { case '3': return HelmVersion.V3; case '2': return HelmVersion.V2; default: throw new InvalidOperationException($"Unsupported helm version '{version}'"); } } } } <file_sep>using System; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Commands; namespace Calamari.Tests.Fixtures.Util { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class ExpectedExceptionAttribute : NUnitAttribute, IWrapTestMethod { private readonly Type _expectedExceptionType; public string ExpectedMessage; public MessageMatch MatchType; public ExpectedExceptionAttribute(Type type = null) { _expectedExceptionType = type; } public TestCommand Wrap(TestCommand command) { return new ExpectedExceptionCommand(command, _expectedExceptionType, ExpectedMessage, MatchType); } private class ExpectedExceptionCommand : DelegatingTestCommand { private readonly Type _expectedType; private readonly string _expectedMessage; private readonly MessageMatch _matchType; public ExpectedExceptionCommand(TestCommand innerCommand, Type expectedType, string expectedMessage, MessageMatch matchType) : base(innerCommand) { _expectedType = expectedType; _expectedMessage = expectedMessage; _matchType = matchType; } public override TestResult Execute(TestExecutionContext context) { Type caughtType = null; string message = null; try { innerCommand.Execute(context); } catch (Exception ex) { if (ex is NUnitException) ex = ex.InnerException; caughtType = ex.GetType(); message = ex.Message; } var expectedTypeName = _expectedType == null ? "an exception" : _expectedType.Name; if ((_expectedType != null && caughtType == _expectedType) || (_expectedType == null && caughtType != null)) { if (MessageMatches(message)) { context.CurrentResult.SetResult(ResultState.Success); } else { string.Format("Expected message to {0} {1} but got {2}", GetMatchText(), _expectedMessage, message); } } else if (caughtType != null) context.CurrentResult.SetResult(ResultState.Failure, string.Format("Expected {0} but got {1}", expectedTypeName, caughtType.Name)); else context.CurrentResult.SetResult(ResultState.Failure, string.Format("Expected {0} but no exception was thrown", expectedTypeName)); return context.CurrentResult; } private string GetMatchText() { switch (_matchType) { case MessageMatch.Equals: return "be"; case MessageMatch.StartsWith: return "start with"; case MessageMatch.EndsWith: return "end with"; case MessageMatch.Contains: return "contain"; default: throw new ArgumentOutOfRangeException(); } } private bool MessageMatches(string message) { if (_expectedMessage == null) return true; switch (_matchType) { case MessageMatch.Equals: return _expectedMessage == message; case MessageMatch.StartsWith: return _expectedMessage.StartsWith(message); case MessageMatch.EndsWith: return _expectedMessage.EndsWith(message); case MessageMatch.Contains: return _expectedMessage.Contains(message); default: throw new ArgumentOutOfRangeException(); } } } } public enum MessageMatch { Equals, StartsWith, EndsWith, Contains } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class PersistentVolumeClaimTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""PersistentVolumeClaim"", ""metadata"": { ""name"": ""my-pvc"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""spec"": { ""volumeName"": ""pvc-08cdb1f6-42e4-4938-b4c7-0576030a8da6"", ""storageClassName"": ""standard"" }, ""status"": { ""phase"": ""Bound"", ""accessModes"": [ ""ReadWriteOnce"" ], ""capacity"": { ""storage"": ""1Mi"" } } }"; var persistentVolumeClaim = ResourceFactory.FromJson(input, new Options()); persistentVolumeClaim.Should().BeEquivalentTo(new { Kind = "PersistentVolumeClaim", Name = "my-pvc", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Status = "Bound", Volume = "pvc-08cdb1f6-42e4-4938-b4c7-0576030a8da6", Capacity = "1Mi", AccessModes = new string [] { "ReadWriteOnce" }, StorageClass = "standard", ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful }); } } } <file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class ReplicaSetTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""ReplicaSet"", ""metadata"": { ""name"": ""nginx"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""status"": { ""availableReplicas"": 2, ""readyReplicas"": 2, ""replicas"": 3, } }"; var replicaSet = ResourceFactory.FromJson(input, new Options()); replicaSet.Should().BeEquivalentTo(new { Kind = "ReplicaSet", Name = "nginx", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Desired = 3, Ready = 2, Current = 2, ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress }); } } }<file_sep>using System; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; namespace Calamari.Terraform.Behaviours { class DestroyPlanBehaviour : PlanBehaviour { public DestroyPlanBehaviour(ILog log, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner) : base(log, fileSystem, commandLineRunner) { } protected override string ExtraParameter => "-destroy"; } }<file_sep>using System; namespace Calamari.Aws.Exceptions { /// <summary> /// Represents an unknown exception that will be passed back to the user /// </summary> public class UnknownException : Exception { public UnknownException() { } public UnknownException(string message) : base(message) { } public UnknownException(string message, Exception inner) : base(message, inner) { } } }<file_sep>#if IIS_SUPPORT using System; using System.Collections.Generic; using System.Linq; using Microsoft.Web.Administration; namespace Calamari.Integration.Iis { public class WebServerSevenSupport : WebServerSupport { const string Localhost = "localhost"; public override void CreateWebSiteOrVirtualDirectory(string webSiteName, string virtualDirectoryPath, string webRootPath, int port) { var virtualParts = (virtualDirectoryPath ?? String.Empty).Split('/', '\\').Select(x => x.Trim()).Where(x => x.Length > 0).ToArray(); Execute(serverManager => { var existing = serverManager.Sites.FirstOrDefault(x => String.Equals(x.Name, webSiteName, StringComparison.OrdinalIgnoreCase)); if (existing == null) { existing = serverManager.Sites.Add(webSiteName, webRootPath, port); } if (virtualParts.Length > 0) { var vd = existing.Applications.Single().VirtualDirectories.Add(virtualDirectoryPath, webRootPath); } serverManager.CommitChanges(); }); } public override string GetHomeDirectory(string webSiteName, string virtualDirectoryPath) { string result = null; FindVirtualDirectory(webSiteName, virtualDirectoryPath, found => { result = found.PhysicalPath; }); if (result == null) { throw new Exception("The virtual directory does not exist."); } return result; } public override void DeleteWebSite(string webSiteName) { Execute(serverManager => { var existing = serverManager.Sites.FirstOrDefault(x => String.Equals(x.Name, webSiteName, StringComparison.OrdinalIgnoreCase)); if (existing == null) { throw new Exception($"The site '{webSiteName}' does not exist."); } existing.Delete(); serverManager.CommitChanges(); }); } public void DeleteApplicationPool(string applicationPoolName) { Execute(serverManager => { var existing = serverManager.ApplicationPools.FirstOrDefault(x => String.Equals(x.Name, applicationPoolName, StringComparison.OrdinalIgnoreCase)); if (existing == null) { throw new Exception($"The application pool '{applicationPoolName}' does not exist"); } existing.Delete(); serverManager.CommitChanges(); }); } public override bool ChangeHomeDirectory(string webSiteName, string virtualDirectoryPath, string newWebRootPath) { var result = false; FindVirtualDirectory(webSiteName, virtualDirectoryPath, found => { found.PhysicalPath = newWebRootPath; result = true; }); return result; } void FindVirtualDirectory(string webSiteName, string virtualDirectoryPath, Action<VirtualDirectory> found) { Execute(serverManager => { var site = serverManager.Sites.FirstOrDefault(s => s.Name.ToLowerInvariant() == webSiteName.ToLowerInvariant()); if (site == null) return; var virtuals = ListVirtualDirectories("", site); foreach (var vdir in virtuals) { if (!string.Equals(Normalize(vdir.FullVirtualPath), Normalize(virtualDirectoryPath), StringComparison.OrdinalIgnoreCase)) continue; found(vdir.VirtualDirectory); serverManager.CommitChanges(); } }); } static string Normalize(string fullVirtualPath) { if (fullVirtualPath == null) return string.Empty; return string.Join("/", fullVirtualPath.Split('/').Where(x => !string.IsNullOrWhiteSpace(x))); } static IEnumerable<VirtualDirectoryNode> ListVirtualDirectories(string path, ConfigurationElement element) { var site = element as Site; if (site != null) { foreach (var child in site.Applications) foreach (var item in ListVirtualDirectories("", child)) yield return item; } var app = element as Application; if (app != null) { foreach (var child in app.VirtualDirectories) foreach (var item in ListVirtualDirectories(path + "/" + app.Path, child)) yield return item; } var vdir = element as VirtualDirectory; if (vdir != null) { yield return new VirtualDirectoryNode { FullVirtualPath = path + "/" + vdir.Path, VirtualDirectory = vdir }; foreach (var child in vdir.ChildElements) foreach (var item in ListVirtualDirectories(path + "/" + vdir.Path, child)) yield return item; } } public VirtualDirectory FindVirtualDirectory(string webSiteName, string virtualDirectoryPath) { VirtualDirectory virtualDirectory = null; FindVirtualDirectory(webSiteName, virtualDirectoryPath, vd => virtualDirectory = vd); return virtualDirectory; } public class VirtualDirectoryNode { public string FullVirtualPath { get; set; } public VirtualDirectory VirtualDirectory { get; set; } } public Site GetWebSite(string webSiteName) { var site = FindWebSite(webSiteName); if (site == null) { throw new Exception($"The site '{webSiteName}' does not exist."); } return site; } public Site FindWebSite(string webSiteName) { return Execute(serverManager => serverManager.Sites.FirstOrDefault(x => String.Equals(x.Name, webSiteName, StringComparison.OrdinalIgnoreCase))); } public bool WebSiteExists(string webSiteName) { return FindWebSite(webSiteName) != null; } public ApplicationPool GetApplicationPool(string applicationPoolName) { var applicationPool = FindApplicationPool(applicationPoolName); if (applicationPool == null) { throw new Exception($"The application pool '{applicationPoolName}' does not exist."); } return applicationPool; } public ApplicationPool FindApplicationPool(string applicationPoolName) { return Execute(serverManager => serverManager.ApplicationPools.FirstOrDefault(x => String.Equals(x.Name, applicationPoolName, StringComparison.OrdinalIgnoreCase))); } public bool ApplicationPoolExists(string applicationPool) { return FindApplicationPool(applicationPool) != null; } private void Execute(Action<ServerManager> action) { using (var serverManager = ServerManager.OpenRemote(Localhost)) { action(serverManager); } } private TResult Execute<TResult>(Func<ServerManager, TResult> func) { var result = default(TResult); Action<ServerManager> action = serverManager => result = func(serverManager); Execute(action); return result; } } } #endif<file_sep>using System.Collections.Generic; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Python { public class PythonFixture : CalamariFixture { [Test, RequiresMinimumPython3Version(4)] public void ShouldCallHello() { var (output, _) = RunScript("hello.py"); output.AssertSuccess(); output.AssertOutput("Hello"); } [Test, RequiresMinimumPython3Version(4)] public void ShouldPrintVariables() { var (output, _) = RunScript("printvariables.py", new Dictionary<string, string> { ["Variable1"] = "ABC", ["Variable2"] = "DEF", ["Variable3"] = "GHI", ["Foo_bar"] = "Hello", ["Host"] = "Never", }); output.AssertSuccess(); output.AssertOutput("V1=ABC"); output.AssertOutput("V2=DEF"); output.AssertOutput("V3=GHI"); output.AssertOutput("Foo_bar=Hello"); } [Test, RequiresMinimumPython3Version(4)] public void ShouldPrintSensitiveVariables() { var (output, _) = RunScript("printvariables.py", new Dictionary<string, string> { ["Variable1"] = "Secret", ["Variable2"] = "DEF", ["Variable3"] = "GHI", ["Foo_bar"] = "Hello", ["Host"] = "Never", }, sensitiveVariablesPassword: "<PASSWORD>=="); output.AssertSuccess(); output.AssertOutput("V1=Secret"); } [Test, RequiresMinimumPython3Version(4)] public void ShouldSetVariables() { var (output, variables) = RunScript("setvariable.py"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='VGVzdEE=' value='V29ybGQh']"); Assert.AreEqual("World!", variables.Get("TestA")); } [Test, RequiresMinimumPython3Version(4)] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ShouldWriteServiceMessageForArtifactsOnWindows() { var (output, _) = RunScript("createartifactwin.py"); output.AssertSuccess(); output.AssertOutput("##octopus[createArtifact path='QzpcUGF0aFxGaWxlLnR4dA==' name='RmlsZS50eHQ=' length='MA==']"); } [Test, RequiresMinimumPython3Version(4)] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void ShouldWriteServiceMessageForArtifactsOnNix() { var (output, _) = RunScript("createartifactnix.py"); output.AssertSuccess(); output.AssertOutput("##octopus[createArtifact path='L2hvbWUvZmlsZS50eHQ=' name='ZmlsZS50eHQ=' length='MA==']"); } [Test, RequiresMinimumPython3Version(4)] public void ShouldWriteUpdateProgress() { var (output, _) = RunScript("updateprogress.py"); output.AssertSuccess(); output.AssertOutput("##octopus[progress percentage='NTA=' message='SGFsZiBXYXk=']"); } [Test, RequiresMinimumPython3Version(4)] public void ShouldCaptureAllOutput() { var (output, _) = RunScript("output.py"); output.AssertSuccess(); output.AssertOutput("Hello!"); output.AssertOutput("Hello verbose!"); output.AssertOutput("Hello warning!"); } [Test, RequiresMinimumPython3Version(4)] public void ShouldConsumeParameters() { var (output, _) = RunScript("parameters.py", new Dictionary<string, string> { [SpecialVariables.Action.Script.ScriptParameters] = "parameter1 parameter2" }); output.AssertSuccess(); output.AssertOutput("Parameters parameter1 parameter2"); } [Test, RequiresMinimumPython3Version(4)] public void ShouldFailStep() { var (output, _) = RunScript("failstep.py"); output.AssertFailure(); } [Test, RequiresMinimumPython3Version(4)] public void ShouldFailStepWithCustomMessage() { var (output, _) = RunScript("failstepwithmessage.py"); output.AssertFailure(); output.AssertOutput("##octopus[resultMessage message='Q3VzdG9tIGZhaWx1cmUgbWVzc2FnZQ==']"); } } }<file_sep>using System.Collections.Generic; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Model; namespace Calamari.Deployment.PackageRetention.Caching { public class FirstInFirstOutJournalEntryComparer : IComparer<JournalEntry> { public int Compare(JournalEntry x, JournalEntry y) { return GetCacheAgeAtFirstPackageUse(x).CompareTo(GetCacheAgeAtFirstPackageUse(y)); } static CacheAge GetCacheAgeAtFirstPackageUse(JournalEntry entry) { return entry.GetUsageDetails().GetCacheAgeAtFirstPackageUse(); } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using Calamari.Common.Plumbing.Logging; namespace Calamari.Common.Plumbing.Proxies { public static class ProxyEnvironmentVariablesGenerator { public const string HttpProxyVariableName = "HTTP_PROXY"; public const string HttpsProxyVariableName = "HTTPS_PROXY"; public const string NoProxyVariableName = "NO_PROXY"; static IEnumerable<string> ProxyEnvironmentVariableNames => new[] { HttpProxyVariableName, HttpsProxyVariableName, NoProxyVariableName } .SelectMany(v => new[] { v.ToUpperInvariant(), v.ToLowerInvariant() }) .ToArray(); public static IEnumerable<EnvironmentVariable> GenerateProxyEnvironmentVariables() { var environmentVariables = Environment.GetEnvironmentVariables(); var existingProxyEnvironmentVariables = new HashSet<string>(ProxyEnvironmentVariableNames.Where(environmentVariables.Contains), StringComparer.Ordinal); if (existingProxyEnvironmentVariables.Any()) { Log.Verbose("Proxy related environment variables already exist. Calamari will not overwrite any proxy environment variables."); return DuplicateVariablesWithUpperAndLowerCasing(existingProxyEnvironmentVariables, environmentVariables); } Log.Verbose("Setting Proxy Environment Variables"); return ProxySettingsInitializer.GetProxySettingsFromEnvironment().GenerateEnvironmentVariables(); } static IEnumerable<EnvironmentVariable> DuplicateVariablesWithUpperAndLowerCasing(ISet<string> existingProxyEnvironmentVariableNames, IDictionary environmentVariables) { foreach (var existingVariableName in existingProxyEnvironmentVariableNames) { var requiredVariables = new[] { existingVariableName.ToUpperInvariant(), existingVariableName.ToLowerInvariant() }; foreach (var requiredVariableName in requiredVariables.Where(v => !existingProxyEnvironmentVariableNames.Contains(v))) yield return new EnvironmentVariable(requiredVariableName, (string)environmentVariables[existingVariableName]); } } public static IEnumerable<EnvironmentVariable> GetProxyEnvironmentVariables( string host, int port, string proxyUsername, string proxyPassword) { string proxyUri; if (!string.IsNullOrEmpty(proxyUsername)) { #if NET40 proxyUri = $"http://{System.Web.HttpUtility.UrlEncode(proxyUsername)}:{System.Web.HttpUtility.UrlEncode(proxyPassword)}@{host}:{port}"; #else proxyUri = $"http://{WebUtility.UrlEncode(proxyUsername)}:{WebUtility.UrlEncode(proxyPassword)}@{host}:{port}"; #endif } else { proxyUri = $"http://{host}:{port}"; } yield return new EnvironmentVariable(HttpProxyVariableName, proxyUri); yield return new EnvironmentVariable(HttpProxyVariableName.ToLowerInvariant(), proxyUri); yield return new EnvironmentVariable(HttpsProxyVariableName, proxyUri); yield return new EnvironmentVariable(HttpsProxyVariableName.ToLowerInvariant(), proxyUri); yield return new EnvironmentVariable(NoProxyVariableName, "127.0.0.1,localhost,169.254.169.254"); yield return new EnvironmentVariable(NoProxyVariableName.ToLowerInvariant(), "127.0.0.1,localhost,169.254.169.254"); } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Logging; using SharpCompress.Readers.GZip; namespace Calamari.Common.Features.Packages { public class TarGzipPackageExtractor : TarPackageExtractor { public TarGzipPackageExtractor(ILog log) : base(log) { } public override string[] Extensions => new[] { ".tgz", ".tar.gz", ".tar.Z" }; protected override Stream GetCompressionStream(Stream stream) { var gzipReader = GZipReader.Open(stream); gzipReader.MoveToNextEntry(); return gzipReader.OpenEntryStream(); } } }<file_sep>#!/bin/bash echo "Hello" $(get_octopusvariable "Name")<file_sep>using System; namespace Calamari.Common.Plumbing.FileSystem { public interface IFreeSpaceChecker { void EnsureDiskHasEnoughFreeSpace(string directoryPath); ulong GetSpaceRequiredToBeFreed(string directoryPath); ulong GetRequiredSpaceInBytes(); } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.Certificates.WindowsNative; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using static Calamari.Integration.Certificates.WindowsNative.WindowsX509Native; using Native = Calamari.Integration.Certificates.WindowsNative.WindowsX509Native; namespace Calamari.Integration.Certificates { public class WindowsX509CertificateStore { public static readonly ISemaphoreFactory Semaphores = SemaphoreFactory.Get(); public static readonly string SemaphoreName = nameof(WindowsX509CertificateStore); const string IntermediateAuthorityStoreName = "CA"; public static readonly string RootAuthorityStoreName = "Root"; private static IDisposable AcquireSemaphore() { return Semaphores.Acquire(SemaphoreName, "Another process is working with the certificate store, please wait..."); } public static void ImportCertificateToStore(byte[] pfxBytes, string password, StoreLocation storeLocation, string storeName, bool privateKeyExportable) { using (AcquireSemaphore()) { CertificateSystemStoreLocation systemStoreLocation; bool useUserKeyStore; switch (storeLocation) { case StoreLocation.CurrentUser: systemStoreLocation = CertificateSystemStoreLocation.CurrentUser; useUserKeyStore = true; break; case StoreLocation.LocalMachine: systemStoreLocation = CertificateSystemStoreLocation.LocalMachine; useUserKeyStore = false; break; default: throw new ArgumentOutOfRangeException(nameof(storeLocation), storeLocation, null); } ImportPfxToStore(systemStoreLocation, storeName, pfxBytes, password, useUserKeyStore, privateKeyExportable); } } /// <summary> /// Import a certificate into a specific user's store /// </summary> public static void ImportCertificateToStore(byte[] pfxBytes, string password, string userName, string storeName, bool privateKeyExportable) { using (AcquireSemaphore()) { var account = new NTAccount(userName); var sid = (SecurityIdentifier) account.Translate(typeof(SecurityIdentifier)); var userStoreName = sid + "\\" + storeName; // Note we use the machine key-store. There is no way to store the private-key in // another user's key-store. var certificate = ImportPfxToStore(CertificateSystemStoreLocation.Users, userStoreName, pfxBytes, password, false, privateKeyExportable); if (certificate.HasPrivateKey()) { // Because we have to store the private-key in the machine key-store, we must grant the user access to it var keySecurity = new[] {new PrivateKeyAccessRule(account, PrivateKeyAccess.FullControl)}; AddPrivateKeyAccessRules(keySecurity, certificate); } } } public static void AddPrivateKeyAccessRules(string thumbprint, StoreLocation storeLocation, string storeName, ICollection<PrivateKeyAccessRule> privateKeyAccessRules) { using (AcquireSemaphore()) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (found.Count == 0) throw new Exception( $"Could not find certificate with thumbprint '{thumbprint}' in store Cert:\\{storeLocation}\\{storeName}"); var certificate = new SafeCertContextHandle(found[0].Handle, false); if (!certificate.HasPrivateKey()) throw new Exception("Certificate does not have a private-key"); AddPrivateKeyAccessRules(privateKeyAccessRules, certificate); store.Close(); } } public static CryptoKeySecurity GetPrivateKeySecurity(string thumbprint, StoreLocation storeLocation, string storeName) { using (AcquireSemaphore()) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); store.Close(); if (found.Count == 0) throw new Exception( $"Could not find certificate with thumbprint '{thumbprint}' in store Cert:\\{storeLocation}\\{storeName}"); var certificate = new SafeCertContextHandle(found[0].Handle, false); if (!certificate.HasPrivateKey()) throw new Exception("Certificate does not have a private-key"); var keyProvInfo = certificate.GetCertificateProperty<KeyProviderInfo>(CertificateProperty.KeyProviderInfo); // If it is a CNG key return keyProvInfo.dwProvType == 0 ? GetCngPrivateKeySecurity(certificate) : GetCspPrivateKeySecurity(certificate); } } /// <summary> /// Unlike X509Store.Remove() this function also cleans up private-keys /// </summary> public static void RemoveCertificateFromStore(string thumbprint, StoreLocation storeLocation, string storeName) { using (AcquireSemaphore()) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (found.Count == 0) return; var certificate = found[0]; var certificateHandle = new SafeCertContextHandle(found[0].Handle, false); // If the certificate has a private-key, remove it if (certificateHandle.HasPrivateKey()) { var keyProvInfo = certificateHandle.GetCertificateProperty<KeyProviderInfo>(CertificateProperty.KeyProviderInfo); // If it is a CNG key if (keyProvInfo.dwProvType == 0) { try { var key = CertificatePal.GetCngPrivateKey(certificateHandle); CertificatePal.DeleteCngKey(key); } catch (Exception ex) { throw new Exception("Exception while deleting CNG private key", ex); } } else // CAPI key { try { IntPtr providerHandle; var acquireContextFlags = CryptAcquireContextFlags.Delete | CryptAcquireContextFlags.Silent; if (storeLocation == StoreLocation.LocalMachine) acquireContextFlags = acquireContextFlags | CryptAcquireContextFlags.MachineKeySet; var success = Native.CryptAcquireContext(out providerHandle, keyProvInfo.pwszContainerName, keyProvInfo.pwszProvName, keyProvInfo.dwProvType, acquireContextFlags); if (!success) throw new CryptographicException(Marshal.GetLastWin32Error()); } catch (Exception ex) { // Swallow keyset does not exist if (!(ex is CryptographicException && ex.Message.Contains("Keyset does not exist"))) { throw new Exception("Exception while deleting CAPI private key", ex); } } } } store.Remove(certificate); store.Close(); } } public static ICollection<string> GetStoreNames(StoreLocation location) { var callback = new CertEnumSystemStoreCallBackProto(CertEnumSystemStoreCallBack); var names = new List<string>(); CertificateSystemStoreLocation locationFlags; switch (location) { case StoreLocation.CurrentUser: locationFlags = CertificateSystemStoreLocation.CurrentUser; break; case StoreLocation.LocalMachine: locationFlags = CertificateSystemStoreLocation.LocalMachine; break; default: throw new ArgumentOutOfRangeException(nameof(location), location, null); } lock (StoreNamesSyncLock) { EnumeratedStoreNames.Clear(); CertEnumSystemStore(locationFlags, IntPtr.Zero, IntPtr.Zero, callback); names.AddRange(EnumeratedStoreNames); } return names; } static SafeCertContextHandle ImportPfxToStore(CertificateSystemStoreLocation storeLocation, string storeName, byte[] pfxBytes, string password, bool useUserKeyStore, bool privateKeyExportable) { var pfxImportFlags = useUserKeyStore ? PfxImportFlags.CRYPT_USER_KEYSET : PfxImportFlags.CRYPT_MACHINE_KEYSET; if (privateKeyExportable) { pfxImportFlags = pfxImportFlags | PfxImportFlags.CRYPT_EXPORTABLE; } var certificates = GetCertificatesFromPfx(pfxBytes, password, pfxImportFlags); // Import the first certificate into the specified store AddCertificateToStore(storeLocation, storeName, certificates.First()); // Any other certificates in the chain are imported into the Intermediate Authority and Root stores // of the Local Machine (importing into user CA stores causes a security-warning dialog to be shown) for (var i = 1; i < certificates.Count; i++) { var certificate = certificates[i]; // If it is the last certificate in the chain and is self-signed then it goes into the Root store if (i == certificates.Count - 1 && IsSelfSigned(certificate)) { AddCertificateToStore(CertificateSystemStoreLocation.LocalMachine, RootAuthorityStoreName, certificate); continue; } // Otherwise into the Intermediate Authority store AddCertificateToStore(CertificateSystemStoreLocation.LocalMachine, IntermediateAuthorityStoreName, certificate); } return certificates.First(); } private static readonly IList<string> EnumeratedStoreNames = new List<string>(); private static readonly object StoreNamesSyncLock = new object(); /// <summary> /// call back function used by CertEnumSystemStore /// /// Currently, there is no managed support for enumerating store /// names on a machine. We use the win32 function CertEnumSystemStore() /// to get a list of stores for a given context. /// /// Each time this callback is called, we add the passed store name /// to the list of stores /// </summary> internal static bool CertEnumSystemStoreCallBack(string storeName, uint dwFlagsNotUsed, IntPtr notUsed1, IntPtr notUsed2, IntPtr notUsed3) { EnumeratedStoreNames.Add(storeName); return true; } static void AddCertificateToStore(CertificateSystemStoreLocation storeLocation, string storeName, SafeCertContextHandle certificate) { try { using (var store = CertOpenStore(CertStoreProviders.CERT_STORE_PROV_SYSTEM, IntPtr.Zero, IntPtr.Zero, storeLocation, storeName)) { var subjectName = CertificatePal.GetSubjectName(certificate); var storeContext = IntPtr.Zero; if (!CertAddCertificateContextToStore(store, certificate, AddCertificateDisposition.CERT_STORE_ADD_NEW, ref storeContext)) { var error = Marshal.GetLastWin32Error(); if (error == (int) CapiErrorCode.CRYPT_E_EXISTS) { Log.Info($"Certificate '{subjectName}' already exists in store '{storeName}'."); return; } throw new CryptographicException(error); } Log.Info($"Imported certificate '{subjectName}' into store '{storeName}'"); } } catch (Exception ex) { throw new Exception("Could not add certificate to store", ex); } } static IList<SafeCertContextHandle> GetCertificatesFromPfx(byte[] pfxBytes, string password, PfxImportFlags pfxImportFlags) { // Marshal PFX bytes into native data structure var pfxData = new CryptoData { cbData = pfxBytes.Length, pbData = Marshal.AllocHGlobal(pfxBytes.Length) }; Marshal.Copy(pfxBytes, 0, pfxData.pbData, pfxBytes.Length); var certificates = new List<SafeCertContextHandle>(); try { using (var memoryStore = PFXImportCertStore(ref pfxData, password, pfxImportFlags)) { if (memoryStore.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); var certificatesToImport = GetCertificatesToImport(pfxBytes, password); foreach (var certificate in certificatesToImport) { var thumbprint = CalculateThumbprint(certificate); // Marshal PFX bytes into native data structure var thumbprintData = new CryptoData { cbData = thumbprint.Length, pbData = Marshal.AllocHGlobal(thumbprint.Length) }; Marshal.Copy(thumbprint, 0, thumbprintData.pbData, thumbprint.Length); var certificateHandle = CertFindCertificateInStore(memoryStore, CertificateEncodingType.Pkcs7OrX509AsnEncoding, IntPtr.Zero, CertificateFindType.Sha1Hash, ref thumbprintData, IntPtr.Zero); if (certificateHandle == null || certificateHandle.IsInvalid) throw new Exception("Could not find certificate"); certificates.Add(certificateHandle); Marshal.FreeHGlobal(thumbprintData.pbData); } return certificates; } } catch (Exception ex) { throw new Exception("Could not read PFX", ex); } finally { Marshal.FreeHGlobal(pfxData.pbData); } } static void AddPrivateKeyAccessRules(ICollection<PrivateKeyAccessRule> accessRules, SafeCertContextHandle certificate) { try { var keyProvInfo = certificate.GetCertificateProperty<KeyProviderInfo>( CertificateProperty.KeyProviderInfo); // If it is a CNG key if (keyProvInfo.dwProvType == 0) { SetCngPrivateKeySecurity(certificate, accessRules); } else { SetCspPrivateKeySecurity(certificate, accessRules); } } catch (Exception ex) { throw new Exception("Could not set security on private-key", ex); } } static void SetCngPrivateKeySecurity(SafeCertContextHandle certificate, ICollection<PrivateKeyAccessRule> accessRules) { using (var key = CertificatePal.GetCngPrivateKey(certificate)) { var security = GetCngPrivateKeySecurity(certificate); foreach (var cryptoKeyAccessRule in accessRules.Select(r => r.ToCryptoKeyAccessRule())) { security.AddAccessRule(cryptoKeyAccessRule); } var securityDescriptorBytes = security.GetSecurityDescriptorBinaryForm(); var gcHandle = GCHandle.Alloc(securityDescriptorBytes, GCHandleType.Pinned); var errorCode = NCryptSetProperty(key, NCryptProperties.SecurityDescriptor, gcHandle.AddrOfPinnedObject(), securityDescriptorBytes.Length, (int)NCryptFlags.Silent | (int)SecurityDesciptorParts.DACL_SECURITY_INFORMATION); gcHandle.Free(); if (errorCode != 0) { throw new CryptographicException(errorCode); } } } static void SetCspPrivateKeySecurity(SafeCertContextHandle certificate, ICollection<PrivateKeyAccessRule> accessRules) { using (var cspHandle = CertificatePal.GetCspPrivateKey(certificate)) { var security = GetCspPrivateKeySecurity(certificate); foreach (var cryptoKeyAccessRule in accessRules.Select(r => r.ToCryptoKeyAccessRule())) { security.AddAccessRule(cryptoKeyAccessRule); } var securityDescriptorBytes = security.GetSecurityDescriptorBinaryForm(); if (!CryptSetProvParam(cspHandle, CspProperties.SecurityDescriptor, securityDescriptorBytes, SecurityDesciptorParts.DACL_SECURITY_INFORMATION)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } } static CryptoKeySecurity GetCngPrivateKeySecurity(SafeCertContextHandle certificate) { using (var key = CertificatePal.GetCngPrivateKey(certificate)) { var security = new CryptoKeySecurity(); security.SetSecurityDescriptorBinaryForm(CertificatePal.GetCngPrivateKeySecurity(key), AccessControlSections.Access); return security; } } static CryptoKeySecurity GetCspPrivateKeySecurity(SafeCertContextHandle certificate) { using (var cspHandle = CertificatePal.GetCspPrivateKey(certificate)) { var security = new CryptoKeySecurity(); security.SetSecurityDescriptorBinaryForm(CertificatePal.GetCspPrivateKeySecurity(cspHandle), AccessControlSections.Access); return security; } } static IList<Org.BouncyCastle.X509.X509Certificate> GetCertificatesToImport(byte[] pfxBytes, string password) { using (var memoryStream = new MemoryStream(pfxBytes)) { var pkcs12Store = new Pkcs12Store(memoryStream, password?.ToCharArray() ?? "".ToCharArray()); if (pkcs12Store.Count < 1) throw new Exception("No certificates were found in PFX"); var aliases = pkcs12Store.Aliases.Cast<string>().ToList(); // Find the first bag which contains a private-key var keyAlias = aliases.FirstOrDefault(alias => pkcs12Store.IsKeyEntry(alias)); if (keyAlias != null) { return pkcs12Store.GetCertificateChain(keyAlias).Select(x => x.Certificate).ToList(); } return new List<Org.BouncyCastle.X509.X509Certificate> { pkcs12Store.GetCertificate(aliases.First()).Certificate }; } } static bool IsSelfSigned(SafeCertContextHandle certificate) { var certificateInfo = (CERT_INFO)Marshal.PtrToStructure(certificate.CertificateContext.pCertInfo, typeof(CERT_INFO)); return CertCompareCertificateName(CertificateEncodingType.Pkcs7OrX509AsnEncoding, ref certificateInfo.Subject, ref certificateInfo.Issuer); } static byte[] CalculateThumbprint(Org.BouncyCastle.X509.X509Certificate certificate) { var der = certificate.GetEncoded(); return DigestUtilities.CalculateDigest("SHA1", der); } } } #endif<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.LogParser; using ServiceMessageParser = Calamari.Common.Plumbing.ServiceMessages.ServiceMessageParser; namespace Calamari.Testing.Helpers { //Ideally sourced directly from Octopus.Worker repo public class CaptureCommandInvocationOutputSink : ICommandInvocationOutputSink { readonly List<string> all = new List<string>(); readonly List<string> infos = new List<string>(); readonly List<string> errors = new List<string>(); readonly ServiceMessageParser serviceMessageParser; readonly IVariables outputVariables = new CalamariVariables(); public CaptureCommandInvocationOutputSink() { serviceMessageParser = new ServiceMessageParser(ParseServiceMessage); } public void WriteInfo(string line) { serviceMessageParser.Parse(line); all.Add(line); infos.Add(line); } public void WriteError(string line) { all.Add(line); errors.Add(line); } public IVariables OutputVariables => outputVariables; public IList<string> Infos => infos; public IList<string> Errors => errors; public IList<string> AllMessages => all; public bool CalamariFoundPackage { get; protected set; } public FoundPackage? FoundPackage { get; protected set; } public DeltaPackage? DeltaVerification { get; protected set; } public string? DeltaError { get; protected set; } void ParseServiceMessage(ServiceMessage message) { switch (message.Name) { case ServiceMessageNames.SetVariable.Name: var variableName = message.GetValue(ServiceMessageNames.SetVariable.NameAttribute); var variableValue = message.GetValue(ServiceMessageNames.SetVariable.ValueAttribute); if (!string.IsNullOrWhiteSpace(variableName)) outputVariables.Set(variableName, variableValue); break; case ServiceMessageNames.CalamariFoundPackage.Name: CalamariFoundPackage = true; break; case ServiceMessageNames.FoundPackage.Name: var foundPackageId = message.GetValue(ServiceMessageNames.FoundPackage.IdAttribute); var foundPackageVersion = message.GetValue(ServiceMessageNames.FoundPackage.VersionAttribute); var foundPackageVersionFormat = message.GetValue(ServiceMessageNames.FoundPackage.VersionFormat ); var foundPackageHash = message.GetValue(ServiceMessageNames.FoundPackage.HashAttribute); var foundPackageRemotePath = message.GetValue(ServiceMessageNames.FoundPackage.RemotePathAttribute); var fileExtension = message.GetValue(ServiceMessageNames.FoundPackage.FileExtensionAttribute); if (foundPackageId != null && foundPackageVersion != null) FoundPackage = new FoundPackage(foundPackageId, foundPackageVersion, foundPackageVersionFormat, foundPackageRemotePath, foundPackageHash, fileExtension); break; case ServiceMessageNames.PackageDeltaVerification.Name: var pdvHash = message.GetValue(ServiceMessageNames.PackageDeltaVerification.HashAttribute); var pdvSize = message.GetValue(ServiceMessageNames.PackageDeltaVerification.SizeAttribute); var pdvRemotePath = message.GetValue(ServiceMessageNames.PackageDeltaVerification.RemotePathAttribute); DeltaError = message.GetValue(ServiceMessageNames.PackageDeltaVerification.Error); if (pdvRemotePath != null && pdvHash != null) { DeltaVerification = new DeltaPackage(pdvRemotePath, pdvHash, long.Parse(pdvSize)); } break; } } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Extensions { public static class FileSizeExtensions { public static string ToFileSizeString(this long bytes) { return ToFileSizeString(bytes <= 0 ? 0 : (ulong)bytes); } // Returns the human-readable file size for an arbitrary, 64-bit file size. // The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB". public static string ToFileSizeString(this ulong i) { // Determine the suffix and readable value. string suffix; double readable; if (i >= 0x1000000000000000) // Exabyte { suffix = "EB"; readable = i >> 50; } else if (i >= 0x4000000000000) // Petabyte { suffix = "PB"; readable = i >> 40; } else if (i >= 0x10000000000) // Terabyte { suffix = "TB"; readable = i >> 30; } else if (i >= 0x40000000) // Gigabyte { suffix = "GB"; readable = i >> 20; } else if (i >= 0x100000) // Megabyte { suffix = "MB"; readable = i >> 10; } else if (i >= 0x400) // Kilobyte { suffix = "KB"; readable = i; } else { return i.ToString("0 B"); // Byte } // Divide by 1024 to get fractional value. readable = readable / 1024; // Return formatted number with suffix. return readable.ToString("0.### ") + suffix; } } }<file_sep>using System; using System.Net; using Calamari.Common.Features.Packages; using Octopus.Versioning; namespace Calamari.Integration.Packages.Download { /// <summary> /// Defines a service for downloading packages locally. /// </summary> public interface IPackageDownloader { /// <summary> /// Downloads the given file to the local cache. /// </summary> PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, string? feedUsername, string? feedPassword, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff); } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment; using Calamari.Deployment.Conventions; namespace Calamari.Aws.Deployment.Conventions { public class GenerateCloudFormationChangesetNameConvention : IInstallConvention { readonly ILog log; public GenerateCloudFormationChangesetNameConvention(ILog log) { this.log = log; } public void Install(RunningDeployment deployment) { var name = $"octo-{Guid.NewGuid():N}"; if (string.Compare(deployment.Variables[AwsSpecialVariables.CloudFormation.Changesets.Generate], "True", StringComparison.OrdinalIgnoreCase) == 0) { deployment.Variables.Set(AwsSpecialVariables.CloudFormation.Changesets.Name, name); } log.SetOutputVariableButDoNotAddToVariables("ChangesetName", name); } } }<file_sep>using System; using System.Reflection; using System.Security.Cryptography; using System.Text; using Calamari.Common.Plumbing.Extensions; using Calamari.Util; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Util { public class MockHashingAlgorithm : HashAlgorithm { public override void Initialize() { } protected override void HashCore(byte[] array, int ibStart, int cbSize) { } protected override byte[] HashFinal() { return Encoding.UTF8.GetBytes("Supercalifragilisticexpialidocious"); } } [TestFixture] public class HashCalculatorFixture { public static Func<THash> CreateHashFipsFailure<THash>() where THash: HashAlgorithm { return () => throw new TargetInvocationException(new InvalidOperationException("This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.")); } public static Func<THash> CreateNullHashFactory<THash>() where THash : HashAlgorithm { return () => null; } [Test] public void ShouldReturnFalseIfHashingAlgorithmIsNotSupported() { Assert.IsFalse(HashCalculator.IsAvailableHashingAlgorithm(CreateHashFipsFailure<MD5>())); } [Test] public void ShouldReturnTrueIfHashingAlgorithmIsSupported() { Assert.IsTrue(HashCalculator.IsAvailableHashingAlgorithm(() => new MockHashingAlgorithm())); } [Test] public void ShouldReturnFalseIfHashingAlgorithmFactoryReturnsNull() { Assert.IsFalse(HashCalculator.IsAvailableHashingAlgorithm(CreateNullHashFactory<MD5>())); } } } <file_sep>using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class ReplicaSet : Resource { public override string ChildKind => "Pod"; public int Desired { get; } public int Current { get; } public int Ready { get; } public ReplicaSet(JObject json, Options options) : base(json, options) { Desired = FieldOrDefault("$.status.replicas", 0); Current = FieldOrDefault($".status.availableReplicas", 0); Ready = FieldOrDefault("$.status.readyReplicas", 0); if (Ready == Desired && Desired == Current) { ResourceStatus = ResourceStatus.Successful; } else { ResourceStatus = ResourceStatus.InProgress; } } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<ReplicaSet>(lastStatus); return last.Desired != Desired|| last.Ready != Ready || last.Current != Current; } } }<file_sep>using System; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.Extensions { public static class VariableExtensions { public static PathToPackage? GetPathToPrimaryPackage(this IVariables variables, ICalamariFileSystem fileSystem, bool required) { var path = variables.Get(TentacleVariables.CurrentDeployment.PackageFilePath); if (string.IsNullOrEmpty(path)) if (required) throw new CommandException($"The `{TentacleVariables.CurrentDeployment.PackageFilePath}` was not specified or blank. This is likely a bug in Octopus, please contact Octopus support."); else return null; path = CrossPlatform.ExpandPathEnvironmentVariables(path); if (!fileSystem.FileExists(path)) throw new CommandException("Could not find package file: " + path); return new PathToPackage(path); } public static bool IsFeatureEnabled(this IVariables variables, string featureName) { var features = variables.GetStrings(KnownVariables.Package.EnabledFeatures) .Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); return features.Contains(featureName); } public static bool IsPackageRetentionEnabled(this IVariables variables) { bool.TryParse(variables.Get(KnownVariables.Calamari.EnablePackageRetention, bool.FalseString), out var retentionEnabled); var tentacleHome = variables.Get(TentacleVariables.Agent.TentacleHome); var packageRetentionJournalPath = variables.Get(KnownVariables.Calamari.PackageRetentionJournalPath); return retentionEnabled && (!string.IsNullOrWhiteSpace(packageRetentionJournalPath) || !string.IsNullOrWhiteSpace(tentacleHome)); } public static void SetOutputVariable(this IVariables variables, string name, string? value) { variables.Set(name, value); // And set the output-variables. // Assuming we are running in a step named 'DeployWeb' and are setting a variable named 'Foo' // then we will set Octopus.Action[DeployWeb].Output.Foo var actionName = variables.Get(ActionVariables.Name); if (string.IsNullOrWhiteSpace(actionName)) return; var actionScopedVariable = ActionVariables.GetOutputVariableName(actionName, name); variables.Set(actionScopedVariable, value); // And if we are on a machine named 'Web01' // Then we will set Octopus.Action[DeployWeb].Output[Web01].Foo var machineName = variables.Get(MachineVariables.Name); if (string.IsNullOrWhiteSpace(machineName)) return; var machineIndexedVariableName = ActionVariables.GetMachineIndexedOutputVariableName(actionName, machineName, name); variables.Set(machineIndexedVariableName, value); } } }<file_sep>#!/bin/bash echo $(get_octopusvariable "PreDeployGreeting") "from PreDeploy.sh"<file_sep>using System; using System.Collections.Generic; using Calamari.Kubernetes.Conventions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] public class ValuesBuilderTests { [Test] public void AllTheThings() { var values = new Dictionary<string, object> { {"foo.bar1", "Hel lo"}, {"size", 21}, {"foo.bat.mat", true}, {"foo.bar2", "World"}, }; var yaml = RawValuesToYamlConverter.Convert(values); var expect = @"foo: bar1: Hel lo bar2: World bat: mat: true size: 21 ".Replace("\r\n", "\n").Replace("\n", Environment.NewLine);; Assert.AreEqual(expect, yaml); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using Nuke.Common.Tools.AzureSignTool; using Nuke.Common.Tools.SignTool; using Nuke.Common.Utilities.Collections; using Serilog; namespace Calamari.Build { public static class Signing { static readonly string[] TimestampUrls = { "http://timestamp.digicert.com?alg=sha256", "http://timestamp.comodoca.com" }; public static void SignAndTimestampBinaries( string outputDirectory, string? azureKeyVaultUrl, string? azureKeyVaultAppId, string? azureKeyVaultAppSecret, string? azureKeyVaultTenantId, string? azureKeyVaultCertificateName, string? signingCertificatePath, string? signingCertificatePassword) { Log.Information("Signing binaries in {OutputDirectory}", outputDirectory); // check that any unsigned libraries, that Octopus Deploy authors, get // signed to play nice with security scanning tools // refer: https://octopusdeploy.slack.com/archives/C0K9DNQG5/p1551655877004400 // decision re: no signing everything: https://octopusdeploy.slack.com/archives/C0K9DNQG5/p1557938890227100 var unsignedExecutablesAndLibraries = GetFilesFromDirectory(outputDirectory, "Calamari*.exe", "Calamari*.dll", "Octo*.exe", "Octo*.dll") .Where(f => !HasAuthenticodeSignature(f)) .ToArray(); if (unsignedExecutablesAndLibraries.IsEmpty()) { Log.Information("No unsigned binaries to sign in {OutputDirectory}", outputDirectory); return; } if (azureKeyVaultUrl.IsNullOrEmpty() && azureKeyVaultAppId.IsNullOrEmpty() && azureKeyVaultAppSecret.IsNullOrEmpty() && azureKeyVaultTenantId.IsNullOrEmpty() && azureKeyVaultCertificateName.IsNullOrEmpty()) { if (signingCertificatePath.IsNullOrEmpty() || signingCertificatePassword.IsNullOrEmpty()) throw new InvalidOperationException("Either Azure Key Vault or Signing " + "Certificate Parameters must be set"); if (!OperatingSystem.IsWindows()) throw new InvalidOperationException("Non-windows builds must either leave binaries " + "unsigned or sign using the AzureSignTool"); Log.Information("Signing files using signtool and the self-signed development code signing certificate"); SignFilesWithSignTool( unsignedExecutablesAndLibraries, signingCertificatePath!, signingCertificatePassword!); } else { Log.Information("Signing files using azuresigntool and the production code signing certificate"); SignFilesWithAzureSignTool( unsignedExecutablesAndLibraries, azureKeyVaultUrl!, azureKeyVaultAppId!, azureKeyVaultAppSecret!, azureKeyVaultTenantId!, azureKeyVaultCertificateName!); } } static IEnumerable<string> GetFilesFromDirectory(string directory, params string[] searchPatterns) => searchPatterns.SelectMany(searchPattern => Directory.GetFiles(directory, searchPattern)); // note: Doesn't check if existing signatures are valid, only that one exists // source: https://blogs.msdn.microsoft.com/windowsmobile/2006/05/17/programmatically-checking-the-authenticode-signature-on-a-file/ static bool HasAuthenticodeSignature(string filePath) { try { X509Certificate.CreateFromSignedFile(filePath); return true; } catch { return false; } } static void SignFilesWithAzureSignTool( ICollection<string> files, string vaultUrl, string vaultAppId, string vaultAppSecret, string vaultTenantId, string vaultCertificateName, string display = "", string displayUrl = "") { Log.Information("Signing {FilesCount} files using Azure Sign Tool", files.Count); TrySignTaskWithEachTimestampUrlUntilSuccess(url => AzureSignToolTasks.AzureSignTool(_ => _.SetKeyVaultUrl(vaultUrl) .SetKeyVaultClientId(vaultAppId) .SetKeyVaultClientSecret(vaultAppSecret) .SetKeyVaultTenantId(vaultTenantId) .SetKeyVaultCertificateName(vaultCertificateName) .SetFileDigest("sha256") .SetDescription(display) .SetDescriptionUrl(displayUrl) .SetTimestampRfc3161Url(url) .SetTimestampDigest(AzureSignToolDigestAlgorithm.sha256) .SetFiles(files))); Log.Information("Finished signing {FilesCount} files", files.Count); } static void SignFilesWithSignTool( IReadOnlyCollection<string> files, string certificatePath, string certificatePassword, string display = "", string displayUrl = "") { if (!File.Exists(certificatePath)) throw new Exception($"The code-signing certificate was not found at {certificatePath}"); Log.Information("Signing {FilesCount} files using certificate at '{CertificatePath}'...", files.Count, certificatePath); TrySignTaskWithEachTimestampUrlUntilSuccess(url => SignToolTasks.SignTool(_ => _.SetFileDigestAlgorithm(SignToolDigestAlgorithm.SHA256) .SetFile(certificatePath) .SetPassword(<PASSWORD>) .SetDescription(display) .SetUrl(displayUrl) .SetRfc3161TimestampServerUrl(url) .SetTimestampServerDigestAlgorithm(SignToolDigestAlgorithm.SHA256) .AddFiles(files))); Log.Information("Finished signing {FilesCount} files", files.Count); } static void TrySignTaskWithEachTimestampUrlUntilSuccess(Action<string> signTask) { foreach (var url in TimestampUrls) { try { signTask(url); break; } catch (Exception ex) { if (url == TimestampUrls.Last()) throw; Log.Error(ex, "Failed to sign files using timestamp url {Url}. Trying the next timestamp url", url); } } } } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class CronJobTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""CronJob"", ""metadata"": { ""name"": ""my-cj"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""spec"": { ""schedule"": ""* * * * *"", ""suspend"": false } }"; var cronJob = ResourceFactory.FromJson(input, new Options()); cronJob.Should().BeEquivalentTo(new { Kind = "CronJob", Name = "my-cj", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Schedule = "* * * * *", Suspend = false, ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful }); } } } <file_sep>using System; using System.IO; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class ExtractPackageFixture { IVariables variables; ExtractPackage extractPackage; ICalamariFileSystem fileSystem; static readonly PathToPackage PathToPackage = new PathToPackage(TestEnvironment.ConstructRootedPath("Acme.Web.1.0.0.zip")); [SetUp] public void SetUp() { fileSystem = Substitute.For<ICalamariFileSystem>(); fileSystem.RemoveInvalidFileNameChars(Arg.Any<string>()).Returns(c => c.Arg<string>().Replace("!", "")); variables = new CalamariVariables(); extractPackage = new ExtractPackage(Substitute.For<ICombinedPackageExtractor>(), fileSystem, variables, new InMemoryLog()); } [Test] public void ShouldPrefixAppPathIfSet() { var rootPath = TestEnvironment.ConstructRootedPath("MyApp"); variables.Set("Octopus.Tentacle.Agent.ApplicationDirectoryPath", rootPath); extractPackage.ExtractToApplicationDirectory(PathToPackage); Assert.That(variables.Get("OctopusOriginalPackageDirectoryPath"), Is.EqualTo(Path.Combine(rootPath, "Acme.Web", "1.0.0"))); } [Test] public void ShouldPrefixSystemDriveIfPathVariableUnavailable() { var expectedRoot = string.Format("X:{0}Applications", Path.DirectorySeparatorChar); variables.Set("env:SystemDrive", "X:"); variables.Set("env:HOME", "SomethingElse"); extractPackage.ExtractToApplicationDirectory(PathToPackage); Assert.That(variables.Get("OctopusOriginalPackageDirectoryPath"), Is.EqualTo(Path.Combine(expectedRoot, "Acme.Web", "1.0.0"))); } [Test] public void ShouldPrefixHomeDriveIfOnlyVariableAvailable() { var variable = string.Format("{0}home{0}MyUser", Path.DirectorySeparatorChar); var expectedRoot = string.Format("{0}{1}Applications", variable, Path.DirectorySeparatorChar); variables.Set("env:HOME", variable); extractPackage.ExtractToApplicationDirectory(PathToPackage); Assert.That(variables.Get("OctopusOriginalPackageDirectoryPath"), Is.EqualTo(Path.Combine(expectedRoot, "Acme.Web", "1.0.0"))); } [Test] [ExpectedException] public void ShouldThrowExceptionIfNoPathUnresolved() { extractPackage.ExtractToApplicationDirectory(PathToPackage); } [Test] public void ShouldExtractToVersionedFolderWithDefaultPath() { variables.Set("Octopus.Tentacle.Agent.ApplicationDirectoryPath", TestEnvironment.ConstructRootedPath()); extractPackage.ExtractToApplicationDirectory(PathToPackage); Assert.That(variables.Get("OctopusOriginalPackageDirectoryPath"), Does.EndWith(Path.Combine("Acme.Web", "1.0.0"))); } [Test] public void ShouldAppendToVersionedFolderIfAlreadyExisting() { variables.Set("Octopus.Tentacle.Agent.ApplicationDirectoryPath", TestEnvironment.ConstructRootedPath()); fileSystem.DirectoryExists(Arg.Is<string>(path => path.EndsWith(Path.Combine("Acme.Web", "1.0.0")))).Returns(true); fileSystem.DirectoryExists(Arg.Is<string>(path => path.EndsWith(Path.Combine("Acme.Web", "1.0.0_1")))).Returns(true); fileSystem.DirectoryExists(Arg.Is<string>(path => path.EndsWith(Path.Combine("Acme.Web", "1.0.0_2")))).Returns(true); extractPackage.ExtractToApplicationDirectory(PathToPackage); Assert.That(variables.Get("OctopusOriginalPackageDirectoryPath"), Does.EndWith(Path.Combine("Acme.Web", "1.0.0_3"))); } [Test] public void ShouldExtractToEnvironmentSpecificFolderIfProvided() { variables.Set("Octopus.Tentacle.Agent.ApplicationDirectoryPath", TestEnvironment.ConstructRootedPath()); variables.Set("Octopus.Environment.Name", "Production"); extractPackage.ExtractToApplicationDirectory(PathToPackage); Assert.That(variables.Get("OctopusOriginalPackageDirectoryPath"), Does.EndWith(Path.Combine("Production","Acme.Web","1.0.0"))); } [Test] public void ShouldExtractToTenantSpecificFolderIfProvided() { variables.Set("Octopus.Tentacle.Agent.ApplicationDirectoryPath", TestEnvironment.ConstructRootedPath()); variables.Set("Octopus.Environment.Name", "Production"); variables.Set("Octopus.Deployment.Tenant.Name", "MegaCorp"); extractPackage.ExtractToApplicationDirectory(PathToPackage); Assert.That(variables.Get("OctopusOriginalPackageDirectoryPath"), Does.EndWith(Path.Combine("MegaCorp", "Production", "Acme.Web", "1.0.0"))); } [Test] public void ShouldRemoveInvalidPathCharsFromEnvironmentName() { variables.Set("Octopus.Tentacle.Agent.ApplicationDirectoryPath", TestEnvironment.ConstructRootedPath()); variables.Set("Octopus.Environment.Name", "Production! Tokyo"); extractPackage.ExtractToApplicationDirectory(PathToPackage); Assert.That(variables.Get("OctopusOriginalPackageDirectoryPath"), Does.EndWith(Path.Combine("Production Tokyo","Acme.Web","1.0.0"))); } } } <file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.PowerShell { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class WindowsPowerShellFixture : PowerShellFixtureBase { protected override PowerShellEdition PowerShellEdition => PowerShellEdition.Desktop; [Test] [Platform] // Windows 2016 (has PowerShell 2) will also match Windows 2019 (no PowerShell 2) so have omitted it. [TestCase("2", "PSVersion 2.0", IncludePlatform = "Win2008Server,Win2008ServerR2,Win2012Server,Win2012ServerR2,Windows10")] [TestCase("2.0", "PSVersion 2.0", IncludePlatform = "Win2008Server,Win2008ServerR2,Win2012Server,Win2012ServerR2,Windows10")] public void ShouldCustomizePowerShellVersionIfRequested(string customPowerShellVersion, string expectedLogMessage) { var variables = new CalamariVariables(); variables.Set(PowerShellVariables.CustomPowerShellVersion, customPowerShellVersion); // Let's just use the Hello.ps1 script for something simples var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script") .Argument("script", GetFixtureResource("Scripts", "Hello.ps1")), variables); if (output.CapturedOutput.AllMessages .Select(line => new string(line.ToCharArray().Where(c => c != '\u0000').ToArray())) .Any(line => line.Contains(".NET Framework is not installed"))) { Assert.Inconclusive("Version 2.0 of PowerShell is not supported on this machine"); } output.AssertSuccess(); output.AssertOutput(expectedLogMessage); output.AssertOutput("Hello!"); } [Test] public void ShouldPrioritizePowerShellScriptsOverOtherSyntaxes() { var variables = new CalamariVariables(); variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.PowerShell), "Write-Host Hello PowerShell"); variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.CSharp), "Write-Host Hello CSharp"); variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.Bash), "echo Hello Bash"); var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script"), variables); output.AssertSuccess(); output.AssertOutput("Hello PowerShell"); } [Test] public void IncorrectPowerShellEditionShouldThrowException() { var nonExistentEdition = "WindowsPowerShell"; var output = RunScript("Hello.ps1", new Dictionary<string, string>() {{PowerShellVariables.Edition, nonExistentEdition}}); output.result.AssertFailure(); output.result.AssertErrorOutput("Attempted to use 'WindowsPowerShell' edition of PowerShell, but this edition could not be found. Possible editions: Core, Desktop"); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Common.Features.ConfigurationVariables; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Deployment.Features; using Calamari.Deployment.PackageRetention; using Calamari.Integration.Iis; using Calamari.Integration.Nginx; namespace Calamari.Commands { [Command("deploy-package", Description = "Extracts and installs a deployment package")] public class DeployPackageCommand : Command { readonly ILog log; readonly IScriptEngine scriptEngine; readonly IVariables variables; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; readonly ISubstituteInFiles substituteInFiles; readonly IExtractPackage extractPackage; readonly IStructuredConfigVariablesService structuredConfigVariablesService; readonly IDeploymentJournalWriter deploymentJournalWriter; PathToPackage pathToPackage; public DeployPackageCommand( ILog log, IScriptEngine scriptEngine, IVariables variables, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner, ISubstituteInFiles substituteInFiles, IExtractPackage extractPackage, IStructuredConfigVariablesService structuredConfigVariablesService, IDeploymentJournalWriter deploymentJournalWriter) { Options.Add("package=", "Path to the deployment package to install.", v => pathToPackage = new PathToPackage(Path.GetFullPath(v))); this.log = log; this.scriptEngine = scriptEngine; this.variables = variables; this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; this.substituteInFiles = substituteInFiles; this.extractPackage = extractPackage; this.structuredConfigVariablesService = structuredConfigVariablesService; this.deploymentJournalWriter = deploymentJournalWriter; } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); Guard.NotNullOrWhiteSpace(pathToPackage, "No package file was specified. Please pass --package YourPackage.nupkg"); if (!File.Exists(pathToPackage)) throw new CommandException("Could not find package file: " + pathToPackage); Log.Info("Deploying package: " + pathToPackage); var featureClasses = new List<IFeature>(); var replacer = new ConfigurationVariablesReplacer(variables, log); var configurationTransformer = ConfigurationTransformer.FromVariables(variables, log); var transformFileLocator = new TransformFileLocator(fileSystem, log); var embeddedResources = new AssemblyEmbeddedResources(); #if IIS_SUPPORT var iis = new InternetInformationServer(); featureClasses.AddRange(new IFeature[] { new IisWebSiteBeforeDeployFeature(), new IisWebSiteAfterPostDeployFeature() }); #endif if (!CalamariEnvironment.IsRunningOnWindows) { featureClasses.Add(new NginxFeature(NginxServer.AutoDetect(), fileSystem)); } var semaphore = SemaphoreFactory.Get(); var journal = new DeploymentJournal(fileSystem, semaphore, variables); var conventions = new List<IConvention> { new AlreadyInstalledConvention(log, journal), new DelegateInstallConvention(d => extractPackage.ExtractToApplicationDirectory(pathToPackage)), new FeatureConvention(DeploymentStages.BeforePreDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new ConfiguredScriptConvention(new PreDeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new PackagedScriptConvention(new PreDeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new FeatureConvention(DeploymentStages.AfterPreDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new SubstituteInFilesConvention(new SubstituteInFilesBehaviour(substituteInFiles)), new ConfigurationTransformsConvention(new ConfigurationTransformsBehaviour(fileSystem, variables, configurationTransformer, transformFileLocator, log)), new ConfigurationVariablesConvention(new ConfigurationVariablesBehaviour(fileSystem, variables, replacer, log)), new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(structuredConfigVariablesService)), new CopyPackageToCustomInstallationDirectoryConvention(fileSystem), new FeatureConvention(DeploymentStages.BeforeDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new PackagedScriptConvention(new DeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new ConfiguredScriptConvention(new DeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new FeatureConvention(DeploymentStages.AfterDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), #if IIS_SUPPORT new LegacyIisWebSiteConvention(fileSystem, iis), #endif new FeatureConvention(DeploymentStages.BeforePostDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new PackagedScriptConvention(new PostDeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new ConfiguredScriptConvention(new PostDeployConfiguredScriptBehaviour( log, fileSystem, scriptEngine, commandLineRunner)), new FeatureConvention(DeploymentStages.AfterPostDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources), new RollbackScriptConvention(log, DeploymentStages.DeployFailed, fileSystem, scriptEngine, commandLineRunner), new FeatureRollbackConvention(DeploymentStages.DeployFailed, fileSystem, scriptEngine, commandLineRunner, embeddedResources) }; var deployment = new RunningDeployment(pathToPackage, variables); var conventionRunner = new ConventionProcessor(deployment, conventions, log); try { conventionRunner.RunConventions(); deploymentJournalWriter.AddJournalEntry(deployment, true, pathToPackage); } catch (Exception) { deploymentJournalWriter.AddJournalEntry(deployment, false, pathToPackage); throw; } return 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using Octopus.CoreUtilities; namespace Calamari.Common.Plumbing.Proxies { public interface IProxySettings { Maybe<IWebProxy> CreateProxy(); IEnumerable<EnvironmentVariable> GenerateEnvironmentVariables(); } public class BypassProxySettings : IProxySettings { public Maybe<IWebProxy> CreateProxy() { return new WebProxy().AsSome<IWebProxy>(); } public IEnumerable<EnvironmentVariable> GenerateEnvironmentVariables() { yield return new EnvironmentVariable(ProxyEnvironmentVariablesGenerator.NoProxyVariableName, "*"); } } public class UseSystemProxySettings : IProxySettings { static readonly Uri TestUri = new Uri("http://proxytestingdomain.octopus.com"); public UseSystemProxySettings(string username, string password) { Username = username; Password = <PASSWORD>; } public string Username { get; } public string Password { get; } public Maybe<IWebProxy> CreateProxy() { return SystemWebProxyRetriever.GetSystemWebProxy() .Select(proxy => { proxy.Credentials = string.IsNullOrWhiteSpace(Username) ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(Username, Password); return proxy; }); } public IEnumerable<EnvironmentVariable> GenerateEnvironmentVariables() { return SystemWebProxyRetriever.GetSystemWebProxy() .SelectValueOr( proxy => { var proxyUri = proxy.GetProxy(TestUri); return ProxyEnvironmentVariablesGenerator.GetProxyEnvironmentVariables( proxyUri.Host, proxyUri.Port, Username, Password); }, Enumerable.Empty<EnvironmentVariable>() ); } } public class UseCustomProxySettings : IProxySettings { public UseCustomProxySettings(string host, int port, string username, string password) { Host = host; Port = port; Username = username; Password = <PASSWORD>; } public string Host { get; } public int Port { get; } public string Username { get; } public string Password { get; } public Maybe<IWebProxy> CreateProxy() { var proxy = new WebProxy(new UriBuilder("http", Host, Port).Uri) { Credentials = string.IsNullOrWhiteSpace(Username) ? new NetworkCredential() : new NetworkCredential(Username, Password) }; return proxy.AsSome<IWebProxy>(); } public IEnumerable<EnvironmentVariable> GenerateEnvironmentVariables() { return ProxyEnvironmentVariablesGenerator.GetProxyEnvironmentVariables( Host, Port, Username, Password ); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.ServiceMessages; using NUnit.Framework; namespace Calamari.Tests.Fixtures.ServiceMessages { [TestFixture] public class ServiceMessageParserFixture { ServiceMessageParser parser; List<ServiceMessage> messages; [SetUp] public void SetUp() { messages = new List<ServiceMessage>(); parser = new ServiceMessageParser((message) => messages.Add(message)); } [Test] public void ShouldLeaveNonMessageText() { parser.Parse("Hello World!"); Assert.IsEmpty(messages); } [Test] public void ShouldRecognizeBasicMessage() { parser.Parse("Hello world!" + Environment.NewLine); parser.Parse("##octopus[foo] Hello" + Environment.NewLine); Assert.That(messages.Count, Is.EqualTo(1)); Assert.That(messages[0].Name, Is.EqualTo("foo")); } [Test] public void ShouldRecognizeMultipleMessages() { parser.Parse("##octopus[Burt] Hello" + Environment.NewLine); parser.Parse("Hello world!" + Environment.NewLine); parser.Parse("##octopus[Ernie] Hello" + Environment.NewLine); Assert.That(messages.Count, Is.EqualTo(2)); Assert.That(messages[0].Name, Is.EqualTo("Burt")); Assert.That(messages[1].Name, Is.EqualTo("Ernie")); } [Test] public void ShouldRecognizeMessageWithNewLineChar() { const string stringWithEncodedCrLf = "dGhpcyBpcyBhIHZlcnkNCg0KdmVyeSBsb25nIGxvbmcgbGluZQ=="; parser.Parse("Hello world!" + Environment.NewLine); parser.Parse(string.Format("##octopus[foo name='UGF1bA==' value='{0}'] Hello", stringWithEncodedCrLf)); Assert.That(messages.Count, Is.EqualTo(1)); Assert.That(messages[0].Name, Is.EqualTo("foo")); Assert.That(messages[0].Properties["name"], Is.EqualTo("Paul")); Assert.That(messages[0].Properties["value"], Is.EqualTo(string.Format("this is a very\r\n\r\nvery long long line"))); } [Test] public void ShouldRecognizeMessageSplitOverMultipleLines() { parser.Parse("Hello world!" + Environment.NewLine); parser.Parse(string.Format("##octopus[foo name{0}='UGF1bA==' value='VGhpcyBzZ{0}W50ZW5jZSBpcyBmYWx{0}{0}zZQ=='] Hello", Environment.NewLine)); Assert.That(messages.Count, Is.EqualTo(1)); Assert.That(messages[0].Name, Is.EqualTo("foo")); Assert.That(messages[0].Properties["name"], Is.EqualTo("Paul")); Assert.That(messages[0].Properties["value"], Is.EqualTo(string.Format("This sentence is false"))); } } }<file_sep>using System; using System.Linq; using System.Text; using System.Xml.Linq; namespace Calamari.Common.Plumbing.ServiceMessages { public class ServiceMessageParser { readonly Action<ServiceMessage> serviceMessage; readonly StringBuilder buffer = new StringBuilder(); State state = State.Default; public ServiceMessageParser(Action<ServiceMessage> serviceMessage) { this.serviceMessage = serviceMessage; } public bool Parse(string line) { foreach (var c in line) switch (state) { case State.Default: if (c == '#') { state = State.PossibleMessage; buffer.Append(c); } break; case State.PossibleMessage: buffer.Append(c); var progress = buffer.ToString(); if ("##octopus" == progress) { state = State.InMessage; buffer.Clear(); } else if (!"##octopus".StartsWith(progress)) { state = State.Default; buffer.Clear(); } break; case State.InMessage: if (c == ']') { var result = ProcessMessage(buffer.ToString()); state = State.Default; buffer.Clear(); return result; } else { buffer.Append(c); } break; default: throw new ArgumentOutOfRangeException(); } return false; } bool ProcessMessage(string message) { try { message = message.Trim().TrimStart('[').Replace("\r", "").Replace("\n", ""); var element = XElement.Parse("<" + message + "/>"); var name = element.Name.LocalName; var values = element.Attributes().ToDictionary(s => s.Name.LocalName, s => Encoding.UTF8.GetString(Convert.FromBase64String(s.Value)), StringComparer.OrdinalIgnoreCase); serviceMessage(new ServiceMessage(name, values)); return true; } catch { return false; } } enum State { Default, PossibleMessage, InMessage } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Aws.Deployment; using Calamari.Aws.Serialization; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Processes; using Calamari.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Integration.S3 { public class VariableS3TargetOptionsProvider : IProvideS3TargetOptions { private readonly IVariables variables; public VariableS3TargetOptionsProvider(IVariables variables) { this.variables = variables; } private IEnumerable<S3FileSelectionProperties> GetFileSelections() { return variables.Get(AwsSpecialVariables.S3.FileSelections) ?.Map(Deserialize<List<S3FileSelectionProperties>>); } private S3PackageOptions GetPackageOptions() { return variables.Get(AwsSpecialVariables.S3.PackageOptions) ?.Map(Deserialize<S3PackageOptions>); } private static JsonSerializerSettings GetEnrichedSerializerSettings() { return JsonSerialization.GetDefaultSerializerSettings() .Tee(x => { x.Converters.Add(new FileSelectionsConverter()); x.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); } private static T Deserialize<T>(string value) { return JsonConvert.DeserializeObject<T>(value, GetEnrichedSerializerSettings()); } public IEnumerable<S3TargetPropertiesBase> GetOptions(S3TargetMode mode) { switch (mode) { case S3TargetMode.EntirePackage: return new List<S3TargetPropertiesBase>{GetPackageOptions()}; case S3TargetMode.FileSelections: return GetFileSelections(); default: throw new ArgumentOutOfRangeException("Invalid s3 target mode provided", nameof(mode)); } } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Common.Features.Processes { public static class SilentProcessRunner { // ReSharper disable once InconsistentNaming const int CP_OEMCP = 1; const int MAX_DEFAULTCHAR = 2; const int MAX_LEADBYTES = 12; const int MAX_PATH = 260; static readonly Encoding oemEncoding; static SilentProcessRunner() { try { CPINFOEX info; if (GetCPInfoEx(CP_OEMCP, 0, out info)) oemEncoding = Encoding.GetEncoding(info.CodePage); else oemEncoding = Encoding.GetEncoding(850); } catch (Exception) { Trace.WriteLine("Couldn't get default OEM encoding"); oemEncoding = Encoding.UTF8; } } public static SilentProcessRunnerResult ExecuteCommand( string executable, string arguments, string workingDirectory, Action<string> output, Action<string> error) { return ExecuteCommand(executable, arguments, workingDirectory, null, null, null, output, error); } public static SilentProcessRunnerResult ExecuteCommand( string executable, string arguments, string workingDirectory, Dictionary<string, string> environmentVars, Action<string> output, Action<string> error) { return ExecuteCommand(executable, arguments, workingDirectory, environmentVars, null, null, output, error); } public static SilentProcessRunnerResult ExecuteCommand( string executable, string arguments, string workingDirectory, Dictionary<string, string>? environmentVars, string? userName, SecureString? password, Action<string> output, Action<string> error) { try { using (var process = new Process()) { process.StartInfo.FileName = executable; process.StartInfo.Arguments = arguments; process.StartInfo.WorkingDirectory = workingDirectory; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.StandardOutputEncoding = oemEncoding; process.StartInfo.StandardErrorEncoding = oemEncoding; if (environmentVars != null) foreach (var environmentVar in environmentVars.Keys) process.StartInfo.EnvironmentVariables[environmentVar] = environmentVars[environmentVar]; RunProcessWithCredentials(process.StartInfo, userName, password); using (var outputWaitHandle = new AutoResetEvent(false)) using (var errorWaitHandle = new AutoResetEvent(false)) { var errorData = new StringBuilder(); process.OutputDataReceived += (sender, e) => { try { if (e.Data == null) outputWaitHandle.Set(); else output(e.Data); } catch (Exception ex) { try { error($"Error occured handling message: {ex.PrettyPrint()}"); } catch { // Ignore } } }; process.ErrorDataReceived += (sender, e) => { try { if (e.Data == null) { errorWaitHandle.Set(); } else { errorData.AppendLine(e.Data); error(e.Data); } } catch (Exception ex) { try { error($"Error occured handling message: {ex.PrettyPrint()}"); } catch { // Ignore } } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); outputWaitHandle.WaitOne(); errorWaitHandle.WaitOne(); return new SilentProcessRunnerResult(process.ExitCode, errorData.ToString()); } } } catch (Exception ex) { throw new Exception($"Error when attempting to execute {executable}: {ex.Message}", ex); } } static void RunProcessWithCredentials(ProcessStartInfo processStartInfo, string? userName, SecureString? password) { if (string.IsNullOrEmpty(userName) || password == null) return; var parts = userName.Split(new[] { '\\' }, 2, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { var domainPart = parts[0]; var userNamePart = parts[1]; processStartInfo.Domain = domainPart; processStartInfo.UserName = userNamePart; WindowStationAndDesktopAccess.GrantAccessToWindowStationAndDesktop(userNamePart, domainPart); } else { processStartInfo.UserName = userName; WindowStationAndDesktopAccess.GrantAccessToWindowStationAndDesktop(userName); } processStartInfo.Password = <PASSWORD>; // Environment variables (such as {env:TentacleHome}) are usually inherited from the parent process. // When running as a different user they are not inherited, so manually add them to the process. AddTentacleEnvironmentVariablesToProcess(processStartInfo); } static void AddTentacleEnvironmentVariablesToProcess(ProcessStartInfo processStartInfo) { foreach (DictionaryEntry environmentVariable in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process)) { var key = environmentVariable.Key.ToString(); if (!key.StartsWith("Tentacle")) continue; processStartInfo.EnvironmentVariables[key] = environmentVariable.Value.ToString(); } } [DllImport("kernel32.dll", SetLastError = true)] static extern bool GetCPInfoEx([MarshalAs(UnmanagedType.U4)] int CodePage, [MarshalAs(UnmanagedType.U4)] int dwFlags, out CPINFOEX lpCPInfoEx); [StructLayout(LayoutKind.Sequential)] struct CPINFOEX { [MarshalAs(UnmanagedType.U4)] public readonly int MaxCharSize; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_DEFAULTCHAR)] public readonly byte[] DefaultChar; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_LEADBYTES)] public readonly byte[] LeadBytes; public readonly char UnicodeDefaultChar; [MarshalAs(UnmanagedType.U4)] public readonly int CodePage; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)] public readonly string CodePageName; } } }<file_sep>using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Amazon; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Octopus.CoreUtilities.Extensions; using Octopus.Versioning; namespace Calamari.Integration.Packages.Download { public class S3PackageDownloader : IPackageDownloader { static string[] knownFileExtensions = { ".zip", ".tar.gz", ".tar.bz2", ".tar.gz", ".tgz", ".tar.bz" }; const char BucketFileSeparator = '/'; readonly ILog log; readonly ICalamariFileSystem fileSystem; static readonly IPackageDownloaderUtils PackageDownloaderUtils = new PackageDownloaderUtils(); public S3PackageDownloader(ILog log, ICalamariFileSystem fileSystem) { this.log = log; this.fileSystem = fileSystem; } string BuildFileName(string prefix, string version, string extension) { return $"{prefix}.{version}{extension}"; } (string BucketName, string Filename) GetBucketAndKey(string searchTerm) { var splitString = searchTerm.Split(new[] { BucketFileSeparator }, 2); if (splitString.Length == 0) return ("", ""); if (splitString.Length == 1) return (splitString[0], ""); return (splitString[0], splitString[1]); } public PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, string? feedUsername, string? feedPassword, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { var (bucketName, prefix) = GetBucketAndKey(packageId); if (string.IsNullOrWhiteSpace(bucketName) || string.IsNullOrWhiteSpace(prefix)) { throw new InvalidOperationException($"Invalid PackageId for S3 feed. Expecting format `<bucketName>/<packageId>`, but received ${bucketName}/{prefix}"); } var cacheDirectory = PackageDownloaderUtils.GetPackageRoot(feedId); if (!forcePackageDownload) { var downloaded = SourceFromCache(packageId, version, cacheDirectory); if (downloaded != null) { Log.VerboseFormat("Package was found in cache. No need to download. Using file: '{0}'", downloaded.FullFilePath); return downloaded; } } int retry = 0; for (; retry < maxDownloadAttempts; ++retry) { try { log.Verbose($"Attempting download of package {packageId} version {version} from S3 bucket {bucketName}. Attempt #{retry + 1}"); var region = GetBucketsRegion(feedUsername, feedPassword, bucketName); using (var s3Client = GetS3Client(feedUsername, feedPassword, region)) { bool fileExists = false; string fileName = ""; for (int i = 0; i < knownFileExtensions.Length && !fileExists; i++) { fileName = BuildFileName(prefix, version.ToString(), knownFileExtensions[i]); fileExists = FileExistsInBucket(s3Client, bucketName, fileName, CancellationToken.None) #if NET40 .Result; #else .GetAwaiter() .GetResult(); #endif } if (!fileExists) throw new Exception($"Unable to download package {packageId} {version}: file not found"); var localDownloadName = Path.Combine(cacheDirectory, PackageName.ToCachedFileName(packageId, version, "." + Path.GetExtension(fileName))); #if NET40 var response = s3Client.GetObject(bucketName, fileName); response.WriteResponseStreamToFile(localDownloadName); #else var response = s3Client.GetObjectAsync(bucketName, fileName).GetAwaiter().GetResult(); response.WriteResponseStreamToFileAsync(localDownloadName, false, CancellationToken.None).GetAwaiter().GetResult(); #endif var packagePhysicalFileMetadata = PackagePhysicalFileMetadata.Build(localDownloadName); return packagePhysicalFileMetadata ?? throw new CommandException($"Unable to retrieve metadata for package {packageId}, version {version}"); } } catch (Exception ex) { log.Verbose($"Download attempt #{retry + 1} failed, with error: {ex.Message}. Retrying in {downloadAttemptBackoff}"); if ((retry + 1) == maxDownloadAttempts) throw new CommandException($"Unable to download package {packageId} {version}: " + ex.Message); Thread.Sleep(downloadAttemptBackoff); } } throw new CommandException($"Failed to download package {packageId} {version}. Attempted {retry} times."); } static AmazonS3Client GetS3Client(string? feedUsername, string? feedPassword, string endpoint = "us-west-1") { var config = new AmazonS3Config { AllowAutoRedirect = true, RegionEndpoint = RegionEndpoint.GetBySystemName(endpoint) }; return string.IsNullOrEmpty(feedUsername) ? new AmazonS3Client(config) : new AmazonS3Client(new BasicAWSCredentials(feedUsername, feedPassword), config); } string GetBucketsRegion(string? feedUsername, string? feedPassword, string bucketName) { using (var s3Client = GetS3Client(feedUsername, feedPassword)) { #if NET40 var region = s3Client.GetBucketLocation(bucketName); #else var region = s3Client.GetBucketLocationAsync(bucketName, CancellationToken.None).GetAwaiter().GetResult(); #endif string regionString = region.Location.Value; // If the bucket is in the us-east-1 region, then the region name is not included in the response. if (string.IsNullOrEmpty(regionString)) { regionString = "us-east-1"; } else if (regionString.Equals("EU", StringComparison.OrdinalIgnoreCase)) { regionString = "eu-west-1"; } return regionString; } } PackagePhysicalFileMetadata? SourceFromCache(string packageId, IVersion version, string cacheDirectory) { Log.VerboseFormat($"Checking package cache for package {packageId} v{version.ToString()}"); var files = fileSystem.EnumerateFilesRecursively(cacheDirectory, PackageName.ToSearchPatterns(packageId, version, knownFileExtensions)); foreach (var file in files) { var package = PackageName.FromFile(file); if (package == null) continue; var idMatches = string.Equals(package.PackageId, packageId, StringComparison.OrdinalIgnoreCase); var versionExactMatch = string.Equals(package.Version.ToString(), version.ToString(), StringComparison.OrdinalIgnoreCase); var semverMatches = package.Version.Equals(version); if (idMatches && (semverMatches || versionExactMatch)) return PackagePhysicalFileMetadata.Build(file, package); } return null; } async Task<bool> FileExistsInBucket(AmazonS3Client client, string bucketName, string prefix, CancellationToken cancellationToken) { var request = new ListObjectsRequest { BucketName = bucketName, Prefix = prefix }; #if NET40 var response = client.ListObjects(request); #else var response = await client.ListObjectsAsync(request, cancellationToken); #endif return response.S3Objects.Any(); } } } <file_sep>using System.Xml.Linq; namespace Calamari.AzureCloudService.CloudServicePackage.ManifestSchema { public class ContentDefinition { public static readonly XName ElementName = PackageDefinition.AzureNamespace + "ContentDefinition"; static readonly XName NameElementName = PackageDefinition.AzureNamespace + "Name"; public ContentDefinition() { } public ContentDefinition(XElement element) { Name = element.Element(NameElementName).Value; Description = new ContentDescription(element.Element(ContentDescription.ElementName)); } public string Name { get; set; } public ContentDescription Description { get; set; } public XElement ToXml() { return new XElement(ElementName, new XElement(NameElementName, Name), Description.ToXml()); } } }<file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes; using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using Calamari.Testing.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus { [TestFixture] public class ResourceUpdateReporterTests { [Test] public void ReportsCreatedResourcesCorrectly() { var variables = new CalamariVariables(); var log = new InMemoryLog(); var reporter = new ResourceUpdateReporter(variables, log); var originalStatuses = new Dictionary<string, Resource>(); var newStatuses = ResourceFactory .FromListJson(TestFileLoader.Load("two-deployments.json"), new Options()) .ToDictionary(resource => resource.Uid, resource => resource); reporter.ReportUpdatedResources(originalStatuses, newStatuses, 1); var serviceMessages = log.ServiceMessages .Where(message => message.Name == SpecialVariables.KubernetesResourceStatusServiceMessageName) .ToList(); serviceMessages.Select(message => message.Properties["name"]) .Should().BeEquivalentTo(new string[] { "nginx", "redis" }); serviceMessages.Select(message => message.Properties["removed"]) .Should().BeEquivalentTo(new string[] { bool.FalseString, bool.FalseString }); serviceMessages.Select(message => message.Properties["checkCount"]) .Should().BeEquivalentTo(new string[] { "1", "1" }); } [Test] public void ReportsUpdatedResourcesCorrectly() { var variables = new CalamariVariables(); var log = new InMemoryLog(); var reporter = new ResourceUpdateReporter(variables, log); var originalStatuses = ResourceFactory .FromListJson(TestFileLoader.Load("two-deployments.json"), new Options()) .ToDictionary(resource => resource.Uid, resource => resource); var newStatuses = ResourceFactory .FromListJson(TestFileLoader.Load("one-old-deployment-and-one-new-deployment.json"), new Options()) .ToDictionary(resource => resource.Uid, resource => resource); reporter.ReportUpdatedResources(originalStatuses, newStatuses, 1); var serviceMessages = log.ServiceMessages .Where(message => message.Name == SpecialVariables.KubernetesResourceStatusServiceMessageName) .ToList(); serviceMessages.Should().ContainSingle().Which.Properties .Should().Contain(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("name", "nginx"), new KeyValuePair<string, string>("removed", bool.FalseString), new KeyValuePair<string, string>("checkCount", "1") }); } [Test] public void ReportsRemovedResourcesCorrectly() { var variables = new CalamariVariables(); var log = new InMemoryLog(); var reporter = new ResourceUpdateReporter(variables, log); var originalStatuses = ResourceFactory .FromListJson(TestFileLoader.Load("two-deployments.json"), new Options()) .ToDictionary(resource => resource.Uid, resource => resource); var newStatuses = ResourceFactory .FromListJson(TestFileLoader.Load("one-deployment.json"), new Options()) .ToDictionary(resource => resource.Uid, resource => resource); reporter.ReportUpdatedResources(originalStatuses, newStatuses, 1); var serviceMessages = log.ServiceMessages .Where(message => message.Name == SpecialVariables.KubernetesResourceStatusServiceMessageName) .ToList(); serviceMessages.Should().ContainSingle().Which.Properties .Should().Contain(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("name", "redis"), new KeyValuePair<string, string>("removed", bool.TrueString), new KeyValuePair<string, string>("checkCount", "1"), }); } } }<file_sep>#nullable enable using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Azure; using Azure.ResourceManager; using Azure.ResourceManager.AppService; using Azure.ResourceManager.Resources; using Calamari.AzureAppService.Azure; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureAppService.Behaviors { internal class AzureAppServiceBehaviour : IDeployBehaviour { public AzureAppServiceBehaviour(ILog log) { Log = log; Archive = new ZipPackageProvider(); } private ILog Log { get; } private IPackageProvider Archive { get; set; } public bool IsEnabled(RunningDeployment context) => FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.IsEnabled(context.Variables); public async Task Execute(RunningDeployment context) { Log.Verbose("Starting Azure App Service deployment."); var variables = context.Variables; var servicePrincipal = ServicePrincipalAccount.CreateFromKnownVariables(variables); Log.Verbose($"Using Azure Tenant '{servicePrincipal.TenantId}'"); Log.Verbose($"Using Azure Subscription '{servicePrincipal.SubscriptionNumber}'"); Log.Verbose($"Using Azure ServicePrincipal AppId/ClientId '{servicePrincipal.ClientId}'"); Log.Verbose($"Using Azure Cloud '{servicePrincipal.AzureEnvironment}'"); string? resourceGroupName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName); if (resourceGroupName == null) throw new Exception("resource group name must be specified"); Log.Verbose($"Using Azure Resource Group '{resourceGroupName}'."); string? webAppName = variables.Get(SpecialVariables.Action.Azure.WebAppName); if (webAppName == null) throw new Exception("Web App Name must be specified"); Log.Verbose($"Using App Service Name '{webAppName}'."); string? slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); Log.Verbose(slotName == null ? "No Deployment Slot specified" : $"Using Deployment Slot '{slotName}'"); var armClient = servicePrincipal.CreateArmClient(); var targetSite = new AzureTargetSite(servicePrincipal.SubscriptionNumber, resourceGroupName, webAppName, slotName); var resourceGroups = armClient .GetSubscriptionResource(SubscriptionResource.CreateResourceIdentifier(targetSite.SubscriptionId)) .GetResourceGroups(); Log.Verbose($"Checking existence of Resource Group '{resourceGroupName}'."); if (!await resourceGroups.ExistsAsync(resourceGroupName)) { Log.Error($"Resource Group '{resourceGroupName}' could not be found. Either it does not exist, or the Azure Account in use may not have permissions to access it."); throw new Exception("Resource Group not found."); } //get a reference to the resource group resource //this does not actually load the resource group, but we can use it later var resourceGroupResource = armClient.GetResourceGroupResource(ResourceGroupResource.CreateResourceIdentifier(targetSite.SubscriptionId, resourceGroupName)); Log.Verbose($"Resource Group '{resourceGroupName}' found."); Log.Verbose($"Checking existence of App Service '{targetSite.Site}'."); if (!await resourceGroupResource.GetWebSites().ExistsAsync(targetSite.Site)) { Log.Error($"Azure App Service '{targetSite.Site}' could not be found in resource group '{resourceGroupName}'. Either it does not exist, or the Azure Account in use may not have permissions to access it."); throw new Exception($"App Service not found."); } var webSiteResource = armClient.GetWebSiteResource(targetSite.CreateWebSiteResourceIdentifier()); Log.Verbose($"App Service '{targetSite.Site}' found, with Azure Resource Manager Id '{webSiteResource.Id.ToString()}'."); var packageFileInfo = new FileInfo(variables.Get(TentacleVariables.CurrentDeployment.PackageFilePath)!); switch (packageFileInfo.Extension) { case ".zip": Archive = new ZipPackageProvider(); break; case ".nupkg": Archive = new NugetPackageProvider(); break; case ".war": Archive = new WarPackageProvider(Log, variables, context); break; default: throw new Exception("Unsupported archive type"); } // Let's process our archive while the slot is spun up. We will await it later before we try to upload to it. Task<WebSiteSlotResource>? slotCreateTask = null; if (targetSite.HasSlot) slotCreateTask = FindOrCreateSlot(armClient, webSiteResource, targetSite); string[]? substitutionFeatures = { KnownVariables.Features.ConfigurationTransforms, KnownVariables.Features.StructuredConfigurationVariables, KnownVariables.Features.SubstituteInFiles }; /* * Calamari default behaviors * https://github.com/OctopusDeploy/Calamari/tree/master/source/Calamari.Common/Features/Behaviours */ var uploadPath = string.Empty; if (substitutionFeatures.Any(featureName => context.Variables.IsFeatureEnabled(featureName))) uploadPath = (await Archive.PackageArchive(context.StagingDirectory, context.CurrentDirectory)).FullName; else uploadPath = (await Archive.ConvertToAzureSupportedFile(packageFileInfo)).FullName; if (uploadPath == null) throw new Exception("Package File Path must be specified"); // need to ensure slot is created as slot creds may be used if (targetSite.HasSlot && slotCreateTask != null) await slotCreateTask; Log.Verbose($"Retrieving publishing profile for App Service to determine correct deployment endpoint."); using var publishingProfileXmlStream = await armClient.GetPublishingProfileXmlWithSecrets(targetSite); var publishingProfile = await PublishingProfile.ParseXml(publishingProfileXmlStream); Log.Verbose($"Using deployment endpoint '{publishingProfile.PublishUrl}' from publishing profile."); Log.Info($"Uploading package to {targetSite.SiteAndSlot}"); await UploadZipAsync(publishingProfile, uploadPath, targetSite.ScmSiteAndSlot); } private async Task<WebSiteSlotResource> FindOrCreateSlot(ArmClient armClient, WebSiteResource webSiteResource, AzureTargetSite site) { Log.Verbose($"Checking if deployment slot '{site.Slot}' exists."); var slots = webSiteResource.GetWebSiteSlots(); if (await slots.ExistsAsync(site.Slot)) { Log.Verbose($"Found existing slot {site.Slot}"); return armClient.GetWebSiteSlotResource(site.CreateResourceIdentifier()); } Log.Verbose($"Slot '{site.Slot}' not found."); Log.Info($"Creating slot '{site.Slot}'."); var operation = await slots.CreateOrUpdateAsync(WaitUntil.Completed, site.Slot, webSiteResource.Data); return operation.Value; } private async Task UploadZipAsync(PublishingProfile publishingProfile, string uploadZipPath, string targetSite) { Log.Verbose($"Path to upload: {uploadZipPath}"); Log.Verbose($"Target Site: {targetSite}"); if (!new FileInfo(uploadZipPath).Exists) throw new FileNotFoundException(uploadZipPath); var zipUploadUrl = $"{publishingProfile.PublishUrl}{Archive.UploadUrlPath}"; Log.Verbose($@"Publishing {uploadZipPath} to {zipUploadUrl}"); using var httpClient = new HttpClient(new HttpClientHandler { #pragma warning disable DE0003 Proxy = WebRequest.DefaultWebProxy #pragma warning restore DE0003 }) { // The HttpClient default timeout is 100 seconds: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=net-5.0#remarks // This timeouts with even relatively small packages: https://octopus.zendesk.com/agent/tickets/69928 // We'll set this to an hour for now, but we should probably implement some more advanced retry logic, similar to https://github.com/OctopusDeploy/Sashimi.AzureWebApp/blob/bbea36152b2fb531c2893efedf0330a06ae0cef0/source/Calamari/AzureWebAppBehaviour.cs#L70 Timeout = TimeSpan.FromHours(1) }; //we add some retry just in case the web app's Kudu/SCM is not running just yet var response = await RetryPolicies.TransientHttpErrorsPolicy.ExecuteAsync(async () => { //we have to create a new request message each time var request = new HttpRequestMessage(HttpMethod.Post, zipUploadUrl) { Headers = { Authorization = new AuthenticationHeaderValue("Basic", publishingProfile.GetBasicAuthCredentials()) }, Content = new StreamContent(new FileStream(uploadZipPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { Headers = { ContentType = new MediaTypeHeaderValue("application/octet-stream") } } }; var r = await httpClient.SendAsync(request); r.EnsureSuccessStatusCode(); return r; }); if (!response.IsSuccessStatusCode) throw new Exception($"Zip upload to {zipUploadUrl} failed with HTTP Status {(int)response.StatusCode} '{response.ReasonPhrase}'."); Log.Verbose("Finished deploying"); } } }<file_sep>#if !NET40 using System; using System.Collections.Generic; using System.IO; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Integration; namespace Calamari.Kubernetes.ResourceStatus { public class ResourceStatusReportWrapper : IScriptWrapper { private readonly Kubectl kubectl; private readonly IVariables variables; private readonly ICalamariFileSystem fileSystem; private readonly IResourceStatusReportExecutor statusReportExecutor; public ResourceStatusReportWrapper( Kubectl kubectl, IVariables variables, ICalamariFileSystem fileSystem, IResourceStatusReportExecutor statusReportExecutor) { this.kubectl = kubectl; this.variables = variables; this.fileSystem = fileSystem; this.statusReportExecutor = statusReportExecutor; } public int Priority => ScriptWrapperPriorities.KubernetesStatusCheckPriority; public IScriptWrapper NextWrapper { get; set; } public bool IsEnabled(ScriptSyntax syntax) { var resourceStatusEnabled = variables.GetFlag(SpecialVariables.ResourceStatusCheck); var isBlueGreen = variables.Get(SpecialVariables.DeploymentStyle) == "bluegreen"; var isWaitDeployment = variables.Get(SpecialVariables.DeploymentWait) == "wait"; if (!resourceStatusEnabled || isBlueGreen || isWaitDeployment) { return false; } var hasClusterUrl = !string.IsNullOrEmpty(variables.Get(SpecialVariables.ClusterUrl)); var hasClusterName = !string.IsNullOrEmpty(variables.Get(SpecialVariables.AksClusterName)) || !string.IsNullOrEmpty(variables.Get(SpecialVariables.EksClusterName)) || !string.IsNullOrEmpty(variables.Get(SpecialVariables.GkeClusterName)); return hasClusterUrl || hasClusterName; } public CommandResult ExecuteScript( Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string> environmentVars) { var workingDirectory = Path.GetDirectoryName(script.File); kubectl.SetWorkingDirectory(workingDirectory); kubectl.SetEnvironmentVariables(environmentVars); var resourceFinder = new ResourceFinder(variables, fileSystem); var result = NextWrapper.ExecuteScript(script, scriptSyntax, commandLineRunner, environmentVars); if (result.ExitCode != 0) { return result; } CommandResult GetStatusResult(string errorMessage) => new CommandResult("K8s Resource Status Reporting", 1, errorMessage, workingDirectory); try { var resources = resourceFinder.FindResources(workingDirectory); var timeoutSeconds = variables.GetInt32(SpecialVariables.Timeout) ?? 0; var waitForJobs = variables.GetFlag(SpecialVariables.WaitForJobs); var statusResult = statusReportExecutor.Start(timeoutSeconds, waitForJobs, resources).WaitForCompletionOrTimeout() .GetAwaiter().GetResult(); if (!statusResult) { return GetStatusResult("Unable to complete Report Status, see log for details."); } } catch (Exception e) { return GetStatusResult(e.Message); } return result; } } } #endif<file_sep>using System; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Common.Plumbing.Variables { public class KnownVariables { public static readonly string RetentionPolicySet = "OctopusRetentionPolicySet"; public static readonly string PrintVariables = "OctopusPrintVariables"; public static readonly string PrintEvaluatedVariables = "OctopusPrintEvaluatedVariables"; public static readonly string OriginalPackageDirectoryPath = "OctopusOriginalPackageDirectoryPath"; public static readonly string DeleteScriptsOnCleanup = "OctopusDeleteScriptsOnCleanup"; public static readonly string AppliedXmlConfigTransforms = "OctopusAppliedXmlConfigTransforms"; public static readonly string NugetHttpTimeout = "OctopusNugetHttpTimeout"; public const string EnabledFeatureToggles = "OctopusEnabledFeatureToggles"; public static class Action { public const string SkipJournal = "Octopus.Action.SkipJournal"; public const string SkipRemainingConventions = "Octopus.Action.SkipRemainingConventions"; public const string FailScriptOnErrorOutput = "Octopus.Action.FailScriptOnErrorOutput"; public static class CustomScripts { public static readonly string Prefix = "Octopus.Action.CustomScripts."; public static string GetCustomScriptStage(string deploymentStage, ScriptSyntax scriptSyntax) { return $"{Prefix}{deploymentStage}.{scriptSyntax.FileExtension()}"; } } } public static class Calamari { public const string WaitForDebugger = "Octopus.Calamari.WaitForDebugger"; public const string EnablePackageRetention = "Octopus.Calamari.EnablePackageRetention"; public const string PackageRetentionJournalPath = "env:CalamariPackageRetentionJournalPath"; public const string PackageRetentionLockExpiration = "Octopus.Calamari.PackageRetentionLockExpiration"; } public static class Release { public static readonly string Number = "Octopus.Release.Number"; } public static class ServerTask { public static readonly string Id = "Octopus.Task.Id"; } public static class Features { public const string CustomScripts = "Octopus.Features.CustomScripts"; public const string ConfigurationVariables = "Octopus.Features.ConfigurationVariables"; public const string ConfigurationTransforms = "Octopus.Features.ConfigurationTransforms"; public const string SubstituteInFiles = "Octopus.Features.SubstituteInFiles"; public const string StructuredConfigurationVariables = "Octopus.Features.JsonConfigurationVariables"; } public static class Package { public static readonly string ShouldDownloadOnTentacle = "Octopus.Action.Package.DownloadOnTentacle"; public static readonly string EnabledFeatures = "Octopus.Action.EnabledFeatures"; public static readonly string UpdateIisWebsite = "Octopus.Action.Package.UpdateIisWebsite"; public static readonly string UpdateIisWebsiteName = "Octopus.Action.Package.UpdateIisWebsiteName"; public static readonly string AutomaticallyUpdateAppSettingsAndConnectionStrings = "Octopus.Action.Package.AutomaticallyUpdateAppSettingsAndConnectionStrings"; public static readonly string JsonConfigurationVariablesEnabled = "Octopus.Action.Package.JsonConfigurationVariablesEnabled"; public static readonly string JsonConfigurationVariablesTargets = "Octopus.Action.Package.JsonConfigurationVariablesTargets"; public static readonly string AutomaticallyRunConfigurationTransformationFiles = "Octopus.Action.Package.AutomaticallyRunConfigurationTransformationFiles"; public static readonly string TreatConfigTransformationWarningsAsErrors = "Octopus.Action.Package.TreatConfigTransformationWarningsAsErrors"; public static readonly string IgnoreConfigTransformationErrors = "Octopus.Action.Package.IgnoreConfigTransformationErrors"; public static readonly string SuppressConfigTransformationLogging = "Octopus.Action.Package.SuppressConfigTransformationLogging"; public static readonly string EnableDiagnosticsConfigTransformationLogging = "Octopus.Action.Package.EnableDiagnosticsConfigTransformationLogging"; public static readonly string AdditionalXmlConfigurationTransforms = "Octopus.Action.Package.AdditionalXmlConfigurationTransforms"; public static readonly string SkipIfAlreadyInstalled = "Octopus.Action.Package.SkipIfAlreadyInstalled"; public static readonly string IgnoreVariableReplacementErrors = "Octopus.Action.Package.IgnoreVariableReplacementErrors"; public static readonly string RunPackageScripts = "Octopus.Action.Package.RunScripts"; public static class ArchiveLimits { public const string Enabled = "Octopus.Calamari.ArchiveLimits.Enabled"; public const string MaximumUncompressedSize = "Octopus.Calamari.ArchiveLimits.MaximumUncompressedSize"; public const string MaximumCompressionRatio = "Octopus.Calamari.ArchiveLimits.MaximumCompressionRatio"; public const string OverrunPreventionEnabled = "Octopus.Calamari.ArchiveLimits.OverrunPrevention.Enabled"; public const string MetricsEnabled = "Octopus.Calamari.ArchiveLimits.Metrics.Enabled"; } } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Commands { public interface ICommandInvocationOutputSink { void WriteInfo(string line); void WriteError(string line); } }<file_sep>using System; namespace Calamari.Common.Features.Processes.Semaphores { public interface ISemaphoreFactory { IDisposable Acquire(string name, string waitMessage); } }<file_sep>#if !NET40 using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.ResourceStatus.Resources; namespace Calamari.Kubernetes.ResourceStatus { public interface IResourceStatusReportExecutor { IRunningResourceStatusCheck Start(int timeoutSeconds, bool waitForJobs, IEnumerable<ResourceIdentifier> initialResources = null); } public class ResourceStatusReportExecutor : IResourceStatusReportExecutor { private readonly IVariables variables; private readonly RunningResourceStatusCheck.Factory runningResourceStatusCheckFactory; public ResourceStatusReportExecutor( IVariables variables, RunningResourceStatusCheck.Factory runningResourceStatusCheckFactory) { this.variables = variables; this.runningResourceStatusCheckFactory = runningResourceStatusCheckFactory; } public IRunningResourceStatusCheck Start(int timeoutSeconds, bool waitForJobs, IEnumerable<ResourceIdentifier> initialResources = null) { initialResources = initialResources ?? Enumerable.Empty<ResourceIdentifier>(); var timeout = timeoutSeconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(timeoutSeconds); return runningResourceStatusCheckFactory(timeout, new Options { WaitForJobs = waitForJobs}, initialResources); } } } #endif<file_sep>using System; namespace Calamari.Common.Features.Processes.Semaphores { public interface ISemaphore { string Name { get; } void ReleaseLock(); bool WaitOne(); bool WaitOne(int millisecondsToWait); } }<file_sep>using Calamari.Commands.Support; using Calamari.Deployment; using Calamari.Deployment.Conventions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Common.Features.ConfigurationVariables; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Commands { [Command(Name, Description = "Invokes a script")] public class RunScriptCommand : Command { public const string Name = "run-script"; string scriptFileArg; string packageFile; string scriptParametersArg; readonly ILog log; readonly IDeploymentJournalWriter deploymentJournalWriter; readonly IVariables variables; readonly IScriptEngine scriptEngine; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; readonly ISubstituteInFiles substituteInFiles; readonly IStructuredConfigVariablesService structuredConfigVariablesService; public RunScriptCommand( ILog log, IDeploymentJournalWriter deploymentJournalWriter, IVariables variables, IScriptEngine scriptEngine, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner, ISubstituteInFiles substituteInFiles, IStructuredConfigVariablesService structuredConfigVariablesService ) { Options.Add("package=", "Path to the package to extract that contains the script.", v => packageFile = Path.GetFullPath(v)); Options.Add("script=", $"Path to the script to execute. If --package is used, it can be a script inside the package.", v => scriptFileArg = v); Options.Add("scriptParameters=", $"Parameters to pass to the script.", v => scriptParametersArg = v); this.log = log; this.deploymentJournalWriter = deploymentJournalWriter; this.variables = variables; this.scriptEngine = scriptEngine; this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; this.substituteInFiles = substituteInFiles; this.structuredConfigVariablesService = structuredConfigVariablesService; } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); var configurationTransformer = ConfigurationTransformer.FromVariables(variables, log); var transformFileLocator = new TransformFileLocator(fileSystem, log); var replacer = new ConfigurationVariablesReplacer(variables, log); ValidateArguments(); var deployment = new RunningDeployment(packageFile, variables); WriteVariableScriptToFile(deployment); var conventions = new List<IConvention> { new StageScriptPackagesConvention(packageFile, fileSystem, new CombinedPackageExtractor(log, variables, commandLineRunner)), // Substitute the script source file new DelegateInstallConvention(d => substituteInFiles.Substitute(d.CurrentDirectory, ScriptFileTargetFactory(d).ToList())), // Substitute any user-specified files new SubstituteInFilesConvention(new SubstituteInFilesBehaviour(substituteInFiles)), new ConfigurationTransformsConvention(new ConfigurationTransformsBehaviour(fileSystem, variables, configurationTransformer, transformFileLocator, log)), new ConfigurationVariablesConvention(new ConfigurationVariablesBehaviour(fileSystem, variables, replacer, log)), new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(structuredConfigVariablesService)), new ExecuteScriptConvention(scriptEngine, commandLineRunner) }; var conventionRunner = new ConventionProcessor(deployment, conventions, log); conventionRunner.RunConventions(); var exitCode = variables.GetInt32(SpecialVariables.Action.Script.ExitCode); deploymentJournalWriter.AddJournalEntry(deployment, exitCode == 0, packageFile); return exitCode.Value; } void WriteVariableScriptToFile(RunningDeployment deployment) { if (!TryGetScriptFromVariables(out var scriptBody, out var relativeScriptFile, out var scriptSyntax) && !WasProvided(variables.Get(ScriptVariables.ScriptFileName))) { throw new CommandException($"Could not determine script to run. Please provide either a `{ScriptVariables.ScriptBody}` variable, " + $"or a `{ScriptVariables.ScriptFileName}` variable."); } if (WasProvided(scriptBody)) { var scriptFile = Path.Combine(deployment.CurrentDirectory, relativeScriptFile); //Set the name of the script we are about to create to the variables collection for replacement later on variables.Set(ScriptVariables.ScriptFileName, relativeScriptFile); // If the script body was supplied via a variable, then we write it out to a file. // This will be deleted with the working directory. // Bash files need SheBang as first few characters. This does not play well with BOM characters var scriptBytes = scriptSyntax == ScriptSyntax.Bash ? scriptBody.EncodeInUtf8NoBom() : scriptBody.EncodeInUtf8Bom(); File.WriteAllBytes(scriptFile, scriptBytes); } } bool TryGetScriptFromVariables(out string scriptBody, out string scriptFileName, out ScriptSyntax syntax) { scriptBody = variables.GetRaw(ScriptVariables.ScriptBody); if (WasProvided(scriptBody)) { var scriptSyntax = variables.Get(ScriptVariables.Syntax); if (scriptSyntax == null) { syntax = scriptEngine.GetSupportedTypes().FirstOrDefault(); Log.Warn($"No script syntax provided. Defaulting to first known supported type {syntax}"); } else if (!Enum.TryParse(scriptSyntax, out syntax)) { throw new CommandException($"Unknown script syntax `{scriptSyntax}` provided"); } scriptFileName = "Script." + syntax.FileExtension(); return true; } // Try get any supported script body variable foreach (var supportedSyntax in scriptEngine.GetSupportedTypes()) { scriptBody = variables.GetRaw(SpecialVariables.Action.Script.ScriptBodyBySyntax(supportedSyntax)); if (scriptBody == null) { continue; } scriptFileName = "Script." + supportedSyntax.FileExtension(); syntax = supportedSyntax; return true; } scriptBody = null; syntax = 0; scriptFileName = null; return false; } void ValidateArguments() { if (WasProvided(scriptFileArg)) { if (WasProvided(variables.Get(ScriptVariables.ScriptBody))) { Log.Warn( $"The `--script` parameter and `{ScriptVariables.ScriptBody}` variable are both set." + $"\r\nThe variable value takes precedence to allow for variable replacement of the script file."); } if (WasProvided(variables.Get(ScriptVariables.ScriptFileName))) { Log.Warn( $"The `--script` parameter and `{ScriptVariables.ScriptFileName}` variable are both set." + $"\r\nThe variable value takes precedence to allow for variable replacement of the script file."); } else { variables.Set(ScriptVariables.ScriptFileName, scriptFileArg); } Log.Warn($"The `--script` parameter is deprecated.\r\n" + $"Please set the `{ScriptVariables.ScriptBody}` and `{ScriptVariables.ScriptFileName}` variable to allow for variable replacement of the script file."); } if (WasProvided(scriptParametersArg)) { if (WasProvided(variables.Get(SpecialVariables.Action.Script.ScriptParameters))) { Log.Warn($"The `--scriptParameters` parameter and `{SpecialVariables.Action.Script.ScriptParameters}` variable are both set.\r\n" + $"Please provide just the `{SpecialVariables.Action.Script.ScriptParameters}` variable instead."); } else { variables.Set(SpecialVariables.Action.Script.ScriptParameters, scriptParametersArg); } } } IEnumerable<string> ScriptFileTargetFactory(RunningDeployment deployment) { // We should not perform variable-replacement if a file arg is passed in since this deprecated property // should only be coming through if something isn't using the variable-dictionary and hence will // have already been replaced on the server if (WasProvided(scriptFileArg) && !WasProvided(packageFile)) { yield break; } var scriptFile = deployment.Variables.Get(ScriptVariables.ScriptFileName); yield return Path.Combine(deployment.CurrentDirectory, scriptFile); } bool WasProvided(string value) { return !string.IsNullOrEmpty(value); } } }<file_sep>using System; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Repositories; using Calamari.Integration.Nginx; using NSubstitute.ExceptionExtensions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.TypeConverters { [TestFixture] public class TinyTypeConverterFixture { [Test] public void WhenValueIsNull_ThenThrowException() { var tc = new TinyTypeTypeConverter<ServerTaskId>(); Assert.Throws<ArgumentNullException>(() => tc.ConvertFrom(null)); } [Test] public void WhenValueIsNonString_ThenThrowException() { var tc = new TinyTypeTypeConverter<ServerTaskId>(); Assert.Throws<Exception>(() => tc.ConvertFrom(1)); } [Test] public void WhenValueIsValidString_ThenProduceTinyType() { var validString = "Valid String"; var tc = new TinyTypeTypeConverter<ServerTaskId>(); var result = tc.ConvertFrom(validString) as ServerTaskId; var expectedResult = CaseInsensitiveTinyType.Create<ServerTaskId>(validString); Assert.AreEqual(expectedResult, result); } } }<file_sep>using Calamari.Deployment.PackageRetention; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public class PackagePath : CaseInsensitiveTinyType { public PackagePath(string value) : base(value) { } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using Calamari.Common.Plumbing.Extensions; using Calamari.Testing.Tools; using Octostache; namespace Calamari.Testing { public class CommandTestBuilderContext { public List<(string? filename, Stream contents)> Files = new List<(string?, Stream)>(); public List<IDeploymentTool> Tools { get; } = new(); internal bool withStagedPackageArgument; public VariableDictionary Variables { get; } = new VariableDictionary(); public CommandTestBuilderContext WithStagedPackageArgument() { withStagedPackageArgument = true; return this; } public CommandTestBuilderContext AddVariable(string key, string value) { Variables.Add(key, value); return this; } public CommandTestBuilderContext WithDataFile(string fileContents, string? fileName = null) { WithDataFile(fileContents.EncodeInUtf8Bom(), fileName); return this; } public CommandTestBuilderContext WithDataFileNoBom(string fileContents, string? fileName = null) { WithDataFile(fileContents.EncodeInUtf8NoBom(), fileName); return this; } public CommandTestBuilderContext WithDataFile(byte[] fileContents, string? fileName = null) { WithDataFile(new MemoryStream(fileContents), fileName); return this; } public CommandTestBuilderContext WithDataFile(Stream fileContents, string? fileName = null, Action<int>? progress = null) { Files.Add((fileName, fileContents)); return this; } public CommandTestBuilderContext WithTool(IDeploymentTool tool) { Tools.Add(tool); return this; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Processes { public class CommandLineRunner : ICommandLineRunner { readonly ILog log; readonly IVariables variables; public CommandLineRunner(ILog log, IVariables variables) { this.log = log; this.variables = variables; } public CommandResult Execute(CommandLineInvocation invocation) { var commandOutput = new SplitCommandInvocationOutputSink(GetCommandOutputs(invocation)); try { var exitCode = SilentProcessRunner.ExecuteCommand( invocation.Executable, invocation.Arguments, invocation.WorkingDirectory, invocation.EnvironmentVars, invocation.UserName, invocation.Password, commandOutput.WriteInfo, commandOutput.WriteError); return new CommandResult( invocation.ToString(), exitCode.ExitCode, exitCode.ErrorOutput, invocation.WorkingDirectory); } catch (Exception ex) { if (ex.InnerException is Win32Exception) commandOutput.WriteError(ConstructWin32ExceptionMessage(invocation.Executable)); commandOutput.WriteError(ex.ToString()); commandOutput.WriteError("The command that caused the exception was: " + invocation); return new CommandResult( invocation.ToString(), -1, ex.ToString(), invocation.WorkingDirectory); } } protected virtual List<ICommandInvocationOutputSink> GetCommandOutputs(CommandLineInvocation invocation) { var outputs = new List<ICommandInvocationOutputSink> { new ServiceMessageCommandInvocationOutputSink(variables) }; if (invocation.OutputToLog) outputs.Add(new LogCommandInvocationOutputSink(log, invocation.OutputAsVerbose)); if (invocation.AdditionalInvocationOutputSink != null) outputs.Add(invocation.AdditionalInvocationOutputSink); return outputs; } public static string ConstructWin32ExceptionMessage(string executable) { return $"Unable to execute {executable}, please ensure that {executable} is installed and is in the PATH.{Environment.NewLine}"; } } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus { [TestFixture] public class KubernetesYamlTests { [Test] public void ShouldGenerateCorrectIdentifiers() { var input = TestFileLoader.Load("single-deployment.yaml"); var got = KubernetesYaml.GetDefinedResources(new string[] { input }, string.Empty); var expected = new ResourceIdentifier[] { new ResourceIdentifier( "Deployment", "nginx", "test" ) }; got.Should().BeEquivalentTo(expected); } [Test] public void ShouldOmitDefinitionIfTheMetadataSectionIsNotSet() { var input = TestFileLoader.Load("invalid.yaml"); var got = KubernetesYaml.GetDefinedResources(new string[] { input }, string.Empty); got.Should().BeEmpty(); } [Test] public void ShouldHandleMultipleResourcesDefinedInTheSameFile() { var input = TestFileLoader.Load("multiple-resources.yaml"); var got = KubernetesYaml.GetDefinedResources(new string[] { input }, string.Empty); var expected = new ResourceIdentifier[] { new ResourceIdentifier("Deployment", "nginx", "default"), new ResourceIdentifier("ConfigMap", "config", "default"), new ResourceIdentifier("Pod", "curl", "default") }; got.Should().BeEquivalentTo(expected); } [Test] public void ShouldUseDefaultNamespaceWhenNoNamespaceIsSuppliedInYaml() { const string defaultNamespace = "DefaultNamespace"; var input = TestFileLoader.Load("no-namespace.yaml"); var got = KubernetesYaml.GetDefinedResources(new string[] { input }, defaultNamespace); var expected = new ResourceIdentifier[] { new ResourceIdentifier( "Deployment", "nginx", defaultNamespace ) }; got.Should().BeEquivalentTo(expected); } [Test] public void ShouldHandleMultipleYamlFiles() { var manifest = TestFileLoader.Load("single-deployment.yaml"); var multipleFileInput = new string[] {manifest, manifest}; var got = KubernetesYaml.GetDefinedResources(multipleFileInput, string.Empty); var expected = new ResourceIdentifier[] { new ResourceIdentifier( "Deployment", "nginx", "test"), new ResourceIdentifier( "Deployment", "nginx", "test"), }; got.Should().BeEquivalentTo(expected); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Plumbing.Variables; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Variables { [TestFixture] public class DeploymentJournalVariableContributorFixture { IDeploymentJournal journal; JournalEntry previous; IVariables variables; [SetUp] public void SetUp() { journal = Substitute.For<IDeploymentJournal>(); journal.GetLatestInstallation(Arg.Any<string>()).Returns(_ => previous); journal.GetLatestSuccessfulInstallation(Arg.Any<string>()).Returns(_ => previous); variables = new CalamariVariables(); } [Test] public void ShouldAddVariablesIfPreviousInstallation() { previous = new JournalEntry("123", "tenant", "env", "proj", "rp01", DateTime.Now, "C:\\App", "C:\\MyApp", false, new List<DeployedPackage>{new DeployedPackage("pkg", "0.0.9", "C:\\PackageOld.nupkg")}); DeploymentJournalVariableContributor.Previous(variables, journal, "123"); Assert.That(variables.Get(TentacleVariables.PreviousInstallation.OriginalInstalledPath), Is.EqualTo("C:\\App")); } [Test] public void ShouldAddEmptyVariablesIfNoPreviousInstallation() { previous = null; DeploymentJournalVariableContributor.Previous(variables, journal, "123"); Assert.That(variables.Get(TentacleVariables.PreviousInstallation.OriginalInstalledPath), Is.EqualTo("")); } [Test] public void ShouldAddVariablesIfPreviousSuccessfulInstallation() { previous = new JournalEntry("123", "tenant", "env", "proj", "rp01", DateTime.Now, "C:\\App", "C:\\MyApp", true, new List<DeployedPackage>{new DeployedPackage("pkg", "0.0.9", "C:\\PackageOld.nupkg")}); DeploymentJournalVariableContributor.PreviousSuccessful(variables, journal, "123"); Assert.That(variables.Get(TentacleVariables.PreviousSuccessfulInstallation.OriginalInstalledPath), Is.EqualTo("C:\\App")); } [Test] public void ShouldAddEmptyVariablesIfNoPreviousSuccessfulInstallation() { previous = null; DeploymentJournalVariableContributor.PreviousSuccessful(variables, journal, "123"); Assert.That(variables.Get(TentacleVariables.PreviousSuccessfulInstallation.OriginalInstalledPath), Is.EqualTo("")); } } } <file_sep>using System; using System.Collections.Generic; using System.Collections; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Variables; using Calamari.Scripting; using Calamari.Testing; using Calamari.Testing.Helpers; using FluentAssertions; using Google.Apis.Auth.OAuth2; using Google.Cloud.Storage.V1; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using NUnit.Framework.Internal; using NUnit.Framework; using GoogleStorageObject = Google.Apis.Storage.v1.Data.Object; using ZipFile = System.IO.Compression.ZipFile; namespace Calamari.GoogleCloudScripting.Tests { [TestFixture] [TestFixtureSource(typeof(DownloadCli))] class GoogleCloudActionHandlerFixture { private readonly string cliPath; private class DownloadCli: IEnumerable { private readonly string postfix = ""; public DownloadCli() { if (OperatingSystem.IsLinux()) { postfix = "-linux-x86_64.tar.gz"; } else if (OperatingSystem.IsWindows()) { postfix = "-windows-x86_64-bundled-python.zip"; } else if (OperatingSystem.IsMacOs()) { postfix = "-darwin-x86_64-bundled-python.tar.gz"; } } private GoogleStorageObject RetrieveFileFromGoogleCloudStorage(StorageClient client) { var results = client.ListObjects("cloud-sdk-release", "google-cloud-sdk-"); var listOfFilesSortedByCreatedDate = new SortedList<DateTime, GoogleStorageObject>(Comparer<DateTime>.Create((a, b) => b.CompareTo(a))); foreach (var result in results) { if (result.TimeCreated.HasValue) { listOfFilesSortedByCreatedDate.Add(result.TimeCreated.Value, result); } } foreach (var file in listOfFilesSortedByCreatedDate.Where(file => file.Value.Name.EndsWith(postfix))) { return file.Value; } throw new Exception( $"Could not find a suitable executable to download from Google cloud storage for the postfix {postfix}"); } private string DownloadFile() { GoogleCredential? credential; try { credential = GoogleCredential.FromJson(EnvironmentJsonKey); } catch (InvalidOperationException) { throw new Exception("Error reading json key file, please ensure file is correct."); } using var client = StorageClient.Create(credential); var fileToDownload = RetrieveFileFromGoogleCloudStorage(client); var rootPath = TestEnvironment.GetTestPath("gcloud"); Directory.CreateDirectory(rootPath); var zipFile = Path.Combine(rootPath, fileToDownload.Name); if (!File.Exists(zipFile)) { using var fileStream = new FileStream(zipFile, FileMode.Create, FileAccess.Write, FileShare.None); client.DownloadObject(fileToDownload, fileStream); } // postfix is stripped from the path to prevent file paths exceeding length limit on Windows 2012 var shortenedName = Path.GetFileName(fileToDownload.Name).Replace(postfix, ""); var destinationDirectory = Path.Combine(rootPath, shortenedName); var gcloudExe = Path.Combine(destinationDirectory, "google-cloud-sdk", "bin", $"gcloud{(OperatingSystem.IsWindows() ? ".cmd" : string.Empty)}"); if (!File.Exists(gcloudExe)) { if (IsGZip(zipFile)) { ExtractGZip(zipFile, destinationDirectory); } else if (IsZip(zipFile)) { ZipFile.ExtractToDirectory(zipFile, destinationDirectory); } else { throw new Exception($"{zipFile} cannot be extracted. Supported compressions are .zip and .tar.gz."); } } ExecutableHelper.AddExecutePermission(gcloudExe); return gcloudExe; } private static bool IsZip(string fileName) => string.Equals(Path.GetExtension(fileName), ".zip", StringComparison.OrdinalIgnoreCase); private static bool IsGZip(string fileName) => string.Equals(Path.GetExtension(fileName), ".gz", StringComparison.OrdinalIgnoreCase); private static void ExtractGZip(string gzArchiveName, string destinationFolder) { using var inStream = File.OpenRead(gzArchiveName); using var gzipStream = new GZipInputStream(inStream); using var tarArchive = TarArchive.CreateInputTarArchive(gzipStream, Encoding.UTF8); tarArchive.ExtractContents(destinationFolder); } private static string PostfixWithoutExtension(string postfix) => IsZip(postfix) ? postfix.Replace(".zip", "") : postfix.Replace(".tar.gz", ""); public IEnumerator GetEnumerator() { var result = DownloadFile(); var startIndex = result.IndexOf("google-cloud-sdk-", StringComparison.Ordinal); var length = result.IndexOf(Path.DirectorySeparatorChar, startIndex + 1) - startIndex; yield return new TestFixtureParameters(new TestFixtureData(result) { TestName = $"{result.Substring(startIndex, length)}{PostfixWithoutExtension(postfix)}" }); } } private const string JsonEnvironmentVariableKey = "GOOGLECLOUD_OCTOPUSAPITESTER_JSONKEY"; private static readonly string? EnvironmentJsonKey = Environment.GetEnvironmentVariable(JsonEnvironmentVariableKey); public GoogleCloudActionHandlerFixture(string cliPath) { this.cliPath = cliPath; } [OneTimeSetUp] public void Setup() { if (EnvironmentJsonKey == null) { throw new Exception($"Environment Variable `{JsonEnvironmentVariableKey}` could not be found. The value can be found in the password store under GoogleCloud - OctopusAPITester"); } } [Test] public async Task ExecuteAnInlineScript() { var psScript = $"{cliPath} info"; await CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { AddDefaults(context); context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); context.Variables.Add(ScriptVariables.Syntax, OperatingSystem.IsWindows() ? ScriptSyntax.PowerShell.ToString() : ScriptSyntax.Bash.ToString()); context.Variables.Add(ScriptVariables.ScriptBody, psScript); }) .Execute(); } [Test] public async Task TryToExecuteAnInlineScriptWithInvalidCredentials() { var psScript = $"{cliPath} info"; await CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { AddDefaults(context, "{ \"name\": \"hello\" }"); context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); context.Variables.Add(ScriptVariables.Syntax, OperatingSystem.IsWindows() ? ScriptSyntax.PowerShell.ToString() : ScriptSyntax.Bash.ToString()); context.Variables.Add(ScriptVariables.ScriptBody, psScript); }) .WithAssert(result => result.WasSuccessful.Should().BeFalse()) .Execute(false); } private void AddDefaults(CommandTestBuilderContext context, string? keyFile = null) { context.Variables.Add("Octopus.Action.GoogleCloudAccount.Variable", "MyVariable"); context.Variables.Add("MyVariable.JsonKey", Convert.ToBase64String(Encoding.UTF8.GetBytes(keyFile ?? EnvironmentJsonKey!))); context.Variables.Add("Octopus.Action.GoogleCloud.CustomExecutable", cliPath); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.PackageRetention.Caching; using Calamari.Deployment.PackageRetention.Model; using Calamari.Deployment.PackageRetention.Repositories; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.PackageRetention.Repository; using FluentAssertions; using NSubstitute; using NUnit.Framework; using Octopus.Versioning; namespace Calamari.Tests.Fixtures.PackageRetention { [TestFixture] public class JournalFixture { static readonly string TentacleHome = TestEnvironment.GetTestPath("Fixtures", "PackageJournal"); static readonly string PackageDirectory = Path.Combine(TentacleHome, "Files"); InMemoryJournalRepository journalRepository; PackageJournal packageJournal; IVariables variables; [SetUp] public void Setup() { variables = new CalamariVariables(); variables.Set(KnownVariables.Calamari.EnablePackageRetention, bool.TrueString); variables.Set(TentacleVariables.Agent.TentacleHome, "SomeDirectory"); journalRepository = new InMemoryJournalRepository(); packageJournal = new PackageJournal( journalRepository, Substitute.For<ILog>(), Substitute.For<ICalamariFileSystem>(), Substitute.For<IRetentionAlgorithm>(), Substitute.For<ISemaphoreFactory>() ); } PackageIdentity CreatePackageIdentity(string packageId, string packageVersion) { var version = VersionFactory.CreateSemanticVersion(packageVersion); var path = new PackagePath($"C:\\{packageId}.{packageVersion}.zip"); return new PackageIdentity(new PackageId(packageId), version, path); } [Test] public void WhenPackageUsageIsRegistered_ThenALockExists() { var thePackage = CreatePackageIdentity("Package", "1.0"); var theDeployment = new ServerTaskId("Deployment-1"); packageJournal.RegisterPackageUse(thePackage, theDeployment, 1); Assert.IsTrue(journalRepository.HasLock(thePackage)); } [Test] public void WhenPackageUsageIsDeregistered_ThenNoLocksExist() { var thePackage = CreatePackageIdentity("Package", "1.0"); var theDeployment = new ServerTaskId("Deployment-1"); packageJournal.RegisterPackageUse(thePackage, theDeployment, 1); packageJournal.RemoveAllLocks(theDeployment); Assert.IsFalse(journalRepository.HasLock(thePackage)); } [Test] public void WhenPackageIsRegisteredForTwoDeploymentsAndDeregisteredForOne_ThenALockExists() { var thePackage = CreatePackageIdentity("Package", "1.0"); var deploymentOne = new ServerTaskId("Deployment-1"); var deploymentTwo = new ServerTaskId("Deployment-2"); packageJournal.RegisterPackageUse(thePackage, deploymentOne, 1); packageJournal.RegisterPackageUse(thePackage, deploymentTwo, 1); packageJournal.RemoveAllLocks(deploymentOne); Assert.IsTrue(journalRepository.HasLock(thePackage)); } [Test] public void WhenPackageIsRegisteredForTwoDeploymentsAndDeregisteredForBoth_ThenNoLocksExist() { var thePackage = CreatePackageIdentity("Package", "1.0"); var deploymentOne = new ServerTaskId("Deployment-1"); var deploymentTwo = new ServerTaskId("Deployment-2"); packageJournal.RegisterPackageUse(thePackage, deploymentOne, 1); packageJournal.RegisterPackageUse(thePackage, deploymentTwo, 1); packageJournal.RemoveAllLocks(deploymentOne); packageJournal.RemoveAllLocks(deploymentTwo); Assert.IsFalse(journalRepository.HasLock(thePackage)); } [Test] public void WhenPackageIsRegistered_ThenUsageIsRecorded() { var thePackage = CreatePackageIdentity("Package", "1.0"); var deploymentOne = new ServerTaskId("Deployment-1"); packageJournal.RegisterPackageUse(thePackage, deploymentOne, 1); Assert.AreEqual(1, journalRepository.GetUsage(thePackage).Count()); } [Test] public void WhenTwoPackagesAreRegisteredAgainstTheSameDeployment_ThenTwoSeparateUsagesAreRecorded() { var package1 = CreatePackageIdentity("Package1", "1.0"); var package2 = CreatePackageIdentity("Package2", "1.0"); var theDeployment = new ServerTaskId("Deployment-1"); packageJournal.RegisterPackageUse(package1, theDeployment, 1); packageJournal.RegisterPackageUse(package2, theDeployment, 1); Assert.AreEqual(1, journalRepository.GetUsage(package1).Count()); Assert.AreEqual(1, journalRepository.GetUsage(package2).Count()); } [Test] public void WhenOnePackageIsRegisteredForTwoDeployments_ThenTwoSeparateUsagesAreRecorded() { var thePackage = CreatePackageIdentity("Package1", "1.0"); var deploymentOne = new ServerTaskId("Deployment-1"); var deploymentTwo = new ServerTaskId("Deployment-2"); packageJournal.RegisterPackageUse(thePackage, deploymentOne, 1); packageJournal.RegisterPackageUse(thePackage, deploymentTwo, 1); Assert.AreEqual(2, journalRepository.GetUsage(thePackage).Count()); } [Test] public void WhenPackageIsRegisteredAndDeregistered_ThenUsageIsStillRecorded() { var thePackage = CreatePackageIdentity("Package", "1.0"); var deploymentOne = new ServerTaskId("Deployment-1"); packageJournal.RegisterPackageUse(thePackage, deploymentOne, 1); packageJournal.RemoveAllLocks(deploymentOne); Assert.AreEqual(1, journalRepository.GetUsage(thePackage).Count()); } [Test] public void WhenRetentionIsApplied_ThenPackageFileAndUsageAreRemoved() { var packageOne = CreatePackageIdentity("PackageOne", "1.0"); var retentionAlgorithm = Substitute.For<IRetentionAlgorithm>(); retentionAlgorithm.GetPackagesToRemove(Arg.Any<IEnumerable<JournalEntry>>()).Returns(new List<PackageIdentity>() { packageOne }); var fileSystem = Substitute.For<ICalamariFileSystem>(); fileSystem.FileExists(packageOne.Path.Value).Returns(true); var thisRepository = new InMemoryJournalRepository(); var thisJournal = new PackageJournal(thisRepository, Substitute.For<ILog>(), fileSystem, retentionAlgorithm, Substitute.For<ISemaphoreFactory>()); thisJournal.RegisterPackageUse(packageOne, new ServerTaskId("Deployment-1"), 1000); thisJournal.ApplyRetention(); thisRepository.GetUsage(packageOne).Should().BeEmpty(); fileSystem.Received().DeleteFile(packageOne.Path.Value, FailureOptions.IgnoreFailure); } [Test] public void WhenRetentionIsAppliedAndCacheSpaceIsNotSufficient_ThenPackageFileAndUsageAreRemoved() { var existingPackage = CreatePackageIdentity("PackageOne", "1.0"); var retentionAlgorithm = Substitute.For<IRetentionAlgorithm>(); retentionAlgorithm.GetPackagesToRemove(Arg.Any<IEnumerable<JournalEntry>>()).Returns(new List<PackageIdentity>() { existingPackage }); var fileSystem = Substitute.For<ICalamariFileSystem>(); fileSystem.FileExists(existingPackage.Path.Value).Returns(true); fileSystem.GetDiskFreeSpace(Arg.Any<string>(), out _) .Returns(x => { x[1] = 10000000000000; //lots of free disk space return true; }); var thisRepository = new InMemoryJournalRepository(); var thisJournal = new PackageJournal(thisRepository, Substitute.For<ILog>(), fileSystem, retentionAlgorithm, Substitute.For<ISemaphoreFactory>()); thisJournal.RegisterPackageUse(existingPackage, new ServerTaskId("Deployment-1"), 1 * 1024 * 1024); //Package is 1 MB thisJournal.ApplyRetention(); thisRepository.GetUsage(existingPackage).Should().BeEmpty(); fileSystem.Received().DeleteFile(existingPackage.Path.Value, FailureOptions.IgnoreFailure); } [Test] public void WhenRetentionIsAppliedAndCacheSpaceIsSufficientButDiskSpaceIsNot_ThenPackageFileAndUsageAreRemoved() { var existingPackage = CreatePackageIdentity("PackageOne", "1.0"); var retentionAlgorithm = Substitute.For<IRetentionAlgorithm>(); retentionAlgorithm.GetPackagesToRemove(Arg.Any<IEnumerable<JournalEntry>>()).Returns(new List<PackageIdentity>() { existingPackage }); var fileSystem = Substitute.For<ICalamariFileSystem>(); fileSystem.FileExists(existingPackage.Path.Value).Returns(true); fileSystem.GetDiskFreeSpace(Arg.Any<string>(), out _) .Returns(x => { x[1] = 0.5M; // 0.5MB free return true; }); var thisRepository = new InMemoryJournalRepository(); var thisJournal = new PackageJournal(thisRepository, Substitute.For<ILog>(), fileSystem, retentionAlgorithm, Substitute.For<ISemaphoreFactory>()); thisJournal.RegisterPackageUse(existingPackage, new ServerTaskId("Deployment-1"), 1 * 1024 * 1024); //Package is 1 MB thisJournal.ApplyRetention(); thisRepository.GetUsage(existingPackage).Should().BeEmpty(); fileSystem.Received().DeleteFile(existingPackage.Path.Value, FailureOptions.IgnoreFailure); } [Test] public void WhenStaleLocksAreExpired_TheLocksAreRemoved() { var thePackage = CreatePackageIdentity("Package", "1.0"); var anotherPackage = CreatePackageIdentity("Another-Package", "1.0"); var packageLocks = new PackageLocks { new UsageDetails(new ServerTaskId("Deployment-1"), new CacheAge(1), new DateTime(2021, 1, 1)), new UsageDetails(new ServerTaskId("Deployment-2"), new CacheAge(2), new DateTime(2021, 1, 2)) }; var journalEntry = new JournalEntry(thePackage, 1, packageLocks); var journalEntries = new Dictionary<PackageIdentity, JournalEntry>() { { thePackage, journalEntry }, { anotherPackage, new JournalEntry(anotherPackage, 1, new PackageLocks(), new PackageUsages())} }; var testJournalRepository = new InMemoryJournalRepository(journalEntries); var testJournal = new PackageJournal(testJournalRepository, Substitute.For<ILog>(), Substitute.For<ICalamariFileSystem>(), Substitute.For<IRetentionAlgorithm>(), Substitute.For<ISemaphoreFactory>()); testJournal.ExpireStaleLocks(TimeSpan.FromDays(14)); Assert.IsFalse(testJournalRepository.HasLock(thePackage)); } [Test] public void OnlyStaleLocksAreExpired() { var packageOne = CreatePackageIdentity("PackageOne", "1.0"); var packageTwo = CreatePackageIdentity("PackageTwo", "1.0"); var packageOneLocks = new PackageLocks { new UsageDetails(new ServerTaskId("Deployment-1"), new CacheAge(1), new DateTime(2021, 1, 1)), }; var packageTwoLocks = new PackageLocks { new UsageDetails(new ServerTaskId("Deployment-2"), new CacheAge(1), DateTime.Now), }; var packageOneJournalEntry = new JournalEntry(packageOne, 1, packageOneLocks); var packageTwoJournalEntry = new JournalEntry(packageTwo, 1, packageTwoLocks); var journalEntries = new Dictionary<PackageIdentity, JournalEntry>() { { packageOne, packageOneJournalEntry }, { packageTwo, packageTwoJournalEntry } }; var testJournalRepository = new InMemoryJournalRepository(journalEntries); var testJournal = new PackageJournal(testJournalRepository, Substitute.For<ILog>(), Substitute.For<ICalamariFileSystem>(), Substitute.For<IRetentionAlgorithm>(), Substitute.For<ISemaphoreFactory>()); testJournal.ExpireStaleLocks(TimeSpan.FromDays(14)); Assert.IsFalse(testJournalRepository.HasLock(packageOne)); Assert.IsTrue(testJournalRepository.HasLock(packageTwo)); } } }<file_sep>using System; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Common.Util; using Octopus.CoreUtilities.Extensions; namespace Calamari.AzureResourceGroup { class TemplateService { readonly ICalamariFileSystem fileSystem; readonly ITemplateResolver resolver; public TemplateService(ICalamariFileSystem fileSystem, ITemplateResolver resolver) { this.fileSystem = fileSystem; this.resolver = resolver; } public string GetSubstitutedTemplateContent(string relativePath, bool inPackage, IVariables variables) { return ResolveAndSubstituteFile(() => resolver.Resolve(relativePath, inPackage, variables).Value, fileSystem.ReadFile, variables); } string ResolveAndSubstituteFile(Func<string> resolvePath, Func<string, string> readContent, IVariables variables) { return resolvePath() .Map(readContent) .Map(variables.Evaluate); } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureServiceFabric.Behaviours { class CheckSdkInstalledBehaviour : IBeforePackageExtractionBehaviour { public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { if (!ServiceFabricHelper.IsServiceFabricSdkKeyInRegistry()) throw new CommandException("Could not find the Azure Service Fabric SDK on this server. This SDK is required before running Service Fabric commands."); return this.CompletedTask(); } } }<file_sep>using System; using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Conventions { public class CopyPackageToCustomInstallationDirectoryConvention : IInstallConvention { readonly ICalamariFileSystem fileSystem; public CopyPackageToCustomInstallationDirectoryConvention(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; } public void Install(RunningDeployment deployment) { var variables = deployment.Variables; string errorString; var customInstallationDirectory = variables.Get(PackageVariables.CustomInstallationDirectory, out errorString); var sourceDirectory = variables.Get(KnownVariables.OriginalPackageDirectoryPath); if (string.IsNullOrWhiteSpace(customInstallationDirectory)) { Log.Verbose("The package has been installed to: " + sourceDirectory); Log.Verbose("If you would like the package to be installed to an alternative location, please use the 'Custom installation directory' feature"); // If the variable was not set then we set it, as it makes it simpler for anything to depend on it from this point on variables.Set(PackageVariables.CustomInstallationDirectory, sourceDirectory); return; } Log.Verbose($"Installing package to custom directory {customInstallationDirectory}"); if (!string.IsNullOrEmpty(errorString)) { throw new CommandException( $"An error occurred when evaluating the value for the custom install directory. {errorString}"); } if (string.IsNullOrEmpty(Path.GetPathRoot(customInstallationDirectory))) { throw new CommandException( $"The custom install directory '{customInstallationDirectory}' is a relative path, please specify the path as an absolute path or a UNC path."); } if (customInstallationDirectory.IsChildOf(sourceDirectory)) { throw new CommandException( $"The custom install directory '{customInstallationDirectory}' is a child directory of the base installation directory '{sourceDirectory}', please specify a different destination."); } try { // Purge if requested if (variables.GetFlag( PackageVariables.CustomInstallationDirectoryShouldBePurgedBeforeDeployment)) { Log.Info("Purging the directory '{0}'", customInstallationDirectory); var purgeExlusions = variables.GetPaths(PackageVariables.CustomInstallationDirectoryPurgeExclusions).ToArray(); if (purgeExlusions.Any()) { Log.Info("Leaving files and directories that match any of: '{0}'", string.Join(", ", purgeExlusions)); } var globMode = GlobModeRetriever.GetFromVariables(variables); fileSystem.PurgeDirectory(deployment.CustomDirectory, FailureOptions.ThrowOnFailure, globMode, purgeExlusions); } // Copy files from staging area to custom directory Log.Info("Copying package contents to '{0}'", customInstallationDirectory); int count = fileSystem.CopyDirectory(deployment.StagingDirectory, deployment.CustomDirectory); Log.Info("Copied {0} files", count); // From this point on, the current directory will be the custom-directory deployment.CurrentDirectoryProvider = DeploymentWorkingDirectory.CustomDirectory; Log.SetOutputVariable(PackageVariables.Output.InstallationDirectoryPath, deployment.CustomDirectory, variables); Log.SetOutputVariable(PackageVariables.Output.DeprecatedInstallationDirectoryPath, deployment.CustomDirectory, variables); Log.SetOutputVariable(PackageVariables.Output.CopiedFileCount, count.ToString(), variables); } catch (UnauthorizedAccessException uae) when (uae.Message.StartsWith("Access to the path")) { var message = $"{uae.Message} Ensure that the application that uses this directory is not running."; if (CalamariEnvironment.IsRunningOnWindows) { message += " If this is an IIS website, stop the application pool or use an app_offline.htm file " + "(see https://g.octopushq.com/TakingWebsiteOffline)."; } throw new CommandException( message ); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Packages; using Calamari.Integration.Packages; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class FileNameEncoderFixture { [Test] [TestCase("Hello", "Hello", Description = "Standard no pecial characters")] [TestCase("Hel%lo", "Hel%25lo", Description = "Percent symbol in input (signal character)")] [TestCase("Hel%%lo", "Hel%25%25lo", Description = "Percent symbol in input")] [TestCase("Hel%25lo", "Hel%2525lo", Description = "Pre-encoded input double encoded")] [TestCase("Hel+lo", "Hel+lo", Description = "Url-unsafe but filename-safe character left alone")] [TestCase("1.0.1+beta", "1.0.1+beta", Description = "Standard version name unchanged")] public void Encode(string input, string expected) { Assert.AreEqual(expected, FileNameEscaper.Escape(input)); } [Test] public void AllInvalidCharactersEncoded() { var reallyUnsafeString = "H%<>:\"/\\|?I"; var encoded = FileNameEscaper.Escape(reallyUnsafeString); var encodedCharacters = FileNameEscaper.EscapedCharacters.ToList(); encodedCharacters.Remove('%'); //Since they are encoded with a % Assert.IsFalse(encoded.Any(encodedCharacters.Contains)); } [Test] [TestCase("Hello", "Hello")] [TestCase("Hel%25lo", "Hel%lo", Description = "Percent decoding (signal character)")] [TestCase("Hel%2Flo", "Hel/lo", Description = "Simple character decoding")] [TestCase("Hel%2F%5Clo", "Hel/\\lo", Description = "Double encoding decodes")] [TestCase("Hel+%/lo", "Hel+%/lo", Description = "Already invalid characters just pass through")] [TestCase("1.0.1+beta", "1.0.1+beta", Description = "Standard version name unchanged")] public void Decode(string input, string expected) { Assert.AreEqual(expected, FileNameEscaper.Unescape(input)); } } } <file_sep>using System; using Calamari.Testing.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Proxies { [TestFixture] public abstract class WindowsScriptProxyFixtureBase : ScriptProxyFixtureBase { protected abstract bool TestWebRequestDefaultProxy { get; } protected CalamariResult RunWith(bool useDefaultProxy, string proxyhost, int proxyPort, string proxyUsername, string proxyPassword, string proxyException) { Environment.SetEnvironmentVariable("TEST_ONLY_PROXY_EXCEPTION_URI", proxyException); return RunWith(useDefaultProxy, proxyhost, proxyPort, proxyUsername, proxyPassword); } [TearDown] public void ResetSystemProxy() { if (IsRunningOnWindows) ProxyRoutines.SetProxy(false).Should().BeTrue(); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public virtual void Initialize_HasSystemProxy_NoProxy() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); var result = RunWith(false, "", 80, "", ""); AssertProxyBypassed(result); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public virtual void Initialize_HasSystemProxy_UseSystemProxy() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); var result = RunWith(true, "", 80, "", ""); AssertUnauthenticatedSystemProxyUsed(result); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public virtual void Initialize_HasSystemProxy_UseSystemProxyWithExceptions() { var proxyException = "octopustestbypassurl.com"; var proxyExceptionUrl = $"http://{proxyException}/"; ProxyRoutines.SetProxy(proxyUrl, proxyException).Should().BeTrue(); var result = RunWith(true, "", 80, "", "", proxyExceptionUrl); AssertUnauthenticatedSystemProxyUsedWithException(result, proxyExceptionUrl); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public virtual void Initialize_HasSystemProxy_UseSystemProxyWithCredentials() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); var result = RunWith(true, "", 80, ProxyUserName, ProxyPassword); AssertAuthenticatedSystemProxyUsed(result); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public virtual void Initialize_HasSystemProxy_CustomProxy() { ProxyRoutines.SetProxy(BadproxyUrl).Should().BeTrue(); var result = RunWith(false, proxyHost, proxyPort, "", ""); AssertUnauthenticatedProxyUsed(result); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public virtual void Initialize_HasSystemProxy_CustomProxyWithCredentials() { ProxyRoutines.SetProxy(BadproxyUrl).Should().BeTrue(); var result = RunWith(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword); AssertAuthenticatedProxyUsed(result); } protected override void AssertAuthenticatedProxyUsed(CalamariResult output) { base.AssertAuthenticatedProxyUsed(output); if (IsRunningOnWindows && TestWebRequestDefaultProxy) // This can be either the authenticated or unauthenticated URL. The authentication part should be ignored output.AssertPropertyValue("WebRequest.DefaultProxy", proxyUrl + "/", authenticatedProxyUrl + "/"); } protected override void AssertUnauthenticatedProxyUsed(CalamariResult output) { base.AssertUnauthenticatedProxyUsed(output); if (IsRunningOnWindows && TestWebRequestDefaultProxy) // This can be either the authenticated or unauthenticated URL. The authentication part should be ignored output.AssertPropertyValue("WebRequest.DefaultProxy", proxyUrl + "/", authenticatedProxyUrl + "/"); } protected override void AssertNoProxyChanges(CalamariResult output) { base.AssertNoProxyChanges(output); if (IsRunningOnWindows && TestWebRequestDefaultProxy) output.AssertPropertyValue("WebRequest.DefaultProxy", "None"); } protected override void AssertProxyBypassed(CalamariResult output) { base.AssertProxyBypassed(output); if (IsRunningOnWindows && TestWebRequestDefaultProxy) output.AssertPropertyValue("WebRequest.DefaultProxy", "None"); } void AssertUnauthenticatedSystemProxyUsedWithException(CalamariResult output, string bypassedUrl) { AssertUnauthenticatedSystemProxyUsed(output); if (TestWebRequestDefaultProxy) output.AssertPropertyValue("ProxyBypassed", bypassedUrl); } void AssertUnauthenticatedSystemProxyUsed(CalamariResult output) { AssertUnauthenticatedProxyUsed(output); } void AssertAuthenticatedSystemProxyUsed(CalamariResult output) { AssertAuthenticatedProxyUsed(output); } } }<file_sep>updateprogress(50, "Half Way") <file_sep> using System.Collections.Generic; using System.Linq; using Amazon.S3.Model; using System; using System.Security.Cryptography; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Integration.FileSystem; using Calamari.Util; using Octopus.CoreUtilities; using Octopus.CoreUtilities.Extensions; using Tag = Amazon.S3.Model.Tag; namespace Calamari.Aws.Integration.S3 { public static class S3ObjectExtensions { //Special headers as per AWS docs - https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html private static readonly IDictionary<string, Func<HeadersCollection, string>> SupportedSpecialHeaders = new Dictionary<string, Func<HeadersCollection, string>>(StringComparer.OrdinalIgnoreCase) .WithHeaderFrom("Cache-Control", headers => headers.CacheControl) .WithHeaderFrom("Content-Disposition", headers => headers.ContentDisposition) .WithHeaderFrom("Content-Encoding", headers => headers.ContentEncoding) .WithHeaderFrom("Content-Type", headers => headers.ContentType) .WithHeaderFrom("Expires") .WithHeaderFrom("x-amz-website-redirect-location") .WithHeaderFrom("x-amz-object-lock-retain-until-date") .WithHeaderFrom("x-amz-object-lock-legal-hold") .WithHeaderFrom("x-amz-object-lock-mode"); private static T WithHeaderFrom<T>(this T values, string key) where T : IDictionary<string, Func<HeadersCollection, string>> { values.Add(key, (headers) => headers[key]); return values; } private static T WithHeaderFrom<T>(this T values, string key, Func<HeadersCollection, string> accessor) where T : IDictionary<string, Func<HeadersCollection, string>> { values.Add(key, accessor); return values; } public static IEnumerable<string> GetKnownSpecialHeaderKeys() { return SupportedSpecialHeaders.Keys; } public static bool MetadataEq(IDictionary<string, string> next, IDictionary<string, string> current) { var allKeys = next.Keys.Union(current.Keys).Distinct().ToList(); var keysInBoth = allKeys.Where(key => next.ContainsKey(key) && current.ContainsKey(key)).ToList(); var missingKeys = allKeys.Except(keysInBoth).ToList(); var differentValues = keysInBoth.Where(key => !string.Equals(next[key], current[key], StringComparison.OrdinalIgnoreCase)).ToList(); return missingKeys.Count == 0 && differentValues.Count == 0; } public static bool HasSameMetadata(this PutObjectRequest request, GetObjectMetadataResponse response) { return MetadataEq(request.ToCombinedMetadata(), response.ToCombinedMetadata()); } public static IDictionary<string, string> ToDictionary(this MetadataCollection collection) { return collection.Keys.ToDictionary(key => key, key => collection[key]); } public static IDictionary<string, string> GetCombinedMetadata(HeadersCollection headers, MetadataCollection metadata) { var result = new Dictionary<string, string>(); foreach (var key in headers.Keys.Where(SupportedSpecialHeaders.ContainsKey)) { result.Add(key, SupportedSpecialHeaders[key](headers)); } foreach (var key in metadata.Keys) { result.Add(key, metadata[key]); } return result; } public static IDictionary<string, string> ToCombinedMetadata(this PutObjectRequest request) { return GetCombinedMetadata(request.Headers, request.Metadata); } public static IDictionary<string, string> ToCombinedMetadata(this GetObjectMetadataResponse response) { return GetCombinedMetadata(response.Headers, response.Metadata); } public static List<Tag> ToTagSet(this IEnumerable<KeyValuePair<string, string>> source) { return source?.Select(x => new Tag {Key = x.Key.Trim(), Value = x.Value?.Trim()}).ToList() ?? new List<Tag>(); } public static PutObjectRequest WithMetadata(this PutObjectRequest request, IEnumerable<KeyValuePair<string, string>> source) { return request.Tee(x => { foreach (var item in source) { var key = item.Key.Trim(); if (!SupportedSpecialHeaders.ContainsKey(key)) { x.Metadata.Add(key, item.Value?.Trim()); } else { x.Headers[key] = item.Value?.Trim(); } } }); } public static PutObjectRequest WithMetadata(this PutObjectRequest request, IHaveMetadata source) { return request.WithMetadata(source.Metadata); } public static PutObjectRequest WithTags(this PutObjectRequest request, IHaveTags source) { return request.Tee(x => x.TagSet = source.Tags.ToTagSet()); } private static Maybe<byte[]> GetMd5Checksum(ICalamariFileSystem fileSystem, string path) { return !fileSystem.FileExists(path) ? Maybe<byte[]>.None : Maybe<byte[]>.Some(HashCalculator.Hash(path, MD5.Create)); } public static PutObjectRequest WithMd5Digest(this PutObjectRequest request, ICalamariFileSystem fileSystem, bool overwrite = false) { if (!string.IsNullOrEmpty(request.MD5Digest) && !overwrite) return request; var checksum = GetMd5Checksum(fileSystem, request.FilePath); if (!checksum.Some()) return request; request.MD5Digest = Convert.ToBase64String(checksum.Value); return request; } public static string Md5DigestToHexString(this PutObjectRequest request) { return Convert.FromBase64String(request.MD5Digest).Map(BinaryExtensions.ToHexString); } public static ETag GetEtag(this GetObjectMetadataResponse metadata) { return new ETag(metadata.ETag); } public static bool IsSameAsRequestMd5Digest(this ETag etag, PutObjectRequest request) { return string.Compare(etag.Hash, request.Md5DigestToHexString(), StringComparison.OrdinalIgnoreCase) == 0; } } } <file_sep>// Required to allow a service to run a process as another user // See http://stackoverflow.com/questions/677874/starting-a-process-with-credentials-from-a-windows-service/30687230#30687230 using System; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; namespace Calamari.Common.Features.Processes { public class WindowStationAndDesktopAccess { public static void GrantAccessToWindowStationAndDesktop(string username, string? domainName = null) { const int windowStationAllAccess = 0x000f037f; GrantAccess(username, domainName, GetProcessWindowStation(), windowStationAllAccess); const int desktopRightsAllAccess = 0x000f01ff; GrantAccess(username, domainName, GetThreadDesktop(GetCurrentThreadId()), desktopRightsAllAccess); } static void GrantAccess(string username, string? domainName, IntPtr handle, int accessMask) { SafeHandle safeHandle = new NoopSafeHandle(handle); var security = new GenericSecurity( false, ResourceType.WindowObject, safeHandle, AccessControlSections.Access); var account = string.IsNullOrEmpty(domainName) ? new NTAccount(username) : new NTAccount(domainName, username); security.AddAccessRule( new GenericAccessRule( account, accessMask, AccessControlType.Allow)); security.Persist(safeHandle, AccessControlSections.Access); } [DllImport("user32.dll", SetLastError = true)] static extern IntPtr GetProcessWindowStation(); [DllImport("user32.dll", SetLastError = true)] static extern IntPtr GetThreadDesktop(int dwThreadId); [DllImport("kernel32.dll", SetLastError = true)] static extern int GetCurrentThreadId(); // All the code to manipulate a security object is available in .NET framework, // but its API tries to be type-safe and handle-safe, enforcing a special implementation // (to an otherwise generic WinAPI) for each handle type. This is to make sure // only a correct set of permissions can be set for corresponding object types and // mainly that handles do not leak. // Hence the AccessRule and the NativeObjectSecurity classes are abstract. // This is the simplest possible implementation that yet allows us to make use // of the existing .NET implementation, sparing necessity to // P/Invoke the underlying WinAPI. class GenericAccessRule : AccessRule { public GenericAccessRule( IdentityReference identity, int accessMask, AccessControlType type) : base(identity, accessMask, false, InheritanceFlags.None, PropagationFlags.None, type) { } } class GenericSecurity : NativeObjectSecurity { public GenericSecurity( bool isContainer, ResourceType resType, SafeHandle objectHandle, AccessControlSections sectionsRequested) : base(isContainer, resType, objectHandle, sectionsRequested) { } public new void Persist(SafeHandle handle, AccessControlSections includeSections) { base.Persist(handle, includeSections); } public new void AddAccessRule(AccessRule rule) { base.AddAccessRule(rule); } #region NativeObjectSecurity Abstract Method Overrides public override Type AccessRightType => throw new NotImplementedException(); public override AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { throw new NotImplementedException(); } public override Type AccessRuleType => typeof(AccessRule); public override AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { throw new NotImplementedException(); } public override Type AuditRuleType => typeof(AuditRule); #endregion } // Handles returned by GetProcessWindowStation and GetThreadDesktop should not be closed class NoopSafeHandle : SafeHandle { public NoopSafeHandle(IntPtr handle) : base(handle, false) { } public override bool IsInvalid => false; protected override bool ReleaseHandle() { return true; } } } }<file_sep>using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Calamari.AzureWebApp.Tests")]<file_sep>namespace Calamari.Deployment.Retention { public interface IRetentionPolicy { void ApplyRetentionPolicy(string retentionPolicySet, int? days, int? releases); } }<file_sep>using System; namespace Calamari.Common.Features.ConfigurationTransforms { public delegate void LogDelegate(object sender); }<file_sep>#if USE_NUGET_V2_LIBS using System; using System.Collections.Concurrent; using System.Net; using NuGet; namespace Calamari.Integration.Packages.Download { public class FeedCredentialsProvider : ICredentialProvider { FeedCredentialsProvider() { } public static FeedCredentialsProvider Instance = new FeedCredentialsProvider(); static readonly ConcurrentDictionary<string, ICredentials> Credentials = new ConcurrentDictionary<string, ICredentials>(); static readonly ConcurrentDictionary<string, RetryTracker> Retries = new ConcurrentDictionary<string, RetryTracker>(); public void SetCredentials(Uri uri, ICredentials credential) { Credentials[Canonicalize(uri)] = credential; } public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying) { var url = Canonicalize(uri); var retry = Retries.GetOrAdd(url, _ => new RetryTracker()); if (!retrying) { retry.Reset(); } else { var retryAllowed = retry.AttemptRetry(); if (!retryAllowed) return null; } return new DynamicCachedCredential(url); } ICredentials GetCurrentCredentials(string url) { ICredentials credential; if (!Credentials.TryGetValue(url, out credential)) { credential = CredentialCache.DefaultNetworkCredentials; } return credential; } string Canonicalize(Uri uri) { return uri.Authority.ToLowerInvariant().Trim(); } public class RetryTracker { const int MaxAttempts = 3; int currentCount; public bool AttemptRetry() { if (currentCount > MaxAttempts) return false; currentCount++; return true; } public void Reset() { currentCount = 0; } } class DynamicCachedCredential : CredentialCache, ICredentials { readonly string url; public DynamicCachedCredential(string url) { this.url = url; } NetworkCredential ICredentials.GetCredential(Uri uri, string authType) { var credential = Instance.GetCurrentCredentials(url); return credential.GetCredential(uri, authType); } } } } #endif<file_sep>using System; using System.Threading; using System.Threading.Tasks; using Calamari.Common.Plumbing.Logging; namespace Calamari.Testing.Helpers { public static class Eventually { public static async Task ShouldEventually(Action action, ILog log, CancellationToken cancellationToken) { Task WrappedAction(CancellationToken ct) => Task.Run(action, ct).WithCancellationToken(cancellationToken); await ShouldEventually(WrappedAction, log, cancellationToken); } public static async Task ShouldEventually(Func<Task> action, ILog log, CancellationToken cancellationToken) { Task WrappedAction(CancellationToken ct) => Task.Run(action, ct).WithCancellationToken(ct); await ShouldEventually(WrappedAction, log, cancellationToken); } public static async Task ShouldEventually(Func<CancellationToken, Task> action, ILog log, CancellationToken cancellationToken) { var strategy = new EventuallyStrategy(log); await strategy.ShouldEventually(action, cancellationToken); } public static async Task ShouldEventually(Func<CancellationToken, Task> action, EventuallyStrategy.Timing timing, ILog log, CancellationToken cancellationToken) { var strategy = new EventuallyStrategy(log, timing); await strategy.ShouldEventually(action, cancellationToken); } } } <file_sep>using System; using System.IO; using System.Text.Json; using Azure.Core; using Azure.Core.Pipeline; namespace Calamari.AzureAppService.Azure { /// <remarks> /// Based on: https://github.com/Azure/azure-sdk-for-net/issues/33384#issuecomment-1428080542 /// </remarks> public class SlotConfigNamesInvalidIdFilterPolicy : HttpPipelineSynchronousPolicy { public override void OnReceivedResponse(HttpMessage message) { if (!message.Request.Uri.Path.EndsWith("slotconfignames", StringComparison.OrdinalIgnoreCase) || message.Response.ContentStream == null) // Change here to get the expected response { return; } using var reader = new StreamReader(message.Response.ContentStream); // rewrite the null id with the request path which is a valid id var content = reader.ReadToEnd().Replace("\"id\":null", $"\"id\":\"{message.Request.Uri.Path}\""); // Assign a valid value to the property id //rewrite the response as JSON var jsonDocument = JsonDocument.Parse(content); var stream = new MemoryStream(); var writer = new Utf8JsonWriter(stream); jsonDocument.WriteTo(writer); writer.Flush(); //reset the content stream result message.Response.ContentStream = stream; message.Response.ContentStream.Position = 0; } } }<file_sep>using System; using System.ComponentModel; using System.Globalization; using Calamari.Deployment.PackageRetention; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public class TinyTypeTypeConverter<T> : TypeConverter where T : CaseInsensitiveTinyType { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (!CanConvertFrom(context, value.GetType())) { throw new Exception($"Cannot convert {value.GetType().Name} to {typeof(T).Name}."); } return CaseInsensitiveTinyType.Create<T>((string)value); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Calamari.Commands.Support; using Calamari.Common; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Testing; using Calamari.Testing.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.NewPipeline { /// <summary> /// Ensures that in both CalamariFlavour programs, we can fall back to the correct file replacer /// for Structured Variable Replacement when the file extension of the target file doesn't match the /// canonical extension for the replacer /// </summary> /// <remarks> /// We don't support content-based fallback for Java Properties files. They must have the .properties extension. /// /// Because of the lack of an actual standard for .properties file (it's basically a glorified set of /// key/value pairs, with very loose rules around content), it's not possible to distinguish between /// a YAML and a Properties file via parsers alone. Properties files will (almost) always succeed in /// the YAML parser. Given the relative improbability of needing to replace a properties file that /// doesn't have the .properties extension, and the relative ubiquity of YAML under a variety of /// extensions, this is a known and accepted constraint. /// </remarks> [TestFixture] public class CalamariFlavourProgramStructuredVariableReplacementFixture { [Test] [TestCase("web.config", "/app/port", "Xml")] [TestCase("json.txt", "app:port", "Json")] [TestCase("yaml.txt", "app:port", "Yaml")] public async Task CalamariFlavourProgram_PerformsReplacementCorrectlyWithoutCanonicalFileExtension(string configFileName, string variableName, string expectedReplacer) { const string newPort = "4444"; using (var tempPath = TemporaryDirectory.Create()) { var targetPath = Path.Combine(tempPath.DirectoryPath, configFileName); File.Copy(BuildConfigPath(configFileName), targetPath); await CommandTestBuilder.Create<NoOpTraditionalCommandWithStructuredVariableReplacementConvention, SyncFlavourProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); context.Variables.Add(ActionVariables.StructuredConfigurationVariablesTargets, configFileName); context.Variables.Add(variableName, newPort); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { //result.FullLog.Should().Contain($"Structured variable replacement succeeded on file {targetPath} with format {expectedReplacer}"); File.ReadAllText(targetPath).Should().Contain(newPort); }) .Execute(); } } [Test] [TestCase("web.config", "/app/port", "Xml")] [TestCase("json.txt", "app:port", "Json")] [TestCase("yaml.txt", "app:port", "Yaml")] public async Task CalamariFlavourProgramAsync_PerformsReplacementCorrectlyWithoutCanonicalFileExtension(string configFileName, string variableName, string expectedReplacer) { const string newPort = "4444"; using (var tempPath = TemporaryDirectory.Create()) { var targetPath = Path.Combine(tempPath.DirectoryPath, configFileName); File.Copy(BuildConfigPath(configFileName), targetPath); await CommandTestBuilder.CreateAsync<NoOpPipelineCommand, AsyncFlavourProgram>() .WithArrange(context => { context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); context.Variables.Add(ActionVariables.StructuredConfigurationVariablesTargets, configFileName); context.Variables.Add(variableName, newPort); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { result.FullLog.Should().Contain($"Structured variable replacement succeeded on file {targetPath} with format {expectedReplacer}"); File.ReadAllText(targetPath).Should().Contain(newPort); }) .Execute(); } } static string BuildConfigPath(string filename) { var path = typeof(CalamariFlavourProgramStructuredVariableReplacementFixture).Namespace.Replace("Calamari.Tests.", string.Empty); path = path.Replace('.', Path.DirectorySeparatorChar); var workingDirectory = Path.Combine(TestEnvironment.CurrentWorkingDirectory, path, "Config"); if (string.IsNullOrEmpty(filename)) return workingDirectory; return Path.Combine(workingDirectory, filename.Replace('\\', Path.DirectorySeparatorChar)); } class AsyncFlavourProgram : CalamariFlavourProgramAsync { public AsyncFlavourProgram(ILog log) : base(log) { } } [Command("no-op-command")] class NoOpPipelineCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<EmptyBehaviour>(); } } class SyncFlavourProgram : CalamariFlavourProgram { public SyncFlavourProgram(ILog log) : base(log) { } } [Command("no-op-command")] class NoOpTraditionalCommandWithStructuredVariableReplacementConvention : Command, ICommand { readonly IStructuredConfigVariablesService structuredConfigVariablesService; readonly ILog log; readonly IVariables variables; public NoOpTraditionalCommandWithStructuredVariableReplacementConvention( ILog log, IVariables variables, IStructuredConfigVariablesService structuredConfigVariablesService) { this.structuredConfigVariablesService = structuredConfigVariablesService; this.log = log; this.variables = variables; } public override int Execute(string[] commandLineArguments) { return Execute(); } public int Execute() { var deployment = new RunningDeployment(variables); var conventions = new List<IConvention> { new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(structuredConfigVariablesService)) }; var conventionRunner = new ConventionProcessor(deployment, conventions, log); conventionRunner.RunConventions(); return 0; } } class EmptyBehaviour : IDeployBehaviour { public bool IsEnabled(RunningDeployment context) { return false; } public Task Execute(RunningDeployment context) { throw new NotImplementedException(); } } } }<file_sep>namespace Calamari.AzureWebApp.Integration.Websites.Publishing { class WebDeployPublishSettings { /// <summary> /// The deployment site name may be different for web deploy especially when using slots. This may /// end up as something like slotname___sitename and is what needs to be provided to web deploy. /// </summary> public string DeploymentSite { get; } public SitePublishProfile PublishProfile { get; } public WebDeployPublishSettings(string deploymentSite, SitePublishProfile publishProfile) { DeploymentSite = deploymentSite; PublishProfile = publishProfile; } } }<file_sep>using System; using Calamari.Common.Plumbing.Variables; using Calamari.Common.Util; using Octopus.CoreUtilities.Extensions; namespace Calamari.Util { public class TemplateReplacement : ITemplateReplacement { private readonly ITemplateResolver resolver; public TemplateReplacement(ITemplateResolver resolver) { this.resolver = resolver; } public string ResolveAndSubstituteFile(Func<string, string> readContent, string relativeFilePath, bool inPackage, IVariables variables) { return ResolveAndSubstituteFile( () => resolver.Resolve(relativeFilePath, inPackage, variables).Value, readContent, variables); } public string ResolveAndSubstituteFile(Func<string> resolvePath, Func<string, string> readContent, IVariables variables) { return resolvePath() .Map(readContent) .Map(variables.Evaluate); } } }<file_sep>using System; using Assent; namespace Calamari.Tests.Helpers { public class CIAssentNamer : INamer { private readonly string postfix; public CIAssentNamer(string postfix = null) { this.postfix = postfix; } public string GetName(TestMetadata metadata) { var name = $"{metadata.TestFixture.GetType().Name}.{metadata.TestName}"; if (postfix != null) { name += $".{postfix}"; } return CalamariFixture.GetFixtureResource( metadata.TestFixture.GetType(), "Approved", name ); } } }<file_sep>namespace Calamari.AzureResourceGroup { static class SpecialVariables { public static class Action { public static class Azure { public static readonly string ResourceGroupTemplate = "Octopus.Action.Azure.ResourceGroupTemplate"; public static readonly string ResourceGroupTemplateParameters = "Octopus.Action.Azure.ResourceGroupTemplateParameters"; public static readonly string ResourceGroupName = "Octopus.Action.Azure.ResourceGroupName"; public static readonly string ResourceGroupDeploymentName = "Octopus.Action.Azure.ResourceGroupDeploymentName"; public static readonly string ResourceGroupDeploymentMode = "Octopus.Action.Azure.ResourceGroupDeploymentMode"; public static readonly string Template = "Octopus.Action.Azure.Template"; public static readonly string TemplateParameters = "Octopus.Action.Azure.TemplateParameters"; public static readonly string TemplateSource = "Octopus.Action.Azure.TemplateSource"; } } } }<file_sep>using System; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Commands { [Command("release-package-lock", Description = "Releases a given package lock for a specific task ID.")] public class ReleasePackageLockCommand : Command { readonly IVariables variables; readonly ILog log; readonly IManagePackageCache journal; readonly TimeSpan defaultTimeBeforeLockExpiration = TimeSpan.FromDays(14); ServerTaskId taskId; public ReleasePackageLockCommand(IVariables variables, IManagePackageCache journal, ILog log) { this.variables = variables; this.log = log; this.journal = journal; Options.Add("taskId=", "Id of the task that is using the package", v => taskId = new ServerTaskId(v)); } TimeSpan GetTimeBeforeLockExpiration() { var expirationVariable = variables.Get(KnownVariables.Calamari.PackageRetentionLockExpiration); return TimeSpan.TryParse(expirationVariable, out var timeBeforeLockExpiration) ? timeBeforeLockExpiration : defaultTimeBeforeLockExpiration; } public override int Execute(string[] commandLineArguments) { try { Options.Parse(commandLineArguments); journal.RemoveAllLocks(taskId); } catch (Exception ex) { log.ErrorFormat("Failed to release package locks"); return ConsoleFormatter.PrintError(log, ex); } journal.ExpireStaleLocks(GetTimeBeforeLockExpiration()); return 0; } } }<file_sep>using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; namespace Calamari.Deployment.Features.Java.Actions { public class TomcatStateAction : JavaAction { public TomcatStateAction(JavaRunner runner): base(runner) { } public override void Execute(RunningDeployment deployment) { var variables = deployment.Variables; Log.Info("Updating Tomcat state"); runner.Run("com.octopus.calamari.tomcat.TomcatState", new Dictionary<string, string>() { {"OctopusEnvironment_Tomcat_Deploy_Name", variables.Get(SpecialVariables.Action.Java.Tomcat.DeployName)}, {"OctopusEnvironment_Tomcat_Deploy_Version", variables.Get(SpecialVariables.Action.Java.Tomcat.Version)}, {"OctopusEnvironment_Tomcat_Deploy_Controller", variables.Get(SpecialVariables.Action.Java.Tomcat.Controller)}, {"OctopusEnvironment_Tomcat_Deploy_User", variables.Get(SpecialVariables.Action.Java.Tomcat.User)}, {"OctopusEnvironment_Tomcat_Deploy_Password", variables.Get(SpecialVariables.Action.Java.Tomcat.Password)}, {"OctopusEnvironment_Tomcat_Deploy_Enabled", variables.Get(SpecialVariables.Action.Java.Tomcat.Enabled)}, }); } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using Microsoft.Win32.SafeHandles; namespace Calamari.Integration.Certificates.WindowsNative { internal class SafeCspHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeCspHandle() : base(true) { } [DllImport("advapi32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptContextAddRef(SafeCspHandle hProv, IntPtr pdwReserved, int dwFlags); [DllImport("advapi32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptReleaseContext(IntPtr hProv, int dwFlags); public SafeCspHandle Duplicate() { bool success = false; RuntimeHelpers.PrepareConstrainedRegions(); try { this.DangerousAddRef(ref success); IntPtr handle = this.DangerousGetHandle(); int hr = 0; SafeCspHandle safeCspHandle = new SafeCspHandle(); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (!SafeCspHandle.CryptContextAddRef(this, IntPtr.Zero, 0)) hr = Marshal.GetLastWin32Error(); else safeCspHandle.SetHandle(handle); } if (hr != 0) { safeCspHandle.Dispose(); throw new CryptographicException(hr); } return safeCspHandle; } finally { if (success) this.DangerousRelease(); } } protected override bool ReleaseHandle() { return SafeCspHandle.CryptReleaseContext(this.handle, 0); } } } #endif<file_sep>using System; namespace Calamari.Common.Plumbing.Retry { /// <summary> /// Implements exponential backoff timing for retry trackers /// </summary> /// <remarks> /// e.g. For network operations, try again after 100ms, then double interval up to 5 seconds /// new LimitedExponentialRetryInterval(100, 5000, 2); /// </remarks> public class LimitedExponentialRetryInterval : RetryInterval { readonly int retryInterval; readonly int maxInterval; readonly double multiplier; public LimitedExponentialRetryInterval(int retryInterval, int maxInterval, double multiplier) { this.retryInterval = retryInterval; this.maxInterval = maxInterval; this.multiplier = multiplier; } public override TimeSpan GetInterval(int retryCount) { var delayTime = retryInterval * Math.Pow(multiplier, retryCount); if (delayTime > maxInterval) return TimeSpan.FromMilliseconds(maxInterval); return TimeSpan.FromMilliseconds((int)delayTime); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Commands; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Kubernetes.Conventions; namespace Calamari.Kubernetes.Commands { [Command("helm-upgrade", Description = "Performs Helm Upgrade with Chart while performing variable replacement")] public class HelmUpgradeCommand : Command { PathToPackage pathToPackage; readonly ILog log; readonly IScriptEngine scriptEngine; readonly IDeploymentJournalWriter deploymentJournalWriter; readonly IVariables variables; readonly ICalamariFileSystem fileSystem; readonly ISubstituteInFiles substituteInFiles; readonly IExtractPackage extractPackage; readonly ICommandLineRunner commandLineRunner; public HelmUpgradeCommand( ILog log, IScriptEngine scriptEngine, IDeploymentJournalWriter deploymentJournalWriter, IVariables variables, ICommandLineRunner commandLineRunner, ICalamariFileSystem fileSystem, ISubstituteInFiles substituteInFiles, IExtractPackage extractPackage ) { Options.Add("package=", "Path to the NuGet package to install.", v => pathToPackage = new PathToPackage(Path.GetFullPath(v))); this.log = log; this.scriptEngine = scriptEngine; this.deploymentJournalWriter = deploymentJournalWriter; this.variables = variables; this.fileSystem = fileSystem; this.substituteInFiles = substituteInFiles; this.extractPackage = extractPackage; this.commandLineRunner = commandLineRunner; } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); if (!File.Exists(pathToPackage)) throw new CommandException("Could not find package file: " + pathToPackage); var conventions = new List<IConvention> { new DelegateInstallConvention(d => extractPackage.ExtractToStagingDirectory(pathToPackage)), new StageScriptPackagesConvention(null, fileSystem, new CombinedPackageExtractor(log, variables, commandLineRunner), true), new ConfiguredScriptConvention(new PreDeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), // Any values.yaml files in any packages referenced by the step will automatically have variable substitution applied (we won't log a warning if these aren't present) new DelegateInstallConvention(d => substituteInFiles.Substitute(d.CurrentDirectory, DefaultValuesFiles().ToList(), false)), // Any values files explicitly specified by the user will also have variable substitution applied new DelegateInstallConvention(d => substituteInFiles.Substitute(d.CurrentDirectory, ExplicitlySpecifiedValuesFiles().ToList(), true)), new ConfiguredScriptConvention(new DeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)), new HelmUpgradeConvention(log, scriptEngine, commandLineRunner, fileSystem), new ConfiguredScriptConvention(new PostDeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)) }; var deployment = new RunningDeployment(pathToPackage, variables); var conventionRunner = new ConventionProcessor(deployment, conventions, log); try { conventionRunner.RunConventions(); deploymentJournalWriter.AddJournalEntry(deployment, true, pathToPackage); } catch (Exception) { deploymentJournalWriter.AddJournalEntry(deployment, false, pathToPackage); throw; } return 0; } /// <summary> /// Any values.yaml files in any packages referenced by the step will automatically have variable substitution applied /// </summary> IEnumerable<string> DefaultValuesFiles() { var packageReferenceNames = variables.GetIndexes(PackageVariables.PackageCollection); foreach (var packageReferenceName in packageReferenceNames) { yield return Path.Combine(PackageDirectory(packageReferenceName), "values.yaml"); } } /// <summary> /// Any values files explicitly specified by the user will also have variable substitution applied /// </summary> IEnumerable<string> ExplicitlySpecifiedValuesFiles() { var packageReferenceNames = variables.GetIndexes(PackageVariables.PackageCollection); foreach (var packageReferenceName in packageReferenceNames) { var paths = variables.GetPaths(SpecialVariables.Helm.Packages.ValuesFilePath(packageReferenceName)); foreach (var path in paths) { yield return Path.Combine(PackageDirectory(packageReferenceName), path); } } } string PackageDirectory(string packageReferenceName) { var packageRoot = packageReferenceName; if (string.IsNullOrEmpty(packageReferenceName)) { packageRoot = variables.Get(PackageVariables.IndexedPackageId(packageReferenceName ?? "")); } return fileSystem.RemoveInvalidFileNameChars(packageRoot ?? string.Empty); } } }<file_sep>print("V1={}".format(octopusvariables['Variable1'])) print("V2={}".format(octopusvariables['Variable2'])) print("V3={}".format(octopusvariables['Variable3'])) print("Foo_bar={}".format(octopusvariables['Foo_bar']))<file_sep>using System; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; namespace Calamari.AzureAppService.Azure { class ServicePrincipalAccount { [JsonConstructor] public ServicePrincipalAccount( string subscriptionNumber, string clientId, string tenantId, string password, string azureEnvironment, string resourceManagementEndpointBaseUri, string activeDirectoryEndpointBaseUri) { this.SubscriptionNumber = subscriptionNumber; this.ClientId = clientId; this.TenantId = tenantId; this.Password = <PASSWORD>; this.AzureEnvironment = azureEnvironment; this.ResourceManagementEndpointBaseUri = resourceManagementEndpointBaseUri; this.ActiveDirectoryEndpointBaseUri = activeDirectoryEndpointBaseUri; } public static ServicePrincipalAccount CreateFromKnownVariables(IVariables variables) => new ServicePrincipalAccount( subscriptionNumber: variables.Get(AccountVariables.SubscriptionId), clientId: variables.Get(AccountVariables.ClientId), tenantId: variables.Get(AccountVariables.TenantId), password: variables.Get(AccountVariables.Password), azureEnvironment: variables.Get(AccountVariables.Environment), resourceManagementEndpointBaseUri: variables.Get(AccountVariables.ResourceManagementEndPoint, DefaultVariables.ResourceManagementEndpoint), activeDirectoryEndpointBaseUri: variables.Get(AccountVariables.ActiveDirectoryEndPoint, DefaultVariables.ActiveDirectoryEndpoint)); public string SubscriptionNumber { get; } public string ClientId { get; } public string TenantId { get; } public string Password { get; } public string AzureEnvironment { get; } public string ResourceManagementEndpointBaseUri { get; } public string ActiveDirectoryEndpointBaseUri { get; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace Calamari.Serialization { public abstract class InheritedClassConverter<TBaseResource, TEnumType> : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteStartObject(); var contractResolver = serializer.ContractResolver; foreach (var property in value.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty) .Where(p => p.CanRead)) { writer.WritePropertyName(getMappedPropertyName(contractResolver, property.Name)); serializer.Serialize(writer, property.GetValue(value, null)); } WriteTypeProperty(writer, value, serializer); writer.WriteEndObject(); } protected virtual void WriteTypeProperty(JsonWriter writer, object value, JsonSerializer serializer) { } protected virtual Type? DefaultType { get; } = null; private static string getMappedPropertyName(IContractResolver resolver, string name) { return resolver is DefaultContractResolver result ? result.GetResolvedPropertyName(name) : name; } public override object? ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; var jo = JObject.Load(reader); var contractResolver = serializer.ContractResolver; var designatingProperty = jo.GetValue(getMappedPropertyName(contractResolver, TypeDesignatingPropertyName)); Type type; if (designatingProperty == null) { if (DefaultType == null) { throw new Exception($"Unable to determine type to deserialize. Missing property `{TypeDesignatingPropertyName}`"); } type = DefaultType; } else { var derivedType = designatingProperty.ToObject<string>(); var enumType = (TEnumType)Enum.Parse(typeof(TEnumType), derivedType); if (!DerivedTypeMappings.ContainsKey(enumType)) { throw new Exception($"Unable to determine type to deserialize. {TypeDesignatingPropertyName} `{enumType}` does not map to a known type"); } type = DerivedTypeMappings[enumType]; } var ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance).Single(); var args = ctor.GetParameters().Select(p => jo.GetValue(char.ToUpper(p.Name[0]) + p.Name.Substring(1)) .ToObject(p.ParameterType, serializer)).ToArray(); var instance = ctor.Invoke(args); foreach (var prop in type .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty) .Where(p => p.CanWrite)) { var propertyName = getMappedPropertyName(contractResolver, prop.Name); var val = jo.GetValue(propertyName); if (val != null) { prop.SetValue(instance, val.ToObject(prop.PropertyType, serializer), null); } } return instance; } public override bool CanConvert(Type objectType) { return typeof(TBaseResource).IsAssignableFrom(objectType); } protected abstract IDictionary<TEnumType, Type> DerivedTypeMappings { get; } protected abstract string TypeDesignatingPropertyName { get; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.Packages.Download; using Calamari.Integration.Time; namespace Calamari.Deployment.Retention { public class RetentionPolicy : IRetentionPolicy { static readonly IPackageDownloaderUtils PackageDownloaderUtils = new PackageDownloaderUtils(); readonly ICalamariFileSystem fileSystem; readonly IDeploymentJournal deploymentJournal; readonly IClock clock; public RetentionPolicy(ICalamariFileSystem fileSystem, IDeploymentJournal deploymentJournal, IClock clock) { this.fileSystem = fileSystem; this.deploymentJournal = deploymentJournal; this.clock = clock; } public void ApplyRetentionPolicy(string retentionPolicySet, int? daysToKeep, int? successfulDeploymentsToKeep) { var deploymentsToDelete = deploymentJournal .GetAllJournalEntries() .Where(x => x.RetentionPolicySet == retentionPolicySet) .ToList(); var preservedEntries = new List<JournalEntry>(); if (daysToKeep.HasValue && daysToKeep.Value > 0) { Log.Info($"Keeping deployments from the last {daysToKeep} days"); deploymentsToDelete = deploymentsToDelete .Where(InstalledBeforePolicyDayCutoff(daysToKeep.Value, preservedEntries)) .ToList(); } else if (successfulDeploymentsToKeep.HasValue && successfulDeploymentsToKeep.Value > 0) { Log.Info($"Keeping this deployment and the previous {successfulDeploymentsToKeep} successful deployments"); // Keep the current deployment, plus specified deployment value // Unsuccessful deployments are not included in the count of deployment to keep deploymentsToDelete = deploymentsToDelete .OrderByDescending(deployment => deployment.InstalledOn) .Where(SuccessfulCountGreaterThanPolicyCountOrDeployedUnsuccessfully(successfulDeploymentsToKeep.Value, preservedEntries)) .ToList(); if (preservedEntries.Count <= successfulDeploymentsToKeep) deploymentsToDelete = new List<JournalEntry>(); } else { Log.Info("Keeping all deployments"); return; } if (!deploymentsToDelete.Any()) { Log.Info("Did not find any deployments to clean up"); } foreach (var deployment in deploymentsToDelete) { DeleteExtractionDestination(deployment, preservedEntries); // Deleting packages is now handled by package retention } deploymentJournal.RemoveJournalEntries(deploymentsToDelete.Select(x => x.Id)); RemovedFailedPackageDownloads(); } void DeleteExtractionDestination(JournalEntry deployment, List<JournalEntry> preservedEntries) { if (string.IsNullOrWhiteSpace(deployment.ExtractedTo) || !fileSystem.DirectoryExists(deployment.ExtractedTo) || preservedEntries.Any(entry => deployment.ExtractedTo.Equals(entry.ExtractedTo, StringComparison.Ordinal))) return; Log.Info($"Removing directory '{deployment.ExtractedTo}'"); fileSystem.PurgeDirectory(deployment.ExtractedTo, FailureOptions.IgnoreFailure); try { fileSystem.DeleteDirectory(deployment.ExtractedTo); } catch (Exception ex) { Log.VerboseFormat("Could not delete directory '{0}' because some files could not be deleted: {1}", deployment.ExtractedTo, ex.Message); } } static Func<JournalEntry, bool> SuccessfulCountGreaterThanPolicyCountOrDeployedUnsuccessfully(int successfulDeploymentsToKeep, List<JournalEntry> preservedEntries) { return journalEntry => { if (journalEntry.WasSuccessful && preservedEntries.Count <= successfulDeploymentsToKeep) { preservedEntries.Add(journalEntry); var preservedDirectories = (!string.IsNullOrEmpty(journalEntry.ExtractedTo) ? new List<string> { journalEntry.ExtractedTo } : new List<string>()) .Concat(journalEntry.Packages.Select(p => p.DeployedFrom).Where(d => !string.IsNullOrEmpty(d))) .ToList(); Log.Verbose($"Keeping {FormatList(preservedDirectories)} as it is the {FormatWithThPostfix(preservedEntries.Count)}most recent successful release"); return false; } return true; }; } Func<JournalEntry, bool> InstalledBeforePolicyDayCutoff(int days, List<JournalEntry> preservedEntries) { return journalEntry => { var installedAgo = (clock.GetUtcTime() - journalEntry.InstalledOn); if (journalEntry.InstalledOn == null) return false; if (installedAgo?.TotalDays > days) return true; var preservedDirectories = (!string.IsNullOrEmpty(journalEntry.ExtractedTo) ? new List<string> { journalEntry.ExtractedTo } : new List<string>()) .Concat(journalEntry.Packages.Select(p => p.DeployedFrom).Where(p => !string.IsNullOrEmpty(p))) .ToList(); Log.Verbose($"Keeping {FormatList(preservedDirectories)} as it was installed {installedAgo?.Days} days and {installedAgo?.Hours} hours ago"); preservedEntries.Add(journalEntry); return false; }; } static string FormatList(IList<string> items) { if (items.Count <= 1) return $"{items.FirstOrDefault() ?? ""}"; return string.Join(", ", items.Take(items.Count - 1)) + $" and {items[items.Count - 1]}"; } static string FormatWithThPostfix(int value) { if (value == 1) return ""; if (value == 11 || value == 12 || value == 13) return value + "th "; switch (value % 10) { case 1: return value + "st "; case 2: return value + "nd "; case 3: return value + "rd "; default: return value + "th "; } } void RemovedFailedPackageDownloads() { var pattern = "*" + NuGetPackageDownloader.DownloadingExtension; if (fileSystem.DirectoryExists(PackageDownloaderUtils.RootDirectory)) { var toDelete = fileSystem.EnumerateFilesRecursively(PackageDownloaderUtils.RootDirectory, pattern) .Where(f => fileSystem.GetCreationTime(f) <= DateTime.Now.AddDays(-1)) .ToArray(); foreach (var file in toDelete) { Log.Verbose($"Removing the failed to download file {file}"); fileSystem.DeleteFile(file, FailureOptions.IgnoreFailure); } } } } }<file_sep>using Calamari.Common.Features.Processes.Semaphores; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { [TestFixture] public class SystemSemaphoreFixture : SemaphoreFixtureBase { [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void SystemSemaphoreWaitsUntilFirstSemaphoreIsReleased() { SecondSemaphoreWaitsUntilFirstSemaphoreIsReleased(new SystemSemaphoreManager()); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void SystemSemaphoreShouldIsolate() { ShouldIsolate(new SystemSemaphoreManager()); } } }<file_sep>namespace Calamari.AzureCloudService { static class SpecialVariables { public static class Action { public static class Azure { public static readonly string Environment = "Octopus.Action.Azure.Environment"; public static readonly string CloudServiceName = "Octopus.Action.Azure.CloudServiceName"; public static readonly string ServiceManagementEndPoint = "Octopus.Action.Azure.ServiceManagementEndPoint"; public static readonly string SubscriptionId = "Octopus.Action.Azure.SubscriptionId"; public static readonly string CertificateBytes = "Octopus.Action.Azure.CertificateBytes"; public static readonly string CertificateThumbprint = "Octopus.Action.Azure.CertificateThumbprint"; public static readonly string CloudServicePackagePath = "Octopus.Action.Azure.CloudServicePackagePath"; public static readonly string CloudServicePackageExtractionDisabled = "Octopus.Action.Azure.CloudServicePackageExtractionDisabled"; public static readonly string LogExtractedCspkg = "Octopus.Action.Azure.LogExtractedCspkg"; public static readonly string PackageExtractionPath = "Octopus.Action.Azure.PackageExtractionPath"; public static readonly string CloudServiceConfigurationFileRelativePath = "Octopus.Action.Azure.CloudServiceConfigurationFileRelativePath"; public static readonly string UseCurrentInstanceCount = "Octopus.Action.Azure.UseCurrentInstanceCount"; public static readonly string StorageEndPointSuffix = "Octopus.Action.Azure.StorageEndpointSuffix"; public static readonly string UploadedPackageUri = "Octopus.Action.Azure.UploadedPackageUri"; public static readonly string DeploymentLabel = "Octopus.Action.Azure.DeploymentLabel"; public static readonly string Slot = "Octopus.Action.Azure.Slot"; public static readonly string SwapIfPossible = "Octopus.Action.Azure.SwapIfPossible"; public static readonly string StorageAccountName = "Octopus.Action.Azure.StorageAccountName"; public static class Output { public static readonly string CloudServiceDeploymentSwapped = "OctopusAzureCloudServiceDeploymentSwapped"; public static readonly string ConfigurationFile = "OctopusAzureConfigurationFile"; } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Deployment.PackageRetention; namespace Calamari.Deployment.PackageRetention.Model { public class PackageUsages : List<UsageDetails> { public CacheAge GetCacheAgeAtFirstPackageUse() { return Count > 0 ? this.Min(m => m.CacheAgeAtUsage) : new CacheAge(int.MaxValue); } } }<file_sep>using System; using Calamari.Common.Plumbing; namespace Calamari.Common.Features.Processes.Semaphores { public static class SemaphoreFactory { public static ISemaphoreFactory Get() { if (CalamariEnvironment.IsRunningOnMono) return new FileBasedSempahoreManager(); return new SystemSemaphoreManager(); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Assent; using Calamari.Aws.Integration; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures.Integration.FileSystem; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] public class KubernetesContextScriptWrapperFixture { const string ServerUrl = "<server>"; const string ClusterToken = "<PASSWORD>"; IVariables variables; InMemoryLog log; Dictionary<string, string> redactMap; InstallTools installTools; Dictionary<string, string> environmentVariables; [SetUp] public void Setup() { variables = new CalamariVariables(); variables.Set(KnownVariables.EnabledFeatureToggles, FeatureToggle.KubernetesAksKubeloginFeatureToggle.ToString()); log = new DoNotDoubleLog(); redactMap = new Dictionary<string, string>(); environmentVariables = new Dictionary<string, string>(); SetTestClusterVariables(); } [Test] [TestCase("Url", "", "", true)] [TestCase("", "Name", "", true)] [TestCase("", "", "Name", true)] [TestCase("", "", "", false)] public void ShouldBeEnabledIfAnyVariablesAreProvided(string clusterUrl, string aksClusterName, string eksClusterName, bool expected) { variables.Set(SpecialVariables.ClusterUrl, clusterUrl); variables.Set(SpecialVariables.AksClusterName, aksClusterName); variables.Set(SpecialVariables.EksClusterName, eksClusterName); var wrapper = CreateWrapper(); var actual = wrapper.IsEnabled(ScriptSyntaxHelper.GetPreferredScriptSyntaxForEnvironment()); actual.Should().Be(expected); } [Test] [NonWindowsTest] public void ExecutionShouldFailWhenAccountTypeNotValid() { variables.Set(Deployment.SpecialVariables.Account.AccountType, "not valid"); variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertFailure(); } [Test] [NonWindowsTest] public void ExecutionShouldApplyChmodInBash() { variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "Token"); variables.Set(Deployment.SpecialVariables.Account.Token, ClusterToken); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [NonWindowsTest] public void ExecutionShouldUseGivenNamespace() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "Token"); variables.Set(Deployment.SpecialVariables.Account.Token, ClusterToken); variables.Set(SpecialVariables.Namespace, "my-special-namespace"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [NonWindowsTest] public void ExecutionShouldOutputKubeConfig() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "Token"); variables.Set(Deployment.SpecialVariables.Account.Token, ClusterToken); variables.Set(SpecialVariables.OutputKubeConfig, Boolean.TrueString); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [NonWindowsTest] public void ExecutionWithCustomKubectlExecutable_FileDoesNotExist() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.Bash.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "Token"); variables.Set(Deployment.SpecialVariables.Account.Token, ClusterToken); variables.Set("Octopus.Action.Kubernetes.CustomKubectlExecutable", "mykubectl"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertFailure(); } [Test] [NonWindowsTest] public void ExecutionWithAzureServicePrincipal() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.Bash.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "AzureServicePrincipal"); variables.Set("Octopus.Action.Kubernetes.AksClusterResourceGroup", "clusterRG"); variables.Set(SpecialVariables.AksClusterName, "asCluster"); variables.Set("Octopus.Action.Kubernetes.AksAdminLogin", Boolean.FalseString); variables.Set("Octopus.Action.Azure.SubscriptionId", "azSubscriptionId"); variables.Set("Octopus.Action.Azure.TenantId", "azTenantId"); variables.Set("Octopus.Action.Azure.Password", "<PASSWORD>"); variables.Set("Octopus.Action.Azure.ClientId", "azClientId"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [NonWindowsTest] public void ExecutionWithAzureServicePrincipalWithAdmin() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "AzureServicePrincipal"); variables.Set("Octopus.Action.Kubernetes.AksClusterResourceGroup", "clusterRG"); variables.Set(SpecialVariables.AksClusterName, "asCluster"); variables.Set("Octopus.Action.Kubernetes.AksAdminLogin", Boolean.TrueString); variables.Set("Octopus.Action.Azure.SubscriptionId", "azSubscriptionId"); variables.Set("Octopus.Action.Azure.TenantId", "azTenantId"); variables.Set("Octopus.Action.Azure.Password", "azPassword"); variables.Set("Octopus.Action.Azure.ClientId", "azClientId"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [NonWindowsTest] public void ExecutionUsingPodServiceAccount_WithoutServerCert() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); using (var dir = TemporaryDirectory.Create()) using (var podServiceAccountToken = new TemporaryFile(Path.Combine(dir.DirectoryPath, "podServiceAccountToken"))) { File.WriteAllText(podServiceAccountToken.FilePath, "podServiceAccountToken"); redactMap[podServiceAccountToken.FilePath] = "<podServiceAccountTokenPath>"; variables.Set("Octopus.Action.Kubernetes.PodServiceAccountTokenPath", podServiceAccountToken.FilePath); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } } [Test] [NonWindowsTest] public void ExecutionUsingPodServiceAccount_WithServerCert() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); using (var dir = TemporaryDirectory.Create()) using (var podServiceAccountToken = new TemporaryFile(Path.Combine(dir.DirectoryPath, "podServiceAccountToken"))) using (var certificateAuthority = new TemporaryFile(Path.Combine(dir.DirectoryPath, "certificateAuthority"))) { File.WriteAllText(podServiceAccountToken.FilePath, "podServiceAccountToken"); File.WriteAllText(certificateAuthority.FilePath, "certificateAuthority"); redactMap[podServiceAccountToken.FilePath] = "<podServiceAccountTokenPath>"; redactMap[certificateAuthority.FilePath] = "<certificateAuthorityPath>"; variables.Set("Octopus.Action.Kubernetes.PodServiceAccountTokenPath", podServiceAccountToken.FilePath); variables.Set("Octopus.Action.Kubernetes.CertificateAuthorityPath", certificateAuthority.FilePath); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } } [Test] [NonWindowsTest] public void ExecutionWithClientAndCertificateAuthority() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.Bash.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); var clientCert = "myclientcert"; variables.Set("Octopus.Action.Kubernetes.ClientCertificate", clientCert); variables.Set($"{clientCert}.CertificatePem", "data"); variables.Set($"{clientCert}.PrivateKeyPem", "data"); var certificateAuthority = "myauthority"; variables.Set("Octopus.Action.Kubernetes.CertificateAuthority", certificateAuthority); variables.Set($"{certificateAuthority}.CertificatePem", "data"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [NonWindowsTest] public void ExecutionWithUsernamePassword() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.Bash.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "UsernamePassword"); variables.Set("Octopus.Account.Username", "myusername"); variables.Set("Octopus.Account.Password", "<PASSWORD>"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [WindowsTest] // This test requires the aws cli tools. Currently only configured to install on Linux & Windows [RequiresNonMono] public async Task ExecutionWithEKS_IAMAuthenticator() { await InstallTools(InstallAwsCli); variables.Set(ScriptVariables.Syntax, ScriptSyntax.Bash.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "AmazonWebServicesAccount"); variables.Set(SpecialVariables.EksClusterName, "my-eks-cluster"); var account = "eks_account"; variables.Set("Octopus.Action.AwsAccount.Variable", account); variables.Set("Octopus.Action.Aws.Region", "eks_region"); variables.Set($"{account}.AccessKey", "eksAccessKey"); variables.Set($"{account}.SecretKey", "eksSecretKey"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [WindowsTest] // This test requires the aws cli tools. Currently only configured to install on Windows [RequiresNonMono] // as Mac and Linux installation requires Distro specific tooling public async Task ExecutionWithEKS_AwsCLIAuthenticator() { await InstallTools(InstallAwsCli); // Overriding the cluster url with a valid url. This is required to hit the aws eks get-token endpoint. variables.Set(SpecialVariables.ClusterUrl, "https://someHash.gr7.ap-southeast-2.eks.amazonaws.com"); variables.Set(ScriptVariables.Syntax, ScriptSyntax.Bash.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "AmazonWebServicesAccount"); variables.Set(SpecialVariables.EksClusterName, "my-eks-cluster"); var account = "eks_account"; variables.Set("Octopus.Action.AwsAccount.Variable", account); variables.Set("Octopus.Action.Aws.Region", "eks_region"); variables.Set($"{account}.AccessKey", "eksAccessKey"); variables.Set($"{account}.SecretKey", "eksSecretKey"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [WindowsTest] // This test requires the GKE GCloud Auth plugin. Currently only configured to install on Windows [RequiresNonMono] // as Mac and Linux installation requires Distro specific tooling public async Task ExecutionWithGoogleCloudAccount_WhenZoneIsProvided() { await InstallTools(InstallGCloud); variables.Set(Deployment.SpecialVariables.Account.AccountType, "GoogleCloudAccount"); variables.Set(SpecialVariables.GkeClusterName, "gke-cluster-name"); var account = "gke_account"; variables.Set("Octopus.Action.GoogleCloudAccount.Variable", account); var jsonKey = ExternalVariables.Get(ExternalVariable.GoogleCloudJsonKeyfile); variables.Set($"{account}.JsonKey", Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonKey))); variables.Set("Octopus.Action.GoogleCloud.Project", "gke-project"); variables.Set("Octopus.Action.GoogleCloud.Zone", "gke-zone"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [WindowsTest] // This test requires the GKE GCloud Auth plugin. Currently only configured to install on Windows [RequiresNonMono] // as Mac and Linux installation requires Distro specific tooling public async Task ExecutionWithGoogleCloudAccount_WhenRegionIsProvided() { await InstallTools(InstallGCloud); variables.Set(Deployment.SpecialVariables.Account.AccountType, "GoogleCloudAccount"); variables.Set(SpecialVariables.GkeClusterName, "gke-cluster-name"); var account = "gke_account"; variables.Set("Octopus.Action.GoogleCloudAccount.Variable", account); var jsonKey = ExternalVariables.Get(ExternalVariable.GoogleCloudJsonKeyfile); variables.Set($"{account}.JsonKey", Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonKey))); variables.Set("Octopus.Action.GoogleCloud.Project", "gke-project"); variables.Set("Octopus.Action.GoogleCloud.Region", "gke-region"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] [WindowsTest] // This test requires the GKE GCloud Auth plugin. Currently only configured to install on Windows [RequiresNonMono] // as Mac and Linux installation requires Distro specific tooling public async Task ExecutionWithGoogleCloudAccount_WhenBothZoneAndRegionAreProvided() { await InstallTools(InstallGCloud); variables.Set(Deployment.SpecialVariables.Account.AccountType, "GoogleCloudAccount"); variables.Set(SpecialVariables.GkeClusterName, "gke-cluster-name"); var account = "gke_account"; variables.Set("Octopus.Action.GoogleCloudAccount.Variable", account); var jsonKey = ExternalVariables.Get(ExternalVariable.GoogleCloudJsonKeyfile); variables.Set($"{account}.JsonKey", Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonKey))); variables.Set("Octopus.Action.GoogleCloud.Project", "gke-project"); variables.Set("Octopus.Action.GoogleCloud.Region", "gke-region"); variables.Set("Octopus.Action.GoogleCloud.Zone", "gke-zone"); var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } [Test] public void ExecutionWithGoogleCloudAccount_WhenNeitherZoneOrRegionAreProvided() { variables.Set(Deployment.SpecialVariables.Account.AccountType, "GoogleCloudAccount"); variables.Set(SpecialVariables.GkeClusterName, "gke-cluster-name"); var account = "gke_account"; variables.Set("Octopus.Action.GoogleCloudAccount.Variable", account); var jsonKey = ExternalVariables.Get(ExternalVariable.GoogleCloudJsonKeyfile); variables.Set($"{account}.JsonKey", Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonKey))); variables.Set("Octopus.Action.GoogleCloud.Project", "gke-project"); var wrapper = CreateWrapper(); Assert.Throws<ArgumentException>(() => TestScriptInReadOnlyMode(wrapper)); } [Test] [NonWindowsTest] public void ExecutionWithCustomKubectlExecutable_FileExists() { variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); variables.Set(PowerShellVariables.Edition, "Desktop"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "Token"); variables.Set(Deployment.SpecialVariables.Account.Token, ClusterToken); using (var dir = TemporaryDirectory.Create()) using (var tempExe = new TemporaryFile(Path.Combine(dir.DirectoryPath, "mykubectl.exe"))) { File.WriteAllText(tempExe.FilePath, string.Empty); variables.Set("Octopus.Action.Kubernetes.CustomKubectlExecutable", tempExe.FilePath); redactMap[tempExe.FilePath] = "<customkubectl>"; var wrapper = CreateWrapper(); TestScriptInReadOnlyMode(wrapper).AssertSuccess(); } } KubernetesContextScriptWrapper CreateWrapper() { return new KubernetesContextScriptWrapper(variables, log, new AssemblyEmbeddedResources(), new TestCalamariPhysicalFileSystem()); } void SetTestClusterVariables() { variables.Set(SpecialVariables.ClusterUrl, ServerUrl); variables.Set(SpecialVariables.SkipTlsVerification, "true"); variables.Set(SpecialVariables.Namespace, "calamari-testing"); } CalamariResult TestScriptInReadOnlyMode(IScriptWrapper wrapper, [CallerMemberName] string testName = null, [CallerFilePath] string filePath = null) { using (var dir = TemporaryDirectory.Create()) using (var temp = new TemporaryFile(Path.Combine(dir.DirectoryPath, $"scriptName.{(variables.Get(ScriptVariables.Syntax) == ScriptSyntax.Bash.ToString() ? "sh" : "ps1")}"))) { File.WriteAllText(temp.FilePath, "kubectl get nodes"); var output = ExecuteScriptInRecordOnlyMode(wrapper, temp.FilePath); redactMap[dir.DirectoryPath + Path.DirectorySeparatorChar] = "<path>"; var sb = new StringBuilder(); foreach (var message in log.Messages) { var text = message.FormattedMessage; text = redactMap.Aggregate(text, (current, pair) => current.Replace(pair.Key, pair.Value)); sb.AppendLine($"[{message.Level}] {text}"); } this.Assent(sb.ToString().Replace("\r\n", "\n"), testName: testName, filePath: filePath, configuration: AssentConfiguration.Default); return output; } } CalamariResult ExecuteScriptInRecordOnlyMode(IScriptWrapper wrapper, string scriptName) { return ExecuteScriptInternal(new RecordOnly(variables, installTools), wrapper, scriptName); } CalamariResult ExecuteScriptInternal(ICommandLineRunner runner, IScriptWrapper wrapper, string scriptName) { var wrappers = new List<IScriptWrapper>(new[] { wrapper }); if (variables.Get(Deployment.SpecialVariables.Account.AccountType) == "AmazonWebServicesAccount") { wrappers.Add(new AwsScriptWrapper(log, variables) { VerifyAmazonLogin = () => Task.FromResult(true) }); } var engine = new ScriptEngine(wrappers); var result = engine.Execute(new Script(scriptName), variables, runner, environmentVariables); return new CalamariResult(result.ExitCode, new CaptureCommandInvocationOutputSink()); } async Task InstallTools(Func<InstallTools, Task> toolInstaller) { var tools = new InstallTools(TestContext.Progress.WriteLine); await toolInstaller(tools); installTools = tools; } static async Task InstallAwsCli(InstallTools tools) { await tools.InstallAwsCli(); } async Task InstallGCloud(InstallTools tools) { await tools.InstallGCloud(); environmentVariables.Add("USE_GKE_GCLOUD_AUTH_PLUGIN", "True"); } class RecordOnly : ICommandLineRunner { IVariables Variables; readonly InstallTools installTools; public RecordOnly(IVariables variables, InstallTools installTools) { Variables = variables; this.installTools = installTools; } public CommandResult Execute(CommandLineInvocation invocation) { // If were running an aws command (we check the version and get the eks token endpoint) or checking it's location i.e. 'where aws' we want to run the actual command result. if (new[] { "aws", "aws.exe" }.Contains(invocation.Executable)) { ExecuteCommand(invocation, installTools.AwsCliExecutable); } if (new[] { "kubectl", "kubectl.exe" }.Contains(invocation.Executable) && invocation.Arguments.Contains("version --client --output=json")) { ExecuteCommand(invocation, invocation.Executable); } // We only want to output executable string. eg. ExecuteCommandAndReturnOutput("where", "kubectl.exe") if (new[] { "kubectl", "az", "gcloud", "kubectl.exe", "az.cmd", "gcloud.cmd", "aws", "aws.exe", "aws-iam-authenticator", "aws-iam-authenticator.exe", "kubelogin", "kubelogin.exe", "gke-gcloud-auth-plugin", "gke-gcloud-auth-plugin.exe" }.Contains(invocation.Arguments)) invocation.AdditionalInvocationOutputSink?.WriteInfo(Path.GetFileNameWithoutExtension(invocation.Arguments)); return new CommandResult(invocation.ToString(), 0); } void ExecuteCommand(CommandLineInvocation invocation, string executable) { var captureCommandOutput = new CaptureCommandInvocationOutputSink(); var installedToolInvocation = new CommandLineInvocation(executable, invocation.Arguments) { EnvironmentVars = invocation.EnvironmentVars, WorkingDirectory = invocation.WorkingDirectory, OutputAsVerbose = false, OutputToLog = false, AdditionalInvocationOutputSink = captureCommandOutput }; var commandLineRunner = new CommandLineRunner(new SilentLog(), Variables); commandLineRunner.Execute(installedToolInvocation); foreach (var message in captureCommandOutput.AllMessages) { invocation.AdditionalInvocationOutputSink?.WriteInfo(message); } } } } }<file_sep>using System; using System.IO; using Calamari.Common.Commands; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.StructuredVariables { [TestFixture] public class StructuredConfigVariablesServiceFixture { const string FileName = "config.json"; static readonly string AdditionalPath = Path.GetFullPath("/additionalPath/"); static readonly string CurrentPath = Path.GetFullPath("/currentPath/"); static readonly string ConfigFileInCurrentPath = Path.Combine(CurrentPath, FileName); static readonly string ConfigFileInAdditionalPath = Path.Combine(AdditionalPath, FileName); void RunAdditionalPathsTest( bool fileExistsInPath, bool fileExistsInAdditionalPath, Action<IFileFormatVariableReplacer> replacerAssertions = null, Action<InMemoryLog> logAssertions = null) { var fileSystem = Substitute.For<ICalamariFileSystem>(); fileSystem.FileExists(ConfigFileInCurrentPath).Returns(fileExistsInPath); fileSystem.FileExists(ConfigFileInAdditionalPath).Returns(fileExistsInAdditionalPath); fileSystem.EnumerateFilesWithGlob(CurrentPath, GlobMode.GroupExpansionMode, FileName) .Returns(fileExistsInPath ? new[]{ ConfigFileInCurrentPath } : new string[0]); fileSystem.EnumerateFilesWithGlob(AdditionalPath, GlobMode.GroupExpansionMode, FileName) .Returns(fileExistsInAdditionalPath ? new[]{ ConfigFileInAdditionalPath } : new string[0]); var replacer = Substitute.For<IFileFormatVariableReplacer>(); replacer.FileFormatName.Returns(StructuredConfigVariablesFileFormats.Json); replacer.IsBestReplacerForFileName(Arg.Any<string>()).Returns(true); var log = new InMemoryLog(); var variables = new CalamariVariables(); variables.Set(ActionVariables.AdditionalPaths, AdditionalPath); variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, FileName); variables.Set(PackageVariables.CustomInstallationDirectory, CurrentPath); var service = new StructuredConfigVariablesService(new PrioritisedList<IFileFormatVariableReplacer> { replacer }, variables, fileSystem, log); var deployment = new RunningDeployment(CurrentPath, variables) { CurrentDirectoryProvider = DeploymentWorkingDirectory.CustomDirectory }; service.ReplaceVariables(deployment.CurrentDirectory); replacerAssertions?.Invoke(replacer); logAssertions?.Invoke(log); } [Test] public void ReplacesVariablesInAdditionalPathIfFileMatchedInWorkingDirectory() { void Assertions(IFileFormatVariableReplacer replacer) { replacer.Received().ModifyFile(ConfigFileInCurrentPath, Arg.Any<IVariables>()); replacer.Received().ModifyFile(ConfigFileInAdditionalPath, Arg.Any<IVariables>()); } RunAdditionalPathsTest(true, true, Assertions); } [Test] public void ReplacesVariablesInAdditionalPathIfFileNotMatchedInWorkingDirectory() { void Assertions(IFileFormatVariableReplacer replacer) { replacer.Received().ModifyFile(ConfigFileInAdditionalPath, Arg.Any<IVariables>()); } RunAdditionalPathsTest(false, true, Assertions); } [Test] public void DoesntReplacesVariablesInAdditionalPathIfFileNotMatchedInAdditionalPath() { void Assertions(IFileFormatVariableReplacer replacer) { replacer.Received().ModifyFile(ConfigFileInCurrentPath, Arg.Any<IVariables>()); } RunAdditionalPathsTest(true, false, Assertions); } [Test] public void LogAWarningIfNoMatchingFileIsFoundInAnyPath() { void Assertions(InMemoryLog log) { log.Messages.Should().Contain(message => message.FormattedMessage == $"No files were found that match the replacement target pattern '{FileName}'"); } RunAdditionalPathsTest(false, false, logAssertions: Assertions); } } }<file_sep>using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Common.Util; using Calamari.Integration.FileSystem; using Octopus.CoreUtilities.Extensions; namespace Calamari.Util { public class TemplateService { private readonly ICalamariFileSystem fileSystem; private readonly ITemplateResolver resolver; private readonly ITemplateReplacement replacement; public TemplateService(ICalamariFileSystem fileSystem, ITemplateResolver resolver, ITemplateReplacement replacement) { this.fileSystem = fileSystem; this.resolver = resolver; this.replacement = replacement; } public string GetTemplateContent(string relativePath, bool inPackage, IVariables variables) { return resolver.Resolve(relativePath, inPackage, variables) .Map(x => x.Value) .Map(fileSystem.ReadFile); } public string GetSubstitutedTemplateContent(string relativePath, bool inPackage, IVariables variables) { return replacement.ResolveAndSubstituteFile( () => resolver.Resolve(relativePath, inPackage, variables).Value, fileSystem.ReadFile, variables); } } }<file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.Scripting { class WriteVariablesToFileBehaviour : IBeforePackageExtractionBehaviour { readonly IVariables variables; readonly IScriptEngine scriptEngine; public WriteVariablesToFileBehaviour(IVariables variables, IScriptEngine scriptEngine) { this.variables = variables; this.scriptEngine = scriptEngine; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { if (!TryGetScriptFromVariables(out var scriptBody, out var relativeScriptFile, out var scriptSyntax) && !WasProvided(variables.Get(ScriptVariables.ScriptFileName))) throw new CommandException($"Could not determine script to run. Please provide either a `{ScriptVariables.ScriptBody}` variable, " + $"or a `{ScriptVariables.ScriptFileName}` variable."); if (WasProvided(scriptBody) && relativeScriptFile is not null) { var scriptFile = Path.GetFullPath(relativeScriptFile); //Set the name of the script we are about to create to the variables collection for replacement later on variables.Set(ScriptVariables.ScriptFileName, relativeScriptFile); // If the script body was supplied via a variable, then we write it out to a file. // This will be deleted with the working directory. // Bash files need SheBang as first few characters. This does not play well with BOM characters var scriptBytes = scriptSyntax == ScriptSyntax.Bash ? scriptBody.EncodeInUtf8NoBom() : scriptBody.EncodeInUtf8Bom(); File.WriteAllBytes(scriptFile, scriptBytes); } return this.CompletedTask(); } bool TryGetScriptFromVariables([NotNullWhen(true)] out string? scriptBody, [NotNullWhen(true)] out string? scriptFileName, out ScriptSyntax syntax) { scriptBody = variables.GetRaw(ScriptVariables.ScriptBody); if (WasProvided(scriptBody)) { var scriptSyntax = variables.Get(ScriptVariables.Syntax); if (scriptSyntax == null) { syntax = scriptEngine.GetSupportedTypes().FirstOrDefault(); Log.Warn($"No script syntax provided. Defaulting to first known supported type {syntax}"); } else if (!Enum.TryParse(scriptSyntax, out syntax)) { throw new CommandException($"Unknown script syntax `{scriptSyntax}` provided"); } scriptFileName = "Script." + syntax.FileExtension(); return true; } // Try get any supported script body variable foreach (var supportedSyntax in scriptEngine.GetSupportedTypes()) { scriptBody = variables.GetRaw(SpecialVariables.Action.Script.ScriptBodyBySyntax(supportedSyntax)); if (scriptBody == null) continue; scriptFileName = "Script." + supportedSyntax.FileExtension(); syntax = supportedSyntax; return true; } scriptBody = null; syntax = 0; scriptFileName = null; return false; } bool WasProvided([NotNullWhen(true)] string? value) { return !string.IsNullOrEmpty(value); } } }<file_sep>using System; using Calamari.Common.Plumbing.Variables; using Octopus.CoreUtilities; namespace Calamari.Common.Util { public class ResolvedTemplatePath { public ResolvedTemplatePath(string value) { Value = value; } public string Value { get; } public static explicit operator ResolvedTemplatePath(string value) { return new ResolvedTemplatePath(value); } public static explicit operator string(ResolvedTemplatePath value) { return value.Value; } public override string ToString() { return Value; } } public interface ITemplateResolver { /// <summary> /// Gets the path to the supplied template file and throw if it does not exist. /// </summary> /// <param name="relativeFilePath">The relative path to the file to process</param> /// <param name="inPackage">True if the file is in a package, and false otherwise</param> /// <param name="variables">The variables that contain the deployment locations</param> /// <returns>The path to the supplied file</returns> ResolvedTemplatePath Resolve(string relativeFilePath, bool inPackage, IVariables variables); /// <summary> /// Gets the path to the supplied template file in a safe way. /// </summary> /// <param name="relativeFilePath">The relative path to the file to process</param> /// <param name="inPackage">True if the file is in a package, and false otherwise</param> /// <param name="variables">The variables that contain the deployment locations</param> /// <returns>Maybe file path or Nothing if it doesn't exist</returns> Maybe<ResolvedTemplatePath> MaybeResolve(string relativeFilePath, bool inPackage, IVariables variables); } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Retry; using Calamari.Testing; using Calamari.Testing.Helpers; using Newtonsoft.Json.Linq; using NUnit.Framework; using SharpCompress.Common; using SharpCompress.Readers; namespace Calamari.Tests.KubernetesFixtures { public class InstallTools { readonly Action<string> log; #if NETCORE readonly IHttpClientFactory httpClientFactory; #endif public InstallTools(Action<string> log) { this.log = log; #if NETCORE httpClientFactory = new TestHttpClientFactory(); #endif } public string TerraformExecutable { get; private set; } public string KubectlExecutable { get; private set; } public string AwsAuthenticatorExecutable { get; private set; } public string AwsCliExecutable { get; private set; } public string KubeloginExecutable { get; private set; } public string GcloudExecutable { get; private set; } public async Task Install() { await InstallTerraform(); await InstallKubectl(); } public async Task InstallTerraform() { using (var client = CreateHttpClient()) { TerraformExecutable = await DownloadCli("Terraform", async () => { var json = await client.GetAsync("https://checkpoint-api.hashicorp.com/v1/check/terraform"); json.EnsureSuccessStatusCode(); var jObject = JObject.Parse(await json.Content.ReadAsStringAsync()); var downloadBaseUrl = jObject["current_download_url"].Value<string>(); var version = jObject["current_version"].Value<string>(); return (version, downloadBaseUrl); }, async (destinationDirectoryName, tuple) => { var fileName = GetTerraformFileName(tuple.version); await DownloadTerraform(fileName, client, tuple.data, destinationDirectoryName); var terraformExecutable = Directory.EnumerateFiles(destinationDirectoryName).FirstOrDefault(); return terraformExecutable; }); } } public async Task InstallKubectl() { using (var client = CreateHttpClient()) { KubectlExecutable = await DownloadCli("Kubectl", async () => { var message = await client.GetAsync("https://storage.googleapis.com/kubernetes-release/release/stable.txt"); message.EnsureSuccessStatusCode(); return (await message.Content.ReadAsStringAsync(), null); }, async (destinationDirectoryName, tuple) => { var downloadUrl = GetKubectlDownloadLink(tuple.version); await Download(Path.Combine(destinationDirectoryName, GetKubectlFileName()), client, downloadUrl); var kubectlExecutable = Directory.EnumerateFiles(destinationDirectoryName).FirstOrDefault(); return kubectlExecutable; }); } } public async Task InstallAwsAuthenticator() { using (var client = CreateHttpClient()) { AwsAuthenticatorExecutable = await DownloadCli("aws-iam-authenticator", async () => { string requiredVersion = "v0.5.9"; client.DefaultRequestHeaders.Add("User-Agent", "Octopus"); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", ExternalVariables.Get(ExternalVariable.GitHubRateLimitingPersonalAccessToken)); var json = await client.GetAsync( $"https://api.github.com/repos/kubernetes-sigs/aws-iam-authenticator/releases/tags/{requiredVersion}"); json.EnsureSuccessStatusCode(); var jObject = JObject.Parse(await json.Content.ReadAsStringAsync()); var downloadUrl = jObject["assets"] .Children() .FirstOrDefault(token => token["name"].Value<string>().EndsWith(GetAWSAuthenticatorFileNameEndsWith()))?[ "browser_download_url"] .Value<string>(); return (requiredVersion, downloadUrl); }, async (destinationDirectoryName, tuple) => { await Download(Path.Combine(destinationDirectoryName, GetAWSAuthenticatorFileName()), client, tuple.data); var terraformExecutable = Directory.EnumerateFiles(destinationDirectoryName).FirstOrDefault(); return terraformExecutable; }); } } // Note this only installs and extracts for Windows public async Task InstallAwsCli() { using (var client = CreateHttpClient()) { AwsCliExecutable = await DownloadCli("aws", () => { var version = "2.11.22"; return Task.FromResult((version, GetAwsCliDownloadLink(version))); }, async (destinationDirectoryName, tuple) => { await Download(Path.Combine(destinationDirectoryName, GetAWSCliFileName()), client, tuple.data); var awsInstaller = Directory.EnumerateFiles(destinationDirectoryName).FirstOrDefault(); if (CalamariEnvironment.IsRunningOnWindows) { ExecuteCommandAndReturnResult("msiexec", $"/a {awsInstaller} /qn TARGETDIR={destinationDirectoryName}\\extract", destinationDirectoryName); } else if (CalamariEnvironment.IsRunningOnNix && !CalamariEnvironment.IsRunningOnMono) { ExecuteCommandAndReturnResult("sudo", "apt-get install unzip", destinationDirectoryName); ExecuteCommandAndReturnResult("unzip", $"{Path.Combine(destinationDirectoryName, GetAWSCliFileName())} -d {destinationDirectoryName}", destinationDirectoryName); } return !string.IsNullOrWhiteSpace(destinationDirectoryName) ? GetAwsCliExecutablePath(destinationDirectoryName) : string.Empty; }); } } public async Task InstallGCloud() { using (var client = CreateHttpClient()) { GcloudExecutable = await DownloadCli("gcloud", () => Task.FromResult<(string, string)>(("436.0.0", string.Empty)), async (destinationDirectoryName, tuple) => { var downloadUrl = GetGcloudDownloadLink(tuple.version); var fileName = GetGcloudZipFileName(tuple.version); await DownloadAndExtractToDestination(fileName, client, downloadUrl, destinationDirectoryName); return GetGcloudExecutablePath(destinationDirectoryName); }); } InstallGkeAuthPlugin(); } void InstallGkeAuthPlugin() { if (!CalamariEnvironment.IsRunningOnWindows) return; log("Checking if GKE GCloud Auth Plugin needs installation"); var variables = new Dictionary<string, string>(); var pythonCopyPath = ExecuteCommandAndReturnResult(GcloudExecutable, "components copy-bundled-python", ".", variables); variables.Add("CLOUDSDK_PYTHON", pythonCopyPath); var gkeComponent = ExecuteCommandAndReturnResult($"\"{GcloudExecutable}\"", "components list --filter=\"Name=gke-gcloud-auth-plugin\" --format=\"json\"", ".", variables); var gkeComponentJObject = JArray.Parse(gkeComponent).First(); var installedState = gkeComponentJObject["state"]["name"].Value<string>(); log($"GKE GCloud Auth Plugin is {installedState}"); if (installedState != "Installed") { log("Installing GKE GCloud Auth Plugin"); ExecuteCommandAndReturnResult(GcloudExecutable, "components install gke-gcloud-auth-plugin --quiet", ".", variables); log($"Installed GKE GCloud Auth Plugin to {Path.Combine(Path.GetDirectoryName(GcloudExecutable), "gke-gcloud-auth-plugin.exe")}"); } } public async Task InstallKubelogin() { using (var client = CreateHttpClient()) { KubeloginExecutable = await DownloadCli("kubelogin", () => Task.FromResult<(string, string)>(("v0.0.25", string.Empty)), async (destinationDirectoryName, tuple) => { var downloadUrl = GetKubeloginDownloadLink(tuple.version); var fileName = GetKubeloginZipFileName(); await DownloadAndExtractToDestination(fileName, client, downloadUrl, destinationDirectoryName); return GetKubeloginExecutablePath(destinationDirectoryName); }); } } static string ExecuteCommandAndReturnResult(string executable, string arguments, string workingDirectory, Dictionary<string, string> environmentVariables = null) { var stdOut = new StringBuilder(); var stdError = new StringBuilder(); var commandExitCode = SilentProcessRunner.ExecuteCommand(executable, arguments, workingDirectory, environmentVariables ?? new Dictionary<string, string>(), (Action<string>)(s => stdOut.AppendLine(s)), (Action<string>)(s => stdError.AppendLine(s))) .ExitCode; if (commandExitCode != 0) { throw new InvalidOperationException($"stdOut: {stdOut}, stdError: {stdError}"); } return stdOut.ToString().Trim('\r', '\n'); } static void AddExecutePermission(string exePath) { if (CalamariEnvironment.IsRunningOnWindows) return; ExecuteCommandAndReturnResult("chmod", $"+x {exePath}", Path.GetDirectoryName(exePath) ?? string.Empty); } static string GetTerraformFileName(string currentVersion) { if (CalamariEnvironment.IsRunningOnNix) return $"terraform_{currentVersion}_linux_amd64.zip"; if (CalamariEnvironment.IsRunningOnMac) return $"terraform_{currentVersion}_darwin_amd64.zip"; return $"terraform_{currentVersion}_windows_amd64.zip"; } static string GetAWSAuthenticatorFileNameEndsWith() { if (CalamariEnvironment.IsRunningOnNix) return "_linux_amd64"; if (CalamariEnvironment.IsRunningOnMac) return "_darwin_amd64"; return "_windows_amd64.exe"; } static string GetKubectlFileName() { if (CalamariEnvironment.IsRunningOnWindows) return "kubectl.exe"; return "kubectl"; } static string GetAWSAuthenticatorFileName() { if (CalamariEnvironment.IsRunningOnWindows) return "aws-iam-authenticator.exe"; return "aws-iam-authenticator"; } static string GetAWSCliFileName() { if (CalamariEnvironment.IsRunningOnNix) return "awscli-exe-linux-x86_64.zip"; if (CalamariEnvironment.IsRunningOnMac) return "AWSCLIV2.pkg"; return "AWSCLIV2.msi"; } static string GetAwsCliDownloadLink(string version) { var versionString = version != "latest" ? $"-{version}" : ""; if (CalamariEnvironment.IsRunningOnNix) return $"https://awscli.amazonaws.com/awscli-exe-linux-x86_64{versionString}.zip"; if (CalamariEnvironment.IsRunningOnMac) return $"https://awscli.amazonaws.com/AWSCLIV2{versionString}.pkg"; return $"https://awscli.amazonaws.com/AWSCLIV2{versionString}.msi"; } static string GetAwsCliExecutablePath(string extractPath) { if (CalamariEnvironment.IsRunningOnWindows) { return Path.Combine(extractPath, "extract", "Amazon", "AWSCLIV2", "aws.exe"); } // For developers on a Mac - ensure aws cli is installed manually and on your PATH. if (CalamariEnvironment.IsRunningOnMac) { return "aws"; } return Path.Combine(extractPath, "aws", "dist", "aws"); } static string GetKubectlDownloadLink(string currentVersion) { if (CalamariEnvironment.IsRunningOnNix) return $"https://dl.k8s.io/release/{currentVersion}/bin/linux/amd64/kubectl"; if (CalamariEnvironment.IsRunningOnMac) return $"https://dl.k8s.io/release/{currentVersion}/bin/darwin/amd64/kubectl"; return $"https://dl.k8s.io/release/{currentVersion}/bin/windows/amd64/kubectl.exe"; } static string GetGcloudDownloadLink(string currentVersion) { return $"https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/{GetGcloudZipFileName(currentVersion)}"; } static string GetKubeloginDownloadLink(string currentVersion) { if (CalamariEnvironment.IsRunningOnNix) { return $"https://github.com/Azure/kubelogin/releases/download/{currentVersion}/kubelogin-linux-amd64.zip"; } return $"https://github.com/Azure/kubelogin/releases/download/{currentVersion}/kubelogin-win-amd64.zip"; } public string GetKubeloginZipFileName() { if (CalamariEnvironment.IsRunningOnWindows) { return $"kubelogin.zip"; } return $"kubelogin-linux-amd64.zip"; } static string GetKubeloginExecutablePath(string extractPath) { var executableName = CalamariEnvironment.IsRunningOnWindows ? "kubelogin.exe" : "kubelogin"; return Path.Combine(extractPath, "bin", CalamariEnvironment.IsRunningOnWindows ? "windows_amd64" : "linux_amd64", executableName); } static string GetGcloudZipFileName(string currentVersion) { if (CalamariEnvironment.IsRunningOnNix) return $"google-cloud-sdk-{currentVersion}-linux-x86_64.tar.gz"; if (CalamariEnvironment.IsRunningOnMac) return $"google-cloud-sdk-{currentVersion}-darwin-x86_64-bundled-python.tar.gz"; return $"google-cloud-sdk-{currentVersion}-windows-x86_64-bundled-python.zip"; } static string GetGcloudExecutablePath(string extractPath) { var executableName = string.Empty; if (CalamariEnvironment.IsRunningOnWindows) executableName = "gcloud.cmd"; else executableName = "gcloud"; return Path.Combine(extractPath, "google-cloud-sdk", "bin", executableName); } static async Task Download(string path, HttpClient client, string downloadUrl) { using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) using (var stream = await client.GetStreamAsync(downloadUrl)) { await stream.CopyToAsync(fileStream); } } static async Task DownloadTerraform(string fileName, HttpClient client, string downloadBaseUrl, string destination) { var zipPath = Path.Combine(Path.GetTempPath(), fileName); var downloadUrl = UriCombine(downloadBaseUrl, fileName); using (new TemporaryFile(zipPath)) { await Download(zipPath, client, downloadUrl); ZipFile.ExtractToDirectory(zipPath, destination); } } static string UriCombine(string downloadBaseUrl, string fileName) { if (downloadBaseUrl.Last() != '/') downloadBaseUrl += '/'; return $"{downloadBaseUrl}{fileName}"; } static async Task DownloadAndExtractToDestination(string fileName, HttpClient client, string downloadUrl, string destination) { var zipPath = Path.Combine(Path.GetTempPath(), fileName); using (new TemporaryFile(zipPath)) { await Download(zipPath, client, downloadUrl); using (Stream stream = File.OpenRead(zipPath)) using (var reader = ReaderFactory.Open(stream)) { reader.WriteAllToDirectory(destination, new ExtractionOptions { ExtractFullPath = true, Overwrite = true, WriteSymbolicLink = WarnThatSymbolicLinksAreNotSupported }); } } } static void WarnThatSymbolicLinksAreNotSupported(string sourcepath, string targetpath) { TestContext.Progress.WriteLine("Cannot create symbolic link: {0}, Calamari does not currently support the extraction of symbolic links", sourcepath); } async Task<string> DownloadCli(string toolName, Func<Task<(string version, string data)>> versionFetcher, Func<string, (string version, string data), Task<string>> downloader) { var data = await versionFetcher(); var destinationDirectoryName = TestEnvironment.GetTestPath("Tools", toolName, data.version); string ShouldDownload() { if (!Directory.Exists(destinationDirectoryName)) { return null; } var path = Directory.EnumerateFiles(destinationDirectoryName).FirstOrDefault(); if (toolName == "gcloud") { path = GetGcloudExecutablePath(destinationDirectoryName); } if (toolName == "aws") { path = GetAwsCliExecutablePath(destinationDirectoryName); } if (toolName == "kubelogin") { path = GetKubeloginExecutablePath(destinationDirectoryName); } if (path == null || !File.Exists(path)) { return null; } log($"Using existing {toolName} located in {path}"); return path; } var executablePath = ShouldDownload(); if (!String.IsNullOrEmpty(executablePath)) { return executablePath; } log($"Downloading {toolName} cli..."); Directory.CreateDirectory(destinationDirectoryName); var retry = new RetryTracker(3, TimeSpan.MaxValue, new LimitedExponentialRetryInterval(1000, 30000, 2)); while (retry.Try()) { try { executablePath = await downloader(destinationDirectoryName, data); AddExecutePermission(executablePath); break; } catch { if (!retry.CanRetry()) { throw; } await Task.Delay(retry.Sleep()); } } log($"Downloaded {toolName} to {executablePath}"); return executablePath; } HttpClient CreateHttpClient() { #if NETCORE return httpClientFactory.CreateClient(); #else return new HttpClient(); #endif } } }<file_sep>using System; using Calamari.Common.Plumbing.Retry; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.FileSystem { [TestFixture] public class RetryFixture { [Test] public void ShouldThrowOnceRetriesExceeded() { const int retries = 100; var subject = new RetryTracker(100, null, new LimitedExponentialRetryInterval(100, 200, 2)); Exception caught = null; var retried = 0; try { while (subject.Try()) { try { throw new Exception("Blah"); } catch { if (subject.CanRetry()) { //swallow exception retried++; } else { throw; } } } } catch (Exception ex) { caught = ex; } Assert.NotNull(caught); Assert.AreEqual(retries, retried); } [Test] public void ShouldTryOnceAfterMaxIsReachedAndResetting() { var cnt = 0; var subject = new RetryTracker(20, null, new LinearRetryInterval(TimeSpan.Zero)); while (subject.Try()) cnt++; cnt.Should().Be(21); subject.Reset(); cnt = 0; while (subject.Try()) cnt++; cnt.Should().Be(1); } [Test] public void ShouldTryToLimitAfterMaxIsNotReachedAndResetting() { var cnt = 0; var subject = new RetryTracker(20, null, new LinearRetryInterval(TimeSpan.Zero)); subject.Try(); subject.Reset(); cnt = 0; while (subject.Try()) cnt++; cnt.Should().Be(21); } } }<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.Terraform.Behaviours { class DestroyBehaviour : TerraformDeployBehaviour { readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; public DestroyBehaviour(ILog log, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner) : base(log) { this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; } protected override Task Execute(RunningDeployment deployment, Dictionary<string, string> environmentVariables) { using (var cli = new TerraformCliExecutor(log, fileSystem, commandLineRunner, deployment, environmentVariables)) { cli.ExecuteCommand("destroy", "-auto-approve", "-no-color", cli.TerraformVariableFiles, cli.ActionParams) .VerifySuccess(); } return this.CompletedTask(); } } }<file_sep>namespace Calamari.AzureCloudService.CloudServicePackage.ManifestSchema { public enum IntegrityCheckHashAlgorithm { None, Sha256 } }<file_sep>using System; using System.IO; using System.IO.Packaging; using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; using Calamari.AzureCloudService.CloudServicePackage; using Calamari.AzureCloudService.CloudServicePackage.ManifestSchema; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureCloudService { public class RePackageCloudServiceBehaviour : IDeployBehaviour { readonly ILog log; readonly ICalamariFileSystem fileSystem; public RePackageCloudServiceBehaviour(ILog log, ICalamariFileSystem fileSystem) { this.log = log; this.fileSystem = fileSystem; } public bool IsEnabled(RunningDeployment context) { return !context.Variables.GetFlag(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled); } public Task Execute(RunningDeployment context) { log.Verbose("Re-packaging cspkg."); var workingDirectory = context.CurrentDirectory; var originalPackagePath = context.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath); var newPackagePath = Path.Combine(Path.GetDirectoryName(originalPackagePath), Path.GetFileNameWithoutExtension(originalPackagePath) + "_repacked.cspkg"); using (var originalPackage = Package.Open(originalPackagePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var newPackage = Package.Open(newPackagePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) { try { var originalManifest = AzureCloudServiceConventions.ReadPackageManifest(originalPackage); var newManifest = new PackageDefinition { MetaData = {AzureVersion = originalManifest.MetaData.AzureVersion} }; AddParts(newPackage, newManifest, Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.ServiceDefinition), AzureCloudServiceConventions.PackageFolders.ServiceDefinition); AddParts(newPackage, newManifest, Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.NamedStreams), AzureCloudServiceConventions.PackageFolders.NamedStreams); AddLocalContent(newPackage, newManifest, workingDirectory); AddPackageManifest(newPackage, newManifest); newPackage.Flush(); } catch (Exception ex) { log.Error(ex.PrettyPrint()); throw new Exception("An exception occured re-packaging the cspkg"); } } fileSystem.OverwriteAndDelete(originalPackagePath, newPackagePath); return this.CompletedTask(); } void AddPackageManifest(Package package, PackageDefinition manifest) { var manifestPartUri = PackUriHelper.CreatePartUri(new Uri("/package.xml", UriKind.Relative)); var manifestPart = package.CreatePart(manifestPartUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum); using (var manifestPartStream = manifestPart.GetStream()) { manifest.ToXml().Save(manifestPartStream); } package.CreateRelationship(manifestPartUri, TargetMode.External, AzureCloudServiceConventions.CtpFormatPackageDefinitionRelationshipType); } void AddParts(Package package, PackageDefinition manifest, string directory, string baseDataStorePath) { foreach (var file in fileSystem.EnumerateFiles(directory)) { var partUri = new Uri(baseDataStorePath + "/" + Path.GetFileName(file), UriKind.Relative); AddContent(package, manifest, partUri, file); } foreach (var subDirectory in fileSystem.EnumerateDirectories(directory).Select(x => new DirectoryInfo(x))) { AddParts(package, manifest, subDirectory.FullName, baseDataStorePath + "/" + subDirectory.Name); } } void AddLocalContent(Package package, PackageDefinition manifest, string workingDirectory) { foreach (var roleDirectory in fileSystem.EnumerateDirectories(Path.Combine(workingDirectory, "LocalContent"))) { var layout = new LayoutDefinition {Name = "Roles/" + new DirectoryInfo(roleDirectory).Name}; manifest.Layouts.Add(layout); AddLocalContentParts(package, manifest, layout, roleDirectory, ""); } } void AddLocalContentParts(Package package, PackageDefinition manifest, LayoutDefinition layout, string baseDirectory, string relativeDirectory) { var currentDirectory = Path.Combine(baseDirectory, relativeDirectory); foreach (var file in fileSystem.EnumerateFiles(currentDirectory)) { var uniqueFileName = Guid.NewGuid().ToString("N"); var partUri = new Uri("LocalContent/" + uniqueFileName, UriKind.Relative); AddContent(package, manifest, partUri, file); //add file definition var fileDate = DateTime.UtcNow; //todo: use original timestamps if un-modified layout.FileDefinitions.Add( new FileDefinition { FilePath = "\\" + Path.Combine(relativeDirectory, Path.GetFileName(file)), Description = new FileDescription { DataContentReference = partUri.ToString(), ReadOnly = false, Created = fileDate, Modified = fileDate } }); } foreach (var subDirectory in Directory.GetDirectories(currentDirectory).Select(x => new DirectoryInfo(x))) { AddLocalContentParts(package, manifest, layout, baseDirectory, Path.Combine(relativeDirectory, subDirectory.Name)); } } void AddContent(Package package, PackageDefinition manifest, Uri partUri, string file) { var part = package.CreatePart( PackUriHelper.CreatePartUri(partUri), System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum); using (var partStream = part.GetStream()) using (var fileStream = fileSystem.OpenFile(file, FileMode.Open)) { fileStream.CopyTo(partStream); partStream.Flush(); fileStream.Position = 0; var hashAlgorithm = new SHA256Managed(); hashAlgorithm.ComputeHash(fileStream); manifest.Contents.Add(new ContentDefinition { Name = partUri.ToString(), Description = new ContentDescription { DataStorePath = partUri, LengthInBytes = (int) fileStream.Length, HashAlgorithm = IntegrityCheckHashAlgorithm.Sha256, Hash = Convert.ToBase64String(hashAlgorithm.Hash) } }); } } } }<file_sep>using System; using System.IO; using System.Net; using System.Threading.Tasks; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Testing; using Calamari.Testing.Helpers; using FluentAssertions; using Microsoft.Azure.Management.AppService.Fluent; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using HttpClient = System.Net.Http.HttpClient; using OperatingSystem = Microsoft.Azure.Management.AppService.Fluent.OperatingSystem; using KnownVariables = Calamari.Common.Plumbing.Variables.KnownVariables; namespace Calamari.AzureWebApp.Tests { [TestFixture] public class DeployAzureWebCommandFixture { IAppServicePlan appServicePlan; IResourceGroup resourceGroup; IAzure azure; string clientId; string clientSecret; string tenantId; string subscriptionId; TemporaryDirectory azureConfigPath; readonly HttpClient client = new HttpClient(); [OneTimeSetUp] public async Task Setup() { azureConfigPath = TemporaryDirectory.Create(); Environment.SetEnvironmentVariable("AZURE_CONFIG_DIR", azureConfigPath.DirectoryPath); clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); var resourceGroupName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud); azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithSubscription(subscriptionId); resourceGroup = await azure.ResourceGroups .Define(resourceGroupName) .WithRegion(Region.USWest) .CreateAsync(); appServicePlan = await azure.AppServices.AppServicePlans .Define(SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60)) .WithRegion(resourceGroup.Region) .WithExistingResourceGroup(resourceGroup) .WithPricingTier(PricingTier.StandardS1) .WithOperatingSystem(OperatingSystem.Windows) .CreateAsync(); } [OneTimeTearDown] public async Task Cleanup() { if (resourceGroup != null) { await azure.ResourceGroups.DeleteByNameAsync(resourceGroup.Name); } azureConfigPath.Dispose(); } [Test] public async Task Deploy_WebApp_Simple() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var webApp = await CreateWebApp(webAppName); using var tempPath = TemporaryDirectory.Create(); const string actualText = "Hello World"; File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), actualText); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.WithFilesToCopy(tempPath.DirectoryPath); }) .Execute(); await AssertContent(webApp.DefaultHostName, actualText); } [Test] public async Task Deploy_WebApp_Using_AppOffline() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var webApp = await CreateWebApp(webAppName); using var tempPath = TemporaryDirectory.Create(); const string actualText = "I'm broken"; File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), "Hello World"); File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "App_Offline.htm"), actualText); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.WithFilesToCopy(tempPath.DirectoryPath); }) .Execute(); var packagePath = TestEnvironment.GetTestPath("Packages", "BrokenApp"); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.Variables.Add(SpecialVariables.Action.Azure.AppOffline, bool.TrueString); context.WithFilesToCopy(packagePath); }) .Execute(); var response = await client.GetAsync($"https://{webApp.DefaultHostName}"); response.IsSuccessStatusCode.Should().BeFalse(); response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); var result = await response.Content.ReadAsStringAsync(); result.Should().Be(actualText); } [Test] public async Task Deploy_WebApp_Using_Checksum() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var webApp = await CreateWebApp(webAppName); using var tempPath = TemporaryDirectory.Create(); const string actualText = "Hello World"; File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), actualText); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.WithFilesToCopy(tempPath.DirectoryPath); }) .Execute(); // We write the file again with same content File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), actualText); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.Variables.Add(SpecialVariables.Action.Azure.UseChecksum, bool.TrueString); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { result.FullLog.Should().Contain("Successfully deployed to Azure. 0 objects added. 0 objects updated. 0 objects deleted."); }) .Execute(); await AssertContent(webApp.DefaultHostName, actualText); } [Test] public async Task Deploy_WebApp_Preserve_App_Data() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var webApp = await CreateWebApp(webAppName); using var tempPath = TemporaryDirectory.Create(); Directory.CreateDirectory(Path.Combine(tempPath.DirectoryPath, "App_Data")); File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "App_Data", "newfile1.txt"), "Hello World"); File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), "Hello World"); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.Variables.Add(SpecialVariables.Action.Azure.RemoveAdditionalFiles, bool.TrueString); context.WithFilesToCopy(tempPath.DirectoryPath); }) .Execute(); var packagePath = TestEnvironment.GetTestPath("Packages", "AppDataList"); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.Variables.Add(SpecialVariables.Action.Azure.RemoveAdditionalFiles, bool.TrueString); context.Variables.Add(SpecialVariables.Action.Azure.PreserveAppData, bool.TrueString); context.WithFilesToCopy(packagePath); }) .Execute(); await AssertContent(webApp.DefaultHostName, "newfile1.txt\r\nnewfile2.txt\r\n"); } [Test] public async Task Deploy_WebApp_Preserve_Files() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var webApp = await CreateWebApp(webAppName); using var tempPath = TemporaryDirectory.Create(); const string actualText = "Hello World"; Directory.CreateDirectory(Path.Combine(tempPath.DirectoryPath, "Keep")); Directory.CreateDirectory(Path.Combine(tempPath.DirectoryPath, "NotKeep")); File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "Keep", "index.html"), actualText); File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "NotKeep", "index.html"), actualText); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.WithFilesToCopy(tempPath.DirectoryPath); }) .Execute(); using var tempPath2 = TemporaryDirectory.Create(); File.WriteAllText(Path.Combine(tempPath2.DirectoryPath, "newfile.html"), actualText); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.Variables.Add(SpecialVariables.Action.Azure.RemoveAdditionalFiles, bool.TrueString); context.Variables.Add(SpecialVariables.Action.Azure.PreservePaths, "\\\\Keep;\\\\Keep\\\\index.html"); context.WithFilesToCopy(tempPath2.DirectoryPath); }) .Execute(); await AssertContent(webApp.DefaultHostName, actualText, "Keep"); await AssertContent(webApp.DefaultHostName, actualText, "newfile.html"); var response = await client.GetAsync($"https://{webApp.DefaultHostName}/NotKeep"); response.IsSuccessStatusCode.Should().BeFalse(); response.StatusCode.Should().Be(HttpStatusCode.NotFound); } [Test] public async Task Deploy_WebApp_To_A_Slot() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var slotName = "staging"; var webApp = await CreateWebApp(webAppName); var deploymentSlot = await webApp.DeploymentSlots.Define(slotName) .WithConfigurationFromParent() .WithAutoSwapSlotName("production") .CreateAsync(); using var tempPath = TemporaryDirectory.Create(); const string actualText = "Hello World"; File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), actualText); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.Variables.Add(SpecialVariables.Action.Azure.WebAppSlot, slotName); context.WithFilesToCopy(tempPath.DirectoryPath); }) .Execute(); await AssertContent(deploymentSlot.DefaultHostName, actualText); } [Test] public async Task Deploy_WebApp_From_Package() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var webApp = await CreateWebApp(webAppName); using var tempPath = TemporaryDirectory.Create(); var actualText = "Hello World"; File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), actualText); await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.WithNewNugetPackage(tempPath.DirectoryPath, "Hello", "1.0.0"); }) .Execute(); await AssertContent(webApp.DefaultHostName, actualText); } [Test] public async Task Deploy_WebApp_With_PhysicalPath() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var webApp = await CreateWebApp(webAppName); using var tempPath = TemporaryDirectory.Create(); var actualText = "Hello World"; File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), actualText); const string rootPath = "Hello"; await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { AddDefaults(context, webAppName); context.Variables.Add(SpecialVariables.Action.Azure.PhysicalPath, rootPath); context.WithFilesToCopy(tempPath.DirectoryPath); }) .Execute(); await AssertContent(webApp.DefaultHostName, actualText, rootPath); } [Test] [RequiresPowerShell5OrAboveAttribute] public async Task Deploy_WebApp_Ensure_Tools_Are_Configured() { var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60); var webApp = await CreateWebApp(webAppName); using var tempPath = TemporaryDirectory.Create(); const string actualText = "Hello World"; File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), actualText); var psScript = @" $ErrorActionPreference = 'Continue' az --version az group list"; File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "PreDeploy.ps1"), psScript); // This should be references from Sashimi.Server.Contracts, since Calamari.AzureWebApp is a net461 project this cannot be included. var AccountType = "Octopus.Account.AccountType"; await CommandTestBuilder.CreateAsync<DeployAzureWebCommand, Program>() .WithArrange(context => { context.Variables.Add(AccountType, "AzureServicePrincipal"); AddDefaults(context, webAppName); context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts); context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.Deploy, ScriptSyntax.PowerShell), psScript); context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.PreDeploy, ScriptSyntax.CSharp), "Console.WriteLine(\"Hello from C#\");"); context.Variables.Add(KnownVariables.Action.CustomScripts.GetCustomScriptStage(DeploymentStages.PostDeploy, ScriptSyntax.FSharp), "printfn \"Hello from F#\""); context.WithFilesToCopy(tempPath.DirectoryPath); }) .WithAssert(result => { result.FullLog.Should().Contain("Hello from C#"); result.FullLog.Should().Contain("Hello from F#"); }) .Execute(); await AssertContent(webApp.DefaultHostName, actualText); } Task<IWebApp> CreateWebApp(string webAppName) { return azure.WebApps .Define(webAppName) .WithExistingWindowsPlan(appServicePlan) .WithExistingResourceGroup(resourceGroup) .WithRuntimeStack(WebAppRuntimeStack.NETCore) .CreateAsync(); } async Task AssertContent(string hostName, string actualText, string rootPath = null) { var result= await client.GetStringAsync($"https://{hostName}/{rootPath}"); result.Should().Be(actualText); } void AddDefaults(CommandTestBuilderContext context, string webAppName) { context.Variables.Add(AzureAccountVariables.SubscriptionId, subscriptionId); context.Variables.Add(AzureAccountVariables.TenantId, tenantId); context.Variables.Add(AzureAccountVariables.ClientId, clientId); context.Variables.Add(AzureAccountVariables.Password, clientSecret); context.Variables.Add(SpecialVariables.Action.Azure.WebAppName, webAppName); context.Variables.Add(SpecialVariables.Action.Azure.ResourceGroupName, resourceGroup.Name); } // TODO: when migrating to Calamari repository remove this in favour of Calamari.Tests RequiresPowerShell5OrAboveAttribute attribute private class RequiresPowerShell5OrAboveAttribute : NUnitAttribute, IApplyToTest { public void ApplyToTest(Test test) { if (ScriptingEnvironment.SafelyGetPowerShellVersion().Major < 5) { test.RunState = RunState.Skipped; test.Properties.Set(PropertyNames.SkipReason, "This test requires PowerShell 5 or newer."); } } } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Pipeline { public interface IPackageExtractionBehaviour: IBehaviour { } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureServiceFabric.Integration { class AzureServiceFabricPowerShellContext : IScriptWrapper { readonly ICalamariFileSystem fileSystem; readonly ICalamariEmbeddedResources embeddedResources; readonly IVariables variables; readonly ILog log; readonly ScriptSyntax[] supportedScriptSyntax = {ScriptSyntax.PowerShell}; public AzureServiceFabricPowerShellContext(IVariables variables, ILog log) { fileSystem = new WindowsPhysicalFileSystem(); embeddedResources = new AssemblyEmbeddedResources(); this.variables = variables; this.log = log; } public int Priority => ScriptWrapperPriorities.CloudAuthenticationPriority; public bool IsEnabled(ScriptSyntax syntax) => !string.IsNullOrEmpty(variables.Get(SpecialVariables.Action.ServiceFabric.ConnectionEndpoint)) && supportedScriptSyntax.Contains(syntax); public IScriptWrapper NextWrapper { get; set; } public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string> environmentVars) { // We only execute this hook if the connection endpoint has been set if (!IsEnabled(scriptSyntax)) { throw new InvalidOperationException( "This script wrapper hook is not enabled, and should not have been run"); } if (!Util.ServiceFabricHelper.IsServiceFabricSdkKeyInRegistry()) throw new Exception("Could not find the Azure Service Fabric SDK on this server. This SDK is required before running Service Fabric commands."); var workingDirectory = Path.GetDirectoryName(script.File); variables.Set("OctopusFabricTargetScript", script.File); variables.Set("OctopusFabricTargetScriptParameters", script.Parameters); // Azure PS modules are required for looking up Azure environments (needed for AAD url lookup in Service Fabric world). SetAzureModulesLoadingMethod(); // Read thumbprint from our client cert variable (if applicable). var securityMode = variables.Get(SpecialVariables.Action.ServiceFabric.SecurityMode); var clientCertThumbprint = string.Empty; if (securityMode == Util.AzureServiceFabricSecurityMode.SecureClientCertificate.ToString()) { var certificateVariable = GetMandatoryVariable(SpecialVariables.Action.ServiceFabric.ClientCertVariable); clientCertThumbprint = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Thumbprint}"); } // Set output variables for our script to access. SetOutputVariable("OctopusFabricConnectionEndpoint", variables.Get(SpecialVariables.Action.ServiceFabric.ConnectionEndpoint)); SetOutputVariable("OctopusFabricSecurityMode", variables.Get(SpecialVariables.Action.ServiceFabric.SecurityMode)); SetOutputVariable("OctopusFabricServerCertThumbprint", variables.Get(SpecialVariables.Action.ServiceFabric.ServerCertThumbprint)); SetOutputVariable("OctopusFabricClientCertThumbprint", clientCertThumbprint); SetOutputVariable("OctopusFabricCertificateFindType", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateFindType, "FindByThumbprint")); SetOutputVariable("OctopusFabricCertificateFindValueOverride", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateFindValueOverride)); SetOutputVariable("OctopusFabricCertificateStoreLocation", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreLocation, "LocalMachine")); SetOutputVariable("OctopusFabricCertificateStoreName", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreName, "MY")); SetOutputVariable("OctopusFabricAadCredentialType", variables.Get(SpecialVariables.Action.ServiceFabric.AadCredentialType)); SetOutputVariable("OctopusFabricAadClientCredentialSecret", variables.Get(SpecialVariables.Action.ServiceFabric.AadClientCredentialSecret)); SetOutputVariable("OctopusFabricAadUserCredentialUsername", variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialUsername)); SetOutputVariable("OctopusFabricAadUserCredentialPassword", variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialPassword)); using (new TemporaryFile(Path.Combine(workingDirectory, "AzureProfile.json"))) using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory))) { return NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars); } } string CreateContextScriptFile(string workingDirectory) { var azureContextScriptFile = Path.Combine(workingDirectory, "Octopus.AzureServiceFabricContext.ps1"); var contextScript = embeddedResources.GetEmbeddedResourceText(GetType().Assembly, $"{GetType().Assembly.GetName().Name}.Scripts.AzureServiceFabricContext.ps1"); fileSystem.OverwriteFile(azureContextScriptFile, contextScript); return azureContextScriptFile; } void SetAzureModulesLoadingMethod() { // We don't bundle the standard Azure PS module for Service Fabric work. We do however need // a certain Active Directory library that is bundled with Calamari. SetOutputVariable("OctopusFabricActiveDirectoryLibraryPath", Path.GetDirectoryName(typeof(AzureServiceFabricPowerShellContext).Assembly.Location)); } void SetOutputVariable(string name, string value) { if (variables.Get(name) != value) { log.SetOutputVariable(name, value, variables); } } string GetMandatoryVariable(string variableName) { var value = variables.Get(variableName); if (string.IsNullOrWhiteSpace(value)) throw new CommandException($"Variable {variableName} was not supplied"); return value; } } }<file_sep>using System; namespace Calamari.Testing.LogParser { public class ScriptServiceMessageNames { public static class SetVariable { public const string Name = "setVariable"; public const string NameAttribute = "name"; public const string ValueAttribute = "value"; public const string SensitiveAttribute = "sensitive"; } public static class StdOutBehaviour { public const string Ignore = "stdout-ignore"; public const string Error = "stdout-error"; public const string Default = "stdout-default"; public const string Warning = "stdout-warning"; public const string Verbose = "stdout-verbose"; public const string Highlight = "stdout-highlight"; public const string Wait = "stdout-wait"; } public static class StdErrBehavior { public const string Ignore = "stderr-ignore"; public const string Progress = "stderr-progress"; public const string Error = "stderr-error"; public const string Default = "stderr-default"; } public static class Progress { public const string Name = "progress"; public const string Percentage = "percentage"; public const string Message = "message"; } public static class CreateArtifact { public const string Name = "createArtifact"; public const string PathAttribute = "path"; public const string NameAttribute = "name"; public const string LengthAttribute = "length"; } public static class ResultMessage { public const string Name = "resultMessage"; public const string MessageAttribute = "message"; } public static class CalamariFoundPackage { public const string Name = "calamari-found-package"; } public static class FoundPackage { public const string Name = "foundPackage"; public const string IdAttribute = "id"; public const string VersionAttribute = "version"; public const string VersionFormat = "versionFormat"; public const string HashAttribute = "hash"; public const string RemotePathAttribute = "remotePath"; public const string FileExtensionAttribute = "fileExtension"; } public static class PackageDeltaVerification { public const string Name = "deltaVerification"; public const string RemotePathAttribute = "remotePath"; public const string HashAttribute = "hash"; public const string SizeAttribute = "size"; public const string Error = "error"; } public static class ScriptOutputActions { public const string AccountIdOrNameAttribute = "account"; public const string CertificateIdOrNameAttribute = "certificate"; public const string UpdateExistingAttribute = "updateIfExisting"; public static class CreateAccount { public const string NameAttribute = "name"; public const string AccountTypeAttribute = "type"; public static class CreateTokenAccount { [ServiceMessageName] public const string Name = "create-tokenaccount"; public const string Token = "token"; } public static class CreateUserPassAccount { [ServiceMessageName] public const string Name = "create-userpassaccount"; public const string Username = "username"; public const string Password = "<PASSWORD>"; } public static class CreateAwsAccount { [ServiceMessageName] public const string Name = "create-awsaccount"; public const string SecretKey = "secretKey"; public const string AccessKey = "accessKey"; } public static class CreateAzureAccount { [ServiceMessageName] public const string Name = "create-azureaccount"; public const string SubscriptionAttribute = "azSubscriptionId"; public static class ServicePrincipal { public const string TypeName = "serviceprincipal"; public const string ApplicationAttribute = "azApplicationId"; public const string TenantAttribute = "azTenantId"; public const string PasswordAttribute = "<PASSWORD>"; public const string EnvironmentAttribute = "azEnvironment"; public const string BaseUriAttribute = "azBaseUri"; public const string ResourceManagementBaseUriAttribute = "azResourceManagementBaseUri"; } } } public static class CreateTarget { public const string NameAttribute = "name"; public const string RolesAttribute = "roles"; public static class CreateKubernetesTarget { [ServiceMessageName] public const string Name = "create-kubernetestarget"; public const string Namespace = "namespace"; public const string ClusterUrl = "clusterUrl"; public const string DefaultWorkerPool = "defaultWorkerPool"; public const string SkipTlsVerification = "skipTlsVerification"; public const string ClusterName = "clusterName"; public const string ClusterResourceGroup = "clusterResourceGroup"; public const string ClientCertificateIdOrName = "clientCertificate"; public const string ServerCertificateIdOrName = "serverCertificate"; } public static class CreateAzureWebAppTarget { [ServiceMessageName] public const string Name = "create-azurewebapptarget"; public const string WebAppNameAttribute = "webAppName"; public const string ResourceGroupNameAttribute = "resourceGroupName"; public const string WebAppSlotNameAttribute = "webAppSlot"; } public static class CreateAzureCloudServiceTarget { [ServiceMessageName] public const string Name = "create-azurecloudservicetarget"; public const string AzureCloudServiceNameAttribute = "azureCloudServiceName"; public const string AzureStorageAccountAttribute = "azureStorageAccount"; public const string AzureDeploymentSlotAttribute = "azureDeploymentSlot"; public const string SwapAttribute = "swap"; public const string InstanceCountAttribute = "instanceCount"; } public static class CreateAzureServiceFabricTarget { [ServiceMessageName] public const string Name = "create-azureservicefabrictarget"; public const string ConnectionEndpointAttribute = "connectionEndpoint"; public const string SecurityModeAttribute = "securityMode"; public const string CertificateThumbprintAttribute = "certificateThumbprint"; public const string ActiveDirectoryUsernameAttribute = "activeDirectoryUsername"; public const string ActiveDirectoryPasswordAttribute = "<PASSWORD>Directory<PASSWORD>"; public const string CertificateStoreLocationAttribute = "certificateStoreLocation"; public const string CertificateStoreNameAttribute = "certificateStoreName"; } } public static class DeleteTarget { [ServiceMessageName] public const string Name = "delete-target"; public const string MachineIdOrNameAttribute = "machine"; } } } }<file_sep>using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Azure.Identity; using Azure.ResourceManager.Resources; using Azure.ResourceManager.Resources.Models; using Calamari.AzureAppService; using Calamari.AzureAppService.Azure; using Calamari.Testing; using FluentAssertions; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.Rest; using NUnit.Framework; using NUnit.Framework.Internal; using Polly; using Polly.Retry; namespace Calamari.AzureAppService.Tests { public abstract class LegacyAppServiceIntegrationTest { protected string clientId; protected string clientSecret; protected string tenantId; protected string subscriptionId; protected string resourceGroupName; protected string resourceGroupLocation; protected string greeting = "Calamari"; protected string authToken; protected WebSiteManagementClient webMgmtClient; protected Site site; private ResourceGroupsOperations resourceGroupClient; private readonly HttpClient client = new HttpClient(); protected RetryPolicy RetryPolicy { get; private set; } protected virtual string DefaultResourceGroupLocation => "eastus"; [OneTimeSetUp] public async Task Setup() { var resourceManagementEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ResourceManagementEndPoint) ?? DefaultVariables.ResourceManagementEndpoint; var activeDirectoryEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ActiveDirectoryEndPoint) ?? DefaultVariables.ActiveDirectoryEndpoint; resourceGroupName = $"{DateTime.UtcNow:yyyyMMdd}-{Guid.NewGuid():N}"; clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); resourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? DefaultResourceGroupLocation; authToken = await Auth.GetAuthTokenAsync(tenantId, clientId, clientSecret, resourceManagementEndpointBaseUri, activeDirectoryEndpointBaseUri); var resourcesClient = new ResourcesManagementClient(subscriptionId, new ClientSecretCredential(tenantId, clientId, clientSecret)); resourceGroupClient = resourcesClient.ResourceGroups; var resourceGroup = new ResourceGroup(resourceGroupLocation) { Tags = { // give them an expiry of 14 days so if the tests fail to clean them up // they will be automatically cleaned up by the Sandbox cleanup process // We keep them for 14 days just in case we need to do debugging/investigation ["LifetimeInDays"] = "14" } }; resourceGroup = await resourceGroupClient.CreateOrUpdateAsync(resourceGroupName, resourceGroup); webMgmtClient = new WebSiteManagementClient(new TokenCredentials(authToken)) { SubscriptionId = subscriptionId, HttpClient = { BaseAddress = new Uri(DefaultVariables.ResourceManagementEndpoint) }, }; //Create a retry policy that retries on 429 errors. This is because we've been getting a number of flaky test failures RetryPolicy = RetryPolicyFactory.CreateForHttp429(); await ConfigureTestResources(resourceGroup); } protected abstract Task ConfigureTestResources(ResourceGroup resourceGroup); [OneTimeTearDown] public async Task Cleanup() { if (resourceGroupClient != null) await resourceGroupClient.StartDeleteAsync(resourceGroupName); } protected async Task AssertContent(string hostName, string actualText, string rootPath = null) { var response = await RetryPolicies.TransientHttpErrorsPolicy.ExecuteAsync(async () => { var r = await client.GetAsync($"https://{hostName}/{rootPath}"); r.EnsureSuccessStatusCode(); return r; }); var result = await response.Content.ReadAsStringAsync(); result.Should().Contain(actualText); } protected static async Task DoWithRetries(int retries, Func<Task> action, int secondsBetweenRetries) { foreach (var retry in Enumerable.Range(1, retries)) { try { await action(); break; } catch { if (retry == retries) throw; await Task.Delay(secondsBetweenRetries * 1000); } } } protected void AddAzureVariables(CommandTestBuilderContext context) { context.Variables.Add(AccountVariables.ClientId, clientId); context.Variables.Add(AccountVariables.Password, clientSecret); context.Variables.Add(AccountVariables.TenantId, tenantId); context.Variables.Add(AccountVariables.SubscriptionId, subscriptionId); context.Variables.Add("Octopus.Action.Azure.ResourceGroupName", resourceGroupName); context.Variables.Add("Octopus.Action.Azure.WebAppName", site.Name); } } }<file_sep>namespace Calamari.Testing.Requirements { public class RequiresMonoVersion480OrAboveForTls12Attribute : RequiresMinimumMonoVersionAttribute { /// <summary> /// TLSv1.2 was only provided from Mono 4.8.0. Running /// </summary> public RequiresMonoVersion480OrAboveForTls12Attribute() : base(4, 8, 0) { } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureAppService.Behaviors { public class RestartAzureWebAppBehaviour : IDeployBehaviour { ILog Log { get; } public RestartAzureWebAppBehaviour(ILog log) { Log = log; } public bool IsEnabled(RunningDeployment context) => FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.IsEnabled(context.Variables); public async Task Execute(RunningDeployment context) { var variables = context.Variables; var principalAccount = ServicePrincipalAccount.CreateFromKnownVariables(variables); var webAppName = variables.Get(SpecialVariables.Action.Azure.WebAppName); var slotName = variables.Get(SpecialVariables.Action.Azure.WebAppSlot); var resourceGroupName = variables.Get(SpecialVariables.Action.Azure.ResourceGroupName); var targetSite = new AzureTargetSite(principalAccount.SubscriptionNumber, resourceGroupName, webAppName, slotName); var armClient = principalAccount.CreateArmClient(); Log.Info("Performing soft restart of web app"); await armClient.RestartWebSiteAsync(targetSite); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Azure; using Azure.ResourceManager.AppService.Models; using Azure.ResourceManager.Resources; using Calamari.AzureAppService.Azure; using Calamari.AzureAppService.Behaviors; using Calamari.AzureAppService.Json; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Newtonsoft.Json; using NUnit.Framework; namespace Calamari.AzureAppService.Tests { [TestFixture] public class AppServiceSettingsBehaviorFixture : AppServiceIntegrationTest { string? slotName; AppServiceConfigurationDictionary existingSettings; ConnectionStringDictionary existingConnectionStrings; protected override async Task ConfigureTestResources(ResourceGroupResource resourceGroup) { var (_, webSiteResource) = await CreateAppServicePlanAndWebApp(resourceGroup); WebSiteResource = webSiteResource; existingSettings = new AppServiceConfigurationDictionary { Properties = { ["ExistingSetting"] = "Foo", ["ReplaceSetting"] = "Foo" } }; existingConnectionStrings = new ConnectionStringDictionary { Properties = { { "ExistingConnectionString", new ConnStringValueTypePair("ConnectionStringValue", ConnectionStringType.SqlAzure) }, { "ReplaceConnectionString", new ConnStringValueTypePair("originalConnectionStringValue", ConnectionStringType.Custom) } } }; await WebSiteResource.UpdateConnectionStringsAsync(existingConnectionStrings); } [Test] public async Task TestSiteAppSettings() { await WebSiteResource.UpdateApplicationSettingsAsync(existingSettings); await WebSiteResource.UpdateConnectionStringsAsync(existingConnectionStrings); var iVars = new CalamariVariables(); AddAzureVariables(iVars); var runningContext = new RunningDeployment("", iVars); iVars.Add("Greeting", "Calamari"); var appSettings = BuildAppSettingsJson(new[] { ("MyFirstAppSetting", "Foo", true), ("MySecondAppSetting", "bar", false), ("ReplaceSetting", "Bar", false) }); iVars.Add(SpecialVariables.Action.Azure.AppSettings, appSettings.json); await new AzureAppServiceSettingsBehaviour(new InMemoryLog()).Execute(runningContext); await AssertAppSettings(appSettings.setting, new ConnectionStringDictionary()); } [Test] public async Task TestSiteConnectionStrings() { await WebSiteResource.UpdateApplicationSettingsAsync(existingSettings); await WebSiteResource.UpdateConnectionStringsAsync(existingConnectionStrings); var iVars = new CalamariVariables(); AddAzureVariables(iVars); var runningContext = new RunningDeployment("", iVars); iVars.Add("Greeting", "Calamari"); var connectionStrings = BuildConnectionStringJson(new[] { ("ReplaceConnectionString", "replacedConnectionStringValue", ConnectionStringType.SqlServer, false), ("NewConnectionString", "newValue", ConnectionStringType.SqlAzure, false), ("ReplaceSlotConnectionString", "replacedSlotConnectionStringValue", ConnectionStringType.MySql, true) }); iVars.Add(SpecialVariables.Action.Azure.ConnectionStrings, connectionStrings.json); await new AzureAppServiceSettingsBehaviour(new InMemoryLog()).Execute(runningContext); await AssertAppSettings(new AppSetting[] { }, connectionStrings.connStrings); } [Test] public async Task TestSlotSettings() { slotName = "stage"; var slotResponse = await WebSiteResource.GetWebSiteSlots() .CreateOrUpdateAsync(WaitUntil.Completed, slotName, WebSiteResource.Data); var slotResource = slotResponse.Value; var existingSettingsTask = slotResource.UpdateApplicationSettingsSlotAsync(existingSettings); var iVars = new CalamariVariables(); AddAzureVariables(iVars); var runningContext = new RunningDeployment("", iVars); iVars.Add("Greeting", slotName); iVars.Add("Octopus.Action.Azure.DeploymentSlot", slotName); var settings = BuildAppSettingsJson(new[] { ("FirstSetting", "Foo", true), ("MySecondAppSetting", "Baz", false), ("MyDeploySlotSetting", slotName, false), ("ReplaceSetting", "Foo", false) }); var connectionStrings = BuildConnectionStringJson(new[] { ("NewKey", "newConnStringValue", ConnectionStringType.Custom, false), ("ReplaceConnectionString", "ChangedConnectionStringValue", ConnectionStringType.SqlServer, false), ("newSlotConnectionString", "ChangedConnectionStringValue", ConnectionStringType.SqlServer, true), ("ReplaceSlotConnectionString", "ChangedSlotConnectionStringValue", ConnectionStringType.Custom, true) }); iVars.Add(SpecialVariables.Action.Azure.AppSettings, settings.json); iVars.Add(SpecialVariables.Action.Azure.ConnectionStrings, connectionStrings.json); await existingSettingsTask; await new AzureAppServiceSettingsBehaviour(new InMemoryLog()).Execute(runningContext); await AssertAppSettings(settings.setting, connectionStrings.connStrings); } private (string json, IEnumerable<AppSetting> setting) BuildAppSettingsJson(IEnumerable<(string name, string value, bool isSlotSetting)> settings) { var appSettings = settings.Select(setting => new AppSetting { Name = setting.name, Value = setting.value, SlotSetting = setting.isSlotSetting }); return (JsonConvert.SerializeObject(appSettings), appSettings); } private (string json, ConnectionStringDictionary connStrings) BuildConnectionStringJson( IEnumerable<(string name, string value, ConnectionStringType type, bool isSlotSetting)> connStrings) { var connections = connStrings.Select(connstring => new ConnectionStringSetting { Name = connstring.name, Value = connstring.value, Type = connstring.type, SlotSetting = connstring.isSlotSetting }); var connectionsDict = new ConnectionStringDictionary(); foreach (var item in connStrings) { connectionsDict.Properties[item.name] = new ConnStringValueTypePair(item.value, item.type); } return (JsonConvert.SerializeObject(connections), connectionsDict); } async Task AssertAppSettings(IEnumerable<AppSetting> expectedAppSettings, ConnectionStringDictionary expectedConnStrings) { // Update existing settings with new replacement values var expectedSettingsArray = expectedAppSettings as AppSetting[] ?? expectedAppSettings.ToArray(); foreach (var (name, value, _) in expectedSettingsArray.Where(x => existingSettings.Properties.ContainsKey(x.Name))) { existingSettings.Properties[name] = value; } if (expectedConnStrings?.Properties != null && expectedConnStrings.Properties.Any()) { foreach (var item in expectedConnStrings.Properties) { existingConnectionStrings.Properties[item.Key] = item.Value; } } // for each existing setting that isn't defined in the expected settings object, add it var expectedSettingsList = expectedSettingsArray.ToList(); expectedSettingsList.AddRange(existingSettings.Properties .Where(x => expectedSettingsArray.All(y => y.Name != x.Key)) .Select(kvp => new AppSetting { Name = kvp.Key, Value = kvp.Value, SlotSetting = false })); // Get the settings from the webapp var targetSite = new AzureTargetSite(SubscriptionId, ResourceGroupName, WebSiteResource.Data.Name, slotName); var settings = await ArmClient.GetAppSettingsListAsync(targetSite); var connStrings = await ArmClient.GetConnectionStringsAsync(targetSite); CollectionAssert.AreEquivalent(expectedSettingsList, settings); foreach (var item in connStrings.Properties) { var existingItem = existingConnectionStrings.Properties[item.Key]; Assert.AreEqual(existingItem.Value, item.Value.Value); Assert.AreEqual(existingItem.ConnectionStringType, item.Value.ConnectionStringType); } //CollectionAssert.AreEquivalent(existingConnectionStrings.Properties, connStrings.Properties); } } }<file_sep>using System.Collections.Generic; using Calamari.Common.Plumbing.Logging; using Calamari.Kubernetes.ResourceStatus.Resources; namespace Calamari.Kubernetes { public static class ResourceLoggingExtensionMethods { public static void LogResources<T>(this ILog log, IEnumerable<T> resourceToLog) where T : IResourceIdentity { foreach (var resourceIdentifier in resourceToLog) { log.Verbose($" - {resourceIdentifier.Kind}/{resourceIdentifier.Name} in namespace {resourceIdentifier.Namespace}"); } } } }<file_sep>using System; using Calamari.Commands; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Commands { [TestFixture] public class RegisterPackageUseCommandTest { [Test] public void SupportsMavenVersionFormats() { var registerPackageCmd = new RegisterPackageUseCommand(Substitute.For<ILog>(), Substitute.For<IManagePackageCache>(), Substitute.For<ICalamariFileSystem>()); registerPackageCmd.Execute(new[] { "-packageId=Blah", "-packageVersion=3.7.4.20220919T144341Z", "-packageVersionFormat=Maven", "-packagePath=C:\\Octopus" }).Should().Be(0); } } }<file_sep>namespace Calamari.Integration.Nginx { public class NixNginxServer : NginxServer { public override string GetConfigRootDirectory() { return "/etc/nginx/conf.d"; } public override string GetSslRootDirectory() { return "/etc/ssl"; } } } <file_sep>using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Runtime; using Calamari.Aws.Exceptions; using Calamari.Common.Plumbing; using Octopus.CoreUtilities; using Octopus.CoreUtilities.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using StackStatus = Calamari.Aws.Deployment.Conventions.StackStatus; namespace Calamari.Aws.Integration.CloudFormation { public static class CloudFormationObjectExtensions { private static readonly HashSet<string> RecognisedCapabilities = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "CAPABILITY_IAM", "CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND" }; // These status indicate that an update or create was not successful. // http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html#w2ab2c15c15c17c11 private static HashSet<string> UnsuccessfulStackEvents = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "CREATE_ROLLBACK_COMPLETE", "CREATE_ROLLBACK_FAILED", "UPDATE_ROLLBACK_COMPLETE", "UPDATE_ROLLBACK_FAILED", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED", "DELETE_FAILED", "CREATE_FAILED", "UPDATE_FAILED" }; /// Some statuses indicate that the only way forward is to delete the stack and try again. /// Here are some of the explanations of the stack states from the docs. /// /// CREATE_FAILED: Unsuccessful creation of one or more stacks. View the stack events to see any associated error /// messages. Possible reasons for a failed creation include insufficient permissions to work with all resources /// in the stack, parameter values rejected by an AWS service, or a timeout during resource creation. /// /// DELETE_FAILED: Unsuccessful deletion of one or more stacks. Because the delete failed, you might have some /// resources that are still running; however, you cannot work with or update the stack. Delete the stack again /// or view the stack events to see any associated error messages. /// /// ROLLBACK_COMPLETE: This status exists only after a failed stack creation. It signifies that all operations /// from the partially created stack have been appropriately cleaned up. When in this state, only a delete operation /// can be performed. /// /// ROLLBACK_FAILED: Unsuccessful removal of one or more stacks after a failed stack creation or after an explicitly /// canceled stack creation. Delete the stack or view the stack events to see any associated error messages. /// /// UPDATE_ROLLBACK_FAILED: Unsuccessful return of one or more stacks to a previous working state after a failed stack /// update. When in this state, you can delete the stack or continue rollback. You might need to fix errors before /// your stack can return to a working state. Or, you can contact customer support to restore the stack to a usable state. /// /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html#w2ab2c15c15c17c11 private static HashSet<string> UnrecoverableStackStatuses = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "CREATE_FAILED", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED", "DELETE_FAILED", "UPDATE_ROLLBACK_FAILED" }; public static Task<DescribeChangeSetResponse> DescribeChangeSetAsync(this Func<IAmazonCloudFormation> factory, StackArn stack, ChangeSetArn changeSet) { return factory().DescribeChangeSetAsync(new DescribeChangeSetRequest { ChangeSetName = changeSet.Value, StackName = stack.Value }); } public static Task<CreateChangeSetResponse> CreateChangeSetAsync(this Func<IAmazonCloudFormation> factory, CreateChangeSetRequest request) { return factory().CreateChangeSetAsync(request); } public static async Task<DescribeChangeSetResponse> WaitForChangeSetCompletion( this Func<IAmazonCloudFormation> clientFactory, TimeSpan waitPeriod, RunningChangeSet runningChangeSet) { var completion = new HashSet<ChangeSetStatus> { ChangeSetStatus.FAILED, ChangeSetStatus.CREATE_COMPLETE, ChangeSetStatus.DELETE_COMPLETE }; while (true) { var result = await clientFactory.DescribeChangeSetAsync(runningChangeSet.Stack, runningChangeSet.ChangeSet); if (completion.Contains(result.Status)) { return result; } await Task.Delay(waitPeriod); } } /// <summary> /// Gets the last stack event by timestamp, optionally filtered by a predicate /// </summary> /// <param name="predicate">The optional predicate used to filter events</param> /// <returns>The stack event</returns> public static async Task<Maybe<StackEvent>> GetLastStackEvent(this Func<IAmazonCloudFormation> clientFactory, StackArn stack, Func<StackEvent, bool> predicate = null) { try { var response = await clientFactory().DescribeStackEventsAsync(new DescribeStackEventsRequest { StackName = stack.Value }); return response? .StackEvents.OrderByDescending(stackEvent => stackEvent.Timestamp) .FirstOrDefault(stackEvent => predicate == null || predicate(stackEvent)) .AsSome(); } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "AccessDenied") { throw new PermissionException( "The AWS account used to perform the operation does not have the required permissions to query the current state of the CloudFormation stack. " + "This step will complete without waiting for the stack to complete, and will not fail if the stack finishes in an error state. " + "Please ensure the current account has permission to perform action 'cloudformation:DescribeStackEvents'." + ex.Message); } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "ExpiredToken") { throw new PermissionException( ex.Message + ". Please increase the session duration and/or check that the system date and time are set correctly. "); } catch (AmazonCloudFormationException) { return Maybe<StackEvent>.None; } } /// <summary> /// Gets all stack events, optionally filtered by a predicate /// </summary> /// <param name="predicate">The optional predicate used to filter events</param> /// <returns>The stack events</returns> public static async Task<List<Maybe<StackEvent>>> GetStackEvents(this Func<IAmazonCloudFormation> clientFactory, StackArn stack, Func<StackEvent, bool> predicate = null) { try { var currentStackEvents = new List<StackEvent>(); var nextToken = (string)null; while (true) { var response = await clientFactory().DescribeStackEventsAsync(new DescribeStackEventsRequest { StackName = stack.Value, NextToken = nextToken }); var stackEvents = response? .StackEvents.Where(stackEvent => predicate == null || predicate(stackEvent)) .ToList(); currentStackEvents.AddRange(stackEvents); if (!string.IsNullOrEmpty(response.NextToken)) nextToken = response.NextToken; // Get the next page of results else break; } var results = new List<Maybe<StackEvent>>(); var nestedStackIds = currentStackEvents .Where(s => s.ResourceType == "AWS::CloudFormation::Stack" && !string.IsNullOrEmpty(s.PhysicalResourceId) && s.PhysicalResourceId != s.StackId) .Select(s => s.PhysicalResourceId) .Distinct() .ToList(); foreach (var nestedStackId in nestedStackIds) { var nestedStackEvents = await GetStackEvents(clientFactory, new StackArn(nestedStackId), predicate); if (nestedStackEvents.Any()) { results.AddRange(nestedStackEvents); } } results.AddRange(currentStackEvents.Select(s => s.AsSome())); return results.OrderBy(s => s.SelectValueOr(e => e.Timestamp, DateTime.MinValue)).ToList(); } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "AccessDenied") { throw new PermissionException( "The AWS account used to perform the operation does not have the required permissions to query the current state of the CloudFormation stack. " + "This step will complete without waiting for the stack to complete, and will not fail if the stack finishes in an error state. " + "Please ensure the current account has permission to perform action 'cloudformation:DescribeStackEvents'" + ex.Message); } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "ExpiredToken") { throw new PermissionException(ex.Message + ". Please increase the session duration and/or check that the system date and time are set correctly." + ex.Message); } catch (AmazonCloudFormationException) { return new List<Maybe<StackEvent>> { Maybe<StackEvent>.None }; } } /// <summary> /// Describe the stack /// </summary> /// <param name="clientFactory"></param> /// <param name="stack"></param> /// <returns></returns> public static async Task<Stack> DescribeStackAsync(this Func<IAmazonCloudFormation> clientFactory, StackArn stack) { var response = await clientFactory().DescribeStacksAsync(new DescribeStacksRequest { StackName = stack.Value }); return response.Stacks.FirstOrDefault(); } /// <summary> /// Check to see if the stack name exists. /// </summary> /// <param name="clientFactory">The client factory method</param> /// <param name="stackArn">The stack name or id</param> /// <param name="defaultValue">The default value to return given no permission to query the stack</param> /// <returns>The current status of the stack</returns> public static async Task<StackStatus> StackExistsAsync(this Func<IAmazonCloudFormation> clientFactory, StackArn stackArn, StackStatus defaultValue) { try { var result = await clientFactory.DescribeStackAsync(stackArn); if (result == null) { return StackStatus.DoesNotExist; } if (result.StackStatus == null || result.StackStatus.Value.EndsWith("_COMPLETE") || result.StackStatus.Value.EndsWith("_FAILED")) { return StackStatus.Completed; } return StackStatus.InProgress; } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "AccessDenied") { return defaultValue; } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "ValidationError") { return StackStatus.DoesNotExist; } } /// <summary> /// Get the potentially useful inner web exception message if there is one. /// </summary> /// <param name="exception"></param> /// <returns></returns> public static string GetWebExceptionMessage(this AmazonServiceException exception) { return (exception.InnerException as WebException)? .Response? .GetResponseStream()? .Map(stream => new StreamReader(stream).ReadToEnd()) .Map(message => "An exception was thrown while contacting the AWS API. " + message) ?? "An exception was thrown while contacting the AWS API."; } /// <summary> /// Wait for a given stack to complete by polling the stack events /// </summary> /// <param name="clientFactory">The client factory method to use</param> /// <param name="waitPeriod">The period to wait between events</param> /// <param name="stack">The stack name or id to query</param> /// param name="action">Callback for each event while waiting /// <param name="filter">The predicate for filtering the stack events</param> public static async Task WaitForStackToComplete(this Func<IAmazonCloudFormation> clientFactory, TimeSpan waitPeriod, StackArn stack, Action<Maybe<StackEvent>> action = null, Func<StackEvent, bool> filter = null) { Guard.NotNull(stack, "Stack should not be null"); Guard.NotNull(clientFactory, "Client factory should not be null"); var status = await clientFactory.StackExistsAsync(stack, StackStatus.DoesNotExist); if (status == StackStatus.DoesNotExist || status == StackStatus.Completed) { return; } do { await Task.Delay(waitPeriod); var @event = await clientFactory.GetLastStackEvent(stack, filter); action?.Invoke(@event); } while (await clientFactory.StackExistsAsync(stack, StackStatus.Completed) == StackStatus.InProgress); /* * The action here logs the event and throws an exception if the event indicates failure. There is a possibility * that between the calls to "clientFactory.GetLastStackEvent" and "clientFactory.StackExistsAsync" above * the stack completed but entered an error state that is not detected. Getting the last event after the stack is * in a completed state ensures we catch any errors. */ var lastStackEvent = await clientFactory.GetLastStackEvent(stack, filter); action?.Invoke(lastStackEvent); } /// <summary> /// Check the stack event status to determine whether it was successful. /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html#w2ab2c15c15c17c11 /// </summary> /// <param name="status">The status to check</param> /// <returns>true if the status indicates a failed create or update, and false otherwise</returns> public static Maybe<bool> MaybeIndicatesSuccess(this StackEvent status) { return status.ToMaybe().Select(x => !UnsuccessfulStackEvents.Contains(x.ResourceStatus.Value)); } public static bool StackIsUnrecoverable(this StackEvent status) { Guard.NotNull(status, "Status should not be null"); return UnrecoverableStackStatuses.Contains(status.ResourceStatus.Value); } public static Task<DeleteStackResponse> DeleteStackAsync(this Func<IAmazonCloudFormation> clientFactory, StackArn stack) { Guard.NotNull(clientFactory, "clientFactory should not be null"); Guard.NotNull(stack, "Stack should not be null"); try { return clientFactory().DeleteStackAsync(new DeleteStackRequest { StackName = stack.Value }); } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "AccessDenied") { throw new PermissionException( "The AWS account used to perform the operation does not have the required permissions to delete the stack. " + "Please ensure the current account has permission to perform action 'cloudformation:DeleteStack'. " + ex.Message ); } } public static async Task<string> CreateStackAsync(this Func<IAmazonCloudFormation> clientFactory, CreateStackRequest request) { try { var response = await clientFactory().CreateStackAsync(request); return response.StackId; } catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "AccessDenied") { throw new PermissionException( "The AWS account used to perform the operation does not have the required permissions to create the stack. " + "Please ensure the current account has permission to perform action 'cloudformation:CreateStack'. " + ex.Message ); } } // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities public static bool IsKnownIamCapability(this string capability) { return RecognisedCapabilities.Contains(capability); } } } <file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment.Conventions; using Calamari.Kubernetes.Integration; namespace Calamari.Kubernetes.Conventions { /// <summary> /// An Implementation of IInstallConvention which setups Kubectl Authentication Context /// </summary> public class KubernetesAuthContextConvention : IInstallConvention { private readonly ILog log; private readonly ICommandLineRunner commandLineRunner; private readonly Kubectl kubectl; public KubernetesAuthContextConvention(ILog log, ICommandLineRunner commandLineRunner, Kubectl kubectl) { this.log = log; this.commandLineRunner = commandLineRunner; this.kubectl = kubectl; } public void Install(RunningDeployment deployment) { var setupKubectlAuthentication = new SetupKubectlAuthentication(deployment.Variables, log, commandLineRunner, kubectl, deployment.EnvironmentVariables, deployment.CurrentDirectory); var accountType = deployment.Variables.Get("Octopus.Account.AccountType"); setupKubectlAuthentication.Execute(accountType); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Autofac.Features.Metadata; using Calamari.Commands; using Calamari.Commands.Support; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json.Linq; namespace Calamari.LaunchTools { [LaunchTool(LaunchTools.Calamari)] public class CalamariExecutor : LaunchTool<CalamariInstructions> { readonly IEnumerable<Meta<Lazy<ICommandWithInputs>, CommandMeta>> commands; public CalamariExecutor(IEnumerable<Meta<Lazy<ICommandWithInputs>, CommandMeta>> commands) { this.commands = commands; } protected override int ExecuteInternal(CalamariInstructions instructions) { var commandToExecute = commands.Single(x => x.Metadata.Name.Equals(instructions.Command, StringComparison.OrdinalIgnoreCase)); commandToExecute.Value.Value.Execute(instructions.Inputs.ToString()); return 0; } } public class CalamariInstructions { public string Command { get; set; } public JObject Inputs { get; set; } } }<file_sep>using System; using System.Linq; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.FileSystem; namespace Calamari.Common.Plumbing.Variables { public static class DeploymentJournalVariableContributor { public static void Contribute(ICalamariFileSystem fileSystem, IVariables variables) { var policySet = variables.Get(KnownVariables.RetentionPolicySet); if (string.IsNullOrWhiteSpace(policySet)) return; var journal = new DeploymentJournal(fileSystem, SemaphoreFactory.Get(), variables); Previous(variables, journal, policySet); PreviousSuccessful(variables, journal, policySet); } internal static void Previous(IVariables variables, IDeploymentJournal journal, string policySet) { var previous = journal.GetLatestInstallation(policySet); if (previous == null) { variables.Set(TentacleVariables.PreviousInstallation.OriginalInstalledPath, ""); variables.Set(TentacleVariables.PreviousInstallation.CustomInstallationDirectory, ""); variables.Set(TentacleVariables.PreviousInstallation.PackageFilePath, ""); variables.Set(TentacleVariables.PreviousInstallation.PackageVersion, ""); } else { var previousPackage = previous.Packages.FirstOrDefault(); variables.Set(TentacleVariables.PreviousInstallation.OriginalInstalledPath, previous.ExtractedTo); variables.Set(TentacleVariables.PreviousInstallation.CustomInstallationDirectory, previous.CustomInstallationDirectory); variables.Set(TentacleVariables.PreviousInstallation.PackageFilePath, previousPackage?.DeployedFrom ?? ""); variables.Set(TentacleVariables.PreviousInstallation.PackageVersion, previousPackage?.PackageVersion ?? ""); } } internal static void PreviousSuccessful(IVariables variables, IDeploymentJournal journal, string policySet) { var previous = journal.GetLatestSuccessfulInstallation(policySet); if (previous == null) { variables.Set(TentacleVariables.PreviousSuccessfulInstallation.OriginalInstalledPath, ""); variables.Set(TentacleVariables.PreviousSuccessfulInstallation.CustomInstallationDirectory, ""); variables.Set(TentacleVariables.PreviousSuccessfulInstallation.PackageFilePath, ""); variables.Set(TentacleVariables.PreviousSuccessfulInstallation.PackageVersion, ""); } else { var previousPackage = previous.Packages.FirstOrDefault(); variables.Set(TentacleVariables.PreviousSuccessfulInstallation.OriginalInstalledPath, previous.ExtractedTo); variables.Set(TentacleVariables.PreviousSuccessfulInstallation.CustomInstallationDirectory, previous.CustomInstallationDirectory); variables.Set(TentacleVariables.PreviousSuccessfulInstallation.PackageFilePath, previousPackage?.DeployedFrom ?? ""); variables.Set(TentacleVariables.PreviousSuccessfulInstallation.PackageVersion, previousPackage?.PackageVersion ?? ""); } } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class PackagedScriptConventionFixture { ICalamariFileSystem fileSystem; IScriptEngine scriptEngine; ICommandLineRunner runner; RunningDeployment deployment; CommandResult commandResult; InMemoryLog log; [SetUp] public void SetUp() { fileSystem = Substitute.For<ICalamariFileSystem>(); fileSystem.EnumerateFiles(Arg.Any<string>(), Arg.Any<string[]>()).Returns(new[] {TestEnvironment.ConstructRootedPath("App", "MyApp", "Hello.ps1"), TestEnvironment.ConstructRootedPath("App", "MyApp", "Deploy.ps1"), TestEnvironment.ConstructRootedPath("App", "MyApp", "Deploy.csx"), TestEnvironment.ConstructRootedPath("App", "MyApp", "PreDeploy.ps1"), TestEnvironment.ConstructRootedPath("App", "MyApp", "PreDeploy.sh"), TestEnvironment.ConstructRootedPath("App", "MyApp", "PostDeploy.ps1"), TestEnvironment.ConstructRootedPath("App", "MyApp", "PostDeploy.sh"), TestEnvironment.ConstructRootedPath("App", "MyApp", "DeployFailed.ps1"), TestEnvironment.ConstructRootedPath("App", "MyApp", "DeployFailed.sh")}); commandResult = new CommandResult("PowerShell.exe foo bar", 0, null); scriptEngine = Substitute.For<IScriptEngine>(); scriptEngine.Execute(Arg.Any<Script>(), Arg.Any<IVariables>(), Arg.Any<ICommandLineRunner>()).Returns(c => commandResult); scriptEngine.GetSupportedTypes().Returns(new[] {ScriptSyntax.CSharp, ScriptSyntax.PowerShell, ScriptSyntax.Bash}); runner = Substitute.For<ICommandLineRunner>(); deployment = new RunningDeployment(TestEnvironment.ConstructRootedPath("Packages"), new CalamariVariables()); log = new InMemoryLog(); } [Test] public void ShouldFindAndCallPreferredPackageScript() { var deployPs1 = TestEnvironment.ConstructRootedPath("App", "MyApp", "Deploy.ps1"); var deployCsx = TestEnvironment.ConstructRootedPath("App", "MyApp", "Deploy.csx"); var convention = CreateConvention("Deploy"); convention.Install(deployment); scriptEngine.DidNotReceive().Execute(Arg.Is<Script>(s => s.File == deployPs1), deployment.Variables, runner); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == deployCsx), deployment.Variables, runner); log.StandardOut.Should().ContainMatch($"Found 2 Deploy scripts. Selected {deployCsx} based on OS preferential ordering: CSharp, PowerShell, Bash"); } [Test] public void ShouldFindAndCallPreferredPreDeployScript() { var preDeployPs1 = TestEnvironment.ConstructRootedPath("App", "MyApp", "PreDeploy.ps1"); var preDeploySh = TestEnvironment.ConstructRootedPath("App", "MyApp", "PreDeploy.sh"); var convention = CreateConvention("PreDeploy"); convention.Install(deployment); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == preDeployPs1), deployment.Variables, runner); scriptEngine.DidNotReceive().Execute(Arg.Is<Script>(s => s.File == preDeploySh), deployment.Variables, runner); log.StandardOut.Should().ContainMatch($"Found 2 PreDeploy scripts. Selected {preDeployPs1} based on OS preferential ordering: CSharp, PowerShell, Bash"); } [Test] public void ShouldDeleteScriptsAfterExecution() { var preDeployPs1 = TestEnvironment.ConstructRootedPath("App", "MyApp", "PreDeploy.ps1"); var preDeploySh = TestEnvironment.ConstructRootedPath("App", "MyApp", "PreDeploy.sh"); var convention = CreateConvention("PreDeploy"); convention.Install(deployment); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == preDeployPs1), deployment.Variables, runner); fileSystem.Received().DeleteFile(preDeployPs1, Arg.Any<FailureOptions>()); fileSystem.Received().DeleteFile(preDeploySh, Arg.Any<FailureOptions>()); log.StandardOut.Should().ContainMatch($"Found 2 PreDeploy scripts. Selected {preDeployPs1} based on OS preferential ordering: CSharp, PowerShell, Bash"); } [Test] public void ShouldDeleteScriptsAfterCleanupExecution() { var convention = CreateRollbackConvention("DeployFailed"); convention.Cleanup(deployment); fileSystem.Received().DeleteFile(TestEnvironment.ConstructRootedPath("App", "MyApp", "DeployFailed.ps1"), Arg.Any<FailureOptions>()); fileSystem.Received().DeleteFile(TestEnvironment.ConstructRootedPath("App", "MyApp", "DeployFailed.sh"), Arg.Any<FailureOptions>()); } [Test] public void ShouldRunPreferredScriptOnRollbackExecution() { var deployFailedPs1 = TestEnvironment.ConstructRootedPath("App", "MyApp", "DeployFailed.ps1"); var deployFailedSh = TestEnvironment.ConstructRootedPath("App", "MyApp", "DeployFailed.sh"); var convention = CreateRollbackConvention("DeployFailed"); convention.Rollback(deployment); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == deployFailedPs1), deployment.Variables, runner); scriptEngine.DidNotReceive().Execute(Arg.Is<Script>(s => s.File == deployFailedSh), deployment.Variables, runner); log.StandardOut.Should().ContainMatch($"Found 2 DeployFailed scripts. Selected {deployFailedPs1} based on OS preferential ordering: CSharp, PowerShell, Bash"); } [Test] public void ShouldNotDeleteDeployFailedScriptAfterExecutionIfSpecialVariableIsSet() { deployment.Variables.Set(SpecialVariables.DeleteScriptsOnCleanup, false.ToString()); var convention = CreateRollbackConvention("DeployFailed"); convention.Cleanup(deployment); fileSystem.DidNotReceive().DeleteFile(TestEnvironment.ConstructRootedPath("App", "MyApp", "DeployFailed.ps1"), Arg.Any<FailureOptions>()); fileSystem.DidNotReceive().DeleteFile(TestEnvironment.ConstructRootedPath("App", "MyApp", "DeployFailed.sh"), Arg.Any<FailureOptions>()); } [Test] public void ShouldNotDeletePreDeployScriptAfterExecutionIfSpecialVariableIsSet() { var preDeployPs1 = TestEnvironment.ConstructRootedPath("App", "MyApp", "PreDeploy.ps1"); var preDeploySh = TestEnvironment.ConstructRootedPath("App", "MyApp", "PreDeploy.sh"); deployment.Variables.Set(SpecialVariables.DeleteScriptsOnCleanup, false.ToString()); var convention = CreateConvention("PreDeploy"); convention.Install(deployment); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == preDeployPs1), deployment.Variables, runner); scriptEngine.DidNotReceive().Execute(Arg.Is<Script>(s => s.File == preDeploySh), deployment.Variables, runner); fileSystem.DidNotReceive().DeleteFile(preDeployPs1, Arg.Any<FailureOptions>()); fileSystem.DidNotReceive().DeleteFile(preDeploySh, Arg.Any<FailureOptions>()); log.StandardOut.Should().ContainMatch($"Found 2 PreDeploy scripts. Selected {preDeployPs1} based on OS preferential ordering: CSharp, PowerShell, Bash"); } [Test] public void ShouldNotDeleteDeployScriptAfterExecutionIfSpecialVariableIsSet() { var deployCsx = TestEnvironment.ConstructRootedPath("App", "MyApp", "Deploy.csx"); var deployPs1 = TestEnvironment.ConstructRootedPath("App", "MyApp", "Deploy.ps1"); deployment.Variables.Set(SpecialVariables.DeleteScriptsOnCleanup, false.ToString()); var convention = CreateConvention("Deploy"); convention.Install(deployment); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == deployCsx), deployment.Variables, runner); scriptEngine.DidNotReceive().Execute(Arg.Is<Script>(s => s.File == deployPs1), deployment.Variables, runner); fileSystem.DidNotReceive().DeleteFile(deployPs1, Arg.Any<FailureOptions>()); fileSystem.DidNotReceive().DeleteFile(deployCsx, Arg.Any<FailureOptions>()); log.StandardOut.Should().ContainMatch($"Found 2 Deploy scripts. Selected {deployCsx} based on OS preferential ordering: CSharp, PowerShell, Bash"); } [Test] public void ShouldNotDeletePostDeployScriptAfterExecutionIfSpecialVariableIsSet() { var postDeployPs1 = TestEnvironment.ConstructRootedPath("App", "MyApp", "PostDeploy.ps1"); var postDeploySh = TestEnvironment.ConstructRootedPath("App", "MyApp", "PostDeploy.sh"); deployment.Variables.Set(SpecialVariables.DeleteScriptsOnCleanup, false.ToString()); var convention = CreateConvention("PostDeploy"); convention.Install(deployment); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == postDeployPs1), deployment.Variables, runner); scriptEngine.DidNotReceive().Execute(Arg.Is<Script>(s => s.File == postDeploySh), deployment.Variables, runner); fileSystem.DidNotReceive().DeleteFile(postDeployPs1, Arg.Any<FailureOptions>()); fileSystem.DidNotReceive().DeleteFile(postDeploySh, Arg.Any<FailureOptions>()); log.StandardOut.Should().ContainMatch($"Found 2 PostDeploy scripts. Selected {postDeployPs1} based on OS preferential ordering: CSharp, PowerShell, Bash"); } PackagedScriptConvention CreateConvention(string scriptName) { PackagedScriptBehaviour scriptBehaviour = null; if (scriptName == DeploymentStages.PreDeploy) scriptBehaviour = new PreDeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, runner); else if (scriptName == DeploymentStages.Deploy) scriptBehaviour = new DeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, runner); else if (scriptName == DeploymentStages.PostDeploy) scriptBehaviour = new PostDeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, runner); return new PackagedScriptConvention(scriptBehaviour); } RollbackScriptConvention CreateRollbackConvention(string scriptName) { return new RollbackScriptConvention(log, scriptName, fileSystem, scriptEngine, runner); } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Pipeline { public interface IDeployBehaviour: IBehaviour { } }<file_sep>using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureAppService { public class WarPackageProvider : IPackageProvider { private ILog Log { get; } private IVariables Variables { get; } private RunningDeployment Deployment { get; } public WarPackageProvider(ILog log, IVariables variables, RunningDeployment deployment) { Log = log; Variables = variables; Deployment = deployment; } public string UploadUrlPath => @"/api/wardeploy"; public async Task<FileInfo> PackageArchive(string sourceDirectory, string targetDirectory) { var cmdLineRunner = new CommandLineRunner(Log, Variables); var jarTool = new JarTool(cmdLineRunner, Log, Variables); var packageMetadata = PackageName.FromFile(Deployment.PackageFilePath); var customPackageFileName = Variables.Get(PackageVariables.CustomPackageFileName); if (!string.IsNullOrWhiteSpace(customPackageFileName)) { Log.Verbose($"Using custom package file-name: '{customPackageFileName}'"); } var targetFilePath = Path.Combine(targetDirectory, customPackageFileName ?? Path.GetFileName(Deployment.PackageFilePath)); var enableCompression = Variables.GetFlag(PackageVariables.JavaArchiveCompression, true); await Task.Run(() => { jarTool.CreateJar(sourceDirectory, targetFilePath, enableCompression); }); return new FileInfo(targetFilePath); } public async Task<FileInfo> ConvertToAzureSupportedFile(FileInfo sourceFile) => await Task.Run(() => sourceFile); } }<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public class CertificateVariables { public static class Properties { public static readonly string Thumbprint = "Thumbprint"; public static readonly string Pfx = "Pfx"; public static readonly string Password = "<PASSWORD>"; public static readonly string Subject = "Subject"; } } }<file_sep>#!/bin/bash update_progress 50 "Half Way" <file_sep>using System.IO.Packaging; using System.Linq; using System.Xml; using System.Xml.Linq; using Calamari.AzureCloudService.CloudServicePackage.ManifestSchema; namespace Calamari.AzureCloudService.CloudServicePackage { public static class AzureCloudServiceConventions { public const string RoleLayoutPrefix = "Roles/"; public const string CtpFormatPackageDefinitionRelationshipType = "http://schemas.microsoft.com/windowsazure/PackageDefinition/Version/2012/03/15"; public static PackageDefinition ReadPackageManifest(Package package) { var manifestPart = package.GetPart( package.GetRelationshipsByType(CtpFormatPackageDefinitionRelationshipType).Single().TargetUri); using (var manifestStream = manifestPart.GetStream()) using (var xmlReader = XmlReader.Create(manifestStream, XmlUtils.DtdSafeReaderSettings)) { return new PackageDefinition(XDocument.Load(xmlReader).Root); } } public static bool RoleLayoutFilePathIsModifiable(string filePath) { return filePath.StartsWith("approot\\") || filePath.StartsWith("sitesroot\\"); } public static class PackageFolders { public const string ServiceDefinition = "ServiceDefinition"; public const string NamedStreams = "NamedStreams"; public const string LocalContent = "LocalContent"; } } }<file_sep>using System; using System.IO; using System.IO.Packaging; using System.Linq; using System.Threading.Tasks; using Calamari.AzureCloudService.CloudServicePackage; using Calamari.AzureCloudService.CloudServicePackage.ManifestSchema; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Util; namespace Calamari.AzureCloudService { public class ExtractAzureCloudServicePackageBehaviour : IAfterPackageExtractionBehaviour { readonly ILog log; readonly ICalamariFileSystem fileSystem; public ExtractAzureCloudServicePackageBehaviour(ILog log, ICalamariFileSystem fileSystem) { this.log = log; this.fileSystem = fileSystem; } public bool IsEnabled(RunningDeployment context) { return !context.Variables.GetFlag(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled); } public Task Execute(RunningDeployment context) { var packagePath = context.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath); log.VerboseFormat("Extracting Cloud Service package: '{0}'", packagePath); using (var package = Package.Open(packagePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var manifest = AzureCloudServiceConventions.ReadPackageManifest(package); var workingDirectory = context.CurrentDirectory; ExtractContents(package, manifest, AzureCloudServiceConventions.PackageFolders.ServiceDefinition, workingDirectory); ExtractContents(package, manifest, AzureCloudServiceConventions.PackageFolders.NamedStreams, workingDirectory); ExtractLayouts(package, manifest, workingDirectory); } if (context.Variables.GetFlag(SpecialVariables.Action.Azure.LogExtractedCspkg)) LogExtractedPackage(context.CurrentDirectory); log.SetOutputVariable(SpecialVariables.Action.Azure.PackageExtractionPath, context.CurrentDirectory, context.Variables); return this.CompletedTask(); } void ExtractContents(Package package, PackageDefinition manifest, string contentNamePrefix, string workingDirectory) { foreach (var namedStreamsContent in manifest.Contents.Where(x => x.Name.StartsWith(contentNamePrefix))) { var destinationFileName = Path.Combine(workingDirectory, ConvertToWindowsPath(namedStreamsContent.Description.DataStorePath.ToString()).TrimStart('\\')); ExtractPart(package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), namedStreamsContent.Description.DataStorePath)), destinationFileName); } } void ExtractLayouts(Package package, PackageDefinition manifest, string workingDirectory) { var localContentDirectory = Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.LocalContent); fileSystem.EnsureDirectoryExists(localContentDirectory); foreach (var layout in manifest.Layouts) { if (!layout.Name.StartsWith(AzureCloudServiceConventions.RoleLayoutPrefix)) continue; var layoutDirectory = Path.Combine(localContentDirectory, layout.Name.Substring(AzureCloudServiceConventions.RoleLayoutPrefix.Length)); fileSystem.EnsureDirectoryExists(layoutDirectory); foreach (var fileDefinition in layout.FileDefinitions) { var contentDefinition = manifest.GetContentDefinition(fileDefinition.Description.DataContentReference); var destinationFileName = Path.Combine(layoutDirectory, fileDefinition.FilePath.TrimStart('\\')); ExtractPart( package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), contentDefinition.Description.DataStorePath)), destinationFileName); } } } void ExtractPart(PackagePart part, string destinationPath) { fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(destinationPath)); using (var packageFileStream = part.GetStream()) using (var destinationFileStream = fileSystem.OpenFile(destinationPath, FileMode.Create)) { packageFileStream.CopyTo(destinationFileStream); destinationFileStream.Flush(); } } static string ConvertToWindowsPath(string path) { return path.Replace("/", "\\"); } void LogExtractedPackage(string workingDirectory) { log.Verbose("CSPKG extracted. Working directory contents:"); DirectoryLoggingHelper.LogDirectoryContents(log, fileSystem, workingDirectory, string.Empty); } } }<file_sep>using System.Linq; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.Decorators; using Calamari.Common.Features.Packages.Decorators.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Packages.ArchiveLimits { [TestFixture] public class LogArchiveMetricsDecoratorFixture : CalamariFixture { readonly string[] testZipPath = { "Fixtures", "Integration", "Packages", "Samples", "Acme.Core.1.0.0.0-bugfix.zip" }; [Test] public void ShouldLogTimedOperation() { var extractor = GetExtractor(WithVariables(featureFlagEnabled: true)); extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(Log.Messages.Any(m => m.FormattedMessage.StartsWith("##octopus[calamari-timed-operation")), "Extract operation should be timed."); } [Test] public void ShouldLogArchiveMetricsIfPossible() { var extractor = GetExtractor(WithVariables(featureFlagEnabled: true)); extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(Log.Messages.Count(m => m.FormattedMessage.StartsWith("##octopus[calamari-deployment-metric")) == 3, "Three deployment metrics should be captured."); } [Test] public void ShouldNotLogWhenFeatureFlagTurnedOff() { var extractor = GetExtractor(WithVariables(featureFlagEnabled: false)); extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(Log.Messages.Any(m => m.FormattedMessage.StartsWith("##octopus[calamari-timed-operation")) == false, "Extract operation should not be timed when feature flag is disabled."); Assert.That(Log.Messages.Count(m => m.FormattedMessage.StartsWith("##octopus[calamari-deployment-metric")) == 0, "No deployment metrics should be captured when feature flag is disabled."); } [Test] public void ShouldNotLogWhenFeatureFlagNotPresent() { var extractor = GetExtractor(new CalamariVariables()); extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(Log.Messages.Any(m => m.FormattedMessage.StartsWith("##octopus[calamari-timed-operation")) == false, "Extract operation should not be timed when feature flag is disabled."); Assert.That(Log.Messages.Count(m => m.FormattedMessage.StartsWith("##octopus[calamari-deployment-metric")) == 0, "No deployment metrics should be captured when feature flag is disabled."); } IPackageExtractor GetExtractor(CalamariVariables variables) { return new NullExtractor().WithExtractionLimits(Log, variables); } static CalamariVariables WithVariables(bool featureFlagEnabled = true) { return new CalamariVariables { { KnownVariables.Package.ArchiveLimits.MetricsEnabled, featureFlagEnabled.ToString() }, }; } } } <file_sep>#!/bin/bash IMAGE=$(get_octopusvariable "Image") echo docker pull $IMAGE docker pull $IMAGE rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi <file_sep>using System.IO; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Conventions { public class RePackArchiveConvention : IInstallConvention { readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly JarTool jarTool; public RePackArchiveConvention( ILog log, ICalamariFileSystem fileSystem, JarTool jarTool) { this.log = log; this.fileSystem = fileSystem; this.jarTool = jarTool; } public void Install(RunningDeployment deployment) { if (deployment.Variables.GetFlag(SpecialVariables.Action.Java.JavaArchiveExtractionDisabled)) { Log.Verbose( $"'{SpecialVariables.Action.Java.JavaArchiveExtractionDisabled}' is set. Skipping re-pack."); return; } if (deployment.Variables.GetFlag(SpecialVariables.Action.Java.DeployExploded)) { Log.Verbose($"'{SpecialVariables.Action.Java.DeployExploded}' is set. Skipping re-pack."); return; } var repackedArchivePath = CreateArchive(deployment); var repackedArchiveDirectory = Path.GetDirectoryName(repackedArchivePath); deployment.Variables.Set(KnownVariables.OriginalPackageDirectoryPath, repackedArchiveDirectory); Log.SetOutputVariable(PackageVariables.Output.InstallationDirectoryPath, repackedArchiveDirectory, deployment.Variables); Log.SetOutputVariable(PackageVariables.Output.InstallationPackagePath, repackedArchivePath, deployment.Variables); } protected string CreateArchive(RunningDeployment deployment) { var packageMetadata = PackageName.FromFile(deployment.PackageFilePath); var applicationDirectory = ApplicationDirectory.GetApplicationDirectory( packageMetadata, deployment.Variables, fileSystem); var customPackageFileName = deployment.Variables.Get(PackageVariables.CustomPackageFileName); if (!string.IsNullOrWhiteSpace(customPackageFileName)) { Log.Verbose($"Using custom package file-name: '{customPackageFileName}'"); } var targetFilePath = Path.Combine(applicationDirectory, customPackageFileName ?? Path.GetFileName(deployment.PackageFilePath)); var stagingDirectory = deployment.CurrentDirectory; var enableCompression = deployment.Variables.GetFlag(PackageVariables.JavaArchiveCompression, true); jarTool.CreateJar(stagingDirectory, targetFilePath, enableCompression); log.Info($"Re-packaging archive: '{targetFilePath}'"); return targetFilePath; } } }<file_sep>using System.Collections.Generic; using Calamari.AzureAppService.Behaviors; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureAppService { [Command("target-discovery", Description = "Discover Azure web applications")] public class TargetDiscoveryCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<TargetDiscoveryBehaviour>(); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Proxies; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Authentication; using Calamari.Kubernetes.Integration; using Newtonsoft.Json.Linq; using Octopus.CoreUtilities; using Octopus.Versioning.Semver; namespace Calamari.Kubernetes { public class SetupKubectlAuthentication { readonly IVariables variables; readonly ILog log; readonly ICommandLineRunner commandLineRunner; private readonly Kubectl kubectl; readonly Dictionary<string, string> environmentVars; readonly string workingDirectory; string aws; public SetupKubectlAuthentication(IVariables variables, ILog log, ICommandLineRunner commandLineRunner, Kubectl kubectl, Dictionary<string, string> environmentVars, string workingDirectory) { this.variables = variables; this.log = log; this.commandLineRunner = commandLineRunner; this.kubectl = kubectl; this.environmentVars = environmentVars; this.workingDirectory = workingDirectory; } public CommandResult Execute(string accountType) { var errorResult = new CommandResult(string.Empty, 1); foreach (var proxyVariable in ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables()) { environmentVars[proxyVariable.Key] = proxyVariable.Value; } var kubeConfig = CreateKubectlConfig(); if (!kubectl.TrySetKubectl()) { return errorResult; } var @namespace = variables.Get(SpecialVariables.Namespace); if (string.IsNullOrEmpty(@namespace)) { log.Verbose("No namespace provided. Using default"); @namespace = "default"; } if (!TrySetupContext(kubeConfig, @namespace, accountType)) { return errorResult; } if (!CreateNamespace(@namespace)) { log.Verbose("Could not create namespace. Continuing on, as it may not be working directly with the target."); }; var outputKubeConfig = variables.GetFlag(SpecialVariables.OutputKubeConfig); if (outputKubeConfig) { kubectl.ExecuteCommandAndAssertSuccess("config", "view"); } return new CommandResult(string.Empty, 0); } bool TrySetupContext(string kubeConfig, string @namespace, string accountType) { var clusterUrl = variables.Get(SpecialVariables.ClusterUrl); var clientCert = variables.Get("Octopus.Action.Kubernetes.ClientCertificate"); var eksUseInstanceRole = variables.GetFlag("Octopus.Action.AwsAccount.UseInstanceRole"); var podServiceAccountTokenPath = variables.Get("Octopus.Action.Kubernetes.PodServiceAccountTokenPath"); var serverCertPath = variables.Get("Octopus.Action.Kubernetes.CertificateAuthorityPath"); var isUsingPodServiceAccount = false; var skipTlsVerification = variables.GetFlag(SpecialVariables.SkipTlsVerification) ? "true" : "false"; var useVmServiceAccount = variables.GetFlag("Octopus.Action.GoogleCloud.UseVMServiceAccount"); var isUsingGoogleCloudAuth = accountType == "GoogleCloudAccount" || useVmServiceAccount; var isUsingAzureServicePrincipalAuth = accountType == "AzureServicePrincipal"; if (!isUsingAzureServicePrincipalAuth && !isUsingGoogleCloudAuth && string.IsNullOrEmpty(clusterUrl)) { log.Error("Kubernetes cluster URL is missing"); return false; } string podServiceAccountToken = null; string serverCert = null; if (string.IsNullOrEmpty(accountType) && string.IsNullOrEmpty(clientCert) && !eksUseInstanceRole && !useVmServiceAccount) { if (string.IsNullOrEmpty(podServiceAccountTokenPath) && string.IsNullOrEmpty(serverCertPath)) { log.Error("Kubernetes account type or certificate is missing"); return false; } if (!string.IsNullOrEmpty(podServiceAccountTokenPath)) { if (File.Exists(podServiceAccountTokenPath)) { podServiceAccountToken = File.ReadAllText(podServiceAccountTokenPath); if (string.IsNullOrEmpty(podServiceAccountToken)) { log.Error("Pod service token file is empty"); return false; } isUsingPodServiceAccount = true; } else { log.Error("Pod service token file not found"); return false; } } if (!string.IsNullOrEmpty(serverCertPath)) { if (File.Exists(serverCertPath)) { serverCert = File.ReadAllText(serverCertPath); } else { log.Error("Certificate authority file not found"); return false; } } } if (isUsingAzureServicePrincipalAuth) { var azureCli = new AzureCli(log, commandLineRunner, workingDirectory, environmentVars); var kubeloginCli = new KubeLogin(log, commandLineRunner, workingDirectory, environmentVars); var azureAuth = new AzureKubernetesServicesAuth(azureCli, kubectl, kubeloginCli, variables); if (!azureAuth.TryConfigure(@namespace, kubeConfig)) return false; } else if (isUsingGoogleCloudAuth) { var gcloudCli = new GCloud(log, commandLineRunner, workingDirectory, environmentVars); var gkeGcloudAuthPlugin = new GkeGcloudAuthPlugin(log, commandLineRunner, workingDirectory, environmentVars); var gcloudAuth = new GoogleKubernetesEngineAuth(gcloudCli, gkeGcloudAuthPlugin, kubectl, variables, log); if (!gcloudAuth.TryConfigure(useVmServiceAccount, @namespace)) return false; } else { const string user = "octouser"; const string cluster = "octocluster"; const string context = "octocontext"; if (isUsingPodServiceAccount) { SetupContextUsingPodServiceAccount(@namespace, cluster, clusterUrl, serverCert, skipTlsVerification, serverCertPath, context, user, podServiceAccountToken); } else { kubectl.ExecuteCommandAndAssertSuccess("config", "set-cluster", cluster, $"--server={clusterUrl}"); kubectl.ExecuteCommandAndAssertSuccess("config", "set-context", context, $"--user={user}", $"--cluster={cluster}", $"--namespace={@namespace}"); kubectl.ExecuteCommandAndAssertSuccess("config", "use-context", context); var clientCertPem = variables.Get($"{clientCert}.CertificatePem"); var clientCertKey = variables.Get($"{clientCert}.PrivateKeyPem"); var certificateAuthority = variables.Get("Octopus.Action.Kubernetes.CertificateAuthority"); var serverCertPem = variables.Get($"{certificateAuthority}.CertificatePem"); if (!string.IsNullOrEmpty(clientCert)) { if (string.IsNullOrEmpty(clientCertPem)) { log.Error("Kubernetes client certificate does not include the certificate data"); return false; } if (string.IsNullOrEmpty(clientCertKey)) { log.Error("Kubernetes client certificate does not include the private key data"); return false; } log.Verbose("Encoding client cert key"); var clientCertKeyEncoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(clientCertKey)); log.Verbose("Encoding client cert pem"); var clientCertPemEncoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(clientCertPem)); // Don't leak the private key in the logs log.SetOutputVariable($"{clientCert}.PrivateKeyPemBase64", clientCertKeyEncoded, variables, true); log.AddValueToRedact(clientCertKeyEncoded, "<data>"); log.AddValueToRedact(clientCertPemEncoded, "<data>"); kubectl.ExecuteCommandAndAssertSuccess("config", "set", $"users.{user}.client-certificate-data", clientCertPemEncoded); kubectl.ExecuteCommandAndAssertSuccess("config", "set", $"users.{user}.client-key-data", clientCertKeyEncoded); } if (!string.IsNullOrEmpty(certificateAuthority)) { if (string.IsNullOrEmpty(serverCertPem)) { log.Error("Kubernetes server certificate does not include the certificate data"); return false; } var authorityData = Convert.ToBase64String(Encoding.ASCII.GetBytes(serverCertPem)); log.AddValueToRedact(authorityData, "<data>"); kubectl.ExecuteCommandAndAssertSuccess("config", "set", $"clusters.{cluster}.certificate-authority-data", authorityData); } else { kubectl.ExecuteCommandAndAssertSuccess("config", "set-cluster", cluster, $"--insecure-skip-tls-verify={skipTlsVerification}"); } switch (accountType) { case "Token": { var token = variables.Get("Octopus.Account.Token"); if (string.IsNullOrEmpty(token)) { log.Error("Kubernetes authentication Token is missing"); return false; } SetupContextForToken(@namespace, token, clusterUrl, user); break; } case "UsernamePassword": { SetupContextForUsernamePassword(user); break; } default: { if (accountType == "AmazonWebServicesAccount" || eksUseInstanceRole) { SetupContextForAmazonServiceAccount(@namespace, clusterUrl, user); } else if (string.IsNullOrEmpty(clientCert)) { log.Error($"Account Type {accountType} is currently not valid for kubectl contexts"); return false; } break; } } } } return true; } void SetupContextForToken(string @namespace, string token, string clusterUrl, string user) { log.AddValueToRedact(token, "<token>"); log.Info($"Creating kubectl context to {clusterUrl} (namespace {@namespace}) using a Token"); kubectl.ExecuteCommandAndAssertSuccess("config", "set-credentials", user, $"--token={token}"); } void SetupContextForUsernamePassword(string user) { var username = variables.Get("Octopus.Account.Username"); var password = variables.Get("Octopus.Account.Password"); if (password != null) { log.AddValueToRedact(password, "<password>"); } kubectl.ExecuteCommandAndAssertSuccess("config", "set-credentials", user, $"--username={username}", $"--password={password}"); } void SetupContextForAmazonServiceAccount(string @namespace, string clusterUrl, string user) { var clusterName = variables.Get(SpecialVariables.EksClusterName); log.Info($"Creating kubectl context to {clusterUrl} (namespace {@namespace}) using EKS cluster name {clusterName}"); if (TrySetKubeConfigAuthenticationToAwsCli(clusterName, clusterUrl, user)) { return; } log.Verbose("Attempting to authenticate with aws-iam-authenticator"); SetKubeConfigAuthenticationToAwsIAm(user, clusterName); } bool TrySetKubeConfigAuthenticationToAwsCli(string clusterName, string clusterUrl, string user) { log.Verbose("Attempting to authenticate with aws-cli"); if (!TrySetAws()) { log.Verbose("Could not find the aws cli, falling back to the aws-iam-authenticator."); return false; } try { var awsCliVersion = GetAwsCliVersion(); var minimumAwsCliVersionForAuth = new SemanticVersion("1.16.156"); if (awsCliVersion.CompareTo(minimumAwsCliVersionForAuth) > 0) { var region = GetEksClusterRegion(clusterUrl); if (!string.IsNullOrWhiteSpace(region)) { var apiVersion = GetEksClusterApiVersion(clusterName, region); SetKubeConfigAuthenticationToAwsCli(user, clusterName, region, apiVersion); return true; } log.Verbose("The EKS cluster Url specified should contain a valid aws region name"); } log.Verbose($"aws cli version: {awsCliVersion} does not support the \"aws eks get-token\" command. Please update to a version later than 1.16.156"); } catch (Exception e) { log.Verbose($"Unable to authenticate to {clusterUrl} using the aws cli. Failed with error message: {e.Message}"); } return false; } string GetEksClusterRegion(string clusterUrl) => clusterUrl.Replace(".eks.amazonaws.com", "").Split('.').Last(); SemanticVersion GetAwsCliVersion() { var awsCliCommandRes = ExecuteCommandAndReturnOutput(aws, "--version").FirstOrDefault(); var awsCliVersionString = awsCliCommandRes.Split() .FirstOrDefault(versions => versions.StartsWith("aws-cli")) .Replace("aws-cli/", string.Empty); return new SemanticVersion(awsCliVersionString); } string GetEksClusterApiVersion(string clusterName, string region) { var logLines = ExecuteCommandAndReturnOutput(aws, "eks", "get-token", $"--cluster-name={clusterName}", $"--region={region}"); var awsEksTokenCommand = string.Join("\n", logLines); return JObject.Parse(awsEksTokenCommand).SelectToken("apiVersion").ToString(); } void SetKubeConfigAuthenticationToAwsCli(string user, string clusterName, string region, string apiVersion) { kubectl.ExecuteCommandAndAssertSuccess("config", "set-credentials", user, "--exec-command=aws", "--exec-arg=eks", "--exec-arg=get-token", $"--exec-arg=--cluster-name={clusterName}", $"--exec-arg=--region={region}", $"--exec-api-version={apiVersion}"); } void SetKubeConfigAuthenticationToAwsIAm(string user, string clusterName) { var kubectlVersion = kubectl.GetVersion(); var apiVersion = kubectlVersion.Some() && kubectlVersion.Value > new SemanticVersion("1.23.6") ? "client.authentication.k8s.io/v1beta1" : "client.authentication.k8s.io/v1alpha1"; kubectl.ExecuteCommandAndAssertSuccess("config", "set-credentials", user, "--exec-command=aws-iam-authenticator", $"--exec-api-version={apiVersion}", "--exec-arg=token", "--exec-arg=-i", $"--exec-arg={clusterName}"); } void SetupContextUsingPodServiceAccount(string @namespace, string cluster, string clusterUrl, string serverCert, string skipTlsVerification, string serverCertPath, string context, string user, string podServiceAccountToken) { kubectl.ExecuteCommandAndAssertSuccess("config", "set-cluster", cluster, $"--server={clusterUrl}"); if (string.IsNullOrEmpty(serverCert)) { kubectl.ExecuteCommandAndAssertSuccess("config", "set-cluster", cluster, $"--insecure-skip-tls-verify={skipTlsVerification}"); } else { kubectl.ExecuteCommandAndAssertSuccess("config", "set-cluster", cluster, $"--certificate-authority={serverCertPath}"); } kubectl.ExecuteCommandAndAssertSuccess("config", "set-context", context, $"--user={user}", $"--cluster={cluster}", $"--namespace={@namespace}"); kubectl.ExecuteCommandAndAssertSuccess("config", "use-context", context); log.Info($"Creating kubectl context to {clusterUrl} (namespace {@namespace}) using a Pod Service Account Token"); log.AddValueToRedact(podServiceAccountToken, "<token>"); kubectl.ExecuteCommandAndAssertSuccess("config", "set-credentials", user, $"--token={podServiceAccountToken}"); } bool TrySetAws() { aws = CalamariEnvironment.IsRunningOnWindows ? ExecuteCommandAndReturnOutput("where", "aws.exe").FirstOrDefault() : ExecuteCommandAndReturnOutput("which", "aws").FirstOrDefault(); if (string.IsNullOrEmpty(aws)) { return false; } aws = aws.Trim(); return true; } bool CreateNamespace(string @namespace) { if (TryExecuteCommandWithVerboseLoggingOnly("get", "namespace", @namespace)) return true; return TryExecuteCommandWithVerboseLoggingOnly("create", "namespace", @namespace); } string CreateKubectlConfig() { var kubeConfig = Path.Combine(workingDirectory, "kubectl-octo.yml"); // create an empty file, to suppress kubectl errors about the file missing File.WriteAllText(kubeConfig, string.Empty); environmentVars.Add("KUBECONFIG", kubeConfig); if (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) { ExecuteCommand("chmod", "u=rw,g=,o=", $"\"{kubeConfig}\""); } log.Verbose($"Temporary kubectl config set to {kubeConfig}"); return kubeConfig; } void ExecuteCommand(string executable, params string[] arguments) { ExecuteCommand(new CommandLineInvocation(executable, arguments)).VerifySuccess(); } bool TryExecuteCommand(string executable, params string[] arguments) { return ExecuteCommand(new CommandLineInvocation(executable, arguments)).ExitCode == 0; } bool TryExecuteCommandWithVerboseLoggingOnly(params string[] arguments) { return ExecuteCommandWithVerboseLoggingOnly(new CommandLineInvocation(kubectl.ExecutableLocation, arguments.Concat(new[] { "--request-timeout=1m" }).ToArray())).ExitCode == 0; } CommandResult ExecuteCommand(CommandLineInvocation invocation) { invocation.EnvironmentVars = environmentVars; invocation.WorkingDirectory = workingDirectory; invocation.OutputAsVerbose = false; invocation.OutputToLog = false; var captureCommandOutput = new CaptureCommandOutput(); invocation.AdditionalInvocationOutputSink = captureCommandOutput; var commandString = invocation.ToString(); log.Verbose(commandString); var result = commandLineRunner.Execute(invocation); foreach (var message in captureCommandOutput.Messages) { if (result.ExitCode == 0) { log.Verbose(message.Text); continue; } switch (message.Level) { case Level.Info: log.Verbose(message.Text); break; case Level.Error: log.Error(message.Text); break; } } return result; } /// <summary> /// This is a special case for when the invocation results in an error /// 1) but is to be expected as a valid scenario; and /// 2) we don't want to inform this at an error level when this happens. /// </summary> /// <param name="invocation"></param> /// <returns></returns> CommandResult ExecuteCommandWithVerboseLoggingOnly(CommandLineInvocation invocation) { invocation.EnvironmentVars = environmentVars; invocation.WorkingDirectory = workingDirectory; invocation.OutputAsVerbose = true; invocation.OutputToLog = false; var captureCommandOutput = new CaptureCommandOutput(); invocation.AdditionalInvocationOutputSink = captureCommandOutput; var commandString = invocation.ToString(); log.Verbose(commandString); var result = commandLineRunner.Execute(invocation); foreach (var message in captureCommandOutput.Messages) { log.Verbose(message.Text); } return result; } IEnumerable<string> ExecuteCommandAndReturnOutput(string exe, params string[] arguments) { var captureCommandOutput = new CaptureCommandOutput(); var invocation = new CommandLineInvocation(exe, arguments) { EnvironmentVars = environmentVars, WorkingDirectory = workingDirectory, OutputAsVerbose = false, OutputToLog = false, AdditionalInvocationOutputSink = captureCommandOutput }; var result = commandLineRunner.Execute(invocation); return result.ExitCode == 0 ? captureCommandOutput.InfoLogs.ToArray() : Enumerable.Empty<string>(); } } }<file_sep>using System; using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Packages.Decorators; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Features.Packages.NuGet; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Packages { public interface ICombinedPackageExtractor : IPackageExtractor { } public class CombinedPackageExtractor : ICombinedPackageExtractor { readonly IPackageExtractor[] extractors; public CombinedPackageExtractor(ILog log, IVariables variables, ICommandLineRunner commandLineRunner) { extractors = new IPackageExtractor[] { // Order is important here since .tar.gz should be checked for before .gz new NupkgExtractor(log), new TarGzipPackageExtractor(log), new TarBzipPackageExtractor(log), new ZipPackageExtractor(log), new TarPackageExtractor(log), new JarPackageExtractor(new JarTool(commandLineRunner, log, variables)) }.Select(e => e.WithExtractionLimits(log, variables)).ToArray(); } public string[] Extensions => extractors.SelectMany(e => e.Extensions).OrderBy(e => e).ToArray(); public int Extract(string packageFile, string directory) { return GetExtractor(packageFile).Extract(packageFile, directory); } public IPackageExtractor GetExtractor(string packageFile) { var extension = Path.GetExtension(packageFile); if (string.IsNullOrEmpty(extension)) throw new CommandException("Package is missing file extension. This is needed to select the correct extraction algorithm."); var file = PackageName.FromFile(packageFile); var extractor = extractors.FirstOrDefault(p => p.Extensions.Any(ext => file.Extension.Equals(ext, StringComparison.OrdinalIgnoreCase))); if (extractor == null) throw new CommandException($"Unsupported file extension `{extension}`"); return extractor; } } } <file_sep>using System; using System.Threading.Tasks; using Calamari.CloudAccounts; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; namespace Calamari.Aws.Integration { public class AwsAuthConvention : IInstallConvention { public delegate AwsAuthConvention Factory(Func<Task<bool>> verifyLogin = null); private readonly ILog log; private readonly IVariables variables; private readonly Func<Task<bool>> verifyLogin; public AwsAuthConvention(ILog log, IVariables variables, Func<Task<bool>> verifyLogin = null) { this.log = log; this.variables = variables; this.verifyLogin = verifyLogin; } public void Install(RunningDeployment deployment) { var awsEnvironmentVars = AwsEnvironmentGeneration.Create(log, variables, verifyLogin).GetAwaiter().GetResult(); foreach (var envVar in awsEnvironmentVars.EnvironmentVars) { deployment.EnvironmentVariables[envVar.Key] = envVar.Value; } } } }<file_sep>using System; using System.Diagnostics; namespace Calamari.Common.Plumbing.Retry { /// <summary> /// Retry logic tracks when to retry vs fail and calculates sleep times for retries /// </summary> /// <remarks> /// while (retryLogic.Try()) /// { .... /// catch /// ... /// if retryLogic.CanRetry() /// { /// Thread.Sleep(retryLogic.Sleep()) /// } /// else /// throw; /// For a file system RetryTracker, use a small fixed interval and a limit of say 1 minute /// For a network RetryTracker, use an exponential retry up to, say, 30 seconds to prevent spamming host /// </remarks> public class RetryTracker { readonly int? maxRetries; readonly TimeSpan? timeLimit; readonly Stopwatch stopWatch = new Stopwatch(); readonly RetryInterval retryInterval; bool shortCircuit; TimeSpan lastTry = TimeSpan.Zero; TimeSpan nextWarning = TimeSpan.Zero; public RetryTracker(int? maxRetries, TimeSpan? timeLimit, RetryInterval retryInterval, bool throwOnFailure = true) { this.maxRetries = maxRetries; if (maxRetries.HasValue && maxRetries.Value < 0) throw new ArgumentException("maxretries must be 0 or more if set"); this.timeLimit = timeLimit; this.retryInterval = retryInterval; ThrowOnFailure = throwOnFailure; } public bool ThrowOnFailure { get; } public int CurrentTry { get; set; } public TimeSpan TotalElapsed => stopWatch.Elapsed; public bool IsNotFirstAttempt => CurrentTry != 1; public bool Try() { stopWatch.Start(); var canRetry = CanRetry(); CurrentTry++; lastTry = stopWatch.Elapsed; return canRetry; } public TimeSpan Sleep() { return retryInterval.GetInterval(CurrentTry); } public bool CanRetry() { var noRetry = shortCircuit && CurrentTry > 0 || maxRetries.HasValue && CurrentTry > maxRetries.Value || timeLimit.HasValue && lastTry + retryInterval.GetInterval(CurrentTry) > timeLimit.Value; return !noRetry; } public bool ShouldLogWarning() { var warn = CurrentTry < 5 || stopWatch.Elapsed > nextWarning; if (warn) nextWarning = stopWatch.Elapsed.Add(TimeSpan.FromSeconds(10)); return warn; } /// <summary> /// Resets the tracker to start from the start. Sets the ShortCircuit flag if the maximums were reached. /// DO NOT call from within a RetryTacker.Try loop as otherwise it will never finish /// </summary> public void Reset() { if (!CanRetry()) shortCircuit = true; stopWatch.Reset(); CurrentTry = 0; } } }<file_sep>using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Calamari.Testing.Helpers { [DebuggerStepThrough] public static class TaskExtensionMethods { public static async Task WithCancellationToken(this Task task, CancellationToken cancellationToken) { var doerTask = task; var thrower = new TaskCompletionSource<object>(); using (cancellationToken.Register(tcs => ((TaskCompletionSource<object>)tcs).SetResult(new object()), thrower)) { var throwerTask = thrower.Task; if (doerTask != await Task.WhenAny(doerTask, throwerTask)) { throw new OperationCanceledException(cancellationToken); } await doerTask; } } } } <file_sep>#!/bin/bash rm -fr ./subdir mkdir -p ./subdir/anotherdir touch ./subdir/anotherdir/myfile new_octopusartifact "./subdir/anotherdir/myfile"<file_sep>using System; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Variables; namespace Calamari.Commands { [Command("substitute-in-files")] public class SubstituteInFilesCommand : Command<SubstituteInFilesCommandInputs> { readonly IVariables variables; readonly ISubstituteInFiles substituteInFiles; public SubstituteInFilesCommand(IVariables variables, ISubstituteInFiles substituteInFiles) { this.variables = variables; this.substituteInFiles = substituteInFiles; } protected override void Execute(SubstituteInFilesCommandInputs inputs) { var targetPath = variables.GetRaw(inputs.TargetPathVariable); if (targetPath == null) { throw new CommandException($"Could not locate target path from variable {inputs.TargetPathVariable} for {nameof(SubstituteInFilesCommand)}"); } substituteInFiles.Substitute(targetPath, inputs.FilesToTarget); } } public class SubstituteInFilesCommandInputs { public string TargetPathVariable { get; set; } public string[] FilesToTarget { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using Serilog; namespace Calamari.ConsolidateCalamariPackages { class CalamariFlavourPackageReference : IPackageReference { private readonly Hasher hasher; public string Name { get; } public string Version { get; } public string PackagePath { get; } public CalamariFlavourPackageReference(Hasher hasher, BuildPackageReference packageReference) { this.hasher = hasher; Name = packageReference.Name; Version = packageReference.Version; PackagePath = packageReference.PackagePath; } public IReadOnlyList<SourceFile> GetSourceFiles(ILogger log) { using (var zip = ZipFile.OpenRead(PackagePath)) return zip.Entries .Where(e => !string.IsNullOrEmpty(e.Name)) .Select(entry => { var parts = entry.FullName.Split('/'); return new SourceFile { PackageId = Path.GetFileNameWithoutExtension(PackagePath), Version = Version, Platform = parts[0], ArchivePath = PackagePath, IsNupkg = false, FullNameInDestinationArchive = string.Join("/", parts.Skip(1)), FullNameInSourceArchive = entry.FullName, Hash = hasher.Hash(entry) }; }) .ToArray(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using StackStatus = Calamari.Aws.Deployment.Conventions.StackStatus; namespace Calamari.Aws.Integration.CloudFormation.Templates { /// <summary> /// Templates capture as much information as possible about the CloudFormation template to be deployed, /// and expose methods to build the request objects required by the AWS SDK. /// </summary> public abstract class BaseTemplate : ICloudFormationRequestBuilder { protected readonly string stackName; protected readonly List<string> capabilities; protected readonly bool disableRollback; protected readonly StackArn stack; protected readonly List<Tag> tags; protected readonly string roleArn; readonly Func<IAmazonCloudFormation> clientFactory; protected readonly IVariables variables; public BaseTemplate(IEnumerable<Parameter> inputs, string stackName, List<string> iamCapabilities, bool disableRollback, string roleArn, IEnumerable<KeyValuePair<string, string>> tags, StackArn stack, Func<IAmazonCloudFormation> clientFactory, IVariables variables) { Inputs = inputs; this.stackName = stackName; this.disableRollback = disableRollback; this.stack = stack; this.roleArn = roleArn; this.clientFactory = clientFactory; this.variables = variables; this.tags = tags?.Select(x => new Tag { Key = x.Key, Value = x.Value }).ToList(); var (validCapabilities, _) = ExcludeAndLogUnknownIamCapabilities(iamCapabilities); capabilities = validCapabilities.ToList(); } protected async Task<StackStatus> GetStackStatus() { return await clientFactory.StackExistsAsync(stack, StackStatus.DoesNotExist); } /// <summary> /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities /// </summary> (IList<string> valid, IList<string> excluded) ExcludeAndLogUnknownIamCapabilities(IEnumerable<string> values) { var (valid, excluded) = ExcludeUnknownIamCapabilities(values); if (excluded.Count > 0) { Log.Warn($"The following unknown IAM Capabilities have been removed: {String.Join(", ", excluded)}"); } return (valid, excluded); } (IList<string> valid, IList<string> excluded) ExcludeUnknownIamCapabilities( IEnumerable<string> capabilities) { return capabilities.Aggregate((new List<string>(), new List<string>()), (prev, current) => { var (valid, excluded) = prev; if (current.IsKnownIamCapability()) valid.Add(current); else excluded.Add(current); return prev; }); } public IEnumerable<Parameter> Inputs { get; } public abstract CreateStackRequest BuildCreateStackRequest(); public abstract UpdateStackRequest BuildUpdateStackRequest(); public abstract Task<CreateChangeSetRequest> BuildChangesetRequest(); } }<file_sep>using System.IO; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class DeployWindowsServiceFixture : DeployWindowsServiceAbstractFixture { protected override string ServiceName => "Acme.Service"; [Test] public void ShouldDeployAndInstallASimpleService() { RunDeployment(); } [Test] public void ShouldDeployAndInstallWhenThereAreSpacesInThePath() { Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.CustomDirectory,Octopus.Features.WindowsService"; var installDir = Path.Combine(CustomDirectory, "A Directory With A Space In It"); Variables[PackageVariables.CustomInstallationDirectory] = installDir; RunDeployment(); Assert.IsTrue(File.Exists(Path.Combine(installDir, $"{ServiceName}.exe")), "Installed in the right location"); } [Test] public void ShouldDeployAndInstallWhenThereAreSpacesInThePathAndArguments() { Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.CustomDirectory,Octopus.Features.WindowsService"; var installDir = Path.Combine(CustomDirectory, "A Directory With A Space In It"); Variables[PackageVariables.CustomInstallationDirectory] = installDir; Variables[SpecialVariables.Action.WindowsService.Arguments] = "\"Argument with Space\" ArgumentWithoutSpace"; RunDeployment(); Assert.IsTrue(File.Exists(Path.Combine(installDir, $"{ServiceName}.exe")), "Installed in the right location"); } [Test] public void ShouldDeployAndInstallWithCustomUserName() { if (!CalamariEnvironment.IsRunningOnWindows) Assert.Inconclusive("Services are only supported on windows"); #if WINDOWS_USER_ACCOUNT_SUPPORT TestUserPrincipal userPrincipal = null; try { userPrincipal = new TestUserPrincipal("calamari-svc-test") .EnsureIsMemberOfGroup("Administrators") .GrantLogonAsAServiceRight(); Variables[SpecialVariables.Action.WindowsService.CustomAccountName] = userPrincipal.NTAccountName; Variables[SpecialVariables.Action.WindowsService.CustomAccountPassword] = userPrincipal.Password; RunDeployment(); } finally { userPrincipal?.Delete(); } #else Assert.Inconclusive("Not yet able to configure user accounts under netcore to test service accounts"); #endif } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using YamlDotNet.Core; using YamlDotNet.Core.Events; namespace Calamari.Common.Features.StructuredVariables { public class YamlFormatVariableReplacer : IFileFormatVariableReplacer { static readonly Regex OctopusReservedVariablePattern = new Regex(@"^Octopus([^:]|$)", RegexOptions.IgnoreCase | RegexOptions.Compiled); readonly ICalamariFileSystem fileSystem; readonly ILog log; public YamlFormatVariableReplacer(ICalamariFileSystem fileSystem, ILog log) { this.fileSystem = fileSystem; this.log = log; } public string FileFormatName => StructuredConfigVariablesFileFormats.Yaml; public bool IsBestReplacerForFileName(string fileName) { return fileName.EndsWith(".yml", StringComparison.InvariantCultureIgnoreCase) || fileName.EndsWith(".yaml", StringComparison.InvariantCultureIgnoreCase); } public void ModifyFile(string filePath, IVariables variables) { try { void LogReplacement(string key) => log.Verbose(StructuredConfigMessages.StructureFound(key)); var replaced = 0; var variablesByKey = variables .Where(v => !OctopusReservedVariablePattern.IsMatch(v.Key)) .DistinctBy(v => v.Key) .ToDictionary<KeyValuePair<string, string>, string, Func<string?>>(v => v.Key, v => () => { LogReplacement(v.Key); replaced++; return variables.Get(v.Key); }, StringComparer.OrdinalIgnoreCase); // Read and transform the input file var fileText = fileSystem.ReadFile(filePath, out var encoding); var lineEnding = fileText.GetMostCommonLineEnding(); var outputEvents = new List<ParsingEvent>(); var indentDetector = new YamlIndentDetector(); using (var reader = new StringReader(fileText)) { var scanner = new Scanner(reader, false); var parser = new Parser(scanner); var classifier = new YamlEventStreamClassifier(); (IYamlNode startEvent, string? replacementValue)? structureWeAreReplacing = null; while (parser.MoveNext()) { var ev = parser.Current; if (ev == null) continue; indentDetector.Process(ev); if (ev is Comment c) ev = c.RestoreLeadingSpaces(); var node = classifier.Process(ev); if (structureWeAreReplacing == null) { // Not replacing: searching for things to replace, copying events to output. if (node is YamlNode<Scalar> scalar && variablesByKey.TryGetValue(scalar.Path, out var newValue)) outputEvents.Add(scalar.Event.ReplaceValue(newValue())); else if (node is YamlNode<MappingStart> mappingStart && variablesByKey.TryGetValue(mappingStart.Path, out var mappingReplacement)) structureWeAreReplacing = (mappingStart, mappingReplacement()); else if (node is YamlNode<SequenceStart> sequenceStart && variablesByKey.TryGetValue(sequenceStart.Path, out var sequenceReplacement)) structureWeAreReplacing = (sequenceStart, sequenceReplacement()); else if (node is YamlNode<Comment> comment) structureWeAreReplacing = (comment, null); else outputEvents.Add(node.Event); } else { // Replacing: searching for the end of the structure we're replacing. No output until then. if (node is YamlNode<MappingEnd> && structureWeAreReplacing.Value.startEvent is YamlNode<MappingStart> mappingStart && structureWeAreReplacing.Value.startEvent.Path == node.Path) { outputEvents.AddRange(ParseFragment(structureWeAreReplacing.Value.replacementValue, mappingStart.Event.Anchor, mappingStart.Event.Tag)); structureWeAreReplacing = null; } else if (node is YamlNode<SequenceEnd> && structureWeAreReplacing.Value.startEvent is YamlNode<SequenceStart> sequenceStart && structureWeAreReplacing.Value.startEvent.Path == node.Path) { outputEvents.AddRange(ParseFragment(structureWeAreReplacing.Value.replacementValue, sequenceStart.Event.Anchor, sequenceStart.Event.Tag)); structureWeAreReplacing = null; } else if ((node is YamlNode<MappingStart> || node is YamlNode<SequenceStart>) && structureWeAreReplacing.Value.startEvent is YamlNode<Comment>) { // We aren't doing any replacement here, YamlDotNet gives us the comment and the // mapping/sequence start element in a different order to what we would expect // (comment first, start element second instead of the other way around), // so we are flipping them back to the other way around so the output is correct. outputEvents.Add(node.Event); outputEvents.Add(structureWeAreReplacing.Value.startEvent.Event); structureWeAreReplacing = null; } else if (structureWeAreReplacing.Value.startEvent is YamlNode<Comment>) { // Comment after any other type of element, just put in the order in which they were given to us outputEvents.Add(structureWeAreReplacing.Value.startEvent.Event); outputEvents.Add(node.Event); structureWeAreReplacing = null; } } } if (replaced == 0) log.Info(StructuredConfigMessages.NoStructuresFound); } fileSystem.OverwriteFile(filePath, writer => { writer.NewLine = lineEnding == StringExtensions.LineEnding.Dos ? "\r\n" : "\n"; var emitter = new Emitter(writer, indentDetector.GetMostCommonIndent()); foreach (var outputEvent in outputEvents) emitter.Emit(outputEvent); }, encoding); } catch (Exception e) when (e is SyntaxErrorException || e is SemanticErrorException) { throw new StructuredConfigFileParseException(e.Message, e); } } List<ParsingEvent> ParseFragment(string? value, string? anchor, string? tag) { var result = new List<ParsingEvent>(); try { using (var reader = new StringReader(value)) { var parser = new Parser(reader); bool added = false; while (parser.MoveNext()) { var ev = parser.Current; if (ev != null && !(ev is StreamStart || ev is StreamEnd || ev is DocumentStart || ev is DocumentEnd)) { result.Add(ev); added = true; } } if (!added) throw new Exception("No content found in fragment"); } } catch { // The input could not be recognized as a structure. Falling back to treating it as a string. result.Add(value != null ? new Scalar(anchor, tag, value, ScalarStyle.DoubleQuoted, true, true) : new Scalar(anchor, tag, "null", ScalarStyle.Plain, true, false)); } return result; } } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Calamari.Testing.Helpers; namespace Calamari.Tests.Helpers { public static class CaptureCommandOutputExtensions { public static string ToApprovalString(this CaptureCommandInvocationOutputSink output) { return output .AllMessages .RemoveIgnoredLines() .TrimRedactedLines() .Aggregate(new StringBuilder(), (builder, s) => builder.AppendLine(s), builder => builder.ToString()) .ScrubGuids() .ScrubTimestampTempFolders(); } private static readonly Regex[] TrimLinesMatching = { new Regex(@"Octopus Deploy: Calamari version", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"PSVersion ", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"WSManStackVersion ", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"SerializationVersion ", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"CLRVersion ", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"BuildVersion ", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"PSCompatibleVersions ", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"PSRemotingProtocolVersion ", RegexOptions.Compiled | RegexOptions.IgnoreCase), }; private static readonly Regex[] IgnoreLinesMatching = { //new Regex(@"THING TO REMOVE", RegexOptions.Compiled | RegexOptions.IgnoreCase), }; public static IEnumerable<string> RemoveIgnoredLines(this IEnumerable<string> lines) { return lines.Where(line => !IgnoreLinesMatching.Any(regex => regex.IsMatch(line))); } public static IEnumerable<string> TrimRedactedLines(this IEnumerable<string> lines) { return lines.Select(line => TrimLinesMatching.FirstOrDefault(regex => regex.IsMatch(line))?.ToString() ?? line); } private static readonly Regex GuidScrubber = new Regex(@"[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?", RegexOptions.Compiled | RegexOptions.IgnoreCase); public static string ScrubGuids(this string subject) { return GuidScrubber.Replace(subject, "<GUID>"); } private static readonly Regex TimestampTempFolderScrubber = new Regex(@"\d{14}\-\d*", RegexOptions.Compiled | RegexOptions.IgnoreCase); public static string ScrubTimestampTempFolders(this string subject) { return TimestampTempFolderScrubber.Replace(subject, "<TIMESTAMP-TEMP-FOLDER>"); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Calamari.Common.Plumbing.Extensions; using Calamari.Integration.Packages.NuGet; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using Calamari.Util; using NUnit.Framework; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class NuGetFileSystemDownloaderFixture : CalamariFixture { private string rootDir; [SetUp] public void Setup() { rootDir = GetFixtureResource(this.GetType().Name); TearDown(); Directory.CreateDirectory(GetFixtureResource(rootDir)); } [TearDown] public void TearDown() { if (Directory.Exists(rootDir)) { Directory.Delete(rootDir, true); } } [Test] public void FindsAndCopiesNugetPackageWithNugetFileFormat() { var originalPath = Path.Combine(rootDir, "Acme.Core.1.0.0.0-bugfix.nupkg"); File.Copy(GetFixtureResource("Samples", "Acme.Core.1.0.0.0-bugfix.nupkg"), originalPath); var downloadPath = Path.Combine(rootDir, "DummyFile.nupkg"); NuGetFileSystemDownloader.DownloadPackage("Acme.Core", new SemanticVersion("1.0.0.0-bugfix"), new Uri(rootDir), downloadPath); Assert.AreEqual(HashCalculator.Hash(originalPath), HashCalculator.Hash(downloadPath), "Expected source file to have been copied"); } [Test] public void IgnoresZipPackages() { File.Copy(GetFixtureResource("Samples", "Acme.Core.1.0.0.0-bugfix.zip"), Path.Combine(rootDir, "Acme.Core.1.0.0.0-bugfix.zip")); var downloadPath = Path.Combine(rootDir, "DummyFile.nupkg"); Assert.Throws<Exception>(() => NuGetFileSystemDownloader.DownloadPackage("Acme.Core", new SemanticVersion("1.0.0.0-bugfix"), new Uri(rootDir), downloadPath) ); FileAssert.DoesNotExist(downloadPath); } private string GetFileName() { return GetFixtureResource("Samples", "Acme.Core.1.0.0.0-bugfix.nupkg"); } } } <file_sep>using System; using Autofac; namespace Calamari.Common.Plumbing.Pipeline { public abstract class Resolver<T> { readonly ILifetimeScope lifetimeScope; protected Resolver(ILifetimeScope lifetimeScope) { this.lifetimeScope = lifetimeScope; } public T Create<TBehaviour>() where TBehaviour : T { return lifetimeScope.Resolve<TBehaviour>(); } } }<file_sep>using System; namespace Calamari.Common.Features.FunctionScriptContributions { public enum ParameterType { String, Bool, Int, } }<file_sep>using System; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureServiceFabric.Behaviours { class SubstituteVariablesInAzureServiceFabricPackageBehaviour : IDeployBehaviour { readonly ICalamariFileSystem fileSystem; readonly IFileSubstituter substituter; public SubstituteVariablesInAzureServiceFabricPackageBehaviour(ICalamariFileSystem fileSystem, IFileSubstituter substituter) { this.fileSystem = fileSystem; this.substituter = substituter; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var configurationFiles = fileSystem.EnumerateFilesRecursively(context.CurrentDirectory, "*.config", "*.xml"); foreach (var configurationFile in configurationFiles) { substituter.PerformSubstitution(configurationFile, context.Variables); } return this.CompletedTask(); } } }<file_sep>using System; using System.Diagnostics; using System.Runtime.Serialization; using System.Threading; namespace Calamari.Common.Features.Processes.Semaphores { public interface IFileLock {} [DataContract] public class FileLock : IFileLock { public FileLock(long processId, string processName, int threadId, long timestamp) { ProcessId = processId; ProcessName = processName; ThreadId = threadId; Timestamp = timestamp; } [DataMember] public long ProcessId { get; } [DataMember] public long Timestamp { get; internal set; } [DataMember] public string ProcessName { get; } [DataMember] public int ThreadId { get; } protected bool Equals(FileLock other) { return ProcessId == other.ProcessId && string.Equals(ProcessName, other.ProcessName) && ThreadId == other.ThreadId; } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((FileLock)obj); } public override int GetHashCode() { unchecked { var hashCode = ProcessId.GetHashCode(); hashCode = (hashCode * 397) ^ (ProcessName?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ ThreadId; return hashCode; } } public bool BelongsToCurrentProcessAndThread() { return ProcessId == Process.GetCurrentProcess().Id && ThreadId == Thread.CurrentThread.ManagedThreadId; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Azure; using Azure.ResourceManager.AppService; using Azure.ResourceManager.AppService.Models; using Azure.ResourceManager.Resources; using Calamari.AzureAppService.Azure; using Calamari.AzureAppService.Behaviors; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using FluentAssertions; using NUnit.Framework; using Octostache; namespace Calamari.AzureAppService.Tests { [TestFixture] public class AzureAppServiceDeployContainerBehaviorFixture : AppServiceIntegrationTest { CalamariVariables newVariables; readonly HttpClient client = new HttpClient(); // For some reason we are having issues creating these linux resources on Standard in EastUS protected override string DefaultResourceGroupLocation => "westus2"; protected override async Task ConfigureTestResources(ResourceGroupResource resourceGroup) { var (_, webSite) = await CreateAppServicePlanAndWebApp(resourceGroup, new AppServicePlanData(resourceGroup.Data.Location) { Kind = "linux", IsReserved = true, Sku = new AppServiceSkuDescription { Name = "S1", Tier = "Standard" } }, new WebSiteData(resourceGroup.Data.Location) { SiteConfig = new SiteConfigProperties { LinuxFxVersion = @"DOCKER|mcr.microsoft.com/azuredocs/aci-helloworld", IsAlwaysOn = true, AppSettings = new List<AppServiceNameValuePair> { new AppServiceNameValuePair { Name = "DOCKER_REGISTRY_SERVER_URL", Value = "https://index.docker.io" }, new AppServiceNameValuePair { Name = "WEBSITES_ENABLE_APP_SERVICE_STORAGE", Value = "false" } } } }); WebSiteResource = webSite; await AssertSetupSuccessAsync(); } [Test] public async Task AzureLinuxContainerDeploy() { newVariables = new CalamariVariables(); AddVariables(newVariables); var runningContext = new RunningDeployment("", newVariables); await new AzureAppServiceDeployContainerBehaviour(new InMemoryLog()).Execute(runningContext); var targetSite = new AzureTargetSite(SubscriptionId, ResourceGroupName, WebSiteResource.Data.Name); await AssertDeploySuccessAsync(targetSite); } [Test] public async Task AzureLinuxContainerSlotDeploy() { var slotName = "stage"; newVariables = new CalamariVariables(); AddVariables(newVariables); newVariables.Add("Octopus.Action.Azure.DeploymentSlot", slotName); await WebSiteResource.GetWebSiteSlots() .CreateOrUpdateAsync(WaitUntil.Completed, slotName, WebSiteResource.Data); var runningContext = new RunningDeployment("", newVariables); await new AzureAppServiceDeployContainerBehaviour(new InMemoryLog()).Execute(runningContext); var targetSite = new AzureTargetSite(SubscriptionId, ResourceGroupName, WebSiteResource.Data.Name, slotName); await AssertDeploySuccessAsync(targetSite); } async Task AssertSetupSuccessAsync() { var response = await RetryPolicies.TransientHttpErrorsPolicy.ExecuteAsync(async () => { var r = await client.GetAsync($@"https://{WebSiteResource.Data.DefaultHostName}"); r.EnsureSuccessStatusCode(); return r; }); var receivedContent = await response.Content.ReadAsStringAsync(); receivedContent.Should().Contain(@"<title>Welcome to Azure Container Instances!</title>"); Assert.IsTrue(response.IsSuccessStatusCode); } async Task AssertDeploySuccessAsync(AzureTargetSite targetSite) { var imageName = newVariables.Get(SpecialVariables.Action.Package.PackageId); var registryUrl = newVariables.Get(SpecialVariables.Action.Package.Registry); var imageVersion = newVariables.Get(SpecialVariables.Action.Package.PackageVersion) ?? "latest"; var config = await WebSiteResource.GetWebSiteConfig().GetAsync(); Assert.AreEqual($@"DOCKER|{imageName}:{imageVersion}", config.Value.Data.LinuxFxVersion); var appSettings = await ArmClient.GetAppSettingsListAsync(targetSite); Assert.AreEqual("https://" + registryUrl, appSettings.FirstOrDefault(app => app.Name == "DOCKER_REGISTRY_SERVER_URL")?.Value); } void AddVariables(VariableDictionary vars) { AddAzureVariables(vars); vars.Add(SpecialVariables.Action.Package.FeedId, "Feeds-42"); vars.Add(SpecialVariables.Action.Package.Registry, "index.docker.io"); vars.Add(SpecialVariables.Action.Package.PackageId, "nginx"); vars.Add(SpecialVariables.Action.Package.Image, "nginx:latest"); vars.Add(SpecialVariables.Action.Package.PackageVersion, "latest"); vars.Add(SpecialVariables.Action.Azure.DeploymentType, "Container"); //vars.Add(SpecialVariables.Action.Azure.ContainerSettings, BuildContainerConfigJson()); } } }<file_sep>using Calamari.Common.Commands; namespace Calamari.Deployment.Conventions { public interface IRollbackConvention : IConvention { void Rollback(RunningDeployment deployment); void Cleanup(RunningDeployment deployment); } }<file_sep>using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class CronJob : Resource { public string Schedule { get; } public bool Suspend { get; } public CronJob(JObject json, Options options) : base(json, options) { Schedule = Field("$.spec.schedule"); Suspend = FieldOrDefault("$.spec.suspend", false); } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<CronJob>(lastStatus); return last.Schedule != Schedule || last.Suspend != Suspend; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using Calamari.Testing.Helpers; using FluentAssertions; using Newtonsoft.Json.Linq; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus { [TestFixture] public class RunningResourceStatusCheckTests { [Test] public async Task ShouldReportStatusesWithIncrementingCheckCount() { var retriever = new TestRetriever(); var reporter = new TestReporter(); var kubectl = GetKubectl(); var statusCheckTaskFactory = GetStatusCheckTaskFactory(retriever, reporter, kubectl, maxChecks: 5); var log = new InMemoryLog(); for (var i = 0; i < 5; i++) { retriever.SetResponses(new List<Resource>{ new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress) }); } var resourceStatusChecker = new RunningResourceStatusCheck(statusCheckTaskFactory, log, new TimeSpan(), new Options(), new[] { new ResourceIdentifier("Pod", "my-pod", "default") }); await resourceStatusChecker.WaitForCompletionOrTimeout(); reporter.CheckCounts().Should().BeEquivalentTo(new List<int> { 1, 2, 3, 4, 5 }); } [Test] public async Task SuccessfulBeforeTimeout_ShouldReturnAsSuccessful() { var retriever = new TestRetriever(); var reporter = new TestReporter(); var kubectl = GetKubectl(); var statusCheckTaskFactory = GetStatusCheckTaskFactory(retriever, reporter, kubectl, maxChecks: 5); var log = new InMemoryLog(); retriever.SetResponses( new List<Resource> { new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful) } ); var resourceStatusChecker = new RunningResourceStatusCheck(statusCheckTaskFactory, log, new TimeSpan(), new Options(), new[] { new ResourceIdentifier("Pod", "my-pod", "default") }); var result = await resourceStatusChecker.WaitForCompletionOrTimeout(); result.Should().BeTrue(); log.StandardError.Should().BeEmpty(); log.StandardOut.Should().Contain(RunningResourceStatusCheck.MessageDeploymentSucceeded); } [Test] public async Task FailureBeforeTimeout_ShouldReturnAsFailed() { var retriever = new TestRetriever(); var reporter = new TestReporter(); var kubectl = GetKubectl(); var statusCheckTaskFactory = GetStatusCheckTaskFactory(retriever, reporter, kubectl, maxChecks: 5); var log = new InMemoryLog(); retriever.SetResponses( new List<Resource> { new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.Failed) } ); var resourceStatusChecker = new RunningResourceStatusCheck(statusCheckTaskFactory, log, new TimeSpan(), new Options(), new[] { new ResourceIdentifier("Pod", "my-pod", "default") }); var result = await resourceStatusChecker.WaitForCompletionOrTimeout(); result.Should().BeFalse(); log.StandardError .Should().ContainSingle().Which .Should().Be(RunningResourceStatusCheck.MessageDeploymentFailed); } [Test] public async Task DeploymentInProgressAtTheEndOfTimeout_ShouldReturnAsFailed() { var retriever = new TestRetriever(); var reporter = new TestReporter(); var kubectl = GetKubectl(); var statusCheckTaskFactory = GetStatusCheckTaskFactory(retriever, reporter, kubectl, maxChecks: 5); var log = new InMemoryLog(); retriever.SetResponses( new List<Resource> { new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress) }, new List<Resource> { new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress) } ); var resourceStatusChecker = new RunningResourceStatusCheck(statusCheckTaskFactory, log, new TimeSpan(), new Options(), new[] { new ResourceIdentifier("Pod", "my-pod", "default") }); var result = await resourceStatusChecker.WaitForCompletionOrTimeout(); result.Should().BeFalse(); log.StandardError .Should().ContainSingle().Which .Should().Be(RunningResourceStatusCheck.MessageInProgressAtTheEndOfTimeout); } [Test] public async Task NonTopLevelResourcesAreIgnoredInCalculatingTheDeploymentStatus() { var retriever = new TestRetriever(); var reporter = new TestReporter(); var kubectl = GetKubectl(); var statusCheckTaskFactory = GetStatusCheckTaskFactory(retriever, reporter, kubectl, maxChecks: 5); var log = new InMemoryLog(); retriever.SetResponses( new List<Resource> { new TestResource("ReplicaSet", Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful, new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.Failed), new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress)) }); var resourceStatusChecker = new RunningResourceStatusCheck(statusCheckTaskFactory, log, new TimeSpan(), new Options(), new[] { new ResourceIdentifier("ReplicaSet", "my-rs", "default") }); var result = await resourceStatusChecker.WaitForCompletionOrTimeout(); result.Should().BeTrue(); log.StandardError.Should().BeEmpty(); log.StandardOut.Should().Contain(RunningResourceStatusCheck.MessageDeploymentSucceeded); } [Test] public async Task ShouldNotReturnSuccessIfSomeOfTheDefinedResourcesWereNotCreated() { var retriever = new TestRetriever(); var reporter = new TestReporter(); var kubectl = GetKubectl(); var statusCheckTaskFactory = GetStatusCheckTaskFactory(retriever, reporter, kubectl, maxChecks: 5); var log = new InMemoryLog(); retriever.SetResponses( new List<Resource> { new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful) }, new List<Resource> { new TestResource("Pod", Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful) } ); var resourceStatusChecker = new RunningResourceStatusCheck(statusCheckTaskFactory, log, new TimeSpan(), new Options(), new[] { new ResourceIdentifier("Pod", "my-pod", "default"), new ResourceIdentifier("Service", "my-service", "default") }); var result = await resourceStatusChecker.WaitForCompletionOrTimeout(); result.Should().BeFalse(); log.StandardError .Should().ContainSingle().Which .Should().Be(RunningResourceStatusCheck.MessageInProgressAtTheEndOfTimeout); } private IKubectl GetKubectl() { var kubectl = Substitute.For<IKubectl>(); kubectl.TrySetKubectl().Returns(true); return kubectl; } private Func<ResourceStatusCheckTask> GetStatusCheckTaskFactory(IResourceRetriever retriever, IResourceUpdateReporter reporter, IKubectl kubectl, int maxChecks) { return () => new ResourceStatusCheckTask(retriever, reporter, kubectl, (_, __) => new TestTimer(maxChecks)); } } public class TestRetriever : IResourceRetriever { private readonly List<List<Resource>> responses = new List<List<Resource>>(); private int current; public IEnumerable<Resource> GetAllOwnedResources( IEnumerable<ResourceIdentifier> resourceIdentifiers, IKubectl kubectl, Options options) { return current >= responses.Count ? new List<Resource>() : responses[current++]; } public void SetResponses(params List<Resource>[] responses) { this.responses.AddRange(responses); } } public class TestReporter : IResourceUpdateReporter { private readonly List<int> checkCounts = new List<int>(); public void ReportUpdatedResources(IDictionary<string, Resource> originalStatuses, IDictionary<string, Resource> newStatuses, int checkCount) { checkCounts.Add(checkCount); } public List<int> CheckCounts() => checkCounts.ToList(); } public class TestTimer : ITimer { private readonly int maxChecks; private int checks; public TestTimer(int maxChecks) => this.maxChecks = maxChecks; public void Start() { } public bool HasCompleted() => checks >= maxChecks; public async Task WaitForInterval() { await Task.CompletedTask; checks++; } } public sealed class TestResource : Resource { public TestResource(string kind, Kubernetes.ResourceStatus.Resources.ResourceStatus status, params Resource[] children) { Uid = Guid.NewGuid().ToString(); Kind = kind; ResourceStatus = status; Children = children.ToList(); } public TestResource(JObject json, Options options) : base(json, options) { } } } <file_sep>using System; namespace Calamari.Testing.LogParser { public class CollectedArtifact { public CollectedArtifact(string name, string? path) { this.Name = name; this.Path = path; } public string Name { get; } public string? Path { get; } public long Length { get; set; } } }<file_sep>namespace Calamari.AzureWebApp.Integration.Websites.Publishing { class AzureTargetSite { public string RawSite { get; set; } public string Site { get; set; } public string Slot { get; set; } public string SiteAndSlot => HasSlot ? $"{Site}/{Slot}" : Site; public string SiteAndSlotLegacy => HasSlot ? $"{Site}({Slot})" : Site; public bool HasSlot => !string.IsNullOrWhiteSpace(Slot); } }<file_sep>namespace Calamari.GoogleCloudScripting { class SpecialVariables { public static class Action { public static class GoogleCloud { public static readonly string JsonKey = "Octopus.Action.GoogleCloudAccount.JsonKey"; } } } }<file_sep>using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class Secret: Resource { public int Data { get; } public string Type { get; } public Secret(JObject json, Options options) : base(json, options) { Type = Field("$.type"); Data = (data.SelectToken("$.data") ?.ToObject<Dictionary<string, string>>() ?? new Dictionary<string, string>()) .Count; } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<Secret>(lastStatus); return last.Data != Data || last.Type != Type; } } } <file_sep>using System; using System.Linq; using System.Text.RegularExpressions; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting.Python; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using NUnit.Framework; using NUnit.Framework.Interfaces; using Octopus.CoreUtilities; namespace Calamari.Testing.Requirements { public class RequiresMinimumPython3VersionAttribute : TestAttribute, ITestAction { const int Major = 3; readonly int minor; public RequiresMinimumPython3VersionAttribute(int minor) { this.minor = minor; } public void BeforeTest(ITest test) { var python3Version = GetPython3Version(); if (python3Version.None()) { Assert.Inconclusive("Requires Python3 to be installed"); } if (python3Version.Value < new Version(Major, minor)) { Assert.Inconclusive($"Requires Python3 {Major}.{minor}"); } } public void AfterTest(ITest test) { } public ActionTargets Targets { get; set; } static readonly Regex PythonVersionFinder = new Regex(@"Python (\d*)\.(\d*)", RegexOptions.Compiled | RegexOptions.IgnoreCase); static Maybe<Version> GetPython3Version() { var executable = PythonBootstrapper.FindPythonExecutable(); var command = new CommandLine(executable).Argument("--version"); var runner = new TestCommandLineRunner(new InMemoryLog(), new CalamariVariables()); var result = runner.Execute(command.Build()); if (result.ExitCode != 0) return Maybe<Version>.None; var allCapturedMessages = runner.Output.AllMessages.Aggregate((a, b) => $"{a}, {b}"); var pythonVersionMatch = PythonVersionFinder.Match(allCapturedMessages); if (!pythonVersionMatch.Success) return Maybe<Version>.None; var major = pythonVersionMatch.Groups[1].Value; var minor = pythonVersionMatch.Groups[2].Value; return new Version(int.Parse(major), int.Parse(minor)).AsSome(); } } }<file_sep>using System; using Octopus.Versioning; namespace Calamari.Testing.LogParser { public class FoundPackage { public string PackageId { get; } public IVersion Version { get; } public string? RemotePath { get; } public string? Hash { get; } public string? FileExtension { get; } public FoundPackage(string packageId, string version, string? versionFormat, string? remotePath, string? hash, string? fileExtension) { PackageId = packageId; if (!Enum.TryParse(versionFormat, out VersionFormat realVersionFormat)) { realVersionFormat = VersionFormat.Semver; }; Version = VersionFactory.CreateVersion(version, realVersionFormat); RemotePath = remotePath; Hash = hash; FileExtension = fileExtension; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Autofac.Features.Metadata; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.LaunchTools; using Calamari.Serialization; using Newtonsoft.Json; namespace Calamari.Commands { [Command("execute-manifest")] public class ExecuteManifestCommand : Command { readonly IVariables variables; readonly IEnumerable<Meta<ILaunchTool, LaunchToolMeta>> executionTools; private readonly ICalamariFileSystem fileSystem; private readonly ILog log; private readonly ICommandLineRunner commandLineRunner; public ExecuteManifestCommand(IVariables variables, IEnumerable<Meta<ILaunchTool, LaunchToolMeta>> executionTools, ICalamariFileSystem fileSystem, ILog log, ICommandLineRunner commandLineRunner) { this.variables = variables; this.executionTools = executionTools; this.fileSystem = fileSystem; this.log = log; this.commandLineRunner = commandLineRunner; } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); var contents = variables.Get(SpecialVariables.Execution.Manifest); if (contents == null) { throw new CommandException("Execution manifest not found in variables."); } var instructions = JsonConvert.DeserializeObject<Instruction[]>(contents, JsonSerialization.GetDefaultSerializerSettings()); if (instructions.Length == 0) { throw new CommandException("The execution manifest must have at least one instruction."); } foreach (var instruction in instructions) { var tool = executionTools.First(x => x.Metadata.Tool == instruction.Launcher); var result = tool.Value.Execute(instruction.LauncherInstructionsRaw); if (result != 0) { return result; } if (variables.GetFlag(KnownVariables.Action.SkipRemainingConventions)) { break; } } return 0; } } }<file_sep>echo "hello from PostDeploy.sh" <file_sep>using System; using System.Collections.Generic; namespace Calamari.Common.Features.Deployment.Journal { public interface IDeploymentJournal { List<JournalEntry> GetAllJournalEntries(); void RemoveJournalEntries(IEnumerable<string> ids); JournalEntry GetLatestInstallation(string retentionPolicySubset); JournalEntry GetLatestInstallation(string retentionPolicySubset, string packageId, string packageVersion); JournalEntry GetLatestSuccessfulInstallation(string retentionPolicySubset); JournalEntry GetLatestSuccessfulInstallation(string retentionPolicySubset, string packageId, string packageVersion); } }<file_sep>namespace Calamari.Commands { public class CommandMeta { public string Name { get; set; } } }<file_sep>using System.IO; using Assent; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { public class DeployPackageWithJsonConfigurationFixture : DeployPackageFixture { const string ServiceName = "Acme.JsonFileOutput"; const string ServiceVersion = "1.0.0"; const string JsonFileName = "values.json"; [SetUp] public override void SetUp() { base.SetUp(); } [Test] public void ShouldReplaceJsonPropertiesFromVariables() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, JsonFileName); Variables.Set("departments:0:employees:0:name", "Jane"); Variables.Set("departments:0:employees:1:age", "40"); Variables.Set("phone", "0123 456 789"); Variables.Set("departments:0:snacks", "[{ \"name\": \"lollies\", \"amount\": 3 }, { \"name\": \"soda\", \"amount\": 24 }]"); Variables.Set("Octopus", "true"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedJsonFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, JsonFileName)); this.Assent(extractedPackageUpdatedJsonFile, AssentConfiguration.Json); } } [TearDown] public override void CleanUp() { base.CleanUp(); } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureAppService.Behaviors { public class AppDeployBehaviour : IDeployBehaviour { readonly AzureAppServiceDeployContainerBehaviour containerBehaviour; readonly AzureAppServiceBehaviour appServiceBehaviour; ILog Log { get; } public AppDeployBehaviour(ILog log) { Log = log; containerBehaviour = new AzureAppServiceDeployContainerBehaviour(log); appServiceBehaviour = new AzureAppServiceBehaviour(log); } public bool IsEnabled(RunningDeployment context) => FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.IsEnabled(context.Variables); public Task Execute(RunningDeployment context) { var deploymentType = context.Variables.Get(SpecialVariables.Action.Azure.DeploymentType); Log.Verbose($"Deployment type: {deploymentType}"); return deploymentType switch { "Container" => containerBehaviour.Execute(context), _ => appServiceBehaviour.Execute(context) }; } } } <file_sep>import os print('HTTP_PROXY:' + os.environ.get('HTTP_PROXY', '')) print('HTTPS_PROXY:' + os.environ.get('HTTPS_PROXY', '')) print('NO_PROXY:' + os.environ.get('NO_PROXY', '')) <file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Model; namespace Calamari.Deployment.PackageRetention.Repositories { public interface IJournalRepository { bool TryGetJournalEntry(PackageIdentity package, out JournalEntry entry); PackageCache Cache { get; } void RemoveAllLocks(ServerTaskId serverTaskId); IList<JournalEntry> GetAllJournalEntries(); void AddJournalEntry(JournalEntry entry); void RemovePackageEntry(PackageIdentity packageIdentity); void Load(); void Commit(); } }<file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Microsoft.Azure; namespace Calamari.AzureCloudService { public class UploadAzureCloudServicePackageBehaviour : IDeployBehaviour { readonly ILog log; readonly AzurePackageUploader azurePackageUploader; public UploadAzureCloudServicePackageBehaviour(ILog log, AzurePackageUploader azurePackageUploader) { this.log = log; this.azurePackageUploader = azurePackageUploader; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment context) { var package = context.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath); log.InfoFormat("Uploading package to Azure blob storage: '{0}'", package); var packageHash = HashCalculator.Hash(package); var nugetPackageVersion = context.Variables.Get(PackageVariables.PackageVersion); var uploadedFileName = Path.ChangeExtension(Path.GetFileName(package), "." + nugetPackageVersion + "_" + packageHash + ".cspkg"); var credentials = GetCredentials(context.Variables); var storageAccountName = context.Variables.Get(SpecialVariables.Action.Azure.StorageAccountName); var storageEndpointSuffix = context.Variables.Get(SpecialVariables.Action.Azure.StorageEndPointSuffix, DefaultVariables.StorageEndpointSuffix); var defaultServiceManagementEndpoint = context.Variables.Get(SpecialVariables.Action.Azure.ServiceManagementEndPoint, DefaultVariables.ServiceManagementEndpoint); var uploadedUri = await azurePackageUploader.Upload(credentials, storageAccountName, package, uploadedFileName,storageEndpointSuffix, defaultServiceManagementEndpoint); log.SetOutputVariable(SpecialVariables.Action.Azure.UploadedPackageUri, uploadedUri.ToString(), context.Variables); log.Info($"Package uploaded to {uploadedUri}"); } SubscriptionCloudCredentials GetCredentials(IVariables variables) { var subscriptionId = variables.Get(SpecialVariables.Action.Azure.SubscriptionId); var certificateThumbprint = variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint); var certificateBytes = Convert.FromBase64String(variables.Get(SpecialVariables.Action.Azure.CertificateBytes)); var certificate = CalamariCertificateStore.GetOrAdd(certificateThumbprint, certificateBytes); return new CertificateCloudCredentials(subscriptionId, certificate); } } }<file_sep>failstep("Custom failure message")<file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using Calamari.CloudAccounts; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Retry; using Calamari.Common.Plumbing.Variables; using Calamari.Terraform.Commands; using Calamari.Terraform.Tests.CommonTemplates; using Calamari.Testing; using Calamari.Testing.Helpers; using FluentAssertions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; namespace Calamari.Terraform.Tests { [TestFixture("0.11.15")] [TestFixture("0.13.0")] [TestFixture("1.0.0")] public class CommandsFixture { string? customTerraformExecutable; string terraformCliVersion; readonly string planCommand = GetCommandFromType(typeof(PlanCommand)); readonly string applyCommand = GetCommandFromType(typeof(ApplyCommand)); readonly string destroyCommand = GetCommandFromType(typeof(DestroyCommand)); readonly string destroyPlanCommand = GetCommandFromType(typeof(DestroyPlanCommand)); Version TerraformCliVersionAsObject => new(terraformCliVersion); public CommandsFixture(string version) { terraformCliVersion = version; InstallTools().GetAwaiter().GetResult(); } [OneTimeTearDown] public static void OneTimeTearDown() { ClearTestDirectories(); } static void ClearTestDirectories() { static void TryDeleteFile(string path) { try { File.Delete(TestEnvironment.GetTestPath(path)); } catch (IOException) { } } static void TryDeleteDirectory(string path, bool recursive) { try { Directory.Delete(TestEnvironment.GetTestPath(path), recursive); } catch (IOException) { } } static void ClearTerraformDirectory(string directory) { TryDeleteFile(Path.Combine(directory, "terraform.tfstate")); TryDeleteFile(Path.Combine(directory, "terraform.tfstate.backup")); TryDeleteFile(Path.Combine(directory, "terraform.log")); TryDeleteDirectory(Path.Combine(directory, ".terraform"), true); TryDeleteDirectory(Path.Combine(directory, "terraform.tfstate.d"), true); TryDeleteDirectory(Path.Combine(directory, "terraformplugins"), true); } ClearTerraformDirectory("AdditionalParams"); ClearTerraformDirectory("AWS"); ClearTerraformDirectory("Azure"); ClearTerraformDirectory("GoogleCloud"); ClearTerraformDirectory("PlanDetailedExitCode"); ClearTerraformDirectory("Simple"); ClearTerraformDirectory($"TemplateDirectory{Path.DirectorySeparatorChar}SubFolder"); ClearTerraformDirectory("TemplateDirectory"); ClearTerraformDirectory("WithOutputSensitiveVariables"); ClearTerraformDirectory("WithVariables"); ClearTerraformDirectory("WithVariablesSubstitution"); } public async Task InstallTools() { ClearTestDirectories(); // pre-emptively clear test directories for better dev experience static string GetTerraformFileName(string currentVersion) { if (CalamariEnvironment.IsRunningOnNix) return $"terraform_{currentVersion}_linux_amd64.zip"; if (CalamariEnvironment.IsRunningOnMac) return $"terraform_{currentVersion}_darwin_amd64.zip"; return $"terraform_{currentVersion}_windows_amd64.zip"; } static async Task DownloadTerraform(string fileName, HttpClient client, string downloadBaseUrl, string destination) { var zipPath = Path.Combine(Path.GetTempPath(), fileName); using (new TemporaryFile(zipPath)) { using (var fileStream = new FileStream(zipPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (var stream = await client.GetStreamAsync($"{downloadBaseUrl}{fileName}")) { await stream.CopyToAsync(fileStream); } ZipFile.ExtractToDirectory(zipPath, destination); } } async Task DownloadCli(string destination, string version) { Console.WriteLine("Downloading terraform cli..."); var retry = new RetryTracker(3, TimeSpan.MaxValue, new LimitedExponentialRetryInterval(1000, 30000, 2)); while (retry.Try()) { try { using (var client = new HttpClient()) { var downloadBaseUrl = $"https://releases.hashicorp.com/terraform/{version}/"; var fileName = GetTerraformFileName(version); await DownloadTerraform(fileName, client, downloadBaseUrl, destination); } customTerraformExecutable = Directory.EnumerateFiles(destination).FirstOrDefault(); Console.WriteLine($"Downloaded terraform to {customTerraformExecutable}"); AddExecutePermission(customTerraformExecutable!); break; } catch { if (!retry.CanRetry()) { throw; } await Task.Delay(retry.Sleep()); } } } var destinationDirectoryName = Path.Combine(TestEnvironment.GetTestPath("TerraformCLIPath"), terraformCliVersion); if (Directory.Exists(destinationDirectoryName)) { var path = Directory.EnumerateFiles(destinationDirectoryName).FirstOrDefault(); if (path != null) { customTerraformExecutable = path; Console.WriteLine($"Using existing terraform located in {customTerraformExecutable}"); return; } } await DownloadCli(destinationDirectoryName, terraformCliVersion); } [Test] public void OverridingCacheFolder_WithNonSense_ThrowsAnError() { IgnoreIfVersionIsNotInRange("0.15.0"); ExecuteAndReturnLogOutput("apply-terraform", _ => { _.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Package); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.EnvironmentVariables, JsonConvert.SerializeObject(new Dictionary<string, string> { { "TF_PLUGIN_CACHE_DIR", "NonSense" } })); }, "Simple") .Should() .ContainAll("The specified plugin cache dir", "cannot be opened"); } [Test] public void NotProvidingEnvVariables_DoesNotCrashEverything() { ExecuteAndReturnLogOutput("apply-terraform", _ => { _.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Package); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.EnvironmentVariables, null); }, "Simple") .Should() .NotContain("Error"); } [Test] public void UserDefinedEnvVariables_OverrideDefaultBehaviour() { string template = TemplateLoader.LoadTextTemplate("SingleVariable.json"); ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, "{}"); _.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.EnvironmentVariables, JsonConvert.SerializeObject(new Dictionary<string, string> { { "TF_VAR_ami", "new ami value" } })); }, String.Empty, _ => { _.OutputVariables.ContainsKey("TerraformValueOutputs[ami]").Should().BeTrue(); _.OutputVariables["TerraformValueOutputs[ami]"].Value.Should().Be("new ami value"); }); } [Test] public void ExtraInitParametersAreSet() { IgnoreIfVersionIsNotInRange("0.11.15", "0.15.0"); var additionalParams = "-var-file=\"backend.tfvars\""; ExecuteAndReturnLogOutput(planCommand, _ => _.Variables.Add(TerraformSpecialVariables.Action.Terraform.AdditionalInitParams, additionalParams), "Simple") .Should() .Contain($"init -no-color -get-plugins=true {additionalParams}"); } [Test] public void AllowPluginDownloadsShouldBeDisabled() { IgnoreIfVersionIsNotInRange("0.11.15", "0.15.0"); ExecuteAndReturnLogOutput(planCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.AllowPluginDownloads, false.ToString()); }, "Simple") .Should() .Contain("init -no-color -get-plugins=false"); } [Test] public void AttachLogFile() { ExecuteAndReturnLogOutput(planCommand, _ => _.Variables.Add(TerraformSpecialVariables.Action.Terraform.AttachLogFile, true.ToString()), "Simple", result => { result.Artifacts.Count.Should().Be(1); }); } [Test] [TestCase(typeof(PlanCommand), "plan -no-color -detailed-exitcode -var my_var=\"Hello world\"")] [TestCase(typeof(ApplyCommand), "apply -no-color -auto-approve -var my_var=\"Hello world\"")] [TestCase(typeof(DestroyPlanCommand), "plan -no-color -detailed-exitcode -destroy -var my_var=\"Hello world\"")] [TestCase(typeof(DestroyCommand), "destroy -auto-approve -no-color -var my_var=\"Hello world\"")] public void AdditionalActionParams(Type commandType, string expected) { var command = GetCommandFromType(commandType); ExecuteAndReturnLogOutput(command, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.AdditionalActionParams, "-var my_var=\"Hello world\""); }, "AdditionalParams") .Should() .Contain(expected); } [Test] [TestCase(typeof(PlanCommand), "plan -no-color -detailed-exitcode -var-file=\"example.tfvars\"")] [TestCase(typeof(ApplyCommand), "apply -no-color -auto-approve -var-file=\"example.tfvars\"")] [TestCase(typeof(DestroyPlanCommand), "plan -no-color -detailed-exitcode -destroy -var-file=\"example.tfvars\"")] [TestCase(typeof(DestroyCommand), "destroy -auto-approve -no-color -var-file=\"example.tfvars\"")] public void VarFiles(Type commandType, string actual) { ExecuteAndReturnLogOutput(GetCommandFromType(commandType), _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.tfvars"); }, "WithVariables") .Should() .Contain(actual); } [Test] public void WithOutputSensitiveVariables() { ExecuteAndReturnLogOutput(applyCommand, _ => { }, "WithOutputSensitiveVariables", result => { result.OutputVariables.Values.Should().OnlyContain(variable => variable.IsSensitive); }); } [Test] public void OutputAndSubstituteOctopusVariables() { ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.txt"); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "example.txt"); _.Variables.Add("Octopus.Action.StepName", "Step Name"); _.Variables.Add("Should_Be_Substituted", "Hello World"); _.Variables.Add("Should_Be_Substituted_in_txt", "Hello World from text"); }, "WithVariablesSubstitution", result => { result.OutputVariables .ContainsKey("TerraformValueOutputs[my_output]") .Should() .BeTrue(); result.OutputVariables["TerraformValueOutputs[my_output]"] .Value .Should() .Be("Hello World"); result.OutputVariables .ContainsKey("TerraformValueOutputs[my_output_from_txt_file]") .Should() .BeTrue(); result.OutputVariables["TerraformValueOutputs[my_output_from_txt_file]"] .Value .Should() .Be("Hello World from text"); }); } [Test] public void EnableNoMatchWarningIsNotSet() { ExecuteAndReturnLogOutput(applyCommand, _ => { }, "Simple") .Should() .NotContain("No files were found that match the substitution target pattern"); } [Test] public void EnableNoMatchWarningIsNotSetWithAdditionSubstitution() { ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "doesNotExist.txt"); }, "Simple") .Should() .MatchRegex("No files were found in (.*) that match the substitution target pattern '\\*\\*/\\*\\.tfvars\\.json'") .And .MatchRegex("No files were found in (.*) that match the substitution target pattern 'doesNotExist.txt'"); } [Test] public void EnableNoMatchWarningIsTrue() { ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "doesNotExist.txt"); _.Variables.Add("Octopus.Action.SubstituteInFiles.EnableNoMatchWarning", "true"); }, "Simple") .Should() .MatchRegex("No files were found in (.*) that match the substitution target pattern '\\*\\*/\\*\\.tfvars\\.json'") .And .MatchRegex("No files were found in (.*) that match the substitution target pattern 'doesNotExist.txt'"); } [Test] public void EnableNoMatchWarningIsFalse() { ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "doesNotExist.txt"); _.Variables.Add("Octopus.Action.SubstituteInFiles.EnableNoMatchWarning", "False"); }, "Simple") .Should() .NotContain("No files were found that match the substitution target pattern"); } [Test] [TestCase(typeof(PlanCommand))] [TestCase(typeof(DestroyPlanCommand))] public void TerraformPlanOutput(Type commandType) { ExecuteAndReturnLogOutput(GetCommandFromType(commandType), _ => { _.Variables.Add("Octopus.Action.StepName", "Step Name"); }, "Simple", result => { result.OutputVariables .ContainsKey("TerraformPlanOutput") .Should() .BeTrue(); }); } [Test] public void UsesWorkSpace() { ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Workspace, "myspace"); }, "Simple") .Should() .Contain("workspace new \"myspace\""); } [Test] public void UsesTemplateDirectory() { ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateDirectory, "SubFolder"); }, "TemplateDirectory") .Should() .Contain($"SubFolder{Path.DirectorySeparatorChar}example.tf"); } [Test] public async Task GoogleCloudIntegration() { IgnoreIfVersionIsNotInRange("0.15.0"); const string jsonEnvironmentVariableKey = "GOOGLECLOUD_OCTOPUSAPITESTER_JSONKEY"; var bucketName = $"e2e-tf-{Guid.NewGuid().ToString("N").Substring(0, 6)}"; using var temporaryFolder = TemporaryDirectory.Create(); CopyAllFiles(TestEnvironment.GetTestPath("GoogleCloud"), temporaryFolder.DirectoryPath); var environmentJsonKey = Environment.GetEnvironmentVariable(jsonEnvironmentVariableKey); if (environmentJsonKey == null) { throw new Exception($"Environment Variable `{jsonEnvironmentVariableKey}` could not be found. The value can be found in the password store under GoogleCloud - OctopusAPITester"); } var jsonKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(environmentJsonKey)); void PopulateVariables(CommandTestBuilderContext _) { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "test.txt"); _.Variables.Add("Hello", "Hello World from Google Cloud"); _.Variables.Add("bucket_name", bucketName); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.tfvars"); _.Variables.Add("Octopus.Action.Terraform.GoogleCloudAccount", bool.TrueString); _.Variables.Add("Octopus.Action.GoogleCloudAccount.JsonKey", jsonKey); _.Variables.Add(KnownVariables.OriginalPackageDirectoryPath, temporaryFolder.DirectoryPath); } var output = await ExecuteAndReturnResult(planCommand, PopulateVariables, temporaryFolder.DirectoryPath); output.OutputVariables.ContainsKey("TerraformPlanOutput").Should().BeTrue(); output = await ExecuteAndReturnResult(applyCommand, PopulateVariables, temporaryFolder.DirectoryPath); output.OutputVariables.ContainsKey("TerraformValueOutputs[url]").Should().BeTrue(); var requestUri = output.OutputVariables["TerraformValueOutputs[url]"].Value; string fileData; using (var client = new HttpClient()) { fileData = await client.GetStringAsync(requestUri).ConfigureAwait(false); } fileData.Should().Be("Hello World from Google Cloud"); await ExecuteAndReturnResult(destroyCommand, PopulateVariables, temporaryFolder.DirectoryPath); using (var client = new HttpClient()) { var response = await client.GetAsync($"{requestUri}&bust_cache").ConfigureAwait(false); response.StatusCode.Should().Be(HttpStatusCode.NotFound); } } [Test] public async Task AzureIntegration() { var random = Guid.NewGuid().ToString("N").Substring(0, 6); var appName = $"cfe2e-{random}"; var expectedHostName = $"{appName}.azurewebsites.net"; using var temporaryFolder = TemporaryDirectory.Create(); CopyAllFiles(TestEnvironment.GetTestPath("Azure"), temporaryFolder.DirectoryPath); void PopulateVariables(CommandTestBuilderContext _) { _.Variables.Add(AzureAccountVariables.SubscriptionId, ExternalVariables.Get(ExternalVariable.AzureSubscriptionId)); _.Variables.Add(AzureAccountVariables.TenantId, ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId)); _.Variables.Add(AzureAccountVariables.ClientId, ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId)); _.Variables.Add(AzureAccountVariables.Password, ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword)); _.Variables.Add("app_name", appName); _.Variables.Add("random", random); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.tfvars"); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.AzureManagedAccount, Boolean.TrueString); _.Variables.Add(KnownVariables.OriginalPackageDirectoryPath, temporaryFolder.DirectoryPath); } var output = await ExecuteAndReturnResult(planCommand, PopulateVariables, temporaryFolder.DirectoryPath); output.OutputVariables.ContainsKey("TerraformPlanOutput").Should().BeTrue(); output = await ExecuteAndReturnResult(applyCommand, PopulateVariables, temporaryFolder.DirectoryPath); output.OutputVariables.ContainsKey("TerraformValueOutputs[url]").Should().BeTrue(); output.OutputVariables["TerraformValueOutputs[url]"].Value.Should().Be(expectedHostName); await AssertRequestResponse(HttpStatusCode.Forbidden); await ExecuteAndReturnResult(destroyCommand, PopulateVariables, temporaryFolder.DirectoryPath); await AssertResponseIsNotReachable(); async Task AssertResponseIsNotReachable() { //This will throw on some platforms and return "NotFound" on others try { await AssertRequestResponse(HttpStatusCode.NotFound); } catch (HttpRequestException ex) { switch (ex.InnerException) { case SocketException socketException: socketException.Message.Should() .BeOneOf( "No such host is known.", "Name or service not known", //Some Linux distros "nodename nor servname provided, or not known" //Mac ); break; case WebException webException: webException.Message.Should() .StartWith("The remote name could not be resolved"); break; default: throw; } } } async Task AssertRequestResponse(HttpStatusCode expectedStatusCode) { using var client = new HttpClient(); var response = await client.GetAsync($"https://{expectedHostName}").ConfigureAwait(false); response.StatusCode.Should().Be(expectedStatusCode); } } //TODO: #team-modern-deployments-requests-and-discussion [Test] [Ignore("Test needs to be updated because s3 bucket doesn't seem to support ACLs anymore.")] public async Task AWSIntegration() { var bucketName = $"cfe2e-tf-{Guid.NewGuid().ToString("N").Substring(0, 6)}"; var expectedUrl = $"https://{bucketName}.s3.amazonaws.com/test.txt"; using var temporaryFolder = TemporaryDirectory.Create(); CopyAllFiles(TestEnvironment.GetTestPath("AWS"), temporaryFolder.DirectoryPath); void PopulateVariables(CommandTestBuilderContext _) { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "test.txt"); _.Variables.Add("Octopus.Action.Amazon.AccessKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey)); _.Variables.Add("Octopus.Action.Amazon.SecretKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey)); _.Variables.Add("Octopus.Action.Aws.Region", "ap-southeast-1"); _.Variables.Add("Hello", "Hello World from AWS"); _.Variables.Add("bucket_name", bucketName); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.tfvars"); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.AWSManagedAccount, "AWS"); _.Variables.Add(KnownVariables.OriginalPackageDirectoryPath, temporaryFolder.DirectoryPath); } var output = await ExecuteAndReturnResult(planCommand, PopulateVariables, temporaryFolder.DirectoryPath); output.OutputVariables.ContainsKey("TerraformPlanOutput").Should().BeTrue(); output = await ExecuteAndReturnResult(applyCommand, PopulateVariables, temporaryFolder.DirectoryPath); output.OutputVariables.ContainsKey("TerraformValueOutputs[url]").Should().BeTrue(); output.OutputVariables["TerraformValueOutputs[url]"].Value.Should().Be(expectedUrl); string fileData; using (var client = new HttpClient()) fileData = await client.GetStringAsync(expectedUrl).ConfigureAwait(false); fileData.Should().Be("Hello World from AWS"); await ExecuteAndReturnResult(destroyCommand, PopulateVariables, temporaryFolder.DirectoryPath); using (var client = new HttpClient()) { var response = await client.GetAsync(expectedUrl).ConfigureAwait(false); response.StatusCode.Should().Be(HttpStatusCode.NotFound); } } [Test] public async Task PlanDetailedExitCode() { using var stateFileFolder = TemporaryDirectory.Create(); void PopulateVariables(CommandTestBuilderContext _) { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.AdditionalActionParams, $"-state=\"{Path.Combine(stateFileFolder.DirectoryPath, "terraform.tfstate")}\" -refresh=false"); } var output = await ExecuteAndReturnResult(planCommand, PopulateVariables, "PlanDetailedExitCode"); output.OutputVariables.ContainsKey("TerraformPlanDetailedExitCode").Should().BeTrue(); output.OutputVariables["TerraformPlanDetailedExitCode"].Value.Should().Be("2"); output = await ExecuteAndReturnResult(applyCommand, PopulateVariables, "PlanDetailedExitCode"); output.FullLog.Should() .Contain("apply -no-color -auto-approve"); output = await ExecuteAndReturnResult(planCommand, PopulateVariables, "PlanDetailedExitCode"); output.OutputVariables.ContainsKey("TerraformPlanDetailedExitCode").Should().BeTrue(); output.OutputVariables["TerraformPlanDetailedExitCode"].Value.Should().Be("0"); } [Test] public void InlineHclTemplateAndVariables() { IgnoreIfVersionIsNotInRange("0.11.15", "0.15.0"); const string variables = "stringvar = \"default string\""; string template = TemplateLoader.LoadTextTemplate("HclWithVariablesV0118.hcl"); ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add("RandomNumber", new Random().Next().ToString()); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, variables); _.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); }, String.Empty, _ => { _.OutputVariables.ContainsKey("TerraformValueOutputs[nestedlist]").Should().BeTrue(); _.OutputVariables.ContainsKey("TerraformValueOutputs[nestedmap]").Should().BeTrue(); }); } [Test] public void InlineHclTemplateAndVariablesV015() { IgnoreIfVersionIsNotInRange("0.15.0"); const string variables = "stringvar = \"default string\""; string template = TemplateLoader.LoadTextTemplate("HclWithVariablesV0150.hcl"); ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add("RandomNumber", new Random().Next().ToString()); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, variables); _.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); }, String.Empty, _ => { _.OutputVariables.ContainsKey("TerraformValueOutputs[nestedlist]").Should().BeTrue(); _.OutputVariables.ContainsKey("TerraformValueOutputs[nestedmap]").Should().BeTrue(); }); } [Test] public void InlineHclTemplateWithMultilineOutput() { const string expected = @"apiVersion: v1 kind: ConfigMap metadata: name: aws-auth namespace: kube-system data: mapRoles: | - rolearn: arbitrary text username: system:node:username groups: - system:bootstrappers - system:nodes"; string template = $@"locals {{ config-map-aws-auth = <<CONFIGMAPAWSAUTH {expected} CONFIGMAPAWSAUTH }} output ""config-map-aws-auth"" {{ value = ""${{local.config-map-aws-auth}}"" }}"; ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, ""); _.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); }, String.Empty, _ => { _.OutputVariables.ContainsKey("TerraformValueOutputs[config-map-aws-auth]").Should().BeTrue(); _.OutputVariables["TerraformValueOutputs[config-map-aws-auth]"] .Value?.TrimEnd() .Replace("\r\n", "\n") .Should() .Be($"{expected.Replace("\r\n", "\n")}"); }); } [Test] public void InlineJsonTemplateAndVariables() { IgnoreIfVersionIsNotInRange("0.11.15", "0.15.0"); const string variables = "{\"ami\":\"new ami value\"}"; string template = TemplateLoader.LoadTextTemplate("InlineJsonWithVariablesV01180.json"); var randomNumber = new Random().Next().ToString(); ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add("RandomNumber", randomNumber); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, variables); _.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); }, String.Empty, _ => { _.OutputVariables.ContainsKey("TerraformValueOutputs[ami]").Should().BeTrue(); _.OutputVariables["TerraformValueOutputs[ami]"].Value.Should().Be("new ami value"); _.OutputVariables.ContainsKey("TerraformValueOutputs[random]").Should().BeTrue(); _.OutputVariables["TerraformValueOutputs[random]"].Value.Should().Be(randomNumber); }); } [Test] public void CanDetermineTerraformVersion() { ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Workspace, "testversionspace"); }, "Simple") .Should() .NotContain("Could not parse Terraform CLI version"); } [Test] public void InlineJsonTemplateAndVariablesV015() { IgnoreIfVersionIsNotInRange("0.15.0"); const string variables = "{\"ami\":\"new ami value\"}"; string template = TemplateLoader.LoadTextTemplate("InlineJsonWithVariablesV0150.json"); var randomNumber = new Random().Next().ToString(); ExecuteAndReturnLogOutput(applyCommand, _ => { _.Variables.Add("RandomNumber", randomNumber); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template); _.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, variables); _.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); }, String.Empty, _ => { _.OutputVariables.ContainsKey("TerraformValueOutputs[ami]").Should().BeTrue(); _.OutputVariables["TerraformValueOutputs[ami]"].Value.Should().Be("new ami value"); _.OutputVariables.ContainsKey("TerraformValueOutputs[random]").Should().BeTrue(); _.OutputVariables["TerraformValueOutputs[random]"].Value.Should().Be(randomNumber); }); } static void CopyAllFiles(string sourceFolderPath, string destinationFolderPath) { if (Directory.Exists(sourceFolderPath)) { var filePaths = Directory.GetFiles(sourceFolderPath); // Copy the files and overwrite destination files if they already exist. foreach (var filePath in filePaths) { var fileName = Path.GetFileName(filePath); var destFilePath = Path.Combine(destinationFolderPath, fileName); File.Copy(filePath, destFilePath, true); } } else { throw new Exception($"'{nameof(sourceFolderPath)}' ({sourceFolderPath}) does not exist!"); } } string ExecuteAndReturnLogOutput(string command, Action<CommandTestBuilderContext> populateVariables, string folderName, Action<TestCalamariCommandResult>? assert = null) { return ExecuteAndReturnResult(command, populateVariables, folderName, assert).Result.FullLog; } async Task<TestCalamariCommandResult> ExecuteAndReturnResult(string command, Action<CommandTestBuilderContext> populateVariables, string folderName, Action<TestCalamariCommandResult>? assert = null) { var assertResult = assert ?? (_ => { }); var terraformFiles = Path.IsPathRooted(folderName) ? folderName : TestEnvironment.GetTestPath(folderName); var result = await CommandTestBuilder.CreateAsync<Program>(command) .WithArrange(context => { context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Package); context.Variables.Add(TerraformSpecialVariables.Packages.PackageId, terraformFiles); context.Variables.Add(TerraformSpecialVariables.Calamari.TerraformCliPath, Path.GetDirectoryName(customTerraformExecutable)); context.Variables.Add(TerraformSpecialVariables.Action.Terraform.CustomTerraformExecutable, customTerraformExecutable); populateVariables(context); var isInline = context.Variables.Get(ScriptVariables.ScriptSource)! .Equals(ScriptVariables.ScriptSourceOptions.Inline, StringComparison.InvariantCultureIgnoreCase); if (isInline) { var template = context.Variables.Get(TerraformSpecialVariables.Action.Terraform.Template); var variables = context.Variables.Get(TerraformSpecialVariables.Action.Terraform.TemplateParameters); var isJsonFormat = true; try { JToken.Parse(template); } catch { isJsonFormat = false; } context.WithDataFileNoBom( template!, isJsonFormat ? TerraformSpecialVariables.JsonTemplateFile : TerraformSpecialVariables.HclTemplateFile); context.WithDataFileNoBom( variables!, isJsonFormat ? TerraformSpecialVariables.JsonVariablesFile : TerraformSpecialVariables.HclVariablesFile); } if (!String.IsNullOrEmpty(folderName)) { context.WithFilesToCopy(terraformFiles); } }) .Execute(); assertResult(result); return result; } static string GetCommandFromType(Type commandType) { return commandType.CustomAttributes.Where(t => t.AttributeType == typeof(Calamari.Common.Commands.CommandAttribute)) .Select(c => c.ConstructorArguments.First().Value) .Single() ?.ToString(); } void IgnoreIfVersionIsNotInRange(string minimum, string? maximum = null) { var minimumVersion = new Version(minimum); var maximumVersion = new Version(maximum ?? "999.0.0"); if (TerraformCliVersionAsObject.CompareTo(minimumVersion) < 0 || TerraformCliVersionAsObject.CompareTo(maximumVersion) >= 0) { Assert.Ignore($"Test ignored as terraform version is not between {minimumVersion} and {maximumVersion}"); } } //TODO: This is ported over from the ExecutableHelper in Sashimi.Tests.Shared. This project doesn't have a valid nuget package for net452 static void AddExecutePermission(string exePath) { if (CalamariEnvironment.IsRunningOnWindows) return; StringBuilder stdOut = new StringBuilder(); StringBuilder stdError = new StringBuilder(); if (SilentProcessRunner.ExecuteCommand("chmod", "+x " + exePath, Path.GetDirectoryName(exePath) ?? string.Empty, (Action<string>)(s => stdOut.AppendLine(s)), (Action<string>)(s => stdError.AppendLine(s))) .ExitCode != 0) throw new Exception(stdOut.ToString() + stdError?.ToString()); } } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class JobTests { [Test] public void ShouldCollectCorrectProperties() { var jobResponse = new JobResponseBuilder() .WithCompletions(3) .WithBackoffLimit(4) .WithSucceeded(3) .WithStartTime("2023-03-29T00:00:00Z") .WithCompletionTime("2023-03-30T02:03:04Z") .Build(); var job = ResourceFactory.FromJson(jobResponse, new Options()); job.Should().BeEquivalentTo(new { Kind = "Job", Name = "my-job", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Completions = "3/3", Duration = "1.02:03:04", ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful }); } [Test] public void WhenWaitForJobsNotEnabled_ShouldHaveStatusOfSuccess() { var jobResponse = new JobResponseBuilder() .WithCompletions(3) .WithBackoffLimit(4) .WithFailed(4) .Build(); var job = ResourceFactory.FromJson(jobResponse, new Options()); job.ResourceStatus.Should().Be(Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful); } [Test] public void WhenWaitForJobsIsEnabled_ShouldHaveStatusOfFailedIfBackOffLimitHasBeenReached() { var jobResponse = new JobResponseBuilder() .WithCompletions(3) .WithBackoffLimit(4) .WithFailed(4) .Build(); var job = ResourceFactory.FromJson(jobResponse, new Options() { WaitForJobs = true }); job.ResourceStatus.Should().Be(Kubernetes.ResourceStatus.Resources.ResourceStatus.Failed); } [Test] public void WhenWaitForJobsIsEnabled_ShouldHaveStatusOfSuccessfulIfDesiredCompletionsHaveBeenAchieved() { var jobResponse = new JobResponseBuilder() .WithCompletions(3) .WithSucceeded(3) .WithFailed(1) .Build(); var job = ResourceFactory.FromJson(jobResponse, new Options() { WaitForJobs = true }); job.ResourceStatus.Should().Be(Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful); } [Test] public void WhenWaitForJobsIsEnabled_ShouldHaveStatusOfInProgressIsDesiredCompletionsHaveNotBeenReached() { var jobResponse = new JobResponseBuilder() .WithCompletions(3) .WithSucceeded(2) .WithFailed(1) .Build(); var job = ResourceFactory.FromJson(jobResponse, new Options() { WaitForJobs = true }); job.ResourceStatus.Should().Be(Kubernetes.ResourceStatus.Resources.ResourceStatus.InProgress); } } public class JobResponseBuilder { private const string Template = @"{{ ""kind"": ""Job"", ""metadata"": {{ ""name"": ""my-job"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }}, ""spec"": {{ ""completions"": {0}, ""backoffLimit"": {1} }}, ""status"": {{ ""succeeded"": {2}, ""failed"": {3}, ""startTime"": ""{4}"", ""completionTime"": ""{5}"" }} }}"; private int Completions { get; set; } private int BackoffLimit { get; set; } private int Succeeded { get; set; } private int Failed { get; set; } private string StartTime { get; set; } private string CompletionTime { get; set; } public JobResponseBuilder WithCompletions(int completions) { Completions = completions; return this; } public JobResponseBuilder WithBackoffLimit(int backoffLimit) { BackoffLimit = backoffLimit; return this; } public JobResponseBuilder WithSucceeded(int succeeded) { Succeeded = succeeded; return this; } public JobResponseBuilder WithFailed(int failed) { Failed = failed; return this; } public JobResponseBuilder WithStartTime(string startTime) { StartTime = startTime; return this; } public JobResponseBuilder WithCompletionTime(string completionTime) { CompletionTime = completionTime; return this; } public string Build() { return string.Format(Template, Completions, BackoffLimit, Succeeded, Failed, StartTime, CompletionTime); } } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.Logging { public static class Log { public static void Verbose(string message) { ConsoleLog.Instance.Verbose(message); } public static void VerboseFormat(string message, params object[] args) { ConsoleLog.Instance.VerboseFormat(message, args); } public static void Info(string message) { ConsoleLog.Instance.Info(message); } public static void Info(string message, params object[] args) { ConsoleLog.Instance.InfoFormat(message, args); } public static void Warn(string message) { ConsoleLog.Instance.Warn(message); } public static void WarnFormat(string message, params object[] args) { ConsoleLog.Instance.WarnFormat(message, args); } public static void Error(string message) { ConsoleLog.Instance.Error(message); } public static void ErrorFormat(string message, params object[] args) { ConsoleLog.Instance.ErrorFormat(message, args); } public static void SetOutputVariable(string name, string value, IVariables variables, bool isSensitive = false) { ConsoleLog.Instance.SetOutputVariable(name, value, variables, isSensitive); } } public class ConsoleLog : AbstractLog { public static ConsoleLog Instance = new ConsoleLog(); readonly IndentedTextWriter stdOut; readonly IndentedTextWriter stdErr; ConsoleLog() { stdOut = new IndentedTextWriter(Console.Out, " "); stdErr = new IndentedTextWriter(Console.Error, " "); } protected override void StdOut(string message) { stdOut.WriteLine(message); } protected override void StdErr(string message) { Console.ForegroundColor = ConsoleColor.Red; stdErr.WriteLine(message); Console.ResetColor(); } } public abstract class AbstractLog : ILog { readonly object sync = new object(); string? stdOutMode; readonly Dictionary<string, string> redactionMap = new Dictionary<string, string>(); protected abstract void StdOut(string message); protected abstract void StdErr(string message); protected string ProcessRedactions(string? message) { if (message == null) return string.Empty; lock (sync) { return redactionMap.Aggregate(message, (current, pair) => current.Replace(pair.Key, pair.Value)); } } void SetMode(string mode) { if (stdOutMode == mode) return; StdOut("##octopus[stdout-" + mode + "]"); stdOutMode = mode; } public void AddValueToRedact(string value, string replacement) { lock (sync) { redactionMap[value] = replacement; } } public virtual void Verbose(string message) { lock (sync) { SetMode("verbose"); StdOut(ProcessRedactions(message)); } } public virtual void VerboseFormat(string messageFormat, params object[] args) { Verbose(string.Format(messageFormat, args)); } public virtual void Info(string message) { lock (sync) { SetMode("default"); StdOut(ProcessRedactions(message)); } } public virtual void InfoFormat(string messageFormat, params object[] args) { Info(string.Format(messageFormat, args)); } public virtual void Warn(string message) { lock (sync) { SetMode("warning"); StdOut(ProcessRedactions(message)); } } public virtual void WarnFormat(string messageFormat, params object[] args) { Warn(string.Format(messageFormat, args)); } public virtual void Error(string message) { lock (sync) { StdErr(ProcessRedactions(message)); } } public virtual void ErrorFormat(string messageFormat, params object[] args) { Error(string.Format(messageFormat, args)); } public void SetOutputVariableButDoNotAddToVariables(string name, string value, bool isSensitive = false) { if (name == null) throw new ArgumentNullException(nameof(name)); if (value == null) throw new ArgumentNullException(nameof(value)); Info(isSensitive ? $"##octopus[setVariable name=\"{ConvertServiceMessageValue(name)}\" value=\"{ConvertServiceMessageValue(value)}\" sensitive=\"{ConvertServiceMessageValue(bool.TrueString)}\"]" : $"##octopus[setVariable name=\"{ConvertServiceMessageValue(name)}\" value=\"{ConvertServiceMessageValue(value)}\"]"); } public void SetOutputVariable(string name, string value, IVariables variables, bool isSensitive = false) { SetOutputVariableButDoNotAddToVariables(name, value, isSensitive); variables?.SetOutputVariable(name, value); } public void NewOctopusArtifact(string fullPath, string name, long fileLength) { Info($"##octopus[createArtifact path=\"{ConvertServiceMessageValue(fullPath)}\" name=\"{ConvertServiceMessageValue(name)}\" length=\"{ConvertServiceMessageValue(fileLength.ToString())}\"]"); } public virtual void WriteServiceMessage(ServiceMessage serviceMessage) { Info(serviceMessage.ToString()); } public void Progress(int percentage, string message) { VerboseFormat("##octopus[progress percentage=\"{0}\" message=\"{1}\"]", ConvertServiceMessageValue(percentage.ToString(CultureInfo.InvariantCulture)), ConvertServiceMessageValue(message)); } public void DeltaVerification(string remotePath, string hash, long size) { VerboseFormat("##octopus[deltaVerification remotePath=\"{0}\" hash=\"{1}\" size=\"{2}\"]", ConvertServiceMessageValue(remotePath), ConvertServiceMessageValue(hash), ConvertServiceMessageValue(size.ToString(CultureInfo.InvariantCulture))); } public void DeltaVerificationError(string error) { VerboseFormat("##octopus[deltaVerification error=\"{0}\"]", ConvertServiceMessageValue(error)); } public string FormatLink(string uri, string? description = null) { return $"[{description ?? uri}]({uri})"; } public static string ConvertServiceMessageValue(string value) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(value)); } public static string UnconvertServiceMessageValue(string value) { var bytes = Convert.FromBase64String(value); return Encoding.UTF8.GetString(bytes); } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using Autofac; using Autofac.Core; using Autofac.Core.Registration; using Calamari.Common.Commands; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.FunctionScriptContributions; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Proxies; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common { public abstract class CalamariFlavourProgram { protected readonly ILog Log; protected CalamariFlavourProgram(ILog log) { Log = log; } protected virtual int Run(string[] args) { try { AppDomainConfiguration.SetDefaultRegexMatchTimeout(); SecurityProtocols.EnableAllSecurityProtocols(); var options = CommonOptions.Parse(args); Log.Verbose($"Calamari Version: {GetType().Assembly.GetInformationalVersion()}"); if (options.Command.Equals("version", StringComparison.OrdinalIgnoreCase)) return 0; var envInfo = string.Join($"{Environment.NewLine} ", EnvironmentHelper.SafelyGetEnvironmentInformation()); Log.Verbose($"Environment Information: {Environment.NewLine} {envInfo}"); EnvironmentHelper.SetEnvironmentVariable("OctopusCalamariWorkingDirectory", Environment.CurrentDirectory); ProxyInitializer.InitializeDefaultProxy(); var builder = new ContainerBuilder(); ConfigureContainer(builder, options); using var container = builder.Build(); container.Resolve<VariableLogger>().LogVariables(); #if DEBUG var waitForDebugger = container.Resolve<IVariables>().Get(KnownVariables.Calamari.WaitForDebugger); if (string.Equals(waitForDebugger, "true", StringComparison.OrdinalIgnoreCase)) { using var proc = Process.GetCurrentProcess(); Log.Info($"Waiting for debugger to attach... (PID: {proc.Id})"); while (!Debugger.IsAttached) { Thread.Sleep(1000); } } #endif return ResolveAndExecuteCommand(container, options); } catch (Exception ex) { return ConsoleFormatter.PrintError(ConsoleLog.Instance, ex); } } protected virtual int ResolveAndExecuteCommand(IContainer container, CommonOptions options) { try { var command = container.ResolveNamed<ICommand>(options.Command); return command.Execute(); } catch (Exception e) when (e is ComponentNotRegisteredException || e is DependencyResolutionException) { throw new CommandException($"Could not find the command {options.Command}"); } } protected virtual void ConfigureContainer(ContainerBuilder builder, CommonOptions options) { var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); builder.RegisterInstance(fileSystem).As<ICalamariFileSystem>(); builder.RegisterType<VariablesFactory>().AsSelf(); builder.Register(c => c.Resolve<VariablesFactory>().Create(options)).As<IVariables>().SingleInstance(); builder.RegisterType<ScriptEngine>().As<IScriptEngine>(); builder.RegisterType<VariableLogger>().AsSelf(); builder.RegisterInstance(Log).As<ILog>().SingleInstance(); builder.RegisterType<FreeSpaceChecker>().As<IFreeSpaceChecker>().SingleInstance(); builder.RegisterType<CommandLineRunner>().As<ICommandLineRunner>().SingleInstance(); builder.RegisterType<FileSubstituter>().As<IFileSubstituter>(); builder.RegisterType<SubstituteInFiles>().As<ISubstituteInFiles>(); builder.RegisterType<CombinedPackageExtractor>().As<ICombinedPackageExtractor>(); builder.RegisterType<ExtractPackage>().As<IExtractPackage>(); builder.RegisterType<CodeGenFunctionsRegistry>().SingleInstance(); builder.RegisterType<AssemblyEmbeddedResources>().As<ICalamariEmbeddedResources>(); var assemblies = GetAllAssembliesToRegister().ToArray(); builder.RegisterAssemblyTypes(assemblies).AssignableTo<ICodeGenFunctions>().As<ICodeGenFunctions>().SingleInstance(); builder.RegisterAssemblyTypes(assemblies) .AssignableTo<IScriptWrapper>() .Except<TerminalScriptWrapper>() .As<IScriptWrapper>() .SingleInstance(); builder.RegisterAssemblyTypes(assemblies) .AssignableTo<ICommand>() .Where(t => ((CommandAttribute)Attribute.GetCustomAttribute(t, typeof(CommandAttribute))).Name .Equals(options.Command, StringComparison.OrdinalIgnoreCase)) .Named<ICommand>(t => ((CommandAttribute)Attribute.GetCustomAttribute(t, typeof(CommandAttribute))).Name); builder.RegisterInstance(options).AsSelf().SingleInstance(); builder.RegisterModule<StructuredConfigVariablesModule>(); } protected virtual Assembly GetProgramAssemblyToRegister() { return GetType().Assembly; } protected virtual IEnumerable<Assembly> GetAllAssembliesToRegister() { var programAssembly = GetProgramAssemblyToRegister(); if (programAssembly != null) yield return programAssembly; // Calamari Flavour yield return typeof(CalamariFlavourProgram).Assembly; // Calamari.Common } } }<file_sep>using System; using System.IO; using System.Linq; using System.Text; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; namespace Calamari.Common.Util { public static class DirectoryLoggingHelper { public static void LogDirectoryContents(ILog log, ICalamariFileSystem fileSystem, string workingDirectory, string currentDirectoryRelativePath, int depth = 0) { var directory = new DirectoryInfo(Path.Combine(workingDirectory, currentDirectoryRelativePath)); var files = fileSystem.EnumerateFiles(directory.FullName).ToList(); for (int i = 0; i < files.Count; i++) { // Only log the first 50 files in each directory if (i == 50) { log.VerboseFormat("{0}And {1} more files...", Indent(depth), files.Count - i); break; } var file = files[i]; log.Verbose(Indent(depth) + Path.GetFileName(file)); } foreach (var subDirectory in fileSystem.EnumerateDirectories(directory.FullName).Select(x => new DirectoryInfo(x))) { log.Verbose(Indent(depth + 1) + "\\" + subDirectory.Name); LogDirectoryContents(log, fileSystem, workingDirectory, Path.Combine(currentDirectoryRelativePath, subDirectory.Name), depth + 1); } } static string Indent(int n) { var indent = new StringBuilder("|"); for (int i = 0; i < n; i++) indent.Append("-"); return indent.ToString(); } } } <file_sep>// This was ported from https://github.com/NuGet/NuGet.Client, as the NuGet libraries are .NET 4.5 and Calamari is .NET 4.0 // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Calamari.Integration.Packages.NuGet { internal static class NuGetServiceTypes { public static readonly string Version300beta = "/3.0.0-beta"; public static readonly string Version300 = "/3.0.0"; public static readonly string Version340 = "/3.4.0"; public static readonly string Version360 = "/3.6.0"; public static readonly string[] RegistrationsBaseUrl = { "RegistrationsBaseUrl" + Version360, "RegistrationsBaseUrl" + Version340, "RegistrationsBaseUrl" + Version300beta }; public static readonly string PackageBaseAddress = "PackageBaseAddress" + Version300; } }<file_sep>using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Integration.Proxies; using NUnit.Framework; namespace Calamari.Tests.Fixtures.PowerShell { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class PowerShellProxyFixture : WindowsScriptProxyFixtureBase { protected override CalamariResult RunScript() { return RunScript("Proxy.ps1").result; } protected override bool TestWebRequestDefaultProxy => true; } }<file_sep>#!/bin/bash set_octopusvariable "Super" "Mario Bros" <file_sep>#!/bin/bash echo "I have failed! DeployFailed.sh" <file_sep>using System; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public interface IUsageDetails { CacheAge CacheAgeAtUsage { get; } ServerTaskId DeploymentTaskId { get; } } }<file_sep>using System; using System.Collections.Generic; namespace Calamari.ConsolidateCalamariPackages { public class MigratedCalamariFlavours { public static List<string> Flavours = new() { "Calamari.AzureAppService", "Calamari.AzureResourceGroup", "Calamari.AzureWebApp", "Calamari.AzureServiceFabric", "Calamari.AzureCloudService", "Calamari.GoogleCloudScripting", "Calamari.AzureScripting", "Calamari.Terraform" }; } }<file_sep>using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] public class HelmInstalledVersionUpgradeFixture : HelmUpgradeFixture { [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void Upgrade_Succeeds() { var result = DeployPackage(); result.AssertSuccess(); result.AssertNoOutput("Using custom helm executable at"); Assert.AreEqual(ReleaseName.ToLower(), result.CapturedOutput.OutputVariables["ReleaseName"]); } protected override string ExplicitExeVersion => null; } }<file_sep>using System; using System.IO; using System.Linq; using System.Xml; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Microsoft.Web.XmlTransform; namespace Calamari.Common.Features.ConfigurationTransforms { public class ConfigurationTransformer : IConfigurationTransformer { readonly TransformLoggingOptions transformLoggingOptions; readonly ILog calamariLog; bool errorEncountered; public ConfigurationTransformer(TransformLoggingOptions transformLoggingOptions, ILog log) { this.transformLoggingOptions = transformLoggingOptions; calamariLog = log; } public void PerformTransform(string configFile, string transformFile, string destinationFile) { var logger = SetupLogger(); try { ApplyTransformation(configFile, transformFile, destinationFile, logger); } catch (CommandException) { throw; } catch (Exception ex) { logger.LogErrorFromException(ex); if (errorEncountered) { throw; } } } IXmlTransformationLogger SetupLogger() { var logger = new VerboseTransformLogger(transformLoggingOptions, calamariLog); logger.Error += delegate { errorEncountered = true; }; if (transformLoggingOptions.HasFlag(TransformLoggingOptions.DoNotLogVerbose)) { calamariLog.Verbose($"Verbose XML transformation logging has been turned off because the variable {KnownVariables.Package.SuppressConfigTransformationLogging} has been set to true."); } if (transformLoggingOptions.HasFlag(TransformLoggingOptions.LogExceptionsAsWarnings)) { calamariLog.Verbose($"XML transformation warnings will be downgraded to information because the variable {KnownVariables.Package.IgnoreConfigTransformationErrors} has been set to true."); } if (transformLoggingOptions.HasFlag(TransformLoggingOptions.LogExceptionsAsWarnings)) { calamariLog.Verbose($"XML transformation exceptions will be downgraded to warnings because the variable {KnownVariables.Package.IgnoreConfigTransformationErrors} has been set to true."); } if (transformLoggingOptions.HasFlag(TransformLoggingOptions.LogWarningsAsErrors)) { calamariLog.Verbose($"Warning will be elevated to errors. Prevent this by adding the variable {KnownVariables.Package.TreatConfigTransformationWarningsAsErrors} and setting it to false."); } return logger; } void ApplyTransformation(string configFile, string transformFile, string destinationFile, IXmlTransformationLogger logger) { errorEncountered = false; using (var transformation = new XmlTransformation(transformFile, logger)) using (var configurationFileDocument = new XmlTransformableDocument { PreserveWhitespace = true }) { configurationFileDocument.Load(configFile); var success = transformation.Apply(configurationFileDocument); if (!success || errorEncountered) { throw new CommandException($"The XML configuration file {configFile} failed with transformation file {transformFile}."); } if (!configurationFileDocument.ChildNodes.OfType<XmlElement>().Any()) { logger.LogWarning("The XML configuration file {0} no longer has a root element and is invalid after being transformed by {1}", new object[] { configFile, transformFile }); } configurationFileDocument.Save(destinationFile); } } public static ConfigurationTransformer FromVariables(IVariables variables, ILog log) { var treatConfigTransformationWarningsAsErrors = variables.GetFlag(KnownVariables.Package.TreatConfigTransformationWarningsAsErrors, true); var ignoreConfigTransformErrors = variables.GetFlag(KnownVariables.Package.IgnoreConfigTransformationErrors); var suppressConfigTransformLogging = variables.GetFlag(KnownVariables.Package.SuppressConfigTransformationLogging); var transformLoggingOptions = TransformLoggingOptions.None; if (treatConfigTransformationWarningsAsErrors) { transformLoggingOptions |= TransformLoggingOptions.LogWarningsAsErrors; } if (ignoreConfigTransformErrors) { transformLoggingOptions |= TransformLoggingOptions.LogExceptionsAsWarnings; transformLoggingOptions |= TransformLoggingOptions.LogWarningsAsInfo; transformLoggingOptions &= ~TransformLoggingOptions.LogWarningsAsErrors; } if (suppressConfigTransformLogging) { transformLoggingOptions |= TransformLoggingOptions.DoNotLogVerbose; } return new ConfigurationTransformer(transformLoggingOptions, log); } } [Flags] public enum TransformLoggingOptions { None = 0, DoNotLogVerbose = 1, LogWarningsAsInfo = 2, LogWarningsAsErrors = 4, LogExceptionsAsWarnings = 8 } } <file_sep>using System; using System.Threading.Tasks; namespace Calamari.Testing.Extensions { public static class TaskExtensions { public static void Ignore(this Task _) { } } } <file_sep>using System.Linq; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.Decorators; using Calamari.Common.Features.Packages.Decorators.ArchiveLimits; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Packages.ArchiveLimits { [TestFixture] public class EnforceDecompressionLimitDecoratorFixture : CalamariFixture { readonly string[] testZipPath = { "Fixtures", "Integration", "Packages", "Samples", "Acme.Core.1.0.0.0-bugfix.zip" }; [Test] [ExpectedException(typeof(ArchiveLimitException))] public void ShouldEnforceLimit() { var extractor = GetExtractor(WithVariables(maximumUncompressedSize: 1)); extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); } [Test] public void ShouldIgnoreNonsenseLimit() { var extractor = GetExtractor(WithVariables(maximumUncompressedSize: -1)); var extractedFiles = extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(extractedFiles, Is.EqualTo(1)); } [Test] public void ShouldExtractWhenUnderLimit() { var extractor = GetExtractor(WithVariables(maximumUncompressedSize: 1000000000)); var extractedFiles = extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(extractedFiles, Is.EqualTo(1)); } [Test] public void ShouldExtractRegardlessOfLimitWithFeatureFlagOff() { var extractor = GetExtractor(WithVariables(featureFlagEnabled: false, maximumUncompressedSize: 1)); var extractedFiles = extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(extractedFiles, Is.EqualTo(1)); } [Test] public void ShouldExtractRegardlessOfLimitWithFeatureFlagNotPresent() { var extractor = GetExtractor(WithVariables(featureFlagEnabled: false, maximumUncompressedSize: 1)); var extractedFiles = extractor.Extract(TestEnvironment.GetTestPath(testZipPath), TestEnvironment.GetTestPath("extracted")); Assert.That(extractedFiles, Is.EqualTo(1)); } IPackageExtractor GetExtractor(CalamariVariables variables) { return new NullExtractor().WithExtractionLimits(Log, variables); } static CalamariVariables WithVariables(int maximumUncompressedSize = 1000000000, bool featureFlagEnabled = true) { return new CalamariVariables { { KnownVariables.Package.ArchiveLimits.Enabled, featureFlagEnabled.ToString() }, { KnownVariables.Package.ArchiveLimits.MaximumUncompressedSize, maximumUncompressedSize.ToString() } }; } } } <file_sep>using System; using Calamari.Common.Plumbing.Extensions; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace Calamari.Testing.Requirements { public class RequiresNonFreeBSDPlatformAttribute : NUnitAttribute, IApplyToTest { readonly string reason; public RequiresNonFreeBSDPlatformAttribute() { } public RequiresNonFreeBSDPlatformAttribute(string reason) { this.reason = reason; } public void ApplyToTest(Test test) { if (ScriptingEnvironment.IsRunningOnMono() && (Environment.GetEnvironmentVariable("TEAMCITY_BUILDCONF_NAME")?.Contains("FreeBSD") ?? false)) { var skipReason = "This test does not run on FreeBSD"; if (!string.IsNullOrWhiteSpace(reason)) { skipReason += $" because {reason}"; } test.RunState = RunState.Skipped; test.Properties.Set(PropertyNames.SkipReason, skipReason); } } } }<file_sep>using System; using System.IO; using System.Text; using Calamari.Common.Plumbing.Logging; using SharpCompress.Common; using SharpCompress.Readers; using SharpCompress.Readers.Tar; #if !NET40 using Polly; #endif namespace Calamari.Common.Features.Packages { public class TarPackageExtractor : IPackageExtractor { readonly ILog log; public TarPackageExtractor(ILog log) { this.log = log; } public virtual string[] Extensions => new[] { ".tar" }; public int Extract(string packageFile, string directory) { var files = 0; using (var inStream = new FileStream(packageFile, FileMode.Open, FileAccess.Read)) { var compressionStream = GetCompressionStream(inStream); try { using (var reader = TarReader.Open(compressionStream, new ReaderOptions { ArchiveEncoding = new ArchiveEncoding { Default = Encoding.UTF8 } })) { while (reader.MoveToNextEntry()) { ProcessEvent(ref files, reader.Entry); ExtractEntry(directory, reader); } } } finally { if (compressionStream != inStream) compressionStream.Dispose(); } } return files; } void ExtractEntry(string directory, TarReader reader) { #if NET40 reader.WriteEntryToDirectory(directory, new PackageExtractionOptions(log)); #else var extractAttempts = 10; Policy.Handle<IOException>() .WaitAndRetry( extractAttempts, i => TimeSpan.FromMilliseconds(50), (ex, retry) => { log.Verbose($"Failed to extract: {ex.Message}. Retry in {retry.Milliseconds} milliseconds."); }) .Execute(() => { reader.WriteEntryToDirectory(directory, new PackageExtractionOptions(log)); }); #endif } protected virtual Stream GetCompressionStream(Stream stream) { return stream; } protected void ProcessEvent(ref int filesExtracted, IEntry entry) { if (entry.IsDirectory) return; filesExtracted++; } } }<file_sep>using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Azure; using Azure.ResourceManager; using Azure.ResourceManager.AppService; using Azure.ResourceManager.AppService.Models; using Calamari.AzureAppService.Azure; using Calamari.AzureAppService.Json; using Octopus.CoreUtilities.Extensions; namespace Calamari.AzureAppService { ///<summary> /// Provides a set of static methods for interacting with an <see cref="ArmClient"/> using an <see cref="AzureTargetSite"/>. ///</summary> /// <remarks> /// These methods are suffixed with <i>Async</i> for consistency with the <see cref="ArmClient"/>. /// In the <b>Azure.ResourceManager</b> SDKs, <i>Async</i>-suffixed methods indicate an API call is made to Azure. /// </remarks> public static class ArmClientExtensions { public static async Task<SiteConfigData> GetSiteConfigDataAsync(this ArmClient armClient, AzureTargetSite targetSite) { return targetSite.HasSlot switch { true => (await armClient.GetWebSiteSlotConfigResource(WebSiteSlotConfigResource.CreateResourceIdentifier( targetSite.SubscriptionId, targetSite.ResourceGroupName, targetSite.Site, targetSite.Slot)) .GetAsync()).Value.Data, false => (await armClient.GetWebSiteConfigResource(WebSiteConfigResource.CreateResourceIdentifier( targetSite.SubscriptionId, targetSite.ResourceGroupName, targetSite.Site)) .GetAsync()).Value.Data }; } public static async Task UpdateSiteConfigDataAsync(this ArmClient armClient, AzureTargetSite targetSite, SiteConfigData siteConfigData) { switch (targetSite.HasSlot) { case true: await armClient.GetWebSiteSlotConfigResource(WebSiteSlotConfigResource.CreateResourceIdentifier( targetSite.SubscriptionId, targetSite.ResourceGroupName, targetSite.Site, targetSite.Slot)) .UpdateAsync(siteConfigData); break; case false: await armClient.GetWebSiteConfigResource(WebSiteConfigResource.CreateResourceIdentifier( targetSite.SubscriptionId, targetSite.ResourceGroupName, targetSite.Site)) .UpdateAsync(siteConfigData); break; } } static readonly CsmPublishingProfile PublishingProfileOptions = new CsmPublishingProfile { Format = PublishingProfileFormat.WebDeploy }; public static async Task<Stream> GetPublishingProfileXmlWithSecrets(this ArmClient armClient, AzureTargetSite targetSite) { return targetSite.HasSlot switch { true => await armClient.GetWebSiteSlotResource(targetSite.CreateResourceIdentifier()) .GetPublishingProfileXmlWithSecretsSlotAsync(PublishingProfileOptions), false => await armClient.GetWebSiteResource(targetSite.CreateResourceIdentifier()) .GetPublishingProfileXmlWithSecretsAsync(PublishingProfileOptions) }; } public static async Task<AppServiceConfigurationDictionary> GetAppSettingsAsync(this ArmClient armClient, AzureTargetSite targetSite) { return targetSite.HasSlot switch { true => await armClient.GetWebSiteSlotResource(targetSite.CreateResourceIdentifier()) .GetApplicationSettingsSlotAsync(), false => await armClient.GetWebSiteResource(targetSite.CreateResourceIdentifier()) .GetApplicationSettingsAsync() }; } /// <summary> /// Patches (add or update) the app settings for a web app or slot using the website management client library extensions. /// If any setting needs to be marked sticky (slot setting), update it via <see cref="PutSlotSettingsListAsync"/>. /// </summary> /// <param name="armClient">A <see cref="ArmClient"/> that is directly used to update app settings.</param> /// <param name="targetSite">The target site containing the resource group name, site and (optional) site name</param> /// <param name="appSettings">A <see cref="AppServiceConfigurationDictionary"/> containing the app settings to set</param> /// <returns>Awaitable <see cref="Task"/></returns> public static async Task UpdateAppSettingsAsync(this ArmClient armClient, AzureTargetSite targetSite, AppServiceConfigurationDictionary appSettings) { switch (targetSite.HasSlot) { case true: await armClient.GetWebSiteSlotResource(targetSite.CreateResourceIdentifier()).UpdateApplicationSettingsSlotAsync(appSettings); break; case false: await armClient.GetWebSiteResource(targetSite.CreateResourceIdentifier()).UpdateApplicationSettingsAsync(appSettings); break; } } public static async Task<IEnumerable<AppSetting>> GetAppSettingsListAsync(this ArmClient armClient, AzureTargetSite targetSite) { var appSettings = await GetAppSettingsAsync(armClient, targetSite); var slotSettings = await GetSlotSettingsAsync(armClient, targetSite); var slotSettingsLookup = slotSettings.ToHashSet(); return appSettings.Properties.Select( setting => new AppSetting { Name = setting.Key, Value = setting.Value, SlotSetting = slotSettingsLookup.Contains(setting.Key) }) .ToList(); } /// <summary> /// Gets list of existing sticky (slot settings) /// </summary> /// <param name="armClient">The <see cref="ArmClient"/> that will be used to submit the get request</param> /// <param name="targetSite">The <see cref="AzureTargetSite"/> that will represents the web app's resource group, name and (optionally) slot that is being deployed to</param> /// <returns>Collection of setting names that are sticky (slot setting)</returns> public static async Task<IEnumerable<string>> GetSlotSettingsAsync(this ArmClient armClient, AzureTargetSite targetSite) { SlotConfigNamesResource configNamesResource = await armClient.GetWebSiteResource(targetSite.CreateWebSiteResourceIdentifier()) .GetSlotConfigNamesResource() .GetAsync(); return configNamesResource.Data.AppSettingNames; } /// <summary> /// Puts (overwrite) List of setting names who's values should be sticky (slot settings). /// </summary> /// <param name="armClient">The <see cref="ArmClient"/> that will be used to submit the new list</param> /// <param name="targetSite">The target site containing the resource group name, site and (optional) site name</param> /// <param name="slotConfigNames">collection of setting names to be marked as sticky (slot setting)</param> /// <returns>Awaitable <see cref="Task"/></returns> public static async Task UpdateSlotSettingsAsync(this ArmClient armClient, AzureTargetSite targetSite, IEnumerable<string> slotConfigNames) { var data = new SlotConfigNamesResourceData(); data.AppSettingNames.AddRange(slotConfigNames); await armClient.GetWebSiteResource(targetSite.CreateWebSiteResourceIdentifier()) .GetSlotConfigNamesResource() .CreateOrUpdateAsync(WaitUntil.Completed, data); } public static async Task<ConnectionStringDictionary> GetConnectionStringsAsync(this ArmClient armClient, AzureTargetSite targetSite) { return targetSite.HasSlot switch { true => await armClient.GetWebSiteSlotResource(targetSite.CreateResourceIdentifier()) .GetConnectionStringsSlotAsync(), false => await armClient.GetWebSiteResource(targetSite.CreateResourceIdentifier()) .GetConnectionStringsAsync() }; } public static async Task UpdateConnectionStringsAsync(this ArmClient armClient, AzureTargetSite targetSite, ConnectionStringDictionary connectionStrings) { switch (targetSite.HasSlot) { case true: await armClient.GetWebSiteSlotResource(targetSite.CreateResourceIdentifier()).UpdateConnectionStringsSlotAsync(connectionStrings); break; case false: await armClient.GetWebSiteResource(targetSite.CreateResourceIdentifier()).UpdateConnectionStringsAsync(connectionStrings); break; } } public static async Task RestartWebSiteAsync(this ArmClient armClient, AzureTargetSite targetSite) { switch (targetSite.HasSlot) { case true: await armClient.GetWebSiteSlotResource(targetSite.CreateResourceIdentifier()) .RestartSlotAsync(); break; case false: await armClient.GetWebSiteResource(targetSite.CreateResourceIdentifier()) .RestartAsync(); break; } } } }<file_sep>using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureServiceFabric { static class CalamariCertificateStore { public static void EnsureCertificateIsInstalled(IVariables variables, string certificateVariable, string storeName, string storeLocation = "CurrentUser") { var location = (StoreLocation) Enum.Parse(typeof(StoreLocation), storeLocation); var name = (StoreName) Enum.Parse(typeof(StoreName), storeName); GetOrAdd(variables, certificateVariable, name, location); } public static void GetOrAdd(IVariables variables, string certificateVariable, StoreName storeName, StoreLocation storeLocation = StoreLocation.CurrentUser) { var pfxBytes = Convert.FromBase64String(variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Pfx}")); var thumbprint = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Thumbprint}"); var password = variables.Get($"{certificateVariable}.{CertificateVariables.Properties.Password}"); GetOrAdd(thumbprint, pfxBytes, password, new X509Store(storeName, storeLocation)); } static void GetOrAdd(string thumbprint, byte[] bytes, string password, X509Store store) { store.Open(OpenFlags.ReadWrite); try { Log.Verbose($"Loading certificate with thumbprint: {thumbprint}"); var certificateFromStore = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false) .OfType<X509Certificate2>() .FirstOrDefault(cert => CheckThatCertificateWasLoadedWithPrivateKeyAndGrantCurrentUserAccessIfRequired(cert, false)); if (certificateFromStore != null) { Log.Verbose("Certificate was found in store"); return; } Log.Verbose("Loading certificate from disk"); var file = Path.Combine(Path.GetTempPath(), $"Octo-{Guid.NewGuid()}"); try { File.WriteAllBytes(file, bytes); var certificate = LoadCertificateWithPrivateKey(file, password); if (CheckThatCertificateWasLoadedWithPrivateKeyAndGrantCurrentUserAccessIfRequired(certificate) == false) { certificate = LoadCertificateWithPrivateKey(file, password); } Log.Info("Adding certificate to store"); store.Add(certificate); } finally { File.Delete(file); } } finally { store.Close(); } } static X509Certificate2 LoadCertificateWithPrivateKey(string file, string password) { return TryLoadCertificate(file, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet, true, password) ?? TryLoadCertificate(file, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet, true, password) ?? TryLoadCertificate(file, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet, true, password) ?? TryLoadCertificate(file, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet, false, password) ?? TryLoadCertificate(file, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet, false, password) ?? TryLoadCertificate(file, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet, false, password); } static bool CheckThatCertificateWasLoadedWithPrivateKeyAndGrantCurrentUserAccessIfRequired(X509Certificate2 certificate, bool log = true) { try { if (!HasPrivateKey(certificate)) { var message = new StringBuilder(); message.AppendFormat("The X509 certificate {0} was loaded but the private key was not loaded.", certificate.Subject).AppendLine(); try { var privateKeyPath = CryptUtils.GetKeyFilePath(certificate); message.AppendLine($"The private key file should be located at {privateKeyPath}"); if (!File.Exists(privateKeyPath)) { message.AppendLine("However, the current user does not appear to be able to access the private key file, or it does not exist."); } message.AppendLine($"Attempting to grant the user {Environment.UserDomainName}\\{Environment.UserName} access to the certificate private key directory."); try { GrantCurrentUserAccessToPrivateKeyDirectory(privateKeyPath); message.AppendLine("The user should now have read access to the private key. The certificate will be reloaded."); } catch (Exception ex) { message.AppendLine($"Unable to grant the current user read access to the private key: {ex.Message}"); } } catch (Exception ex) { message.AppendLine($"Furthermore, the private key file could not be located: {ex.Message}"); } var logMessage = message.ToString().Trim(); if (log) { Log.Info(logMessage); } return false; } return true; } catch (Exception ex) { Log.Warn(ex.ToString()); return false; } } static bool HasPrivateKey(X509Certificate2 certificate2) { try { return certificate2.HasPrivateKey && certificate2.PrivateKey != null; } catch (Exception) { return false; } } static X509Certificate2 TryLoadCertificate(string file, X509KeyStorageFlags flags, bool requirePrivateKey, string password = null) { try { var cert = new X509Certificate2(file, password, flags); // ReSharper disable once InvertIf if (!HasPrivateKey(cert) && requirePrivateKey) { cert.Reset(); return null; } return cert; } catch (Exception) { return null; } } static void GrantCurrentUserAccessToPrivateKeyDirectory(string privateKeyPath) { var folderPath = Path.GetDirectoryName(privateKeyPath); if (folderPath == null) throw new Exception("There was no directory specified in the private key path."); var current = WindowsIdentity.GetCurrent(); if (current == null || current.User == null) throw new Exception("There is no current windows identity."); var directoryInfo = new DirectoryInfo(folderPath); var security = directoryInfo.GetAccessControl(); security.AddAccessRule(new FileSystemAccessRule(current.User, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); directoryInfo.SetAccessControl(security); } #region Nested type: CryptUtils // This code is from a Microsoft sample that resolves the path to a certificate's private key static class CryptUtils { public static string GetKeyFilePath(X509Certificate2 certificate2) { var keyFileName = GetKeyFileName(certificate2); var keyFileDirectory = GetKeyFileDirectory(keyFileName); return Path.Combine(keyFileDirectory, keyFileName); } static string GetKeyFileName(X509Certificate2 cert) { var zero = IntPtr.Zero; var flag = false; const uint dwFlags = 0u; var num = 0; string text = null; if (CryptAcquireCertificatePrivateKey(cert.Handle, dwFlags, IntPtr.Zero, ref zero, ref num, ref flag)) { var intPtr = IntPtr.Zero; var num2 = 0; try { if (CryptGetProvParam(zero, CryptGetProvParamType.PP_UNIQUE_CONTAINER, IntPtr.Zero, ref num2, 0u)) { intPtr = Marshal.AllocHGlobal(num2); if (CryptGetProvParam(zero, CryptGetProvParamType.PP_UNIQUE_CONTAINER, intPtr, ref num2, 0u)) { var array = new byte[num2]; Marshal.Copy(intPtr, array, 0, num2); text = Encoding.ASCII.GetString(array, 0, array.Length - 1); } } } finally { if (flag) { CryptReleaseContext(zero, 0u); } if (intPtr != IntPtr.Zero) { Marshal.FreeHGlobal(intPtr); } } } if (text == null) { throw new InvalidOperationException($"Unable to obtain private key file name, error code: {Marshal.GetLastWin32Error()}"); } return text; } static string GetKeyFileDirectory(string keyFileName) { var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var text = Path.Combine(folderPath, "Microsoft", "Crypto", "RSA", "MachineKeys"); var array = Directory.GetFiles(text, keyFileName); string result; if (array.Length <= 0) { var folderPath2 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); var path = Path.Combine(folderPath2, "Microsoft", "Crypto", "RSA"); array = Directory.GetDirectories(path); // ReSharper disable once InvertIf if (array.Length > 0) { var array2 = array; foreach (var text2 in array2) { array = Directory.GetFiles(text2, keyFileName); // ReSharper disable once InvertIf if (array.Length != 0) { result = text2; return result; } } } throw new InvalidOperationException("Unable to locate private key file directory"); } result = text; return result; } [DllImport("crypt32", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CryptAcquireCertificatePrivateKey(IntPtr pCert, uint dwFlags, IntPtr pvReserved, ref IntPtr phCryptProv, ref int pdwKeySpec, ref bool pfCallerFreeProv); [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CryptGetProvParam(IntPtr hCryptProv, CryptGetProvParamType dwParam, IntPtr pvData, ref int pcbData, uint dwFlags); [DllImport("advapi32", SetLastError = true)] static extern bool CryptReleaseContext(IntPtr hProv, uint dwFlags); enum CryptGetProvParamType { PP_ENUMALGS = 1, PP_ENUMCONTAINERS, PP_IMPTYPE, PP_NAME, PP_VERSION, PP_CONTAINER, PP_CHANGE_PASSWORD, PP_KEYSET_SEC_DESCR, PP_CERTCHAIN, PP_KEY_TYPE_SUBTYPE, PP_PROVTYPE = 16, PP_KEYSTORAGE, PP_APPLI_CERT, PP_SYM_KEYSIZE, PP_SESSION_KEYSIZE, PP_UI_PROMPT, PP_ENUMALGS_EX, PP_ENUMMANDROOTS = 25, PP_ENUMELECTROOTS, PP_KEYSET_TYPE, PP_ADMIN_PIN = 31, PP_KEYEXCHANGE_PIN, PP_SIGNATURE_PIN, PP_SIG_KEYSIZE_INC, PP_KEYX_KEYSIZE_INC, PP_UNIQUE_CONTAINER, PP_SGC_INFO, PP_USE_HARDWARE_RNG, PP_KEYSPEC, PP_ENUMEX_SIGNING_PROT, PP_CRYPT_COUNT_KEY_USE } } #endregion } }<file_sep>using System; using System.Net; using System.Threading; namespace Calamari.Common.Plumbing.Extensions { public static class WebClientExtensions { public delegate void ProgressEventHandler(int progressPercentage, long totalBytes); public static void DownloadFileWithProgress(this WebClient client, string uri, string fileName, ProgressEventHandler progressHandler) { var lastCall = DateTime.Now; var throttle = TimeSpan.FromSeconds(3).Ticks; var hasCalled = false; client.DownloadProgressChanged += (sender, args) => { if (DateTime.Now.Ticks - lastCall.Ticks <= throttle && !(hasCalled && args.ProgressPercentage == 100)) return; progressHandler(args.ProgressPercentage, args.TotalBytesToReceive); hasCalled = true; lastCall = DateTime.Now; }; client.DownloadFileCompleted += (sender, args) => { lock (args.UserState) { Monitor.Pulse(args.UserState); } }; var syncObject = new object(); lock (syncObject) { client.DownloadFileAsync(new Uri(uri), fileName, syncObject); Monitor.Wait(syncObject); } } } }<file_sep>using Calamari.Integration.Processes; using NUnit.Framework; using Octopus.CoreUtilities.Extensions; using System; using System.IO; using System.Reflection; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; namespace Calamari.Tests.Fixtures.Commands { [TestFixture] public class RunScriptTest { [Test] public void RunScript() { var program = new TestProgram(); var retCode = program.RunStubCommand(); retCode.Should().Be(0); program.StubWasCalled.Should().BeTrue(); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Packages.Download; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class DockerImagePackageDownloaderFixture { static readonly string AuthFeedUri = "https://octopusdeploy-docker.jfrog.io"; static readonly string FeedUsername = "e2e-reader"; static readonly string FeedPassword = ExternalVariables.Get(ExternalVariable.HelmPassword); static readonly string Home = Path.GetTempPath(); static readonly string DockerHubFeedUri = "https://index.docker.io"; static readonly string DockerTestUsername = "octopustestaccount"; static readonly string DockerTestPassword = ExternalVariables.Get(ExternalVariable.DockerReaderPassword); [OneTimeSetUp] public void TestFixtureSetUp() { Environment.SetEnvironmentVariable("TentacleHome", Home); } [OneTimeTearDown] public void TestFixtureTearDown() { Environment.SetEnvironmentVariable("TentacleHome", null); } [Test] [RequiresDockerInstalled] public void PackageWithoutCredentials_Loads() { var downloader = GetDownloader(); var pkg = downloader.DownloadPackage("alpine", new SemanticVersion("3.6.5"), "docker-feed", new Uri(DockerHubFeedUri), null, null, true, 1, TimeSpan.FromSeconds(3)); Assert.AreEqual("alpine", pkg.PackageId); Assert.AreEqual(new SemanticVersion("3.6.5"), pkg.Version); Assert.AreEqual(string.Empty, pkg.FullFilePath); } [Test] [RequiresDockerInstalled] public void DockerHubWithCredentials_Loads() { const string privateImage = "octopusdeploy/octo-prerelease"; var version = new SemanticVersion("7.3.7-alpine"); var downloader = GetDownloader(); var pkg = downloader.DownloadPackage(privateImage, version, "docker-feed", new Uri(DockerHubFeedUri), DockerTestUsername, DockerTestPassword, true, 1, TimeSpan.FromSeconds(3)); Assert.AreEqual(privateImage, pkg.PackageId); Assert.AreEqual(version, pkg.Version); Assert.AreEqual(string.Empty, pkg.FullFilePath); } [Test] [RequiresDockerInstalled] public void PackageWithCredentials_Loads() { var downloader = GetDownloader(); var pkg = downloader.DownloadPackage("octopus-echo", new SemanticVersion("1.1"), "docker-feed", new Uri(AuthFeedUri), FeedUsername, FeedPassword, true, 1, TimeSpan.FromSeconds(3)); Assert.AreEqual("octopus-echo", pkg.PackageId); Assert.AreEqual(new SemanticVersion("1.1"), pkg.Version); Assert.AreEqual(string.Empty, pkg.FullFilePath); } [Test] [RequiresDockerInstalled] public void PackageWithWrongCredentials_Fails() { var downloader = GetDownloader(); var exception = Assert.Throws<CommandException>(() => downloader.DownloadPackage("octopus-echo", new SemanticVersion("1.1"), "docker-feed", new Uri(AuthFeedUri), FeedUsername, "SuperDooper", true, 1, TimeSpan.FromSeconds(3))); StringAssert.Contains("Unable to log in Docker registry", exception.Message); } [Test] [RequiresDockerInstalled] [TestCase("octopusdeploy/octo-prerelease", "7.3.7-alpine")] [TestCase("alpine", "3.6.5")] public void CachedDockerHubPackage_DoesNotGenerateImageNotCachedMessage(string image, string tag) { PreCacheImage(image, tag, DockerHubFeedUri, DockerTestUsername, DockerTestPassword); var log = new InMemoryLog(); var downloader = GetDownloader(log); downloader.DownloadPackage(image, new SemanticVersion(tag), "docker-feed", new Uri(DockerHubFeedUri), DockerTestUsername, DockerTestPassword, true, 1, TimeSpan.FromSeconds(3)); Assert.False(log.Messages.Any(m => m.FormattedMessage.Contains($"The docker image '{image}:{tag}' may not be cached"))); } [Test] [RequiresDockerInstalled] public void CachedNonDockerHubPackage_DoesNotGenerateImageNotCachedMessage() { const string image = "octopus-echo"; const string tag = "1.1"; var log = new InMemoryLog(); var downloader = GetDownloader(log); PreCacheImage(image, tag, AuthFeedUri, FeedUsername, FeedPassword); downloader.DownloadPackage(image, new SemanticVersion(tag), "docker-feed", new Uri(AuthFeedUri), FeedUsername, FeedPassword, true, 1, TimeSpan.FromSeconds(3)); Assert.False(log.Messages.Any(m => m.FormattedMessage.Contains($"The docker image '{image}:{tag}' may not be cached"))); } [Test] [RequiresDockerInstalled] [TestCase("octopusdeploy/octo-prerelease", "7.3.7-alpine")] [TestCase("alpine", "3.6.5")] public void NotCachedDockerHubPackage_GeneratesImageNotCachedMessage(string image, string tag) { var log = new InMemoryLog(); var downloader = GetDownloader(log); RemoveCachedImage(image, tag); downloader.DownloadPackage(image, new SemanticVersion(tag), "docker-feed", new Uri(DockerHubFeedUri), DockerTestUsername, DockerTestPassword, true, 1, TimeSpan.FromSeconds(3)); Assert.True(log.Messages.Any(m => m.FormattedMessage.Contains($"The docker image '{image}:{tag}' may not be cached"))); } [Test] [RequiresDockerInstalled] public void NotCachedNonDockerHubPackage_GeneratesImageNotCachedMessage() { const string image = "octopus-echo"; const string tag = "1.1"; var feed = new Uri(AuthFeedUri); var imageFullName = $"{feed.Authority}/{image}"; var log = new InMemoryLog(); var downloader = GetDownloader(log); RemoveCachedImage(imageFullName, tag); downloader.DownloadPackage(image, new SemanticVersion(tag), "docker-feed", feed, FeedUsername, FeedPassword, true, 1, TimeSpan.FromSeconds(3)); Assert.True(log.Messages.Any(m => m.FormattedMessage.Contains($"The docker image '{imageFullName}:{tag}' may not be cached"))); } static void PreCacheImage(string packageId, string tag, string feedUri, string username, string password) { GetDownloader(new SilentLog()).DownloadPackage(packageId, new SemanticVersion(tag), "docker-feed", new Uri(feedUri), username, password, true, 1, TimeSpan.FromSeconds(3)); } static void RemoveCachedImage(string image, string tag) { SilentProcessRunner.ExecuteCommand("docker", $"rmi {image}:{tag}", ".", new Dictionary<string, string>(), (output) => { }, (error) => { }); } static DockerImagePackageDownloader GetDownloader() { return GetDownloader(ConsoleLog.Instance); } static DockerImagePackageDownloader GetDownloader(ILog log) { var runner = new CommandLineRunner(log, new CalamariVariables()); return new DockerImagePackageDownloader(new ScriptEngine(Enumerable.Empty<IScriptWrapper>()), CalamariPhysicalFileSystem.GetPhysicalFileSystem(), runner, new CalamariVariables(), log); } } } <file_sep>// // Options.cs // // Authors: // <NAME> <<EMAIL>> // // Copyright (C) 2008 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // using System; namespace Calamari.Common.Plumbing.Commands.Options { public delegate void OptionAction<TKey, TValue>(TKey key, TValue value); }<file_sep>namespace Calamari.Aws.Integration.S3 { public class S3SingleFileSelectionProperties : S3FileSelectionProperties, IHaveBucketKeyBehaviour { public string BucketKey { get; set; } public string BucketKeyPrefix { get; set; } public BucketKeyBehaviourType BucketKeyBehaviour { get; set; } public string Path { get; set; } public bool PerformVariableSubstitution { get; set; } public bool PerformStructuredVariableSubstitution { get; set; } } }<file_sep>using System; using Autofac; using Calamari.Common.Features.Behaviours; namespace Calamari.Common.Plumbing.Pipeline { public class BeforePackageExtractionResolver: Resolver<IBeforePackageExtractionBehaviour> { public BeforePackageExtractionResolver(ILifetimeScope lifetimeScope) : base(lifetimeScope) { } } }<file_sep>echo "hello from Deploy.sh" <file_sep>using Amazon.CloudFormation; using Amazon.IdentityManagement; using Amazon.Runtime; using Amazon.S3; using Amazon.SecurityToken; using Calamari.Aws.Integration; using Calamari.CloudAccounts; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Util { public static class ClientExtensions { public static TConfig AsClientConfig<TConfig>(this AwsEnvironmentGeneration environment) where TConfig : ClientConfig, new() { return new TConfig().Tee(x => { x.RegionEndpoint = environment.AwsRegion; x.AllowAutoRedirect = true; }); }} public static class ClientHelpers { public static AmazonIdentityManagementServiceClient CreateIdentityManagementServiceClient( AwsEnvironmentGeneration environment) { return new AmazonIdentityManagementServiceClient(environment.AwsCredentials, environment.AsClientConfig<AmazonIdentityManagementServiceConfig>()); } public static AmazonSecurityTokenServiceClient CreateSecurityTokenServiceClient( AwsEnvironmentGeneration environment) { return new AmazonSecurityTokenServiceClient(environment.AwsCredentials, environment.AsClientConfig<AmazonSecurityTokenServiceConfig>()); } public static AmazonS3Client CreateS3Client(AwsEnvironmentGeneration environment) { return new AmazonS3Client(environment.AwsCredentials, environment.AsClientConfig<AmazonS3Config>()); } public static IAmazonCloudFormation CreateCloudFormationClient(AwsEnvironmentGeneration environment) { return new AmazonCloudFormationClient(environment.AwsCredentials, environment.AsClientConfig<AmazonCloudFormationConfig>()); } } } <file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class ConfigMapTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""ConfigMap"", ""metadata"": { ""name"": ""my-cm"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""data"": { ""x"": ""y"", ""a"": ""b"" } }"; var configMap = ResourceFactory.FromJson(input, new Options()); configMap.Should().BeEquivalentTo(new { Kind = "ConfigMap", Name = "my-cm", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Data = 2, ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful }); } } } <file_sep>using System; using System.Net.Http.Headers; using System.Text; namespace Calamari.Common.Plumbing.Extensions { public static class HttpClientExtensions { public static void AddAuthenticationHeader(this HttpRequestHeaders headers, string userName, string password) { if (!string.IsNullOrWhiteSpace(userName)) { var byteArray = Encoding.ASCII.GetBytes($"{userName}:{password}"); headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); } else if (!string.IsNullOrWhiteSpace(password)) { headers.Authorization = new AuthenticationHeaderValue("Token", password); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using YamlDotNet.Core; using YamlDotNet.Core.Events; namespace Calamari.Common.Features.StructuredVariables { enum YamlStructure { Mapping, Sequence } class YamlPathComponent { public YamlPathComponent(YamlStructure structure) { Type = structure; } public YamlStructure Type { get; } public string? MappingKey { get; set; } public int SequenceIndex { get; set; } = -1; } class YamlPathStack { readonly Stack<YamlPathComponent> stack = new Stack<YamlPathComponent>(); public void Push(YamlStructure structure) { stack.Push(new YamlPathComponent(structure)); } public void Pop() { stack.Pop(); } IEnumerable<string> GetPathComponents() { foreach (var stackItem in stack.Reverse()) if (stackItem.MappingKey != null) yield return stackItem.MappingKey; else if (stackItem.Type == YamlStructure.Sequence && stackItem.SequenceIndex != -1) yield return stackItem.SequenceIndex.ToString(); } public string GetPath() { return string.Join(":", GetPathComponents()); } public bool TopIsSequence() { return stack.Count > 0 && stack.Peek().Type == YamlStructure.Sequence; } public void TopSequenceIncrementIndex() { if (TopIsSequence()) stack.Peek().SequenceIndex++; } public bool TopIsMappingExpectingKey() { return stack.Count > 0 && stack.Peek().Type == YamlStructure.Mapping && stack.Peek().MappingKey == null; } public void TopMappingKeyStart(string key) { if (TopIsMappingExpectingKey()) stack.Peek().MappingKey = key; } public void TopMappingKeyEnd() { if (stack.Count > 0) stack.Peek().MappingKey = null; } } public interface IYamlNode { ParsingEvent Event { get; } string Path { get; } } public class YamlNode<T> : IYamlNode where T : ParsingEvent { public YamlNode(T parsingEvent, string path) { Event = parsingEvent; Path = path; } public T Event { get; } public string Path { get; } ParsingEvent IYamlNode.Event => Event; } public static class ParsingEventExtensions { public static Scalar ReplaceValue(this Scalar scalar, string? newValue) { return newValue != null ? new Scalar(scalar.Anchor, scalar.Tag, newValue, scalar.Style, scalar.IsPlainImplicit, scalar.IsQuotedImplicit, scalar.Start, scalar.End) : new Scalar(scalar.Anchor, "!!null", "null", ScalarStyle.Plain, true, false, scalar.Start, scalar.End); } public static Comment RestoreLeadingSpaces(this Comment comment) { // The YamlDotNet Parser strips leading spaces, but we can get closer to preserving alignment by // putting some back based on input file offset information. const int outputCommentPrefixLength = 2; // The YamlDotNet Emitter is hard-coded to output `# ` var leadingSpaces = comment.Start.Line == comment.End.Line ? comment.End.Column - comment.Value.Length - comment.Start.Column - outputCommentPrefixLength : 0; return leadingSpaces > 0 ? new Comment(new string(' ', leadingSpaces) + comment.Value, comment.IsInline, comment.Start, comment.End) : comment; } } public class YamlEventStreamClassifier { readonly YamlPathStack stack = new YamlPathStack(); public IYamlNode Process(ParsingEvent ev) { IYamlNode? classifiedNode = null; if (stack.TopIsSequence() && (ev is MappingStart || ev is SequenceStart || ev is Scalar)) stack.TopSequenceIncrementIndex(); switch (ev) { case MappingStart ms: classifiedNode = new YamlNode<MappingStart>(ms, stack.GetPath()); stack.Push(YamlStructure.Mapping); break; case MappingEnd me: stack.Pop(); classifiedNode = new YamlNode<MappingEnd>(me, stack.GetPath()); stack.TopMappingKeyEnd(); break; case SequenceStart ss: classifiedNode = new YamlNode<SequenceStart>(ss, stack.GetPath()); stack.Push(YamlStructure.Sequence); break; case SequenceEnd se: stack.Pop(); classifiedNode = new YamlNode<SequenceEnd>(se, stack.GetPath()); stack.TopMappingKeyEnd(); break; case Scalar sc: if (stack.TopIsMappingExpectingKey()) { // This is a map key stack.TopMappingKeyStart(sc.Value); } else { // This is a value in a map or sequence classifiedNode = new YamlNode<Scalar>(sc, stack.GetPath()); stack.TopMappingKeyEnd(); } break; case Comment c: classifiedNode = new YamlNode<Comment>(c, stack.GetPath()); break; } return classifiedNode ?? new YamlNode<ParsingEvent>(ev, stack.GetPath()); } } }<file_sep>using System; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; namespace Calamari.Common.Plumbing.Extensions { public class ScriptingEnvironment { public static bool IsNetFramework() { #if NETFRAMEWORK return true; #else return false; #endif } public static bool IsNet45OrNewer() { // Class "ReflectionContext" exists from .NET 4.5 onwards. return Type.GetType("System.Reflection.ReflectionContext", false) != null; } public static bool IsRunningOnMono() { var monoRuntime = Type.GetType("Mono.Runtime"); return monoRuntime != null; } public static Version GetMonoVersion() { // A bit hacky, but this is what Mono community seems to be using: // http://stackoverflow.com/questions/8413922/programmatically-determining-mono-runtime-version var monoRuntime = Type.GetType("Mono.Runtime"); if (monoRuntime == null) throw new MonoVersionCanNotBeDeterminedException("It looks like the code is not running on Mono."); var dispalayNameMethod = monoRuntime.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (dispalayNameMethod == null) throw new MonoVersionCanNotBeDeterminedException("Mono.Runtime.GetDisplayName can not be found."); var displayName = dispalayNameMethod.Invoke(null, null).ToString(); var match = Regex.Match(displayName, @"^\d+\.\d+.\d+"); if (match == null || !match.Success || string.IsNullOrEmpty(match.Value)) throw new MonoVersionCanNotBeDeterminedException($"Display name does not seem to include version number. Retrieved value: {displayName}."); return Version.Parse(match.Value); } public static Version SafelyGetPowerShellVersion() { try { foreach (var cmd in new[] { "powershell.exe", "pwsh.exe" }) { var stdOut = new StringBuilder(); var stdError = new StringBuilder(); var result = SilentProcessRunner.ExecuteCommand( cmd, $"-command \"{"$PSVersionTable.PSVersion.ToString()"}\"", Environment.CurrentDirectory, s => stdOut.AppendLine(s), s => stdError.AppendLine(s)); if (result.ExitCode == 0) return Version.Parse(stdOut.ToString()); } } catch { //silently ignore it - we dont want to } return Version.Parse("0.0.0"); } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace Calamari.Integration.Certificates.WindowsNative { /// <summary> /// <para> /// SafeCertContextHandle provides a SafeHandle class for an X509Certificate's certificate context /// as stored in its <see cref="System.Security.Cryptography.X509Certificates.X509Certificate.Handle" /> /// property. This can be used instead of the raw IntPtr to avoid races with the garbage /// collector, ensuring that the X509Certificate object is not cleaned up from underneath you /// while you are still using the handle pointer. /// </para> /// <para> /// This safe handle type represents a native CERT_CONTEXT. /// (http://msdn.microsoft.com/en-us/library/aa377189.aspx) /// </para> /// <para> /// A SafeCertificateContextHandle for an X509Certificate can be obtained by calling the <see /// cref="X509CertificateExtensionMethods.GetCertificateContext" /> extension method. /// </para> /// </summary> internal sealed class SafeCertContextHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeCertContextHandle() : base(true) { } public SafeCertContextHandle(IntPtr handle, bool ownsHandle) : base(false) { SetHandle(handle); } [DllImport("crypt32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CertFreeCertificateContext(IntPtr pCertContext); public WindowsX509Native.CERT_CONTEXT CertificateContext => (WindowsX509Native.CERT_CONTEXT)Marshal.PtrToStructure(handle, typeof(WindowsX509Native.CERT_CONTEXT)); protected override bool ReleaseHandle() { return CertFreeCertificateContext(handle); } public SafeCertContextHandle Duplicate() { return WindowsX509Native.CertDuplicateCertificateContext(this.DangerousGetHandle()); } public IntPtr Disconnect() { var ptr = DangerousGetHandle(); SetHandle(IntPtr.Zero); return ptr; } } } #endif<file_sep>dagger: † euro: € <file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Model; namespace Calamari.Deployment.PackageRetention.Repositories { public abstract class JournalRepositoryBase : IJournalRepository { protected Dictionary<PackageIdentity, JournalEntry> journalEntries; public PackageCache Cache { get; protected set; } protected JournalRepositoryBase(Dictionary<PackageIdentity, JournalEntry> journalEntries = null) { this.journalEntries = journalEntries ?? new Dictionary<PackageIdentity, JournalEntry>(); } public bool TryGetJournalEntry(PackageIdentity package, out JournalEntry entry) { return journalEntries.TryGetValue(package, out entry); } public void RemoveAllLocks(ServerTaskId serverTaskId) { foreach (var entry in journalEntries.Values) entry.RemoveLock(serverTaskId); } public IList<JournalEntry> GetAllJournalEntries() { return journalEntries.Select(pair => pair.Value) .ToList(); } public void AddJournalEntry(JournalEntry entry) { if (journalEntries.ContainsKey(entry.Package)) return; //This shouldn't ever happen - if it already exists, then we should have just added to that entry. journalEntries.Add(entry.Package, entry); } public void RemovePackageEntry(PackageIdentity packageIdentity) { journalEntries.Remove(packageIdentity); } public abstract void Load(); public abstract void Commit(); } } <file_sep>using Calamari.Util; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] public class HelmVersionParserFixture { [Test] public void ParseVersion_V2Version_V2() { HelmVersionParser.ParseVersion("Client: v2.16.1+gbbdfe5e").Should().Be(HelmVersion.V2); } [Test] public void ParseVersion_V3Version_V3() { HelmVersionParser.ParseVersion("v3.0.2+g19e47ee").Should().Be(HelmVersion.V3); } [Test] public void ParseVersion_OtherVersion_Null() { HelmVersionParser.ParseVersion("v4.0.2+g19e47ee").Should().BeNull(); } [Test] public void ParseVersion_V3UppercaseVersion_Null() { HelmVersionParser.ParseVersion("V3.0.2+g19e47ee").Should().BeNull(); } [Test] public void ParseVersion_V3WithoutPrefix_Null() { HelmVersionParser.ParseVersion("3.0.2+g19e47ee").Should().BeNull(); } [TestCase("vzsd3242347ee", Description = "Has a v")] [TestCase("zsd3242347ee", Description = "No v")] [TestCase("v", Description = "Just v")] public void ParseVersion_Rubbish_Null(string version) { HelmVersionParser.ParseVersion(version).Should().BeNull(); } } }<file_sep>using System; using System.Security.AccessControl; using System.Security.Principal; using System.Threading; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; namespace Calamari.Common.Features.Processes.Semaphores { public class SystemSemaphoreManager : ISemaphoreFactory { readonly ILog log; readonly int initialWaitBeforeShowingLogMessage; public SystemSemaphoreManager() { log = ConsoleLog.Instance; initialWaitBeforeShowingLogMessage = (int)TimeSpan.FromSeconds(3).TotalMilliseconds; } public SystemSemaphoreManager(ILog log, TimeSpan initialWaitBeforeShowingLogMessage) { this.log = log; this.initialWaitBeforeShowingLogMessage = (int)initialWaitBeforeShowingLogMessage.TotalMilliseconds; } public IDisposable Acquire(string name, string waitMessage) { return CalamariEnvironment.IsRunningOnWindows ? AcquireSemaphore(name, waitMessage) : AcquireMutex(name, waitMessage); } IDisposable AcquireSemaphore(string name, string waitMessage) { Semaphore semaphore; var globalName = $"Global\\{name}"; try { semaphore = CreateGlobalSemaphoreAccessibleToEveryone(globalName); } catch (Exception ex) { log.Verbose($"Acquiring semaphore failed: {ex.PrettyPrint()}"); log.Verbose("Retrying without setting access controls..."); semaphore = new Semaphore(1, 1, globalName); } try { if (!semaphore.WaitOne(initialWaitBeforeShowingLogMessage)) { log.Verbose(waitMessage); semaphore.WaitOne(); } } catch (AbandonedMutexException) { // We are now the owners of the mutex // If a thread terminates while owning a mutex, the mutex is said to be abandoned. // The state of the mutex is set to signaled and the next waiting thread gets ownership. } return new Releaser(() => { semaphore.Release(); semaphore.Dispose(); }); } IDisposable AcquireMutex(string name, string waitMessage) { var globalName = $"Global\\{name}"; var mutex = new Mutex(false, globalName); try { if (!mutex.WaitOne(initialWaitBeforeShowingLogMessage)) { log.Verbose(waitMessage); mutex.WaitOne(); } } catch (AbandonedMutexException) { // We are now the owners of the mutex // If a thread terminates while owning a mutex, the mutex is said to be abandoned. // The state of the mutex is set to signaled and the next waiting thread gets ownership. } return new Releaser(() => { mutex.ReleaseMutex(); mutex.Dispose(); }); } static Semaphore CreateGlobalSemaphoreAccessibleToEveryone(string name) { var semaphoreSecurity = new SemaphoreSecurity(); var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var rule = new SemaphoreAccessRule(everyone, SemaphoreRights.FullControl, AccessControlType.Allow); semaphoreSecurity.AddAccessRule(rule); bool createdNew; var semaphore = new Semaphore(1, 1, name, out createdNew); semaphore.SetAccessControl(semaphoreSecurity); return semaphore; } class Releaser : IDisposable { readonly Action dispose; public Releaser(Action dispose) { this.dispose = dispose; } public void Dispose() { dispose(); } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Proxies; using Calamari.Common.Plumbing.Variables; namespace Calamari.GoogleCloudScripting { public class GoogleCloudContextScriptWrapper : IScriptWrapper { private readonly ILog log; readonly IVariables variables; readonly ScriptSyntax[] supportedScriptSyntax = {ScriptSyntax.PowerShell, ScriptSyntax.Bash}; public GoogleCloudContextScriptWrapper(ILog log, IVariables variables) { this.log = log; this.variables = variables; } public int Priority => ScriptWrapperPriorities.CloudAuthenticationPriority; public bool IsEnabled(ScriptSyntax syntax) => supportedScriptSyntax.Contains(syntax); public IScriptWrapper? NextWrapper { get; set; } public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars) { var workingDirectory = Path.GetDirectoryName(script.File)!; environmentVars ??= new Dictionary<string, string>(); var setupGCloudAuthentication = new SetupGCloudAuthentication(variables, log, commandLineRunner, environmentVars, workingDirectory); var result = setupGCloudAuthentication.Execute(); if (result.ExitCode != 0) { return result; } return NextWrapper!.ExecuteScript(script, scriptSyntax, commandLineRunner, environmentVars); } class SetupGCloudAuthentication { readonly IVariables variables; readonly ILog log; readonly ICommandLineRunner commandLineRunner; readonly Dictionary<string, string> environmentVars; readonly string workingDirectory; private string? gcloud = String.Empty; public SetupGCloudAuthentication(IVariables variables, ILog log, ICommandLineRunner commandLineRunner, Dictionary<string, string> environmentVars, string workingDirectory) { this.variables = variables; this.log = log; this.commandLineRunner = commandLineRunner; this.environmentVars = environmentVars; this.workingDirectory = workingDirectory; } public CommandResult Execute() { var errorResult = new CommandResult(string.Empty, 1); foreach (var proxyVariable in ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables()) { environmentVars[proxyVariable.Key] = proxyVariable.Value; } environmentVars.Add("CLOUDSDK_CORE_DISABLE_PROMPTS", "1"); var gcloudConfigPath = Path.Combine(workingDirectory, "gcloud-cli"); environmentVars.Add("CLOUDSDK_CONFIG", gcloudConfigPath); Directory.CreateDirectory(gcloudConfigPath); gcloud = variables.Get("Octopus.Action.GoogleCloud.CustomExecutable"); if (!string.IsNullOrEmpty(gcloud)) { if (!File.Exists(gcloud)) { log.Error($"The custom gcloud location of {gcloud} does not exist. Please make sure gcloud is installed in that location."); return errorResult; } } else { gcloud = CalamariEnvironment.IsRunningOnWindows ? ExecuteCommandAndReturnOutput("where", "gcloud.cmd") : ExecuteCommandAndReturnOutput("which", "gcloud"); if (gcloud == null) { log.Error("Could not find gcloud. Make sure gcloud is on the PATH."); return errorResult; } } log.Verbose($"Using gcloud from {gcloud}."); var useVmServiceAccount = variables.GetFlag("Octopus.Action.GoogleCloud.UseVMServiceAccount"); string? impersonationEmails = null; if (variables.GetFlag("Octopus.Action.GoogleCloud.ImpersonateServiceAccount")) { impersonationEmails = variables.Get("Octopus.Action.GoogleCloud.ServiceAccountEmails"); } var project = variables.Get("Octopus.Action.GoogleCloud.Project") ?? string.Empty; var region = variables.Get("Octopus.Action.GoogleCloud.Region") ?? string.Empty; var zone = variables.Get("Octopus.Action.GoogleCloud.Zone") ?? string.Empty; if (!string.IsNullOrEmpty(project)) { environmentVars.Add("CLOUDSDK_CORE_PROJECT", project); } if (!string.IsNullOrEmpty(region)) { environmentVars.Add("CLOUDSDK_COMPUTE_REGION", region); } if (!string.IsNullOrEmpty(zone)) { environmentVars.Add("CLOUDSDK_COMPUTE_ZONE", zone); } if (!useVmServiceAccount) { var accountVariable = variables.Get("Octopus.Action.GoogleCloudAccount.Variable"); var jsonKey = variables.Get($"{accountVariable}.JsonKey"); if (jsonKey == null) { log.Error("Failed to authenticate with gcloud. Key file is empty."); return errorResult; } log.Verbose("Authenticating to gcloud with key file"); var bytes = Convert.FromBase64String(jsonKey); using (var keyFile = new TemporaryFile(Path.Combine(workingDirectory, Path.GetRandomFileName()))) { File.WriteAllBytes(keyFile.FilePath, bytes); if (ExecuteCommand("auth", "activate-service-account", $"--key-file=\"{keyFile.FilePath}\"") .ExitCode != 0) { log.Error("Failed to authenticate with gcloud."); return errorResult; } } log.Verbose("Successfully authenticated with gcloud"); } else { log.Verbose("Bypassing authentication with gcloud"); } if (impersonationEmails != null) { if (ExecuteCommand("config", "set", "auth/impersonate_service_account", impersonationEmails) .ExitCode != 0) { log.Error("Failed to impersonate service account."); return errorResult; } log.Verbose("Impersonation emails set."); } return new CommandResult(string.Empty, 0); } CommandResult ExecuteCommand(params string[] arguments) { if (gcloud == null) { throw new Exception("gcloud is null"); } var captureCommandOutput = new CaptureCommandOutput(); var invocation = new CommandLineInvocation(gcloud, arguments) { EnvironmentVars = environmentVars, WorkingDirectory = workingDirectory, OutputAsVerbose = false, OutputToLog = false, AdditionalInvocationOutputSink = captureCommandOutput }; log.Verbose(invocation.ToString()); var result = commandLineRunner.Execute(invocation); foreach (var message in captureCommandOutput.Messages) { if (result.ExitCode == 0) { log.Verbose(message.Text); continue; } switch (message.Level) { case Level.Verbose: log.Verbose(message.Text); break; case Level.Error: log.Error(message.Text); break; } } return result; } string? ExecuteCommandAndReturnOutput(string exe, params string[] arguments) { var captureCommandOutput = new CaptureCommandOutput(); var invocation = new CommandLineInvocation(exe, arguments) { EnvironmentVars = environmentVars, WorkingDirectory = workingDirectory, OutputAsVerbose = false, OutputToLog = false, AdditionalInvocationOutputSink = captureCommandOutput }; var result = commandLineRunner.Execute(invocation); return result.ExitCode == 0 ? String.Join(Environment.NewLine, captureCommandOutput.Messages.Where(m => m.Level == Level.Verbose).Select(m => m.Text).ToArray()).Trim() : null; } class CaptureCommandOutput : ICommandInvocationOutputSink { private List<Message> messages = new List<Message>(); public List<Message> Messages => messages; public void WriteInfo(string line) { Messages.Add(new Message(Level.Verbose, line)); } public void WriteError(string line) { Messages.Add(new Message(Level.Error, line)); } } class Message { public Level Level { get; } public string Text { get; } public Message(Level level, string text) { Level = level; Text = text; } } enum Level { Verbose, Error } } } }<file_sep>using System; using Calamari.Testing.Helpers; namespace Calamari.Tests.KubernetesFixtures { class DoNotDoubleLog : InMemoryLog { protected override void StdErr(string message) { } protected override void StdOut(string message) { } } }<file_sep>#!/bin/bash # Enter any commands that are required by the NGINX feature in a way the program doesn't do anything, like displaying the commands help requiredCommandsToCheck=" cp --help mv --help rm --help nginx -h " function check_user_has_sudo_access_without_password_to_command { sudo -n $1 $2 > /dev/null 2>&1 if [[ $? -ne 0 ]]; then echo >&2 "User does not have 'sudo' access without password to command '$1'" failedSudoCheck=1 fi } function check_user_has_sudo_access_without_password_to_required_commands { IFS=$'\n' read -rd '' -a cmdArr <<< "$requiredCommandsToCheck" failedSudoCheck=0 for cmd in "${cmdArr[@]}" do check_user_has_sudo_access_without_password_to_command ${cmd} done || exit $? if [[ $failedSudoCheck -ne 0 ]]; then echo >&2 "User does not have the required 'sudo' access without password." echo >&2 "See https://g.octopushq.com/NginxUserPermissions from more information" exit 1 fi } function check_nginx_exists { sudo -n bash -c 'command -v nginx' > /dev/null 2>&1 if [[ $? -ne 0 ]]; then echo >&2 "The executable 'nginx' does not exist, or cannot be located using the PATH in" echo >&2 "the 'sudo' environment, or the user does not have the required 'sudo' access" echo >&2 "without a password." echo >&2 "For more on installing nginx, see https://g.octopushq.com/NginxInstall." echo >&2 "For more on sudo settings see https://g.octopushq.com/NginxUserPermissions," echo >&2 "and the 'secure_path' and 'NOPASSWD' options in 'man sudoers'." exit 1 fi } check_nginx_exists check_user_has_sudo_access_without_password_to_required_commands <file_sep>using System; using System.IO; using System.Text; using System.Threading; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.FileSystem; using Newtonsoft.Json; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { [TestFixture] public class LockIoTests { [Test] public void ReadLockReturnsMissingFileLockIfFileNotFound() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => { throw new FileNotFoundException(); } ); var lockIo = new LockIo(fileSystem); var result = lockIo.ReadLock(lockFilePath); Assert.That(result, Is.InstanceOf<MissingFileLock>()); } [Test] public void ReadLockReturnsOtherProcessHasExclusiveLockIfIoException() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => { throw new IOException("Sharing violation"); }); var lockIo = new LockIo(fileSystem); var result = lockIo.ReadLock(lockFilePath); Assert.That(result, Is.InstanceOf<OtherProcessHasExclusiveLockOnFileLock>()); } [Test] public void ReadLockReturnsUnableToDeserialiseWhenDeserialisationFails() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var fileCreationTime = DateTime.Now; fileSystem.GetCreationTime(lockFilePath).Returns(fileCreationTime); var lockIo = new LockIo(fileSystem); fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => { throw new JsonReaderException(); }); var result = lockIo.ReadLock(lockFilePath); Assert.That(result, Is.InstanceOf<UnableToDeserialiseLockFile>()); Assert.That(((UnableToDeserialiseLockFile)result).CreationTime, Is.EqualTo(fileCreationTime)); } [Test] public void ReadLockReturnsOtherProcessHasExclusiveLockIfUnknownException() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => { throw new ApplicationException(); }); var result = lockIo.ReadLock(lockFilePath); Assert.That(result, Is.InstanceOf<OtherProcessHasExclusiveLockOnFileLock>()); } [Test] public void ReadLockReturnsLockDetailsIfLockBelongsToUs() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var fileContent = $"{{\"__type\":\"FileLock:#Calamari.Integration.Processes.Semaphores\",\"ProcessId\":{currentProcess.Id},\"ProcessName\":\"{currentProcess.ProcessName}\",\"ThreadId\":{Thread.CurrentThread.ManagedThreadId},\"Timestamp\":636114372739676700}}"; fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => new MemoryStream(Encoding.UTF8.GetBytes(fileContent))); var result = lockIo.ReadLock(lockFilePath) as FileLock; Assert.That(result, Is.InstanceOf<FileLock>()); Assert.That(result.ProcessId, Is.EqualTo(currentProcess.Id)); Assert.That(result.ProcessName, Is.EqualTo(currentProcess.ProcessName)); Assert.That(result.ThreadId, Is.EqualTo(Thread.CurrentThread.ManagedThreadId)); Assert.That(result.Timestamp, Is.EqualTo(636114372739676700)); } [Test] public void ReadLockReturnsOtherProcessOwnsFileLockIfLockBelongsToSomeoneElse() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var fileContent = $"{{\"__type\":\"FileLock:#Calamari.Integration.Processes.Semaphores\",\"ProcessId\":{currentProcess.Id + 1},\"ProcessName\":\"{currentProcess.ProcessName}\",\"ThreadId\":{Thread.CurrentThread.ManagedThreadId},\"Timestamp\":636114372739676700}}"; fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => new MemoryStream(Encoding.UTF8.GetBytes(fileContent))); var result = lockIo.ReadLock(lockFilePath) as OtherProcessOwnsFileLock; Assert.That(result, Is.InstanceOf<OtherProcessOwnsFileLock>()); Assert.That(result.ProcessId, Is.EqualTo(currentProcess.Id + 1)); Assert.That(result.ProcessName, Is.EqualTo(currentProcess.ProcessName)); Assert.That(result.ThreadId, Is.EqualTo(Thread.CurrentThread.ManagedThreadId)); Assert.That(result.Timestamp, Is.EqualTo(636114372739676700)); } [Test] public void DeleteLockSwallowsExceptions() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); fileSystem.When(x => x.DeleteFile(lockFilePath)).Do(x => { throw new Exception("failed to delete file"); }); Assert.DoesNotThrow(() => lockIo.DeleteLock(lockFilePath)); } [Test] public void WriteLockDoesNotOverwriteLockFileIfItsIdenticalToWhatWeAreWantingToWrite() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); fileSystem.FileExists(lockFilePath).Returns(true); var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var fileContent = $"{{\"__type\":\"FileLock:#Calamari.Integration.Processes.Semaphores\",\"ProcessId\":{currentProcess.Id},\"ProcessName\":\"{currentProcess.ProcessName}\",\"ThreadId\":{Thread.CurrentThread.ManagedThreadId},\"Timestamp\":636114372739676700}}"; fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => new MemoryStream(Encoding.UTF8.GetBytes(fileContent))); var lockFile = (FileLock)lockIo.ReadLock(lockFilePath); lockIo.WriteLock(lockFilePath, lockFile); } [Test] public void WriteLockOverwritesLockFileIfTimestampIsDifferent() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); fileSystem.FileExists(lockFilePath).Returns(true); var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var fileContent = $"{{\"__type\":\"FileLock:#Calamari.Integration.Processes.Semaphores\",\"ProcessId\":{currentProcess.Id},\"ProcessName\":\"{currentProcess.ProcessName}\",\"ThreadId\":{Thread.CurrentThread.ManagedThreadId},\"Timestamp\":636114372739676700}}"; fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => new MemoryStream(Encoding.UTF8.GetBytes(fileContent))); var lockFile = (FileLock)lockIo.ReadLock(lockFilePath); lockFile.Timestamp = lockFile.Timestamp + 1; fileSystem.OpenFileExclusively(lockFilePath, FileMode.Create, FileAccess.Write) .Returns(x => new MemoryStream()); var result = lockIo.WriteLock(lockFilePath, lockFile); Assert.That(result, Is.True); } [Test] public void WriteLockDeletesLockIfUnableToDeserialise() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); fileSystem.FileExists(lockFilePath).Returns(true); var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var expectedFileContent = $"{{\"__type\":\"FileLock:#Calamari.Integration.Processes.Semaphores\",\"ProcessId\":{currentProcess.Id},\"ProcessName\":\"{currentProcess.ProcessName}\",\"ThreadId\":{Thread.CurrentThread.ManagedThreadId},\"Timestamp\":636114372739676700}}"; fileSystem.OpenFileExclusively(lockFilePath, FileMode.Open, FileAccess.Read) .Returns(x => new MemoryStream(Encoding.UTF8.GetBytes("non deserialisable content")), x => new MemoryStream(Encoding.UTF8.GetBytes(expectedFileContent))); fileSystem.OpenFileExclusively(lockFilePath, FileMode.CreateNew, FileAccess.Write) .Returns(x => new MemoryStream()); var result = lockIo.WriteLock(lockFilePath, new FileLock(currentProcess.Id, currentProcess.ProcessName, Thread.CurrentThread.ManagedThreadId, 636114372739676700)); fileSystem.Received().DeleteFile(lockFilePath); Assert.That(result, Is.True); } [Test] public void WriteLockReturnsFalseIfIoException() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); fileSystem.FileExists(lockFilePath).Returns(true); fileSystem.OpenFileExclusively(lockFilePath, Arg.Any<FileMode>(), Arg.Any<FileAccess>()) .Returns(x => { throw new IOException("Sharing exception"); }); var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var result = lockIo.WriteLock(lockFilePath, new FileLock(currentProcess.Id, currentProcess.ProcessName, Thread.CurrentThread.ManagedThreadId, 636114372739676700)); Assert.That(result, Is.False); } [Test] public void WriteLockReturnsFalseIfUnknownException() { var fileSystem = Substitute.For<ICalamariFileSystem>(); var lockFilePath = "fake path"; var lockIo = new LockIo(fileSystem); fileSystem.FileExists(lockFilePath).Returns(true); fileSystem.OpenFileExclusively(lockFilePath, Arg.Any<FileMode>(), Arg.Any<FileAccess>()) .Returns(x => { throw new Exception("Unknown exception"); }); var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var result = lockIo.WriteLock(lockFilePath, new FileLock(currentProcess.Id, currentProcess.ProcessName, Thread.CurrentThread.ManagedThreadId, 636114372739676700)); Assert.That(result, Is.False); } } } <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Azure; using Azure.ResourceManager.AppService; using Azure.ResourceManager.Resources; using Calamari.AzureAppService.Azure; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureAppService { [Command("health-check", Description = "Run a health check on a DeploymentTargetType")] public class HealthCheckCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<HealthCheckBehaviour>(); } } class HealthCheckBehaviour : IDeployBehaviour { public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var account = ServicePrincipalAccount.CreateFromKnownVariables(context.Variables); var resourceGroupName = context.Variables.Get(SpecialVariables.Action.Azure.ResourceGroupName); var webAppName = context.Variables.Get(SpecialVariables.Action.Azure.WebAppName); return ConfirmWebAppExists(account, resourceGroupName, webAppName); } private async Task ConfirmWebAppExists(ServicePrincipalAccount servicePrincipal, string resourceGroupName, string siteAndSlotName) { var client = servicePrincipal.CreateArmClient(); var resourceGroupResource = client.GetResourceGroupResource(ResourceGroupResource.CreateResourceIdentifier(servicePrincipal.SubscriptionNumber, resourceGroupName)); //if the website doesn't exist, throw if (!await resourceGroupResource.GetWebSites().ExistsAsync(siteAndSlotName)) throw new Exception($"Could not find site {siteAndSlotName} in resource group {resourceGroupName}, using Service Principal with subscription {servicePrincipal.SubscriptionNumber}"); } } }<file_sep>using System; namespace Calamari.Common.Features.Scripts { public enum ScriptSyntax { [FileExtension("ps1")] PowerShell, [FileExtension("csx")] CSharp, [FileExtension("sh")] Bash, [FileExtension("fsx")] FSharp, [FileExtension("py")] Python } }<file_sep>using System; Console.WriteLine("Parameters " + Args[0] + Args[1]);<file_sep>#if JAVA_SUPPORT using System; using System.IO; using System.IO.Compression; using System.Linq; using Calamari.Commands.Java; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Java.Fixtures.Deployment { [TestFixture] public class DeployJavaArchiveFixture : CalamariFixture { ICalamariFileSystem fileSystem; string applicationDirectory; int returnCode; InMemoryLog log; string sourcePackage; [SetUp] public virtual void SetUp() { fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); log = new InMemoryLog(); // Ensure staging directory exists and is empty applicationDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestStaging"); fileSystem.EnsureDirectoryExists(applicationDirectory); fileSystem.PurgeDirectory(applicationDirectory, FailureOptions.ThrowOnFailure); Environment.SetEnvironmentVariable("TentacleJournal", Path.Combine(applicationDirectory, "DeploymentJournal.xml")); sourcePackage = TestEnvironment.GetTestPath("Java", "Fixtures", "Deployment", "Packages", "HelloWorld.0.0.1.jar"); } [TearDown] public virtual void CleanUp() { CalamariPhysicalFileSystem.GetPhysicalFileSystem().PurgeDirectory(applicationDirectory, FailureOptions.IgnoreFailure); } [Test] public void CanDeployJavaArchive() { DeployPackage(sourcePackage, GenerateVariables()); Assert.AreEqual(0, returnCode); //Archive is re-packed log.StandardOut.Should().Contain($"Re-packaging archive: '{Path.Combine(applicationDirectory, "HelloWorld", "0.0.1", "HelloWorld.0.0.1.jar")}'"); } // https://github.com/OctopusDeploy/Issues/issues/4733 [Test] public void EnsureMetafileDataRepacked() { DeployPackage(sourcePackage, GenerateVariables()); Assert.AreEqual(0, returnCode); var targetFile = Path.Combine(applicationDirectory, "HelloWorld", "0.0.1", "HelloWorld.0.0.1.jar"); //Archive is re-packed log.StandardOut.Should().Contain($"Re-packaging archive: '{targetFile}'"); //Check the manifest is copied from the original using (var stream = new FileStream(targetFile, FileMode.Open)) using (var archive = new ZipArchive(stream, ZipArchiveMode.Read)) { var manifestEntry = archive.Entries.First(e => e.FullName == "META-INF/MANIFEST.MF"); using (var reader = new StreamReader(manifestEntry.Open())) { var manifest = reader.ReadToEnd(); Assert.That(manifest.Contains("CustomProperty: Foo")); } } } [Test] public void CanTransformConfigInJar() { const string configFile = "config.properties"; var variables = GenerateVariables(); variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.SubstituteInFiles); variables.Set(PackageVariables.SubstituteInFilesTargets, configFile); DeployPackage(sourcePackage, variables); Assert.AreEqual(0, returnCode); log.StandardOut.Should().Contain($"Performing variable substitution on '{Path.Combine(Environment.CurrentDirectory, "staging", configFile)}'"); } [Test] public void CanDeployJavaArchiveUncompressed() { var variables = GenerateVariables(); variables.Set(PackageVariables.JavaArchiveCompression, false.ToString()); DeployPackage(sourcePackage, variables); Assert.AreEqual(0, returnCode); // Archive is re-packed var path = Path.Combine(applicationDirectory, "HelloWorld", "0.0.1", "HelloWorld.0.0.1.jar"); log.StandardOut.Should().Contain($"Re-packaging archive: '{path}'"); using (var stream = new FileStream(path, FileMode.Open)) using (var archive = new ZipArchive(stream, ZipArchiveMode.Read)) { archive.Entries.All(a => a.CompressedLength == a.Length).Should().BeTrue(); } } void DeployPackage(string packageName, IVariables variables) { var commandLineRunner = new CommandLineRunner(log, variables); var command = new DeployJavaArchiveCommand( log, new ScriptEngine(Enumerable.Empty<IScriptWrapper>()), variables, fileSystem, commandLineRunner, new SubstituteInFiles(log, fileSystem, new FileSubstituter(log, fileSystem), variables), new ExtractPackage(new CombinedPackageExtractor(log, variables, commandLineRunner), fileSystem, variables, log), new StructuredConfigVariablesService(new PrioritisedList<IFileFormatVariableReplacer> { new JsonFormatVariableReplacer(fileSystem, log), new XmlFormatVariableReplacer(fileSystem, log), new YamlFormatVariableReplacer(fileSystem, log), new PropertiesFormatVariableReplacer(fileSystem, log), }, variables, fileSystem, log), new DeploymentJournalWriter(fileSystem) ); returnCode = command.Execute(new[] { "--archive", $"{packageName}" }); } protected IVariables GenerateVariables() { var variables = new VariablesFactory(fileSystem).Create(new CommonOptions("test")); variables.Set(TentacleVariables.Agent.ApplicationDirectoryPath, applicationDirectory); return variables; } } } #endif<file_sep>using System; namespace Calamari.Common.Features.StructuredVariables { public class StructuredConfigFileParseException : Exception { public StructuredConfigFileParseException(string message, Exception innerException) : base(message, innerException) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calamari.Common.Features.Discovery { public interface ITargetDiscoveryContext { public TargetDiscoveryScope Scope { get; } } /// <summary> /// This type and the types it uses are duplicated here from Octopus.Core, because: /// a) There is currently no existing project to place code shared between server and Calamari, and /// b) We expect a bunch of stuff in the Sashimi/Calamari space to be refactored back into the OctopusDeploy solution soon. /// </summary> public class TargetDiscoveryContext<TAuthentication> : ITargetDiscoveryContext where TAuthentication : class,ITargetDiscoveryAuthenticationDetails { public TargetDiscoveryContext(TargetDiscoveryScope? scope, TAuthentication? authentication) { this.Scope = scope; this.Authentication = authentication; } public TargetDiscoveryScope? Scope { get; set; } public TAuthentication? Authentication { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using Calamari.Common.Features.Packages; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; using Octopus.Versioning; namespace Calamari.Tests.Fixtures.PackageDownload { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class NuGetFeedVersionSupportFixture : CalamariFixture { const string TestNuGetPackageId = "Calamari.Tests.Fixtures.PackageDownload.NuGetFeedSupport"; // TODO: Packages here were generated using the nuspec file in the .\NuGetFeedSupport folder // Right now, they have been manually uploaded to the feedz.io and Artifactory repositories below. // In future, we should ensure this test fixture sets its own data up from scratch before running // and tears it down on completion, rather than relying on external state as it currently does. static readonly string FeedzNuGetV2FeedUrl = ExternalVariables.Get(ExternalVariable.FeedzNuGetV2FeedUrl); static readonly string FeedzNuGetV3FeedUrl = ExternalVariables.Get(ExternalVariable.FeedzNuGetV3FeedUrl); static readonly string ArtifactoryNuGetV2FeedUrl = ExternalVariables.Get(ExternalVariable.ArtifactoryNuGetV2FeedUrl); static readonly string ArtifactoryNuGetV3FeedUrl = ExternalVariables.Get(ExternalVariable.ArtifactoryNuGetV3FeedUrl); static readonly string TentacleHome = TestEnvironment.GetTestPath("Fixtures", "PackageDownload"); [SetUp] public void SetUp() { if (!Directory.Exists(TentacleHome)) Directory.CreateDirectory(TentacleHome); Directory.SetCurrentDirectory(TentacleHome); Environment.SetEnvironmentVariable("TentacleHome", TentacleHome); Console.WriteLine("TentacleHome is set to: " + TentacleHome); } [TearDown] public void TearDown() { var downloadPath = TestEnvironment.GetTestPath(TentacleHome, "Files"); if (Directory.Exists(downloadPath)) Directory.Delete(downloadPath, true); Environment.SetEnvironmentVariable("TentacleHome", null); } [Test] [TestCaseSource(nameof(FeedzNuGet2SupportedVersionStrings))] public void ShouldSupportFeedzNuGetVersion2Feeds(string versionString) { var calamariResult = DownloadPackage(TestNuGetPackageId, versionString, "nuget-local", FeedzNuGetV2FeedUrl); calamariResult.AssertSuccess(); } [Test] [TestCaseSource(nameof(FeedzNuGet2SupportedVersionStrings))] [TestCaseSource(nameof(FeedzNuGet3SupportedVersionStrings))] public void ShouldSupportFeedzNuGetVersion3Feeds(string versionString) { var calamariResult = DownloadPackage(TestNuGetPackageId, versionString, "nuget-local", FeedzNuGetV3FeedUrl); calamariResult.AssertSuccess(); } [Test] [TestCaseSource(nameof(ArtifactoryNuGet3SupportedVersionStrings))] [TestCaseSource(nameof(ArtifactoryNuGet2SupportedVersionStrings))] [Platform("Net-4.5")] public void ArtifactoryShouldSupportNuGetVersion3Feeds(string versionString) { var calamariResult = DownloadPackage(TestNuGetPackageId, versionString, "nuget-local", ArtifactoryNuGetV3FeedUrl); calamariResult.AssertSuccess(); } [Test] [TestCaseSource(nameof(ArtifactoryNuGet2SupportedVersionStrings))] public void ArtifactoryShouldSupportNuGetVersion2Feeds(string versionString) { var calamariResult = DownloadPackage(TestNuGetPackageId, versionString, "nuget-local", ArtifactoryNuGetV2FeedUrl); calamariResult.AssertSuccess(); } public static IEnumerable<TestCaseData> FeedzNuGet2SupportedVersionStrings { get { yield return new TestCaseData("1.0.0"); yield return new TestCaseData("1.4.92").SetDescription("Multi-digit Patch Version"); yield return new TestCaseData("2.0.0-beta").SetDescription("SemVer 1.0 beta pre-release"); } } public static IEnumerable<TestCaseData> FeedzNuGet3SupportedVersionStrings { get { yield return new TestCaseData("2.0.0-beta+abcd16bd").SetDescription("Pre-release version with metadata"); yield return new TestCaseData("2.0.0-beta.1+abcd16bd").SetDescription("Pre-release version with dot suffix and metadata"); yield return new TestCaseData("2.0.0-beta.2").SetDescription("Pre-release version with dot suffix"); yield return new TestCaseData("2.0.0-beta.2.1").SetDescription("Pre-release version with double-dot suffix"); } } public static IEnumerable<TestCaseData> ArtifactoryNuGet2SupportedVersionStrings { get { yield return new TestCaseData("1.0.0").SetDescription("Pre-release version with metadata"); } } public static IEnumerable<TestCaseData> ArtifactoryNuGet3SupportedVersionStrings { get { yield return new TestCaseData("1.0.0-alpha.3+metadata").SetDescription("Pre-release version with dot suffix and metadata"); } } CalamariResult DownloadPackage(string packageId, string packageVersion, string feedId, string feedUri, string feedUsername = "", string feedPassword = "") { var calamari = Calamari() .Action("download-package") .Argument("packageId", packageId) .Argument("packageVersion", packageVersion) .Argument("packageVersionFormat", VersionFormat.Semver) .Argument("feedId", feedId) .Argument("feedUri", feedUri) .Argument("feedType", FeedType.NuGet) .Argument("attempts", 1) .Argument("attemptBackoffSeconds", 0); if (!string.IsNullOrWhiteSpace(feedUsername)) calamari.Argument("feedUsername", feedUsername); if (!string.IsNullOrWhiteSpace(feedPassword)) calamari.Argument("feedPassword", feedPassword); return Invoke(calamari); } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public class PowerShellVariables { public static readonly string CustomPowerShellVersion = "Octopus.Action.PowerShell.CustomPowerShellVersion"; public static readonly string ExecuteWithoutProfile = "Octopus.Action.PowerShell.ExecuteWithoutProfile"; public static readonly string DebugMode = "Octopus.Action.PowerShell.DebugMode"; public static readonly string UserName = "Octopus.Action.PowerShell.UserName"; public static readonly string Password = "<PASSWORD>"; public static readonly string Edition = "Octopus.Action.PowerShell.Edition"; public static class PSDebug { public static readonly string Trace = "Octopus.Action.PowerShell.PSDebug.Trace"; public static readonly string Strict = "Octopus.Action.PowerShell.PSDebug.Strict"; } } }<file_sep>using System; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; using Calamari.Aws.Integration; using Calamari.Aws.Util; using Calamari.CloudAccounts; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment; using Calamari.Deployment.Conventions; namespace Calamari.Aws.Deployment.Conventions { public class CreateS3BucketConvention: IInstallConvention { private readonly AwsEnvironmentGeneration awsEnvironmentGeneration; private readonly Func<RunningDeployment, string> bucketFactory; public CreateS3BucketConvention(AwsEnvironmentGeneration awsEnvironmentGeneration, Func<RunningDeployment, string> bucketFactory) { this.awsEnvironmentGeneration = awsEnvironmentGeneration; this.bucketFactory = bucketFactory; } public void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private Task InstallAsync(RunningDeployment deployment) { Guard.NotNull(deployment, "Deployment should not be null"); Guard.NotNull(bucketFactory, "Bucket factory should not be null"); AmazonS3Client ClientFactory() => ClientHelpers.CreateS3Client(awsEnvironmentGeneration); return EnsureBucketExists(ClientFactory, bucketFactory(deployment)); } public async Task EnsureBucketExists(Func<AmazonS3Client> clientFactory, string bucketName) { Guard.NotNull(clientFactory, "Client factory should not be null"); Guard.NotNullOrWhiteSpace(bucketName, "Bucket name should not be null or empty"); using (var client = clientFactory()) { if (await Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async(client, bucketName)) { Log.Verbose($"Bucket {bucketName} exists in region {awsEnvironmentGeneration.AwsRegion}. Skipping creation."); return; } var request = new PutBucketRequest { BucketName = bucketName.Trim(), UseClientRegion = true }; Log.Info($"Creating {bucketName}."); await client.PutBucketAsync(request); } } } } <file_sep>#if !NET40 using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Calamari.Kubernetes.ResourceStatus { /// <summary> /// Represents a timer that completes the countdown after a predefined period of time once started. /// </summary> public interface ITimer { void Start(); bool HasCompleted(); Task WaitForInterval(); } public class Timer : ITimer { public delegate ITimer Factory(TimeSpan interval, TimeSpan duration); private readonly Stopwatch stopwatch = new Stopwatch(); private readonly TimeSpan interval; private readonly TimeSpan duration; public Timer(TimeSpan interval, TimeSpan duration) { this.interval = interval; this.duration = duration; } public void Start() => stopwatch.Start(); public bool HasCompleted() => duration != Timeout.InfiniteTimeSpan && stopwatch.IsRunning && stopwatch.Elapsed >= duration; public async Task WaitForInterval() => await Task.Delay(interval); } } #endif<file_sep>using System; namespace Calamari.Build { public static class FixedRuntimes { public const string Cloud = "Cloud"; public const string Linux = "linux-x64"; public const string Windows = "win-x64"; } }<file_sep>using System; namespace Calamari.Common.Features.Scripting { public class InvalidScriptException : Exception { public InvalidScriptException(string message) : base(message) { } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System.Linq; using Calamari.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Integration.Certificates; using NUnit.Framework; using Octostache; namespace Calamari.Tests.Fixtures.Certificates { [TestFixture] public class PrivateKeyAccessRuleSerializationTestFixture { [Test] public void CanDeserializeJson() { const string json = @"[ {""Identity"": ""BUILTIN\\Administrators"", ""Access"": ""FullControl""}, {""Identity"": ""BUILTIN\\Users"", ""Access"": ""ReadOnly""} ]"; var result = PrivateKeyAccessRule.FromJson(json).ToList(); Assert.AreEqual(2, result.Count); Assert.AreEqual("BUILTIN\\Administrators", result[0].Identity.ToString()); Assert.AreEqual(PrivateKeyAccess.FullControl, result[0].Access); Assert.AreEqual("BUILTIN\\Users", result[1].Identity.ToString()); Assert.AreEqual(PrivateKeyAccess.ReadOnly, result[1].Access); } [Test] public void CanDeserializeNestedVariable() { var variables = new CalamariVariables(); const string json = @"[ {""Identity"": ""#{UserName}"", ""Access"": ""FullControl""} ]"; variables.Set("UserName", "AmericanEagles\\RogerRamjet"); variables.Set(SpecialVariables.Certificate.PrivateKeyAccessRules, json); var result = ImportCertificateCommand.GetPrivateKeyAccessRules(variables).ToList(); Assert.AreEqual(1, result.Count); Assert.AreEqual("AmericanEagles\\RogerRamjet", result[0].Identity.ToString()); Assert.AreEqual(PrivateKeyAccess.FullControl, result[0].Access); } } } #endif<file_sep>using System; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public interface IManagePackageCache { void RegisterPackageUse(PackageIdentity package, ServerTaskId deploymentTaskId, ulong packageSizeBytes); void RemoveAllLocks(ServerTaskId serverTaskId); void ApplyRetention(); void ExpireStaleLocks(TimeSpan timeBeforeExpiration); } }<file_sep>using System; using System.IO; using System.Linq; using Calamari.Common.Plumbing; using Calamari.Testing.Helpers; using SharpCompress.Archives; using SharpCompress.Archives.Tar; using SharpCompress.Common; using SharpCompress.Writers; namespace Calamari.Tests.Helpers { public static class TarGzBuilder { public static string BuildSamplePackage(string name, string version, bool excludeNonNativePlatformScripts = true) { var sourceDirectory = TestEnvironment.GetTestPath("Fixtures", "Deployment", "Packages", name); var output = Path.Combine(Path.GetTempPath(), "CalamariTestPackages"); Directory.CreateDirectory(output); var outputTarFilename = Path.Combine(output, name + "." + version + ".tar.gz"); if (File.Exists(outputTarFilename)) File.Delete(outputTarFilename); using (Stream stream = File.OpenWrite(outputTarFilename)) using (var writer = WriterFactory.Open(stream, ArchiveType.Tar, new WriterOptions(CompressionType.GZip) {LeaveStreamOpen = false})) { var isRunningOnWindows = CalamariEnvironment.IsRunningOnWindows; var files = Directory.EnumerateFiles(sourceDirectory, "*.*", SearchOption.AllDirectories) .Select(f => new FileInfo(f)) .Where(f => isRunningOnWindows ? !IsNixNuspecFile(f) : !IsNotANuspecFile(f) || IsNixNuspecFile(f)); if (excludeNonNativePlatformScripts) files = files.Where(f => isRunningOnWindows ? f.Extension != ".sh" : f.Extension != ".ps1"); foreach(var file in files) writer.Write(GetFilePathRelativeToRoot(sourceDirectory, file), file); } return outputTarFilename; bool IsNixNuspecFile(FileInfo f) => f.Name.EndsWith(".Nix.nuspec"); bool IsNotANuspecFile(FileInfo f) => f.Name.EndsWith(".nuspec"); } static string GetFilePathRelativeToRoot(string root, FileInfo file) { var directory = new DirectoryInfo(root); var rootDirectoryUri = new Uri(directory.FullName + Path.DirectorySeparatorChar); var fileUri = new Uri(file.FullName); return rootDirectoryUri.MakeRelativeUri(fileUri).ToString(); } } } <file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using Calamari.Integration.Certificates; using NUnit.Framework; using System.Linq; using Calamari.Testing.Helpers; namespace Calamari.Tests.Helpers.Certificates { public class SampleCertificate { private readonly string fileName; public const string CngPrivateKeyId = "CngWithPrivateKey"; public static readonly SampleCertificate CngWithPrivateKey = new SampleCertificate("cng_privatekey_password.pfx", "<PASSWORD>", "<PASSWORD>", true); public const string CapiWithPrivateKeyId = "CapiWithPrivateKey"; public static readonly SampleCertificate CapiWithPrivateKey = new SampleCertificate("capi_self_signed_privatekey_password.pfx", "<PASSWORD>!", "<PASSWORD>", true); public const string CapiWithPrivateKeyNoPasswordId = "CapiWithPrivateKeyNoPassword"; public static readonly SampleCertificate CapiWithPrivateKeyNoPassword = new SampleCertificate("capi_self_signed_privatekey_no_password.pfx", null, "E7D0BF9F1A62AED35BA22BED80F9795012A53636", true); public const string CertificateChainId = "CertificateChain"; public static readonly SampleCertificate CertificateChain = new SampleCertificate("3-cert-chain.pfx", "hello world", "A11C309EFDF2864B1641F43A7A5B5019EB4CB816", true); public const string ChainSignedByLegacySha1RsaId = "ChainSignedByLegacySha1Rsa"; public static readonly SampleCertificate ChainSignedByLegacySha1Rsa = new SampleCertificate("chain-signed-by-legacy-sha1-rsa.pfx", "<PASSWORD>!", "47F51DED16E944AFC4B49B419D1C554974C895D2", true); public const string CertWithNoPrivateKeyId = "CertWithNoPrivateKey"; public static readonly SampleCertificate CertWithNoPrivateKey = new SampleCertificate("cert-with-no-private-key.pfx", null, "FADD35F52F269FF0123D08396E2A6C1706496EE6", false); public static readonly IDictionary<string, SampleCertificate> SampleCertificates = new Dictionary<string, SampleCertificate> { {CngPrivateKeyId, CngWithPrivateKey}, {CapiWithPrivateKeyId, CapiWithPrivateKey}, {CapiWithPrivateKeyNoPasswordId, CapiWithPrivateKeyNoPassword}, {CertificateChainId, CertificateChain}, {ChainSignedByLegacySha1RsaId, ChainSignedByLegacySha1Rsa}, }; public SampleCertificate(string fileName, string password, string thumbprint, bool hasPrivateKey) { Password = <PASSWORD>; Thumbprint = thumbprint; HasPrivateKey = hasPrivateKey; this.fileName = fileName; } public string Password { get; set; } public string Thumbprint { get; } public bool HasPrivateKey { get; } public string Base64Bytes() { return Convert.ToBase64String(File.ReadAllBytes(FilePath)); } public void EnsureCertificateIsInStore(StoreName storeName, StoreLocation storeLocation) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); store.Add(LoadAsX509Certificate2()); store.Close(); } public void EnsureCertificateIsInStore(string storeName, StoreLocation storeLocation) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); store.Add(LoadAsX509Certificate2()); store.Close(); } public void EnsureCertificateNotInStore(StoreName storeName, StoreLocation storeLocation) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); EnsureCertificateNotInStore(store); store.Close(); } public void EnsureCertificateNotInStore(string storeName, StoreLocation storeLocation) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); EnsureCertificateNotInStore(store); store.Close(); } private void EnsureCertificateNotInStore(X509Store store) { var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, Thumbprint, false); if (certificates.Count == 0) return; WindowsX509CertificateStore.RemoveCertificateFromStore(Thumbprint, store.Location, store.Name); } public void AssertCertificateIsInStore(string storeName, StoreLocation storeLocation) { Assert.NotNull(GetCertificateFromStore(storeName, storeLocation), $"Could not find certificate with thumbprint {Thumbprint} in store {storeLocation}\\{storeName}"); } public X509Certificate2 GetCertificateFromStore(string storeName, StoreLocation storeLocation) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); var foundCertificates = store.Certificates.Find(X509FindType.FindByThumbprint, Thumbprint, false); return foundCertificates.Count > 0 ? foundCertificates[0] : null; } public static void AssertIdentityHasPrivateKeyAccess(X509Certificate2 certificate, IdentityReference identity, CryptoKeyRights rights) { if (!certificate.HasPrivateKey) throw new Exception("Certificate does not have private key"); var cspAlgorithm = certificate.PrivateKey as ICspAsymmetricAlgorithm; if (cspAlgorithm == null) throw new Exception("Private key is not a CSP key"); var keySecurity = cspAlgorithm.CspKeyContainerInfo.CryptoKeySecurity; foreach(var accessRule in keySecurity.GetAccessRules(true, false, identity.GetType()).Cast<CryptoKeyAccessRule>()) { if (accessRule.IdentityReference.Equals(identity) && accessRule.CryptoKeyRights.HasFlag(rights)) return; } throw new Exception($"Identity '{identity.ToString()}' does not have access right '{rights}' to private-key"); } X509Certificate2 LoadAsX509Certificate2() { return new X509Certificate2(FilePath, Password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); } string FilePath => TestEnvironment.GetTestPath("Helpers", "Certificates", "SampleCertificateFiles", fileName); } } #endif<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Threading.Tasks; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using Calamari.Aws.Exceptions; using Calamari.Aws.Integration.S3; using Calamari.Aws.Util; using Calamari.CloudAccounts; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using Calamari.Util; using Octopus.CoreUtilities; using Octopus.CoreUtilities.Extensions; using SharpCompress.Archives; using SharpCompress.Archives.Tar; using SharpCompress.Archives.Zip; using SharpCompress.Writers.Tar; using CompressionType = SharpCompress.Common.CompressionType; namespace Calamari.Aws.Deployment.Conventions { public class UploadAwsS3Convention : IInstallConvention { readonly ILog log; private readonly ICalamariFileSystem fileSystem; private readonly AwsEnvironmentGeneration awsEnvironmentGeneration; private readonly string bucket; private readonly S3TargetMode targetMode; private readonly IProvideS3TargetOptions optionsProvider; readonly IBucketKeyProvider bucketKeyProvider; readonly ISubstituteInFiles substituteInFiles; readonly IStructuredConfigVariablesService structuredConfigVariablesService; private readonly bool md5HashSupported; private static readonly HashSet<S3CannedACL> CannedAcls = new HashSet<S3CannedACL>(ConstantHelpers.GetConstantValues<S3CannedACL>()); public UploadAwsS3Convention( ILog log, ICalamariFileSystem fileSystem, AwsEnvironmentGeneration awsEnvironmentGeneration, string bucket, S3TargetMode targetMode, IProvideS3TargetOptions optionsProvider, IBucketKeyProvider bucketKeyProvider, ISubstituteInFiles substituteInFiles, IStructuredConfigVariablesService structuredConfigVariablesService ) { this.log = log; this.fileSystem = fileSystem; this.awsEnvironmentGeneration = awsEnvironmentGeneration; this.bucket = bucket; this.targetMode = targetMode; this.optionsProvider = optionsProvider; this.bucketKeyProvider = bucketKeyProvider; this.substituteInFiles = substituteInFiles; this.structuredConfigVariablesService = structuredConfigVariablesService; this.md5HashSupported = HashCalculator.IsAvailableHashingAlgorithm(MD5.Create); } private static string ExceptionMessageWithFilePath(PutObjectRequest request, Exception exception) { return $"Failed to upload file {request.FilePath}. {exception.Message}"; } private static string InvalidArgumentExceptionMessage(PutObjectRequest request, Exception exception) { //There isn't an associated error we can check for the Canned ACL so just check it against what we can determine //from the values in the SDK. string error = $"Failed to upload {request.FilePath}. An invalid argument was provided."; return !CannedAcls.Contains(request.CannedACL) ? $"{error} This is possibly due to the value specified for the canned ACL." : error; } //Errors we care about for each upload. private readonly Dictionary<string, Func<PutObjectRequest, Exception, string>> perFileUploadErrors = new Dictionary<string, Func<PutObjectRequest, Exception, string>> { { "RequestIsNotMultiPartContent", ExceptionMessageWithFilePath }, { "UnexpectedContent", ExceptionMessageWithFilePath }, { "MetadataTooLarge", ExceptionMessageWithFilePath }, { "MaxMessageLengthExceeded", ExceptionMessageWithFilePath }, { "KeyTooLongError", ExceptionMessageWithFilePath }, { "SignatureDoesNotMatch", ExceptionMessageWithFilePath }, { "InvalidStorageClass", ExceptionMessageWithFilePath }, { "InvalidArgument", InvalidArgumentExceptionMessage }, { "InvalidTag", ExceptionMessageWithFilePath } }; public void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private async Task InstallAsync(RunningDeployment deployment) { //The bucket should exist at this point Guard.NotNull(deployment, "deployment can not be null"); if (!md5HashSupported) { Log.Info("MD5 hashes are not supported in executing environment. Files will always be uploaded."); } var options = optionsProvider.GetOptions(targetMode); AmazonS3Client Factory() => ClientHelpers.CreateS3Client(awsEnvironmentGeneration); try { (await UploadAll(options, Factory, deployment)).Tee(responses => { var results = responses.Where(z => z.IsSuccess()).ToArray(); if (targetMode == S3TargetMode.EntirePackage && results.FirstOrDefault() != null) { SetOutputVariables(deployment, results.FirstOrDefault()); } else if (targetMode == S3TargetMode.FileSelections) { foreach (var result in results) { var fileName = Path.GetFileName(result.BucketKey); SetOutputVariables(deployment, result, fileName); } } }); } catch (AmazonS3Exception exception) { if (exception.ErrorCode == "AccessDenied") { throw new PermissionException("The AWS account used to perform the operation does not have the " + $"the required permissions to upload to bucket {bucket}"); } throw new UnknownException( $"An unrecognized {exception.ErrorCode} error was thrown while uploading to bucket {bucket}"); } catch (AmazonServiceException exception) { HandleAmazonServiceException(exception); throw; } } void SetOutputVariables(RunningDeployment deployment, S3UploadResult result, string index = "") { log.SetOutputVariableButDoNotAddToVariables(PackageVariables.Output.FileName, Path.GetFileName(deployment.PackageFilePath)); log.SetOutputVariableButDoNotAddToVariables(PackageVariables.Output.FilePath, deployment.PackageFilePath); var actionName = deployment.Variables["Octopus.Action.Name"]; log.Info($"Saving object version id to variable \"Octopus.Action[{actionName}].Output.Files[{result.BucketKey}]\""); log.SetOutputVariableButDoNotAddToVariables($"Files[{result.BucketKey}]", result.Version); var packageKeyVariableName = index.IsNullOrEmpty() ? "Package.Key" : $"Package.Key[{index}]"; var packageKeyVariableValue = result.BucketKey; log.Info($"Saving bucket key to variable \"Octopus.Action[{actionName}].Output.{packageKeyVariableName}\""); log.SetOutputVariableButDoNotAddToVariables(packageKeyVariableName, packageKeyVariableValue); var packageS3UriVariableName = index.IsNullOrEmpty() ? "Package.S3Uri" : $"Package.S3Uri[{index}]"; var packageS3UriVariableValue = $"s3://{result.BucketName}/{result.BucketKey}"; log.Info($"Saving object S3 URI to variable \"Octopus.Action[{actionName}].Output.{packageS3UriVariableName}\""); log.SetOutputVariableButDoNotAddToVariables(packageS3UriVariableName, packageS3UriVariableValue); var packageUriVariableName = index.IsNullOrEmpty() ? "Package.Uri" : $"Package.Uri[{index}]"; var packageUriVariableValue = $"https://{result.BucketName}.s3.{awsEnvironmentGeneration.AwsRegion.SystemName}.amazonaws.com/{bucketKeyProvider.EncodeBucketKeyForUrl(result.BucketKey)}"; log.Info($"Saving object URI to variable \"Octopus.Action[{actionName}].Output.{packageUriVariableName}\""); log.SetOutputVariableButDoNotAddToVariables(packageUriVariableName, packageUriVariableValue); // ARN format: `arn:aws:s3:::bucket-name/key` (Note: China (Beijing region (cn-north-1) uses `aws-cn` instead of `aws`) var packageArnVariableName = index.IsNullOrEmpty() ? "Package.Arn" : $"Package.Arn[{index}]"; var packageArnVariableValue = $"arn:{(awsEnvironmentGeneration.AwsRegion.SystemName.Equals("cn-north-1") ? "aws-cn" : "aws")}:s3:::{result.BucketName}/{result.BucketKey}"; log.Info($"Saving object ARN to variable \"Octopus.Action[{actionName}].Output.{packageArnVariableName}\""); log.SetOutputVariableButDoNotAddToVariables(packageArnVariableName, packageArnVariableValue); var packageObjectVersionVariableName = index.IsNullOrEmpty() ? "Package.ObjectVersion" : $"Package.ObjectVersion[{index}]"; var packageObjectVersionVariableValue = result.Version; log.Info($"Saving object version id to variable \"Octopus.Action[{actionName}].Output.{packageObjectVersionVariableName}\""); log.SetOutputVariableButDoNotAddToVariables(packageObjectVersionVariableName, packageObjectVersionVariableValue); } private static void ThrowInvalidFileUpload(Exception exception, string message) { throw new AmazonFileUploadException(message, exception); } private static void WarnAndIgnoreException(Exception exception, string message) { Log.Warn(message); } async Task<IEnumerable<S3UploadResult>> UploadAll(IEnumerable<S3TargetPropertiesBase> options, Func<AmazonS3Client> clientFactory, RunningDeployment deployment) { var result = new List<S3UploadResult>(); foreach (var option in options) { switch (option) { case S3PackageOptions package: result.Add(await UploadUsingPackage(clientFactory, deployment, package)); break; case S3SingleFileSelectionProperties selection: result.Add(await UploadSingleFileSelection(clientFactory, deployment, selection)); break; case S3MultiFileSelectionProperties selection: result.AddRange(await UploadMultiFileSelection(clientFactory, deployment, selection)); break; } } return result; } /// <summary> /// Uploads multiple files given the globbing patterns provided by the selection properties. /// </summary> /// <param name="clientFactory"></param> /// <param name="deployment"></param> /// <param name="selection"></param> private async Task<IEnumerable<S3UploadResult>> UploadMultiFileSelection(Func<AmazonS3Client> clientFactory, RunningDeployment deployment, S3MultiFileSelectionProperties selection) { Guard.NotNull(deployment, "Deployment may not be null"); Guard.NotNull(selection, "Multi file selection properties may not be null"); Guard.NotNull(clientFactory, "Client factory must not be null"); var results = new List<S3UploadResult>(); var globMode = GlobModeRetriever.GetFromVariables(deployment.Variables); var files = new RelativeGlobber( (@base, pattern) => fileSystem.EnumerateFilesWithGlob(@base, globMode, pattern), deployment.StagingDirectory).EnumerateFilesWithGlob(selection.Pattern).ToList(); if (!files.Any()) { Log.Info($"The glob pattern '{selection.Pattern}' didn't match any files. Nothing was uploaded to S3."); return results; } Log.Info($"Glob pattern '{selection.Pattern}' matched {files.Count} files"); var substitutionPatterns = SplitFilePatternString(selection.VariableSubstitutionPatterns); if(substitutionPatterns.Any()) substituteInFiles.Substitute(deployment.CurrentDirectory, substitutionPatterns); var structuredSubstitutionPatterns = SplitFilePatternString(selection.StructuredVariableSubstitutionPatterns); if(structuredSubstitutionPatterns.Any()) structuredConfigVariablesService.ReplaceVariables(deployment.CurrentDirectory, structuredSubstitutionPatterns.ToList()); foreach (var matchedFile in files) { var request = CreateRequest(matchedFile.FilePath,$"{selection.BucketKeyPrefix}{matchedFile.MappedRelativePath}", selection); LogPutObjectRequest(matchedFile.FilePath, request); results.Add(await HandleUploadRequest(clientFactory(), request, WarnAndIgnoreException)); } return results; } string[] SplitFilePatternString(string patterns) => patterns?.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries) ?? new string[0]; /// <summary> /// Uploads a single file with the given properties /// </summary> /// <param name="clientFactory"></param> /// <param name="deployment"></param> /// <param name="selection"></param> public Task<S3UploadResult> UploadSingleFileSelection(Func<AmazonS3Client> clientFactory, RunningDeployment deployment, S3SingleFileSelectionProperties selection) { Guard.NotNull(deployment, "Deployment may not be null"); Guard.NotNull(selection, "Single file selection properties may not be null"); Guard.NotNull(clientFactory, "Client factory must not be null"); var filePath = Path.Combine(deployment.StagingDirectory, selection.Path); if (!fileSystem.FileExists(filePath)) { throw new FileNotFoundException($"The file {selection.Path} could not be found in the package."); } if(selection.PerformVariableSubstitution) substituteInFiles.Substitute(deployment.CurrentDirectory, new List<string>{ filePath }); if(selection.PerformStructuredVariableSubstitution) structuredConfigVariablesService.ReplaceVariables(deployment.CurrentDirectory, new List<string>{ filePath }); return CreateRequest(filePath, GetBucketKey(filePath.AsRelativePathFrom(deployment.StagingDirectory), selection), selection) .Tee(x => LogPutObjectRequest(filePath, x)) .Map(x => HandleUploadRequest(clientFactory(), x, ThrowInvalidFileUpload)); } /// <summary> /// Uploads the given package file with the provided package options /// </summary> /// <param name="clientFactory"></param> /// <param name="deployment"></param> /// <param name="options"></param> public Task<S3UploadResult> UploadUsingPackage(Func<AmazonS3Client> clientFactory, RunningDeployment deployment, S3PackageOptions options) { Guard.NotNull(deployment, "Deployment may not be null"); Guard.NotNull(options, "Package options may not be null"); Guard.NotNull(clientFactory, "Client factory must not be null"); var targetArchivePath = PerformVariableReplacement(deployment, options); var filename = GetNormalizedPackageFilename(deployment); return CreateRequest(targetArchivePath, GetBucketKey(filename, options, targetArchivePath), options) .Tee(x => LogPutObjectRequest("entire package", x)) .Map(x => HandleUploadRequest(clientFactory(), x, ThrowInvalidFileUpload)); } string PerformVariableReplacement(RunningDeployment deployment, S3PackageOptions options) { Guard.NotNull(deployment.StagingDirectory, "deployment.StagingDirectory must not be null"); if (options.VariableSubstitutionPatterns.IsNullOrEmpty() && options.StructuredVariableSubstitutionPatterns.IsNullOrEmpty()) return deployment.PackageFilePath; var stagingDirectory = deployment.StagingDirectory; var substitutionPatterns = SplitFilePatternString(options.VariableSubstitutionPatterns); substituteInFiles.Substitute(stagingDirectory, substitutionPatterns); var structuredSubstitutionPatterns = SplitFilePatternString(options.StructuredVariableSubstitutionPatterns); structuredConfigVariablesService.ReplaceVariables(stagingDirectory, structuredSubstitutionPatterns.ToList()); return Repackage(stagingDirectory, Path.GetFileName(deployment.PackageFilePath)); } string Repackage(string stagingDirectory, string fileName) { var supportedZipExtensions = new[] {".nupkg", ".zip"}; var supportedJavaExtensions = new[] {".jar", ".war", ".ear", ".rar"}; var supportedTarExtensions = new[] {".tar"}; var supportedTarGZipExtensions = new[] { ".tgz", ".tar.gz", ".tar.Z"}; var supportedTarBZip2Extensions = new[] { "tar.bz", ".tar.bz2", ".tbz"}; var lowercasedFileName = fileName.ToLower(); using (var targetArchive = fileSystem.CreateTemporaryFile(string.Empty, out var targetArchivePath)) { if (supportedZipExtensions.Any(lowercasedFileName.EndsWith) || supportedJavaExtensions.Any(lowercasedFileName.EndsWith)) { using (var archive = ZipArchive.Create()) { archive.AddAllFromDirectory(stagingDirectory); archive.SaveTo(targetArchive, CompressionType.Deflate); } } else if (supportedTarExtensions.Any(lowercasedFileName.EndsWith)) { using (var archive = TarArchive.Create()) { archive.AddAllFromDirectory(stagingDirectory); archive.SaveTo(targetArchive, CompressionType.None); } } else if (supportedTarGZipExtensions.Any(lowercasedFileName.EndsWith)) { using (var archive = TarArchive.Create()) { archive.AddAllFromDirectory(stagingDirectory); archive.SaveTo(targetArchive, CompressionType.GZip); } } else if (supportedTarBZip2Extensions.Any(lowercasedFileName.EndsWith)) { using (var archive = TarArchive.Create()) { archive.AddAllFromDirectory(stagingDirectory); archive.SaveTo(targetArchive, CompressionType.BZip2); } } else { throw new ArgumentException($"Unable to compress file {fileName.ToLower()}, the extension is unsupported."); } return targetArchivePath; } } public string GetNormalizedPackageFilename(RunningDeployment deployment) { var id = deployment.Variables.Get(PackageVariables.PackageId); var version = deployment.Variables.Get(PackageVariables.PackageVersion); var extension = GetPackageExtension(deployment); return $"{id}.{version}{extension}"; } static string GetPackageExtension(RunningDeployment deployment) { return PackageName.TryMatchTarExtensions(Path.GetFileName(deployment.PackageFilePath) ?? "", out _, out var extension) ? extension : Path.GetExtension(deployment.PackageFilePath); } /// <summary> /// Creates an upload file request based on the s3 target properties for a given file and bucket key. /// </summary> /// <param name="path"></param> /// <param name="bucketKey"></param> /// <param name="properties"></param> /// <returns>PutObjectRequest with all information including metadata and tags from provided properties</returns> private PutObjectRequest CreateRequest(string path, string bucketKey, S3TargetPropertiesBase properties) { Guard.NotNullOrWhiteSpace(path, "The given path may not be null"); Guard.NotNullOrWhiteSpace(bucket, "The provided bucket key may not be null"); Guard.NotNull(properties, "Target properties may not be null"); var request = new PutObjectRequest { FilePath = path, BucketName = bucket?.Trim(), Key = bucketKey?.Trim(), StorageClass = S3StorageClass.FindValue(properties.StorageClass?.Trim()), CannedACL = S3CannedACL.FindValue(properties.CannedAcl?.Trim()) } .WithMetadata(properties) .WithTags(properties); return md5HashSupported ? request.WithMd5Digest(fileSystem) : request; } string GetBucketKey(string defaultKey, IHaveBucketKeyBehaviour behaviour, string packageFilePath = "") { return bucketKeyProvider.GetBucketKey(defaultKey, behaviour, packageFilePath); } /// <summary> /// Displays the current information regarding the object that will be uploaded to the user. /// </summary> /// <param name="fileOrPackageDescription"></param> /// <param name="request"></param> private static void LogPutObjectRequest(string fileOrPackageDescription, PutObjectRequest request) { Log.Info($"Attempting to upload {fileOrPackageDescription} to bucket {request.BucketName} with key {request.Key}."); } /// <summary> /// Handle the file upload request throwing exceptions only on errors from AWS which is critical enough to fail /// the entire deployment i.e. access denied while per file errors will result in warnings. /// </summary> /// <param name="client">The client to use</param> /// <param name="request">The request to send</param> /// <param name="errorAction">Action to take on per file error</param> private async Task<S3UploadResult> HandleUploadRequest(AmazonS3Client client, PutObjectRequest request, Action<AmazonS3Exception, string> errorAction) { try { if (!await ShouldUpload(client, request)) { Log.Verbose( $"Object key {request.Key} exists for bucket {request.BucketName} with same content hash and metadata. Skipping upload."); return new S3UploadResult(request, Maybe<PutObjectResponse>.None); } return new S3UploadResult(request, Maybe<PutObjectResponse>.Some(await client.PutObjectAsync(request))); } catch (AmazonS3Exception ex) { var permissions = new List<string> {"s3:PutObject"}; if (request.TagSet.Count > 0) { permissions.Add("s3:PutObjectTagging"); permissions.Add("s3:PutObjectVersionTagging"); } if (ex.ErrorCode == "AccessDenied") throw new PermissionException( "The AWS account used to perform the operation does not have the required permissions to upload to the bucket.\n" + $"Please ensure the current account has permission to perform action(s) {string.Join(", ", permissions)}'.\n" + ex.Message + "\n"); if (!perFileUploadErrors.ContainsKey(ex.ErrorCode)) throw; perFileUploadErrors[ex.ErrorCode](request, ex).Tee((message) => errorAction(ex, message)); return new S3UploadResult(request, Maybe<PutObjectResponse>.None); } catch (ArgumentException exception) { throw new AmazonFileUploadException($"An error occurred uploading file with bucket key {request.Key} possibly due to metadata. Metadata keys must be valid HTTP header values. \n" + "Metadata:\n" + request.Metadata.Keys.Aggregate(string.Empty, (values, key) => $"{values}'{key}' = '{request.Metadata[key]}'\n") + "\n" + $"Please see the {log.FormatLink("https://g.octopushq.com/AwsS3UsingMetadata", "AWS documentation")} for more information." , exception); } } /// <summary> /// Check whether the object key exists and hash is equivalent. If these are the same we will skip the upload. /// </summary> /// <param name="client"></param> /// <param name="request"></param> /// <returns></returns> private async Task<bool> ShouldUpload(AmazonS3Client client, PutObjectRequest request) { //This isn't ideal, however the AWS SDK doesn't really provide any means to check the existence of an object. try { if (!md5HashSupported) return true; var metadataResponse = await client.GetObjectMetadataAsync(request.BucketName, request.Key); return !metadataResponse.GetEtag().IsSameAsRequestMd5Digest(request) || !request.HasSameMetadata(metadataResponse); } catch (AmazonServiceException exception) { if (exception.StatusCode == HttpStatusCode.NotFound) { return true; } throw; } } /// <summary> /// The AmazonServiceException can hold additional information that is useful to include in /// the log. /// </summary> /// <param name="exception">The exception</param> private void HandleAmazonServiceException(AmazonServiceException exception) { ((exception.InnerException as WebException)? .Response? .GetResponseStream()? .Map(stream => new StreamReader(stream).ReadToEnd()) .Map(message => "An exception was thrown while contacting the AWS API.\n" + message) ?? "An exception was thrown while contacting the AWS API.") .Tee(Log.Warn); } } }<file_sep>using System; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Octopus.Versioning; namespace Calamari.Integration.Packages.Download { /// <summary> /// This class knows how to interpret a package id and request a download /// from a specific downloader implementation. /// </summary> public class PackageDownloaderStrategy { readonly IScriptEngine engine; readonly ICalamariFileSystem fileSystem; readonly ICommandLineRunner commandLineRunner; readonly IVariables variables; readonly ILog log; public PackageDownloaderStrategy( ILog log, IScriptEngine engine, ICalamariFileSystem fileSystem, ICommandLineRunner commandLineRunner, IVariables variables) { this.log = log; this.engine = engine; this.fileSystem = fileSystem; this.commandLineRunner = commandLineRunner; this.variables = variables; } public PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, FeedType feedType, string feedUsername, string feedPassword, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { IPackageDownloader? downloader = null; switch (feedType) { case FeedType.Maven: downloader = new MavenPackageDownloader(fileSystem); break; case FeedType.NuGet: downloader = new NuGetPackageDownloader(fileSystem, variables); break; case FeedType.GitHub: downloader = new GitHubPackageDownloader(log, fileSystem); break; case FeedType.Helm: downloader = new HelmChartPackageDownloader(fileSystem); break; case FeedType.OciRegistry: downloader = new OciPackageDownloader(fileSystem, new CombinedPackageExtractor(log, variables, commandLineRunner)); break; case FeedType.Docker: case FeedType.AwsElasticContainerRegistry: case FeedType.AzureContainerRegistry: case FeedType.GoogleContainerRegistry: downloader = new DockerImagePackageDownloader(engine, fileSystem, commandLineRunner, variables, log); break; case FeedType.S3: downloader = new S3PackageDownloader(log, fileSystem); break; default: throw new NotImplementedException($"No Calamari downloader exists for feed type `{feedType}`."); } Log.Verbose($"Feed type provided `{feedType}` using {downloader.GetType().Name}"); return downloader.DownloadPackage( packageId, version, feedId, feedUri, feedUsername, feedPassword, forcePackageDownload, maxDownloadAttempts, downloadAttemptBackoff); } } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class ServiceTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""Service"", ""metadata"": { ""name"": ""my-svc"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""spec"": { ""type"": ""LoadBalancer"", ""clusterIP"": ""10.96.0.1"", ""ports"": [ { ""name"": ""https"", ""port"": 443, ""protocol"": ""TCP"", ""targetPort"": 8443 }, { ""name"": """", ""port"": 80, ""protocol"": ""TCP"", ""targetPort"": 8080, ""nodePort"": 30080 } ] }, ""status"": { ""loadBalancer"": { ""ingress"": [ { ""ip"": ""192.168.49.2"" } ] } } }"; var service = ResourceFactory.FromJson(input, new Options()); service.Should().BeEquivalentTo(new { Kind = "Service", Name = "my-svc", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", Type = "LoadBalancer", ClusterIp = "10.96.0.1", ExternalIp = "192.168.49.2", Ports = new string[] { "443/TCP", "80:30080/TCP" }, ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful }); } } } <file_sep>#if USE_NUGET_V3_LIBS using NuGet.Packaging; #else using NuGet; #endif using System; using System.IO; using Calamari.Common.Plumbing; using SharpCompress.Archives.Zip; namespace Calamari.Common.Features.Packages.NuGet { public class LocalNuGetPackage { readonly string filePath; readonly Lazy<ManifestMetadata> metadata; public LocalNuGetPackage(string filePath) { Guard.NotNullOrWhiteSpace(filePath, "Must supply a non-empty file-path"); if (!File.Exists(filePath)) throw new FileNotFoundException($"Could not find package file '{filePath}'"); this.filePath = filePath; metadata = new Lazy<ManifestMetadata>(() => ReadMetadata(this.filePath)); } public ManifestMetadata Metadata => metadata.Value; public void GetStream(Action<Stream> process) { using (var fileStream = File.OpenRead(filePath)) { process(fileStream); } } static ManifestMetadata ReadMetadata(string filePath) { using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) using (var archive = ZipArchive.Open(fileStream)) { foreach (var entry in archive.Entries) { if (entry.IsDirectory || !IsManifest(entry.Key)) continue; using (var manifestStream = entry.OpenEntryStream()) { // NuGet keeps adding new elements to the NuSpec schema, // which in turn breaks us when we try to read the manifest, // so we now read the manifest without schema validation // https://github.com/OctopusDeploy/Issues/issues/3487 var manifest = Manifest.ReadFrom(manifestStream, false); return manifest.Metadata; } } throw new InvalidOperationException("Package does not contain a manifest"); } } static bool IsManifest(string path) { return Path.GetExtension(path).Equals(".nuspec", StringComparison.OrdinalIgnoreCase); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.ResourceStatus.Resources; using Newtonsoft.Json; namespace Calamari.Kubernetes.ResourceStatus { public interface IResourceUpdateReporter { /// <summary> /// Reports the difference of the originalStatuses and newStatuses to server. /// </summary> void ReportUpdatedResources(IDictionary<string, Resource> originalStatuses, IDictionary<string, Resource> newStatuses, int checkCount); } /// <summary> /// <inheritdoc /> /// </summary> public class ResourceUpdateReporter : IResourceUpdateReporter { private readonly IVariables variables; private readonly ILog log; public ResourceUpdateReporter(IVariables variables, ILog log) { this.variables = variables; this.log = log; } public void ReportUpdatedResources(IDictionary<string, Resource> originalStatuses, IDictionary<string, Resource> newStatuses, int checkCount) { var createdOrUpdatedResources = GetCreatedOrUpdatedResources(originalStatuses, newStatuses).ToList(); foreach (var resource in createdOrUpdatedResources) { SendServiceMessage(resource, false, checkCount); } var removedResources = GetRemovedResources(originalStatuses, newStatuses).ToList(); foreach (var resource in removedResources) { SendServiceMessage(resource, true, checkCount); } log.Verbose($"Resource Status Check: reported {createdOrUpdatedResources.Count} updates, {removedResources.Count} removals"); } private static IEnumerable<Resource> GetCreatedOrUpdatedResources(IDictionary<string, Resource> originalStatuses, IDictionary<string, Resource> newStatuses) { return newStatuses.Where(resource => !originalStatuses.ContainsKey(resource.Key) || resource.Value.HasUpdate(originalStatuses[resource.Key])) .Select(resource => resource.Value); } private static IEnumerable<Resource> GetRemovedResources(IDictionary<string, Resource> originalStatuses, IDictionary<string, Resource> newStatuses) { return originalStatuses .Where(resource => !newStatuses.ContainsKey(resource.Key)) .Select(resource => resource.Value); } private void SendServiceMessage(Resource resource, bool removed, int checkCount) { var actionNumber = variables.Get("Octopus.Action.Number", string.Empty); var stepNumber = variables.Get("Octopus.Step.Number"); var stepName = variables.Get("Octopus.Step.Name"); if (actionNumber.IndexOf(".", StringComparison.Ordinal) > 0) { stepNumber = actionNumber; stepName = variables.Get("Octopus.Action.Name"); } var parameters = new Dictionary<string, string> { {"type", "k8s-status"}, {"actionId", variables.Get("Octopus.Action.Id")}, {"stepName", $"Step {stepNumber}: {stepName}"}, {"taskId", variables.Get(KnownVariables.ServerTask.Id)}, {"targetId", variables.Get("Octopus.Machine.Id")}, {"targetName", variables.Get("Octopus.Machine.Name")}, {"spaceId", variables.Get("Octopus.Space.Id")}, {"uuid", resource.Uid}, {"kind", resource.Kind}, {"name", resource.Name}, {"namespace", resource.Namespace}, {"status", resource.ResourceStatus.ToString()}, {"data", JsonConvert.SerializeObject(resource)}, {"removed", removed.ToString()}, {"checkCount", checkCount.ToString()} }; var message = new ServiceMessage(SpecialVariables.KubernetesResourceStatusServiceMessageName, parameters); log.WriteServiceMessage(message); } } }<file_sep>using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.ResourceManager; using Azure.ResourceManager.AppService; using Azure.ResourceManager.AppService.Models; using Azure.ResourceManager.Resources; using Calamari.AzureAppService.Azure; using Calamari.Testing; using FluentAssertions; using NUnit.Framework; using Octostache; namespace Calamari.AzureAppService.Tests { public abstract class AppServiceIntegrationTest { protected string ClientId { get; private set; } protected string ClientSecret { get; private set; } protected string TenantId { get; private set; } protected string SubscriptionId { get; private set; } protected string ResourceGroupName { get; private set; } protected string ResourceGroupLocation { get; private set; } protected string greeting = "Calamari"; protected ArmClient ArmClient { get; private set; } protected SubscriptionResource SubscriptionResource { get; private set; } protected ResourceGroupResource ResourceGroupResource { get; private set; } protected WebSiteResource WebSiteResource { get; private protected set; } private readonly HttpClient client = new HttpClient(); protected virtual string DefaultResourceGroupLocation => "eastus"; [OneTimeSetUp] public async Task Setup() { var resourceManagementEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ResourceManagementEndPoint) ?? DefaultVariables.ResourceManagementEndpoint; var activeDirectoryEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ActiveDirectoryEndPoint) ?? DefaultVariables.ActiveDirectoryEndpoint; ResourceGroupName = $"{DateTime.UtcNow:yyyyMMdd}-{Guid.NewGuid():N}"; ClientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); ClientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); TenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); SubscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); ResourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? DefaultResourceGroupLocation; var servicePrincipalAccount = new ServicePrincipalAccount(SubscriptionId, ClientId, TenantId, ClientSecret, "Azure<PASSWORD>", resourceManagementEndpointBaseUri, activeDirectoryEndpointBaseUri); ArmClient = servicePrincipalAccount.CreateArmClient(retryOptions => { retryOptions.MaxRetries = 5; retryOptions.Mode = RetryMode.Exponential; retryOptions.Delay = TimeSpan.FromSeconds(2); }); //create the resource group SubscriptionResource = ArmClient.GetSubscriptionResource(SubscriptionResource.CreateResourceIdentifier(SubscriptionId)); var response = await SubscriptionResource .GetResourceGroups() .CreateOrUpdateAsync(WaitUntil.Completed, ResourceGroupName, new ResourceGroupData(new AzureLocation(ResourceGroupLocation)) { Tags = { // give them an expiry of 14 days so if the tests fail to clean them up // they will be automatically cleaned up by the Sandbox cleanup process // We keep them for 14 days just in case we need to do debugging/investigation ["LifetimeInDays"] = "14" } }); ResourceGroupResource = response.Value; await ConfigureTestResources(ResourceGroupResource); } protected abstract Task ConfigureTestResources(ResourceGroupResource resourceGroup); [OneTimeTearDown] public virtual async Task Cleanup() { await ArmClient.GetResourceGroupResource(ResourceGroupResource.CreateResourceIdentifier(SubscriptionId, ResourceGroupName)) .DeleteAsync(WaitUntil.Started); } protected async Task AssertContent(string hostName, string actualText, string rootPath = null) { var response = await RetryPolicies.TransientHttpErrorsPolicy.ExecuteAsync(async () => { var r = await client.GetAsync($"https://{hostName}/{rootPath}"); r.EnsureSuccessStatusCode(); return r; }); var result = await response.Content.ReadAsStringAsync(); result.Should().Contain(actualText); } protected static async Task DoWithRetries(int retries, Func<Task> action, int secondsBetweenRetries) { foreach (var retry in Enumerable.Range(1, retries)) { try { await action(); break; } catch { if (retry == retries) throw; await Task.Delay(secondsBetweenRetries * 1000); } } } protected void AddAzureVariables(CommandTestBuilderContext context) { AddAzureVariables(context.Variables); } protected void AddAzureVariables(VariableDictionary variables) { variables.Add(AccountVariables.ClientId, ClientId); variables.Add(AccountVariables.Password, ClientSecret); variables.Add(AccountVariables.TenantId, TenantId); variables.Add(AccountVariables.SubscriptionId, SubscriptionId); variables.Add(SpecialVariables.Action.Azure.ResourceGroupName, ResourceGroupName); variables.Add(SpecialVariables.Action.Azure.WebAppName, WebSiteResource.Data.Name); } protected async Task<(AppServicePlanResource, WebSiteResource)> CreateAppServicePlanAndWebApp( ResourceGroupResource resourceGroup, AppServicePlanData appServicePlanData = null, WebSiteData webSiteData = null) { appServicePlanData ??= new AppServicePlanData(resourceGroup.Data.Location) { Sku = new AppServiceSkuDescription { Name = "S1", Tier = "Standard" } }; var servicePlanResponse = await resourceGroup.GetAppServicePlans() .CreateOrUpdateAsync(WaitUntil.Completed, resourceGroup.Data.Name, appServicePlanData); webSiteData ??= new WebSiteData(resourceGroup.Data.Location); webSiteData.AppServicePlanId = servicePlanResponse.Value.Id; var webSiteResponse = await resourceGroup.GetWebSites() .CreateOrUpdateAsync(WaitUntil.Completed, resourceGroup.Data.Name, webSiteData); return (servicePlanResponse.Value, webSiteResponse.Value); } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Util; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Storage; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; namespace Calamari.AzureCloudService { public class AzurePackageUploader { readonly ILog log; const string OctopusPackagesContainerName = "octopuspackages"; public AzurePackageUploader(ILog log) { this.log = log; } public async Task<Uri> Upload(SubscriptionCloudCredentials credentials, string storageAccountName, string packageFile, string uploadedFileName, string storageEndpointSuffix, string serviceManagementEndpoint) { var cloudStorage = new CloudStorageAccount(new StorageCredentials(storageAccountName, await GetStorageAccountPrimaryKey(credentials, storageAccountName,serviceManagementEndpoint)),storageEndpointSuffix, true); var blobClient = cloudStorage.CreateCloudBlobClient(); var container = blobClient.GetContainerReference(OctopusPackagesContainerName); await container.CreateIfNotExistsAsync(); var permission = await container.GetPermissionsAsync(); permission.PublicAccess = BlobContainerPublicAccessType.Off; await container.SetPermissionsAsync(permission); var fileInfo = new FileInfo(packageFile); var packageBlob = GetUniqueBlobName(uploadedFileName, fileInfo, container); if (await packageBlob.ExistsAsync()) { log.VerboseFormat("A blob named {0} already exists with the same length, so it will be used instead of uploading the new package.", packageBlob.Name); return packageBlob.Uri; } await UploadBlobInChunks(fileInfo, packageBlob, blobClient); log.Info("Package upload complete"); return packageBlob.Uri; } CloudBlockBlob GetUniqueBlobName(string uploadedFileName, FileInfo fileInfo, CloudBlobContainer container) { var length = fileInfo.Length; var packageBlob = Uniquifier.UniquifyUntil( uploadedFileName, container.GetBlockBlobReference, blob => { if (blob.Exists() && blob.Properties.Length != length) { log.Verbose("A blob named " + blob.Name + " already exists but has a different length."); return true; } return false; }); return packageBlob; } async Task UploadBlobInChunks(FileInfo fileInfo, CloudBlockBlob packageBlob, CloudBlobClient blobClient) { var operationContext = new OperationContext(); operationContext.ResponseReceived += delegate(object sender, RequestEventArgs args) { var statusCode = (int) args.Response.StatusCode; var statusDescription = args.Response.StatusDescription; log.Verbose($"Uploading, response received: {statusCode} {statusDescription}"); if (statusCode >= 400) { log.Error("Error when uploading the package. Azure returned a HTTP status code of: " + statusCode + " " + statusDescription); log.Verbose("The upload will be retried"); } }; await blobClient.SetServicePropertiesAsync(blobClient.GetServiceProperties(), new BlobRequestOptions(), operationContext); log.VerboseFormat("Uploading the package to blob storage. The package file is {0}.", fileInfo.Length.ToFileSizeString()); using (var fileReader = fileInfo.OpenRead()) { var blocklist = new List<string>(); long uploadedSoFar = 0; var data = new byte[1024 * 1024]; var id = 1; while (true) { id++; var read = await fileReader.ReadAsync(data, 0, data.Length); if (read == 0) { await packageBlob.PutBlockListAsync(blocklist); break; } var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(id.ToString(CultureInfo.InvariantCulture).PadLeft(30, '0'))); await packageBlob.PutBlockAsync(blockId, new MemoryStream(data, 0, read, true), null); blocklist.Add(blockId); uploadedSoFar += read; log.Progress((int) ((uploadedSoFar * 100)/fileInfo.Length), "Uploading package to blob storage"); log.VerboseFormat("Uploading package to blob storage: {0} of {1}", uploadedSoFar.ToFileSizeString(), fileInfo.Length.ToFileSizeString()); } } log.Verbose("Upload complete"); } async Task<string> GetStorageAccountPrimaryKey(SubscriptionCloudCredentials credentials, string storageAccountName,string serviceManagementEndpoint) { using var cloudClient = new StorageManagementClient(credentials, new Uri(serviceManagementEndpoint)); var getKeysResponse = await cloudClient.StorageAccounts.GetKeysAsync(storageAccountName); if (getKeysResponse.StatusCode != HttpStatusCode.OK) throw new Exception($"GetKeys for storage-account {storageAccountName} returned HTTP status-code {getKeysResponse.StatusCode}"); return getKeysResponse.PrimaryKey; } } }<file_sep>#!/usr/bin/env dotnet-script #r "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=<KEY>" using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Net; using System.Security.Cryptography; using System.Diagnostics; using System.Security.Principal; using System.Linq; public static class Octopus { public static OctopusParametersDictionary Parameters { get; private set; } static Octopus() { InitializeDefaultProxy(); } public static void Initialize(string password) { if (Parameters != null) { throw new Exception("Octopus can only be initialized once."); } Parameters = new OctopusParametersDictionary(password); LogEnvironmentInformation(); } static void LogEnvironmentInformation() { if (Parameters.ContainsKey("Octopus.Action.Script.SuppressEnvironmentLogging") && Parameters["Octopus.Action.Script.SuppressEnvironmentLogging"] == "True") return; var environmentInformationStamp = $"Dotnet-Script Environment Information:{Environment.NewLine}" + $" {string.Join($"{Environment.NewLine} ", SafelyGetEnvironmentInformation())}"; Console.WriteLine("##octopus[stdout-verbose]"); Console.WriteLine(environmentInformationStamp); Console.WriteLine("##octopus[stdout-default]"); } #region Logging Helpers static string[] SafelyGetEnvironmentInformation() { var envVars = GetEnvironmentVars() .Concat(GetPathVars()) .Concat(GetProcessVars()); return envVars.ToArray(); } private static string SafelyGet(Func<string> thingToGet) { try { return thingToGet.Invoke(); } catch (Exception) { return "Unable to retrieve environment information."; } } static IEnumerable<string> GetEnvironmentVars() { yield return SafelyGet(() => $"OperatingSystem: {Environment.OSVersion}"); yield return SafelyGet(() => $"OsBitVersion: {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}"); yield return SafelyGet(() => $"Is64BitProcess: {Environment.Is64BitProcess}"); yield return SafelyGet(() => $"CurrentUser: {WindowsIdentity.GetCurrent().Name}"); yield return SafelyGet(() => $"MachineName: {Environment.MachineName}"); yield return SafelyGet(() => $"ProcessorCount: {Environment.ProcessorCount}"); } static IEnumerable<string> GetPathVars() { yield return SafelyGet(() => $"CurrentDirectory: {Directory.GetCurrentDirectory()}"); yield return SafelyGet(() => $"TempDirectory: {Path.GetTempPath()}"); } static IEnumerable<string> GetProcessVars() { yield return SafelyGet(() => { var process = Process.GetCurrentProcess(); return $"HostProcess: {process.ProcessName} ({process.Id})"; }); } #endregion public class OctopusParametersDictionary : System.Collections.Generic.Dictionary<string, string> { private byte[] Key { get; set; } public OctopusParametersDictionary(string key) : base(System.StringComparer.OrdinalIgnoreCase) { Key = Convert.FromBase64String(key); /*{{VariableDeclarations}}*/ } public string DecryptString(string encrypted, string iv) { using (var algorithm = Aes.Create()) { algorithm.Mode = CipherMode.CBC; algorithm.Padding = PaddingMode.PKCS7; algorithm.KeySize = 128; algorithm.BlockSize = 128; algorithm.Key = Key; algorithm.IV = Convert.FromBase64String(iv); using (var dec = algorithm.CreateDecryptor()) using (var ms = new MemoryStream(Convert.FromBase64String(encrypted))) using (var cs = new CryptoStream(ms, dec, CryptoStreamMode.Read)) using (var sr = new StreamReader(cs, Encoding.UTF8)) { return sr.ReadToEnd(); } } } } private static string EncodeServiceMessageValue(string value) { var valueBytes = System.Text.Encoding.UTF8.GetBytes(value); return Convert.ToBase64String(valueBytes); } public static void FailStep(string message = null) { if (message != null) { message = EncodeServiceMessageValue(message); Console.WriteLine("##octopus[resultMessage message='{0}']", message); } Environment.Exit(-1); } public static void SetVariable(string name, string value, bool sensitive = false) { name = EncodeServiceMessageValue(name); value = EncodeServiceMessageValue(value); Parameters[name] = value; if (sensitive) { Console.WriteLine("##octopus[setVariable name='{0}' value='{1}' sensitive='{2}']", name, value, EncodeServiceMessageValue("True")); } else { Console.WriteLine("##octopus[setVariable name='{0}' value='{1}']", name, value); } } public static void CreateArtifact(string path, string fileName = null) { if (fileName == null) { fileName = System.IO.Path.GetFileName(path); } var serviceFileName = EncodeServiceMessageValue(fileName); var length = System.IO.File.Exists(path) ? new System.IO.FileInfo(path).Length.ToString() : "0"; length = EncodeServiceMessageValue(length); path = System.IO.Path.GetFullPath(path); var servicepath = EncodeServiceMessageValue(path); Console.WriteLine("##octopus[stdout-verbose]"); Console.WriteLine("Artifact {0} will be collected from {1} after this step completes", fileName, path); Console.WriteLine("##octopus[stdout-default]"); Console.WriteLine("##octopus[createArtifact path='{0}' name='{1}' length='{2}']", servicepath, serviceFileName, length); } public static void UpdateProgress(int percentage, string message = "") { Console.WriteLine("##octopus[progress percentage='{0}' message='{1}']", EncodeServiceMessageValue(percentage.ToString()), EncodeServiceMessageValue(message)); } public static void WriteVerbose(string message) { Console.WriteLine("##octopus[stdout-verbose]"); Console.WriteLine(message); Console.WriteLine("##octopus[stdout-default]"); } public static void WriteHighlight(string message) { Console.WriteLine("##octopus[stdout-highlight]"); Console.WriteLine(message); Console.WriteLine("##octopus[stdout-default]"); } public static void WriteWait(string message) { Console.WriteLine("##octopus[stdout-wait]"); Console.WriteLine(message); Console.WriteLine("##octopus[stdout-default]"); } public static void WriteWarning(string message) { Console.WriteLine("##octopus[stdout-warning]"); Console.WriteLine(message); Console.WriteLine("##octopus[stdout-default]"); } public static void InitializeDefaultProxy() { var proxyUsername = Environment.GetEnvironmentVariable("TentacleProxyUsername"); var proxyPassword = Environment.GetEnvironmentVariable("TentacleProxyPassword"); var proxyHost = Environment.GetEnvironmentVariable("TentacleProxyHost"); var proxyPortText = Environment.GetEnvironmentVariable("TentacleProxyPort"); int proxyPort; int.TryParse(proxyPortText, out proxyPort); var useDefaultProxyText = Environment.GetEnvironmentVariable("TentacleUseDefaultProxy"); bool useDefaultProxy; bool.TryParse(useDefaultProxyText, out useDefaultProxy); var useCustomProxy = !string.IsNullOrWhiteSpace(proxyHost); var bypassProxy = !useCustomProxy && !useDefaultProxy; var proxy = useCustomProxy ? new WebProxy(new UriBuilder("http", proxyHost, proxyPort).Uri) : useDefaultProxy ? WebRequest.GetSystemWebProxy() : new WebProxy(); var useDefaultCredentials = string.IsNullOrWhiteSpace(proxyUsername); if (!bypassProxy) proxy.Credentials = useDefaultCredentials ? useCustomProxy ? new NetworkCredential() : CredentialCache.DefaultNetworkCredentials : new NetworkCredential(proxyUsername, proxyPassword); WebRequest.DefaultWebProxy = proxy; } } public class ScriptArgsEnv { public ScriptArgsEnv(IList<string> args) { ScriptArgs = args; } public IList<string> ScriptArgs { get; set; } } var Env = new ScriptArgsEnv(Args); Octopus.Initialize(Args[Args.Count - 1]);<file_sep>using Newtonsoft.Json; namespace Calamari.Kubernetes.ResourceStatus.Resources { // Subset of: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.26/#serviceport-v1-core public class ServicePort { [JsonProperty("port")] public int Port { get; set; } [JsonProperty("nodePort")] public int? NodePort { get; set; } [JsonProperty("protocol")] public string Protocol { get; set; } } }<file_sep>namespace Calamari.Deployment.PackageRetention.Repositories { public interface IJsonJournalPathProvider { string GetJournalPath(); } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using System.Collections.Generic; using System.Security.AccessControl; using System.Security.Principal; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Octostache; namespace Calamari.Integration.Certificates { public class PrivateKeyAccessRule { [JsonConstructor] public PrivateKeyAccessRule(string identity, PrivateKeyAccess access) :this(new NTAccount(identity), access) { } public PrivateKeyAccessRule(IdentityReference identity, PrivateKeyAccess access) { Identity = identity; Access = access; } public IdentityReference Identity { get; } public PrivateKeyAccess Access { get; } public static ICollection<PrivateKeyAccessRule> FromJson(string json) { return JsonConvert.DeserializeObject<List<PrivateKeyAccessRule>>(json, JsonSerializerSettings); } internal CryptoKeyAccessRule ToCryptoKeyAccessRule() { switch (Access) { case PrivateKeyAccess.ReadOnly: return new CryptoKeyAccessRule(Identity, CryptoKeyRights.GenericRead, AccessControlType.Allow); case PrivateKeyAccess.FullControl: // We use 'GenericAll' here rather than 'FullControl' as 'FullControl' doesn't correctly set the access for CNG keys return new CryptoKeyAccessRule(Identity, CryptoKeyRights.GenericAll, AccessControlType.Allow); default: throw new ArgumentOutOfRangeException(nameof(Access)); } } private static JsonSerializerSettings JsonSerializerSettings => new JsonSerializerSettings { Converters = new List<JsonConverter> { new StringEnumConverter(), } }; } } #endif<file_sep>using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { [TestFixture] public class SemaphoreFactoryFixture { [Test] [RequiresMono] public void ReturnsFileBasedSemaphoreManagerForMono() { if (!CalamariEnvironment.IsRunningOnMono) Assert.Ignore("This test is designed to run on mono"); var result = SemaphoreFactory.Get(); Assert.That(result, Is.InstanceOf<FileBasedSempahoreManager>()); } #if NETFX [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void ReturnsSystemSemaphoreManagerForWindows() { if (!CalamariEnvironment.IsRunningOnWindows) Assert.Ignore("This test is designed to run on windows"); var result = SemaphoreFactory.Get(); Assert.That(result, Is.InstanceOf<SystemSemaphoreManager>()); } #else [Test] public void ReturnsSystemSemaphoreManagerForAllPlatformsUnderNetCore() { var result = SemaphoreFactory.Get(); Assert.That(result, Is.InstanceOf<SystemSemaphoreManager>()); } #endif } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Threading.Tasks; using Calamari.ConsolidateCalamariPackages; using NuGet.Packaging; using Nuke.Common; using Nuke.Common.CI.TeamCity; using Nuke.Common.IO; using Nuke.Common.ProjectModel; using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.NuGet; using Nuke.Common.Utilities.Collections; using Serilog; using static Nuke.Common.IO.FileSystemTasks; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.Git.GitTasks; using static Nuke.Common.Tools.NuGet.NuGetTasks; namespace Calamari.Build { class Build : NukeBuild { const string RootProjectName = "Calamari"; [Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")] readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release; [Required] readonly Solution Solution = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProjectModelTasks.ParseSolution(SourceDirectory / "Calamari.sln") : ProjectModelTasks.ParseSolution(SourceDirectory / "Calamari.NonWindows.sln"); [Parameter("Run packing step in parallel")] readonly bool PackInParallel; [Parameter] readonly DotNetVerbosity BuildVerbosity = DotNetVerbosity.Minimal; [Parameter] readonly bool SignBinaries; // When building locally signing isn't really necessary and it could take // up to 3-4 minutes to sign all the binaries as we build for many, many // different runtimes so disabling it locally means quicker turn around // when doing local development. bool WillSignBinaries => !IsLocalBuild || SignBinaries; [Parameter] readonly bool AppendTimestamp; [Parameter("Set Calamari Version on OctopusServer")] readonly bool SetOctopusServerVersion; [Parameter] readonly string? AzureKeyVaultUrl; [Parameter] readonly string? AzureKeyVaultAppId; [Parameter] [Secret] readonly string? AzureKeyVaultAppSecret; [Parameter] [Secret] readonly string? AzureKeyVaultTenantId; [Parameter] readonly string? AzureKeyVaultCertificateName; [Parameter(Name = "signing_certificate_path")] readonly string SigningCertificatePath = RootDirectory / "certificates" / "OctopusDevelopment.pfx"; [Parameter(Name = "signing_certificate_password")] [Secret] readonly string SigningCertificatePassword = "<PASSWORD>!"; [Required] [GitVersion] readonly GitVersion? GitVersionInfo; static readonly List<string> CalamariProjectsToSkipConsolidation = new() { "Calamari.CloudAccounts", "Calamari.Common", "Calamari.ConsolidateCalamariPackages" }; List<Task> SignDirectoriesTasks = new(); List<Task> ProjectCompressionTasks = new(); public Build() { NugetVersion = new Lazy<string>(GetNugetVersion); // This initialisation is required to ensure the build script can // perform actions such as GetRuntimeIdentifiers() on projects. ProjectModelTasks.Initialize(); } static AbsolutePath SourceDirectory => RootDirectory / "source"; static AbsolutePath BuildDirectory => RootDirectory / "build"; static AbsolutePath ArtifactsDirectory => RootDirectory / "artifacts"; static AbsolutePath PublishDirectory => RootDirectory / "publish"; static AbsolutePath LocalPackagesDirectory => RootDirectory / "../LocalPackages"; static AbsolutePath ConsolidateCalamariPackagesProject => SourceDirectory / "Calamari.ConsolidateCalamariPackages.Tests" / "Calamari.ConsolidateCalamariPackages.Tests.csproj"; static AbsolutePath ConsolidatedPackageDirectory => ArtifactsDirectory / "consolidated"; Lazy<string> NugetVersion { get; } Target CheckForbiddenWords => _ => _.Executes(() => { Log.Information("Checking codebase for forbidden words"); const string arguments = "grep -i -I -n -f ForbiddenWords.txt -- \"./*\" \":(exclude)ForbiddenWords.txt\""; var process = ProcessTasks.StartProcess(GitPath, arguments) .AssertWaitForExit(); if (process.ExitCode == 1) { Log.Information("Sanity check passed"); return; } var filesContainingForbiddenWords = process.Output.Select(o => o.Text).ToArray(); if (filesContainingForbiddenWords.Any()) throw new Exception("Found forbidden words in the following files, " + "please clean them up:\r\n" + string.Join("\r\n", filesContainingForbiddenWords)); }); Target Clean => _ => _.Executes(() => { SourceDirectory.GlobDirectories("**/bin", "**/obj", "**/TestResults").ForEach(DeleteDirectory); EnsureCleanDirectory(ArtifactsDirectory); EnsureCleanDirectory(PublishDirectory); }); Target Restore => _ => _.DependsOn(Clean) .Executes(() => { var localRuntime = FixedRuntimes.Windows; if (!OperatingSystem.IsWindows()) localRuntime = FixedRuntimes.Linux; DotNetRestore(_ => _.SetProjectFile(Solution) .SetRuntime(localRuntime) .SetProperty("DisableImplicitNuGetFallbackFolder", true)); }); Target Compile => _ => _.DependsOn(CheckForbiddenWords) .DependsOn(Restore) .Executes(() => { Log.Information("Compiling Calamari v{CalamariVersion}", NugetVersion.Value); DotNetBuild(_ => _.SetProjectFile(Solution) .SetConfiguration(Configuration) .SetNoRestore(true) .SetVersion(NugetVersion.Value) .SetInformationalVersion(GitVersionInfo?.InformationalVersion)); }); Target CalamariConsolidationTests => _ => _.DependsOn(Compile) .OnlyWhenStatic(() => !IsLocalBuild) .Executes(() => { DotNetTest(_ => _ .SetProjectFile(ConsolidateCalamariPackagesProject) .SetConfiguration(Configuration) .EnableNoBuild()); }); Target Publish => _ => _.DependsOn(Compile) .Executes(() => { if (!OperatingSystem.IsWindows()) Log.Warning("Building Calamari on a non-windows machine will result " + "in the {DefaultNugetPackageName} and {CloudNugetPackageName} " + "nuget packages being built as .Net Core 6.0 packages " + "instead of as .Net Framework 4.0 and 4.5.2 respectively. " + "This can cause compatibility issues when running certain " + "deployment steps in Octopus Server", RootProjectName, $"{RootProjectName}.{FixedRuntimes.Cloud}"); var nugetVersion = NugetVersion.Value; DoPublish(RootProjectName, OperatingSystem.IsWindows() ? Frameworks.Net40 : Frameworks.Net60, nugetVersion); DoPublish(RootProjectName, OperatingSystem.IsWindows() ? Frameworks.Net452 : Frameworks.Net60, nugetVersion, FixedRuntimes.Cloud); // Create the self-contained Calamari packages for each runtime ID defined in Calamari.csproj foreach (var rid in Solution.GetProject(RootProjectName).GetRuntimeIdentifiers()!) DoPublish(RootProjectName, Frameworks.Net60, nugetVersion, rid); }); Target PublishCalamariFlavourProjects => _ => _ .DependsOn(Compile) .Executes(async () => { var migratedCalamariFlavoursTests = MigratedCalamariFlavours.Flavours.Select(f => $"{f}.Tests"); var calamariFlavourProjects = Solution.Projects .Where(project => MigratedCalamariFlavours.Flavours.Contains(project.Name) || migratedCalamariFlavoursTests.Contains(project.Name)); // Calamari.Scripting is a library that other calamari flavours depend on; not a flavour on its own right. // Unlike other *Calamari* tests, we would still want to produce Calamari.Scripting.Zip and its tests, like its flavours. var calamariScripting = "Calamari.Scripting"; var calamariScriptingProjectAndTest = Solution.Projects.Where(project => project.Name == calamariScripting || project.Name == $"{calamariScripting}.Tests"); var calamariProjects = calamariFlavourProjects .Concat(calamariScriptingProjectAndTest) .ToList(); await PublishCalamariProjects(calamariProjects); }); async Task PublishCalamariProjects(List<Project> projects) { // All cross-platform Target Frameworks contain dots, all NetFx Target Frameworks don't // eg: net40, net452, net48 vs netcoreapp3.1, net5.0, net6.0 bool IsCrossPlatform(string targetFramework) => targetFramework.Contains('.'); var calamariPackages = projects .SelectMany(project => project.GetTargetFrameworks()!, (p, f) => new { Project = p, Framework = f, CrossPlatform = IsCrossPlatform(f) }).ToList(); // for NetFx target frameworks, we use "netfx" as the architecture, and ignore defined runtime identifiers var netFxPackages = calamariPackages .Where(p => !p.CrossPlatform) .Select(packageToBuild => new CalamariPackageMetadata() { Project = packageToBuild.Project, Framework = packageToBuild.Framework, Architecture = null, IsCrossPlatform = packageToBuild.CrossPlatform }); // for cross-platform frameworks, we combine each runtime identifier with each target framework var crossPlatformPackages = calamariPackages .Where(p => p.CrossPlatform) .SelectMany(packageToBuild => packageToBuild.Project.GetRuntimeIdentifiers() ?? Enumerable.Empty<string>(), (packageToBuild, runtimeIdentifier) => new CalamariPackageMetadata() { Project = packageToBuild.Project, Framework = packageToBuild.Framework, Architecture = runtimeIdentifier, IsCrossPlatform = packageToBuild.CrossPlatform }) .Distinct(t => new {t.Project?.Name, t.Architecture, t.Framework}); var packagesToPublish = crossPlatformPackages.Concat(netFxPackages); packagesToPublish.ForEach(PublishPackage); await Task.WhenAll(SignDirectoriesTasks); projects.ForEach(CompressCalamariProject); await Task.WhenAll(ProjectCompressionTasks); } void PublishPackage(CalamariPackageMetadata calamariPackageMetadata) { if (!OperatingSystem.IsWindows() && !calamariPackageMetadata.IsCrossPlatform) { Log.Warning($"Not building {calamariPackageMetadata.Framework}: can only build netfx on a Windows OS"); return; } Log.Information( $"Building {calamariPackageMetadata.Project?.Name} for framework '{calamariPackageMetadata.Framework}' and arch '{calamariPackageMetadata.Architecture}'"); var project = calamariPackageMetadata.Project; var outputDirectory = PublishDirectory / project?.Name / (calamariPackageMetadata.IsCrossPlatform ? calamariPackageMetadata.Architecture : "netfx"); DotNetPublish(s => s .SetConfiguration(Configuration) .SetProject(project) .SetFramework(calamariPackageMetadata.Framework) .SetRuntime(calamariPackageMetadata.Architecture) .SetOutput(outputDirectory) ); if (!project.Name.Contains("Tests")) { var signDirectoryTask = Task.Run(() => SignDirectory(outputDirectory)); SignDirectoriesTasks.Add(signDirectoryTask); } File.Copy(RootDirectory / "global.json", outputDirectory / "global.json"); } void CompressCalamariProject(Project project) { Log.Verbose($"Compressing Calamari flavour {PublishDirectory}/{project.Name}"); var compressionSource = PublishDirectory / project.Name; if (!Directory.Exists(compressionSource)) { Log.Verbose($"Skipping compression for {project.Name} since nothing was built"); return; } var compressionTask = Task.Run(() => CompressionTasks.CompressZip(compressionSource, $"{ArtifactsDirectory / project.Name}.zip")); ProjectCompressionTasks.Add(compressionTask); } Target PackBinaries => _ => _.DependsOn(Publish) .DependsOn(PublishCalamariFlavourProjects) .Executes(async () => { var nugetVersion = NugetVersion.Value; var packageActions = new List<Action> { () => DoPackage(RootProjectName, OperatingSystem.IsWindows() ? Frameworks.Net40 : Frameworks.Net60, nugetVersion), () => DoPackage(RootProjectName, OperatingSystem.IsWindows() ? Frameworks.Net452 : Frameworks.Net60, nugetVersion, FixedRuntimes.Cloud), }; // Create the self-contained Calamari packages for each runtime ID defined in Calamari.csproj // ReSharper disable once LoopCanBeConvertedToQuery foreach (var rid in Solution.GetProject(RootProjectName).GetRuntimeIdentifiers()!) packageActions.Add(() => DoPackage(RootProjectName, Frameworks.Net60, nugetVersion, rid)); var dotNetCorePackSettings = new DotNetPackSettings().SetConfiguration(Configuration) .SetOutputDirectory(ArtifactsDirectory) .EnableNoBuild() .EnableIncludeSource() .SetVersion(nugetVersion) .SetNoRestore(true); var commonProjects = Directory.GetFiles(SourceDirectory, "*.Common.csproj", new EnumerationOptions { RecurseSubdirectories = true }); // ReSharper disable once LoopCanBeConvertedToQuery foreach (var project in commonProjects) packageActions.Add(() => SignAndPack(project.ToString(), dotNetCorePackSettings)); var sourceProjectPath = SourceDirectory / "Calamari.CloudAccounts" / "Calamari.CloudAccounts.csproj"; packageActions.Add(() => SignAndPack(sourceProjectPath, dotNetCorePackSettings)); await RunPackActions(packageActions); }); Target PackTests => _ => _.DependsOn(Publish) .DependsOn(PublishCalamariFlavourProjects) .Executes(async () => { var nugetVersion = NugetVersion.Value; var defaultTarget = OperatingSystem.IsWindows() ? Frameworks.Net461 : Frameworks.Net60; AbsolutePath binFolder = SourceDirectory / "Calamari.Tests" / "bin" / Configuration / defaultTarget; Directory.Exists(binFolder); var actions = new List<Action> { () => { CompressionTasks.Compress(binFolder, ArtifactsDirectory / "Binaries.zip"); } }; // Create a Zip for each runtime for testing // ReSharper disable once LoopCanBeConvertedToQuery foreach (var rid in Solution.GetProject("Calamari.Tests").GetRuntimeIdentifiers()!) actions.Add(() => { var publishedLocation = DoPublish("Calamari.Tests", Frameworks.Net60, nugetVersion, rid); var zipName = $"Calamari.Tests.{rid}.{nugetVersion}.zip"; File.Copy(RootDirectory / "global.json", publishedLocation / "global.json"); CompressionTasks.Compress(publishedLocation, ArtifactsDirectory / zipName); }); actions.Add(() => { var testingProjectPath = SourceDirectory / "Calamari.Testing" / "Calamari.Testing.csproj"; DotNetPack(new DotNetPackSettings().SetConfiguration(Configuration) .SetProject(testingProjectPath) .SetOutputDirectory(ArtifactsDirectory) .EnableNoBuild() .EnableIncludeSource() .SetVersion(nugetVersion) .SetNoRestore(true)); }); await RunPackActions(actions); }); Target Pack => _ => _.DependsOn(PackTests) .DependsOn(PackBinaries); Target CopyToLocalPackages => _ => _.Requires(() => IsLocalBuild) .DependsOn(PackBinaries) .Executes(() => { Directory.CreateDirectory(LocalPackagesDirectory); foreach (var file in Directory.GetFiles(ArtifactsDirectory, "Calamari.*.nupkg")) CopyFile(file, LocalPackagesDirectory / Path.GetFileName(file), FileExistsPolicy.Overwrite); }); Target PackageConsolidatedCalamariZip => _ => _.DependsOn(CalamariConsolidationTests) .DependsOn(PackBinaries) .Executes(() => { var artifacts = Directory.GetFiles(ArtifactsDirectory, "*.nupkg") .Where(a => !CalamariProjectsToSkipConsolidation.Any(a.Contains)); var packageReferences = new List<BuildPackageReference>(); foreach (var artifact in artifacts) { using var zip = ZipFile.OpenRead(artifact); var nuspecFileStream = zip.Entries.First(e => e.Name.EndsWith(".nuspec")).Open(); var nuspecReader = new NuspecReader(nuspecFileStream); var metadata = nuspecReader.GetMetadata().ToList(); packageReferences.Add(new BuildPackageReference { Name = metadata.Where(kvp => kvp.Key == "id").Select(i => i.Value).First(), Version = metadata.Where(kvp => kvp.Key == "version").Select(i => i.Value).First(), PackagePath = artifact }); } foreach (var flavour in MigratedCalamariFlavours.Flavours) { if (Solution.GetProject(flavour) != null) { packageReferences.Add(new BuildPackageReference { Name = flavour, Version = NugetVersion.Value, PackagePath = ArtifactsDirectory / $"{flavour}.zip" }); } } Directory.CreateDirectory(ConsolidatedPackageDirectory); var (result, packageFilename) = new Consolidate(Log.Logger).Execute(ConsolidatedPackageDirectory, packageReferences); if (!result) throw new Exception("Failed to consolidate calamari Packages"); Log.Information($"Created consolidated package zip: {packageFilename}"); }); Target PackCalamariConsolidatedNugetPackage => _ => _.DependsOn(PackageConsolidatedCalamariZip) .Executes(() => { NuGetPack(s => s.SetTargetPath(BuildDirectory / "Calamari.Consolidated.nuspec") .SetBasePath(BuildDirectory) .SetVersion(NugetVersion.Value) .SetOutputDirectory(ArtifactsDirectory)); }); Target UpdateCalamariVersionOnOctopusServer => _ => _.OnlyWhenStatic(() => SetOctopusServerVersion) .Requires(() => IsLocalBuild) .DependsOn(CopyToLocalPackages) .Executes(() => { var serverProjectFile = RootDirectory / ".." / "OctopusDeploy" / "source" / "Octopus.Server" / "Octopus.Server.csproj"; if (File.Exists(serverProjectFile)) { Log.Information("Setting Calamari version in Octopus Server " + "project {ServerProjectFile} to {NugetVersion}", serverProjectFile, NugetVersion.Value); SetOctopusServerCalamariVersion(serverProjectFile); } else { Log.Warning("Could not set Calamari version in Octopus Server project " + "{ServerProjectFile} to {NugetVersion} as could not find " + "project file", serverProjectFile, NugetVersion.Value); } }); Target SetTeamCityVersion => _ => _.Executes(() => { TeamCity.Instance?.SetBuildNumber(NugetVersion.Value); }); Target BuildLocal => _ => _.DependsOn(PackCalamariConsolidatedNugetPackage) .DependsOn(UpdateCalamariVersionOnOctopusServer); Target BuildCi => _ => _.DependsOn(SetTeamCityVersion) .DependsOn(Pack) .DependsOn(PackCalamariConsolidatedNugetPackage); public static int Main() => Execute<Build>(x => IsServerBuild ? x.BuildCi : x.BuildLocal); async Task RunPackActions(List<Action> actions) { if (PackInParallel) { var tasks = actions.Select(Task.Run).ToList(); await Task.WhenAll(tasks); } else { foreach (var action in actions) action(); } } AbsolutePath DoPublish(string project, string framework, string version, string? runtimeId = null) { var publishedTo = PublishDirectory / project / framework; if (!runtimeId.IsNullOrEmpty()) { publishedTo /= runtimeId; runtimeId = runtimeId != "portable" && runtimeId != "Cloud" ? runtimeId : null; } DotNetPublish(_ => _.SetProject(Solution.GetProject(project)) .SetConfiguration(Configuration) .SetOutput(publishedTo) .SetFramework(framework) .SetVersion(NugetVersion.Value) .SetVerbosity(BuildVerbosity) .SetRuntime(runtimeId) .SetVersion(version)); if (WillSignBinaries) Signing.SignAndTimestampBinaries(publishedTo, AzureKeyVaultUrl, AzureKeyVaultAppId, AzureKeyVaultAppSecret, AzureKeyVaultTenantId, AzureKeyVaultCertificateName, SigningCertificatePath, SigningCertificatePassword); return publishedTo; } void SignProject(string project) { if (!WillSignBinaries) return; var binDirectory = $"{Path.GetDirectoryName(project)}/bin/{Configuration}/"; SignDirectory(binDirectory); } void SignDirectory(string directory) { if (!WillSignBinaries) return; Log.Information("Signing directory: {Directory} and sub-directories", directory); var binariesFolders = Directory.GetDirectories(directory, "*", new EnumerationOptions { RecurseSubdirectories = true }); foreach (var subDirectory in binariesFolders.Append(directory)) Signing.SignAndTimestampBinaries(subDirectory, AzureKeyVaultUrl, AzureKeyVaultAppId, AzureKeyVaultAppSecret, AzureKeyVaultTenantId, AzureKeyVaultCertificateName, SigningCertificatePath, SigningCertificatePassword); } void SignAndPack(string project, DotNetPackSettings dotNetCorePackSettings) { Log.Information("SignAndPack project: {Project}", project); SignProject(project); DotNetPack(dotNetCorePackSettings.SetProject(project)); } void DoPackage(string project, string framework, string version, string? runtimeId = null) { var publishedTo = PublishDirectory / project / framework; var projectDir = SourceDirectory / project; var packageId = $"{project}"; var nugetPackProperties = new Dictionary<string, object>(); if (!runtimeId.IsNullOrEmpty()) { publishedTo /= runtimeId; packageId = $"{project}.{runtimeId}"; nugetPackProperties.Add("runtimeId", runtimeId!); } if (WillSignBinaries) Signing.SignAndTimestampBinaries(publishedTo, AzureKeyVaultUrl, AzureKeyVaultAppId, AzureKeyVaultAppSecret, AzureKeyVaultTenantId, AzureKeyVaultCertificateName, SigningCertificatePath, SigningCertificatePassword); var nuspec = $"{publishedTo}/{packageId}.nuspec"; CopyFile($"{projectDir}/{project}.nuspec", nuspec, FileExistsPolicy.Overwrite); var text = File.ReadAllText(nuspec); text = text.Replace("$id$", packageId) .Replace("$version$", version); File.WriteAllText(nuspec, text); NuGetTasks.NuGetPack(_ => _.SetBasePath(publishedTo) .SetOutputDirectory(ArtifactsDirectory) .SetTargetPath(nuspec) .SetVersion(NugetVersion.Value) .SetVerbosity(NuGetVerbosity.Normal) .SetProperties(nugetPackProperties)); } // Sets the Octopus.Server.csproj Calamari.Consolidated package version void SetOctopusServerCalamariVersion(string projectFile) { var text = File.ReadAllText(projectFile); text = Regex.Replace(text, @"<PackageReference Include=""Calamari.Consolidated"" Version=""([\S])+"" />", $"<PackageReference Include=\"Calamari.Consolidated\" Version=\"{NugetVersion.Value}\" />"); File.WriteAllText(projectFile, text); } string GetNugetVersion() { return AppendTimestamp ? $"{GitVersionInfo?.NuGetVersion}-{DateTime.Now:yyyyMMddHHmmss}" : GitVersionInfo?.NuGetVersion ?? throw new InvalidOperationException("Unable to retrieve valid Nuget Version"); } } }<file_sep>using System; namespace Calamari.Common.Features.Discovery { public class KubernetesCluster { public static KubernetesCluster CreateForEks(string name, string clusterName, string endpoint, string? accountId, AwsAssumeRole? assumeRole, string? workerPool, TargetTags tags) { return new KubernetesCluster(name, clusterName, null, endpoint, accountId, assumeRole, workerPool, tags, accountId == null); } public static KubernetesCluster CreateForAks(string name, string clusterName, string resourceGroupName, string accountId, TargetTags tags) { return new KubernetesCluster(name, clusterName, resourceGroupName, null, accountId, null, null, tags); } KubernetesCluster( string name, string clusterName, string? resourceGroupName, string? endpoint, string? accountId, AwsAssumeRole? awsAssumeRole, string? workerPool, TargetTags tags, bool awsUseWorkerCredentials = false) { Name = name; ClusterName = clusterName; ResourceGroupName = resourceGroupName; Endpoint = endpoint; AccountId = accountId; AwsAssumeRole = awsAssumeRole; WorkerPool = workerPool; Tags = tags; AwsUseWorkerCredentials = awsUseWorkerCredentials; } public string? WorkerPool { get; } public string Name { get; } public string ClusterName { get; } public string? ResourceGroupName { get; } public string? Endpoint { get; } public string? AccountId { get; } public bool AwsUseWorkerCredentials { get; } public AwsAssumeRole? AwsAssumeRole { get; } public TargetTags Tags { get; } } public class AwsAssumeRole { public AwsAssumeRole( string arn, string? session = null, int? sessionDuration = null, string? externalId = null) { Arn = arn; Session = session; SessionDuration = sessionDuration; ExternalId = externalId; } public string? ExternalId { get; set; } public int? SessionDuration { get; set; } public string? Session { get; set; } public string Arn { get; set; } } }<file_sep>using System; using Azure.Identity; using Azure.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Fluent; namespace Calamari.AzureAppService.Azure { public sealed class AzureKnownEnvironment { /// <param name="environment">The environment name exactly matching the names defined in Azure SDK (see here https://github.com/Azure/azure-libraries-for-net/blob/master/src/ResourceManagement/ResourceManager/AzureEnvironment.cs) /// Other names are allowed in case this list is ever expanded/changed, but will likely result in an error at deployment time. /// </param> public AzureKnownEnvironment(string environment) { Value = environment; if (string.IsNullOrEmpty(environment) || environment == "AzureCloud") // This environment name is defined in Sashimi.Azure.Accounts.AzureEnvironmentsListAction Value = Global.Value; // We interpret it as the normal Azure environment for historical reasons) azureSdkEnvironment = AzureEnvironment.FromName(Value) ?? throw new InvalidOperationException($"Unknown environment name {Value}"); } private readonly AzureEnvironment azureSdkEnvironment; public string Value { get; } public static readonly AzureKnownEnvironment Global = new AzureKnownEnvironment("AzureGlobalCloud"); public static readonly AzureKnownEnvironment AzureChinaCloud = new AzureKnownEnvironment("AzureChinaCloud"); public static readonly AzureKnownEnvironment AzureUSGovernment = new AzureKnownEnvironment("AzureUSGovernment"); public static readonly AzureKnownEnvironment AzureGermanCloud = new AzureKnownEnvironment("AzureGermanCloud"); public AzureEnvironment AsAzureSDKEnvironment() { return azureSdkEnvironment; } public ArmEnvironment AsAzureArmEnvironment() => ToArmEnvironment(Value); private static ArmEnvironment ToArmEnvironment(string name) => name switch { "AzureGlobalCloud" => ArmEnvironment.AzurePublicCloud, "AzureChinaCloud" => ArmEnvironment.AzureChina, "AzureGermanCloud" => ArmEnvironment.AzureGermany, "AzureUSGovernment" => ArmEnvironment.AzureGovernment, _ => throw new InvalidOperationException($"ARM Environment {name} is not a known Azure Environment name.") }; public Uri GetAzureAuthorityHost() => ToAzureAuthorityHost(Value); private static Uri ToAzureAuthorityHost(string name) => name switch { "AzureGlobalCloud" => AzureAuthorityHosts.AzurePublicCloud, "AzureChinaCloud" => AzureAuthorityHosts.AzureChina, "AzureGermanCloud" => AzureAuthorityHosts.AzureGermany, "AzureUSGovernment" => AzureAuthorityHosts.AzureGovernment, _ => throw new InvalidOperationException($"ARM Environment {name} is not a known Azure Environment name.") }; } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.Python { public class PythonBootstrapper { const string WindowsNewLine = "\r\n"; static readonly string ConfigurationScriptTemplate; static readonly string InstallDependenciesScriptTemplate; static readonly string SensitiveVariablePassword = AesEncryption.RandomString(16); static readonly AesEncryption VariableEncryptor = new AesEncryption(SensitiveVariablePassword); static readonly ICalamariFileSystem CalamariFileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); static PythonBootstrapper() { ConfigurationScriptTemplate = EmbeddedResource.ReadEmbeddedText(typeof(PythonBootstrapper).Namespace + ".Configuration.py"); InstallDependenciesScriptTemplate = EmbeddedResource.ReadEmbeddedText(typeof(PythonBootstrapper).Namespace + ".InstallDependencies.py"); } public static string FormatCommandArguments(string bootstrapFile, string? scriptParameters) { var encryptionKey = ToHex(AesEncryption.GetEncryptionKey(SensitiveVariablePassword)); var commandArguments = new StringBuilder(); commandArguments.Append($"\"-u\" \"{bootstrapFile}\" {scriptParameters} \"{encryptionKey}\""); return commandArguments.ToString(); } public static string PrepareConfigurationFile(string workingDirectory, IVariables variables) { var configurationFile = Path.Combine(workingDirectory, "Configure." + Guid.NewGuid().ToString().Substring(10) + ".py"); var builder = new StringBuilder(ConfigurationScriptTemplate); builder.Replace("{{VariableDeclarations}}", $"octopusvariables = {{ {string.Join(",", GetVariables(variables))} }}"); using (var file = new FileStream(configurationFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.ASCII)) { writer.Write(builder.Replace(WindowsNewLine, Environment.NewLine)); writer.Flush(); } File.SetAttributes(configurationFile, FileAttributes.Hidden); return configurationFile; } static IEnumerable<string> GetVariables(IVariables variables) { return variables.GetNames() .Select(variable => { var variableValue = DecryptValueCommand(variables.Get(variable)); return $"decode(\"{EncodeValue(variable)}\") : {variableValue}"; }); } static string DecryptValueCommand(string? value) { var encrypted = VariableEncryptor.Encrypt(value ?? ""); var rawEncrypted = AesEncryption.ExtractIV(encrypted, out var iv); return $@"decrypt(""{Convert.ToBase64String(rawEncrypted)}"",""{ToHex(iv)}"")"; } static string ToHex(byte[] bytes) { return BitConverter.ToString(bytes).Replace("-", ""); } static string EncodeValue(string value) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(value ?? "")); } public static string FindPythonExecutable() { return CalamariEnvironment.IsRunningOnWindows ? "python" : "python3"; } static void EnsureValidUnixFile(string scriptFilePath) { var text = File.ReadAllText(scriptFilePath); text = text.Replace(WindowsNewLine, Environment.NewLine); File.WriteAllText(scriptFilePath, text); } public static (string bootstrapFile, string[] temporaryFiles) PrepareBootstrapFile(Script script, string workingDirectory, string configurationFile, IVariables variables) { var bootstrapFile = Path.Combine(workingDirectory, "Bootstrap." + Guid.NewGuid().ToString().Substring(10) + "." + Path.GetFileName(script.File)); var scriptModulePaths = PrepareScriptModules(variables, workingDirectory).ToArray(); using (var file = new FileStream(bootstrapFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.UTF8)) { writer.WriteLine("from runpy import run_path"); writer.WriteLine("configuration = run_path(\"" + configurationFile.Replace("\\", "\\\\") + "\")"); writer.WriteLine("run_path(\"" + script.File.Replace("\\", "\\\\") + "\", configuration)"); writer.Flush(); } File.SetAttributes(bootstrapFile, FileAttributes.Hidden); EnsureValidUnixFile(script.File); return (bootstrapFile, scriptModulePaths); } static IEnumerable<string> PrepareScriptModules(IVariables variables, string workingDirectory) { foreach (var variableName in variables.GetNames().Where(ScriptVariables.IsLibraryScriptModule)) if (ScriptVariables.GetLibraryScriptModuleLanguage(variables, variableName) == ScriptSyntax.Python) { var libraryScriptModuleName = ScriptVariables.GetLibraryScriptModuleName(variableName); var name = new string(libraryScriptModuleName.Where(x => char.IsLetterOrDigit(x) || x == '_').ToArray()); var moduleFileName = $"{name}.py"; Log.VerboseFormat("Writing script module '{0}' as python module {1}. Import this module via `import {2}`.", libraryScriptModuleName, moduleFileName, name); var moduleFilePath = Path.Combine(workingDirectory, moduleFileName); var contents = variables.Get(variableName); if (contents == null) throw new InvalidOperationException($"Value for variable {variableName} could not be found."); CalamariFileSystem.OverwriteFile(moduleFilePath, contents, Encoding.UTF8); yield return name; } } public static string PrepareDependencyInstaller(string workingDirectory) { var dependencyInstallerFile = Path.Combine(workingDirectory, "InstallDependencies." + Guid.NewGuid().ToString().Substring(10) + ".py"); var builder = new StringBuilder(InstallDependenciesScriptTemplate); using (var file = new FileStream(dependencyInstallerFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.ASCII)) { writer.Write(builder.Replace(WindowsNewLine, Environment.NewLine)); writer.Flush(); } File.SetAttributes(dependencyInstallerFile, FileAttributes.Hidden); return dependencyInstallerFile; } } }<file_sep>using System; using System.Net; using System.Net.Http; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using AzureEnvironmentEnum = Microsoft.Azure.Management.ResourceManager.Fluent.AzureEnvironment; namespace Calamari.Azure { public class ServicePrincipalAccount { public ServicePrincipalAccount( string subscriptionNumber, string clientId, string tenantId, string password, string azureEnvironment, string resourceManagementEndpointBaseUri, string activeDirectoryEndpointBaseUri) { SubscriptionNumber = subscriptionNumber; ClientId = clientId; TenantId = tenantId; Password = <PASSWORD>; AzureEnvironment = azureEnvironment; ResourceManagementEndpointBaseUri = resourceManagementEndpointBaseUri; ActiveDirectoryEndpointBaseUri = activeDirectoryEndpointBaseUri; } public string SubscriptionNumber { get; } public string ClientId { get; } public string TenantId { get; } public string Password { get; } public string AzureEnvironment { get; } public string ResourceManagementEndpointBaseUri { get; } public string ActiveDirectoryEndpointBaseUri { get; } public IAzure CreateAzureClient() { var environment = string.IsNullOrEmpty(AzureEnvironment) || AzureEnvironment == "AzureCloud" ? AzureEnvironmentEnum.AzureGlobalCloud : AzureEnvironmentEnum.FromName(AzureEnvironment) ?? throw new InvalidOperationException($"Unknown environment name {AzureEnvironment}"); var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(ClientId, Password, TenantId, environment ); // to ensure the Azure API uses the appropriate web proxy var client = new HttpClient(new HttpClientHandler {Proxy = WebRequest.DefaultWebProxy}); return Microsoft.Azure.Management.Fluent.Azure.Configure() .WithHttpClient(client) .Authenticate(credentials) .WithSubscription(SubscriptionNumber); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using Calamari.Common.Plumbing.ServiceMessages; namespace Calamari.Common.Plumbing.Logging { public class Operation : IDisposable { public bool IsAbandoned { get; private set; } public string OperationId { get; } readonly ILog logger; readonly Stopwatch stopwatch; readonly string operationName; bool isCompleted; bool isDisposed; public Operation(ILog logger, string operationName) { OperationId = Guid.NewGuid().ToString("n"); this.logger = logger; this.operationName = operationName; stopwatch = Stopwatch.StartNew(); isDisposed = false; logger.VerboseFormat($"Timed operation '{operationName}' started."); } public void Complete() { if (isCompleted || IsAbandoned) throw new InvalidOperationException("This logging operation has already been completed or abandoned."); logger.VerboseFormat($"Timed operation '{operationName}' completed in {stopwatch.ElapsedMilliseconds}ms."); LogTimedOperationServiceMessage(stopwatch.ElapsedMilliseconds, Outcome.Completed); isCompleted = true; Dispose(); } void LogTimedOperationServiceMessage(long stopwatchElapsedMilliseconds, Outcome operationOutcome) { // Determine operation duration // Construct service message ##octopus[serviceMessage='calamari-timed-operation' name='Deployment package extraction' operationId='679d7cfadc614909a87e2005000c84c1' durationMilliseconds='1642' outcome='Completed'] var serviceMessageParameters = new Dictionary<string, string> { { ServiceMessageNames.CalamariTimedOperation.OperationIdAttribute, OperationId }, { ServiceMessageNames.CalamariTimedOperation.NameAttribute, operationName }, { ServiceMessageNames.CalamariTimedOperation.DurationMillisecondsAttribute, stopwatchElapsedMilliseconds.ToString() }, { ServiceMessageNames.CalamariTimedOperation.OutcomeAttribute, operationOutcome.ToString() }, }; logger.WriteServiceMessage(new ServiceMessage(ServiceMessageNames.CalamariTimedOperation.Name, serviceMessageParameters)); } public void Abandon(Exception? ex = null) { if (isCompleted || IsAbandoned) throw new InvalidOperationException("This logging operation has already been completed or abandoned."); LogTimedOperationServiceMessage(stopwatch.ElapsedMilliseconds, Outcome.Abandoned); IsAbandoned = true; Dispose(); } public void Dispose() { if (isDisposed) { return; } if (!isCompleted && !IsAbandoned) { Abandon(); } isDisposed = true; } enum Outcome { Completed, Abandoned } } } <file_sep>namespace Calamari.Tests.Helpers { // This file is a clone of how the server represents delta package responses from Calamari public class DeltaPackage { public DeltaPackage(string fullPathOnRemoteMachine, string hash, long size) { FullPathOnRemoteMachine = fullPathOnRemoteMachine; Hash = hash; Size = size; } public string FullPathOnRemoteMachine { get; } public string Hash { get; } public long Size { get; } } }<file_sep>using System.IO; using System.Linq; using Calamari.Commands; using System.Runtime.CompilerServices; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; namespace Calamari.Integration.Processes { public class OctoDiffCommandLineRunner { readonly ICommandLineRunner commandLineRunner; public CommandLine OctoDiff { get; } public OctoDiffCommandLineRunner(ICommandLineRunner commandLineRunner) { this.commandLineRunner = commandLineRunner; OctoDiff = new CommandLine(FindOctoDiffExecutable()); } public CommandResult Execute() { var result = commandLineRunner.Execute(OctoDiff.Build()); return result; } public static string FindOctoDiffExecutable([CallerFilePath] string? callerPath = null) { var basePath = Path.GetDirectoryName(typeof(ApplyDeltaCommand).Assembly.Location); var executable = Path.GetFullPath(Path.Combine(basePath, "Octodiff.exe")); if (File.Exists(executable)) return executable; var alternatePath = Path.Combine(Path.GetDirectoryName(callerPath), @"..\bin"); // Resharper uses a weird path executable = Directory.EnumerateFiles(alternatePath, "Octodiff.exe", SearchOption.AllDirectories).FirstOrDefault(); if (executable != null) return executable; throw new CommandException($"Could not find Octodiff.exe at {executable} or {alternatePath}."); } } }<file_sep>using System.IO; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Conventions { public class TransferPackageConvention :IInstallConvention { readonly ILog log; private readonly ICalamariFileSystem fileSystem; public TransferPackageConvention(ILog log, ICalamariFileSystem fileSystem) { this.log = log; this.fileSystem = fileSystem; } public void Install(RunningDeployment deployment) { var transferPath = CrossPlatform.ExpandPathEnvironmentVariables(deployment.Variables.Get(PackageVariables.TransferPath)); fileSystem.EnsureDirectoryExists(transferPath); var fileName = deployment.Variables.Get(PackageVariables.OriginalFileName) ?? Path.GetFileName(deployment.PackageFilePath); var filePath = Path.Combine(transferPath, fileName); if (fileSystem.FileExists(filePath)) { log.Info($"File {filePath} already exists so it will be attempted to be overwritten"); } fileSystem.CopyFile(deployment.PackageFilePath, filePath); log.Info($"Copied package '{fileName}' to directory '{transferPath}'"); log.SetOutputVariableButDoNotAddToVariables(PackageVariables.Output.DirectoryPath, transferPath); log.SetOutputVariableButDoNotAddToVariables(PackageVariables.Output.FileName, fileName); log.SetOutputVariableButDoNotAddToVariables(PackageVariables.Output.FilePath, filePath); } } }<file_sep>using System; using Calamari.Common.Features.Processes; using NUnit.Framework; using NUnit.Framework.Interfaces; namespace Calamari.Testing.Requirements { public class RequiresDockerInstalledAttribute : TestAttribute, ITestAction { readonly Lazy<bool> isDockerInstalled; public RequiresDockerInstalledAttribute() { isDockerInstalled = new Lazy<bool>(() => { try { var result = SilentProcessRunner.ExecuteCommand("docker", "ps -q", ".", (stdOut) => { }, (stdErr) => { }); return result.ExitCode == 0; } catch (Exception) { return false; } }); } public void BeforeTest(ITest testDetails) { if (!isDockerInstalled.Value) { Assert.Ignore( "It appears as though docker is not installed on this machine. This test will be skipped"); } } public void AfterTest(ITest test) { } public ActionTargets Targets { get; } } }<file_sep>using System; using System.IO; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.Deployment; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class ConfiguredScriptConventionFixture { ICalamariFileSystem fileSystem; IScriptEngine scriptEngine; ICommandLineRunner commandLineRunner; RunningDeployment deployment; IVariables variables; const string stagingDirectory = "c:\\applications\\acme\\1.0.0"; [SetUp] public void SetUp() { fileSystem = Substitute.For<ICalamariFileSystem>(); scriptEngine = Substitute.For<IScriptEngine>(); commandLineRunner = Substitute.For<ICommandLineRunner>(); scriptEngine.GetSupportedTypes().Returns(new[] { ScriptSyntax.PowerShell }); variables = new CalamariVariables(); variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts); deployment = new RunningDeployment("C:\\packages", variables) { StagingDirectory = stagingDirectory }; } [Test] public void ShouldRunScriptAtAppropriateStage() { const string stage = DeploymentStages.PostDeploy; const string scriptBody = "lorem ipsum blah blah blah"; var scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.PowerShell); var scriptPath = Path.Combine(stagingDirectory, scriptName); var script = new Script(scriptPath); variables.Set(scriptName, scriptBody); var convention = CreateConvention(stage); scriptEngine.Execute(Arg.Any<Script>(), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.Received().WriteAllBytes(scriptPath, Arg.Any<byte[]>()); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == scriptPath), variables, commandLineRunner); } [Test] public void ShouldRemoveScriptFileAfterRunning() { const string stage = DeploymentStages.PostDeploy; var scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.PowerShell); var scriptPath = Path.Combine(stagingDirectory, scriptName); var script = new Script(scriptPath); variables.Set(scriptName, "blah blah"); var convention = CreateConvention(stage); scriptEngine.Execute(Arg.Any<Script>(), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.Received().DeleteFile(scriptPath, Arg.Any<FailureOptions>()); } [Test] public void ShouldNotRemoveCustomPostDeployScriptFileAfterRunningIfSpecialVariableIsSet() { deployment.Variables.Set(SpecialVariables.DeleteScriptsOnCleanup, false.ToString()); const string stage = DeploymentStages.PostDeploy; var scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.PowerShell); var scriptPath = Path.Combine(stagingDirectory, scriptName); variables.Set(scriptName, "blah blah"); var convention = CreateConvention(stage); scriptEngine.Execute(Arg.Any<Script>(), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.DidNotReceive().DeleteFile(scriptPath, Arg.Any<FailureOptions>()); } [Test] public void ShouldThrowAnErrorIfAScriptExistsWithTheWrongType() { const string stage = DeploymentStages.PostDeploy; var scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.CSharp); variables.Set(scriptName, "blah blah"); var convention = CreateConvention(stage); Action exec = () => convention.Install(deployment); exec.Should().Throw<CommandException>().WithMessage("CSharp scripts are not supported on this platform (PostDeploy)"); } private ConfiguredScriptConvention CreateConvention(string deployStage) { ConfiguredScriptBehaviour scriptBehaviour = null; if (deployStage == DeploymentStages.PreDeploy) scriptBehaviour = new PreDeployConfiguredScriptBehaviour(new InMemoryLog(), fileSystem, scriptEngine, commandLineRunner); else if (deployStage == DeploymentStages.Deploy) scriptBehaviour = new DeployConfiguredScriptBehaviour(new InMemoryLog(), fileSystem, scriptEngine, commandLineRunner); else if (deployStage == DeploymentStages.PostDeploy) scriptBehaviour = new PostDeployConfiguredScriptBehaviour(new InMemoryLog(), fileSystem, scriptEngine, commandLineRunner); return new ConfiguredScriptConvention(scriptBehaviour); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Runtime; using Calamari.Aws.Exceptions; using Calamari.Aws.Integration.CloudFormation; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Integration.Processes; using Octopus.CoreUtilities; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Deployment.Conventions { public abstract class CloudFormationInstallationConventionBase: IInstallConvention { protected readonly StackEventLogger Logger; public CloudFormationInstallationConventionBase(StackEventLogger logger) { Logger = logger; } public abstract void Install(RunningDeployment deployment); /// <summary> /// The AmazonServiceException can hold additional information that is useful to include in /// the log. /// </summary> /// <param name="exception">The exception</param> protected void LogAmazonServiceException(AmazonServiceException exception) { exception.GetWebExceptionMessage() .Tee(message => DisplayWarning("AWS-CLOUDFORMATION-ERROR-0014", message)); } /// <summary> /// Run an action and log any AmazonServiceException detail. /// </summary> /// <param name="func">The exception</param> protected T WithAmazonServiceExceptionHandling<T>(Func<T> func) { try { return func(); } catch (AmazonServiceException exception) { LogAmazonServiceException(exception); throw; } } /// <summary> /// Run an action and log any AmazonServiceException detail. /// </summary> /// <param name="action">The action to invoke</param> protected void WithAmazonServiceExceptionHandling(Action action) { WithAmazonServiceExceptionHandling<ValueTuple>(() => default(ValueTuple).Tee(x=> action())); } /// <summary> /// Display an warning message to the user (without duplicates) /// </summary> /// <param name="errorCode">The error message code</param> /// <param name="message">The error message body</param> /// <returns>true if it was displayed, and false otherwise</returns> protected bool DisplayWarning(string errorCode, string message) { return Logger.Warn(errorCode, message); } /// <summary> /// Creates a handler which will log stack events and throw on common rollback events /// </summary> /// <param name="clientFactory">The client factory</param> /// <param name="stack">The stack to query</param> /// <param name="filter">The filter for stack events</param> /// <param name="expectSuccess">Whether we expected a success</param> /// <param name="missingIsFailure"></param> /// <returns>Stack event handler</returns> protected Action<Maybe<StackEvent>> LogAndThrowRollbacks(Func<IAmazonCloudFormation> clientFactory, StackArn stack, bool expectSuccess = true, bool missingIsFailure = true, Func<StackEvent, bool> filter = null) { return @event => { try { Logger.Log(@event); Logger.LogRollbackError( @event, x => WithAmazonServiceExceptionHandling(() => clientFactory.GetStackEvents(stack, (e) => x(e) && (filter == null || filter(e))).GetAwaiter().GetResult()), expectSuccess, missingIsFailure); } catch (PermissionException exception) { Log.Warn(exception.Message); } }; } protected void SetOutputVariable(IVariables variables, string name, string value) { Log.SetOutputVariable($"AwsOutputs[{name}]", value ?? "", variables); Log.Info($"Saving variable \"Octopus.Action[{variables["Octopus.Action.Name"]}].Output.AwsOutputs[{name}]\""); } protected Task<Stack> QueryStackAsync(Func<IAmazonCloudFormation> clientFactory, StackArn stack) { try { return clientFactory.DescribeStackAsync(stack); } catch (AmazonServiceException ex) when (ex.ErrorCode == "AccessDenied") { throw new PermissionException( "The AWS account used to perform the operation does not have the required permissions to describe the CloudFormation stack. " + "This means that the step is not able to generate any output variables.\n " + "Please ensure the current account has permission to perform action 'cloudformation:DescribeStacks'.\n" + ex.Message + "\n" + ex); } catch (AmazonServiceException ex) { throw new Exception("An unrecognised exception was thrown while querying the CloudFormation stacks.", ex); } } protected Func<StackEvent, bool> FilterStackEventsSince(DateTime timestamp) { return (e) => e.Timestamp >= timestamp; } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting { /// <summary> /// The last wrapper in any chain. It calls the script engine directly. /// </summary> public class TerminalScriptWrapper : IScriptWrapper { readonly IScriptExecutor scriptExecutor; readonly IVariables variables; public TerminalScriptWrapper(IScriptExecutor scriptExecutor, IVariables variables) { this.scriptExecutor = scriptExecutor; this.variables = variables; } public int Priority => ScriptWrapperPriorities.TerminalScriptPriority; public IScriptWrapper? NextWrapper { get => throw new MethodAccessException("TerminalScriptWrapper does not have a NextWrapper"); set => throw new MethodAccessException("TerminalScriptWrapper does not have a NextWrapper"); } public bool IsEnabled(ScriptSyntax syntax) { return true; } public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars) { return scriptExecutor.Execute(script, variables, commandLineRunner, environmentVars); } } }<file_sep>#!/bin/bash echo "Hello from Deploy.sh"<file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public static class MachineVariables { public const string Name = "Octopus.Machine.Name"; public const string DeploymentTargetType = "Octopus.Machine.DeploymentTargetType"; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.PackageRetention.Model; using Calamari.Integration.Packages.Download; namespace Calamari.Deployment.PackageRetention.Caching { public class PercentFreeDiskSpacePackageCleaner : IRetentionAlgorithm { const string PackageRetentionPercentFreeDiskSpace = "OctopusPackageRetentionPercentFreeDiskSpace"; const int DefaultPercentFreeDiskSpace = 20; const int FreeSpacePercentBuffer = 30; readonly ISortJournalEntries sortJournalEntries; readonly IVariables variables; readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly IPackageDownloaderUtils packageUtils = new PackageDownloaderUtils(); public PercentFreeDiskSpacePackageCleaner(ICalamariFileSystem fileSystem, ISortJournalEntries sortJournalEntries, IVariables variables, ILog log) { this.fileSystem = fileSystem; this.sortJournalEntries = sortJournalEntries; this.variables = variables; this.log = log; } public IEnumerable<PackageIdentity> GetPackagesToRemove(IEnumerable<JournalEntry> journalEntries) { if (!fileSystem.GetDiskFreeSpace(packageUtils.RootDirectory, out var totalNumberOfFreeBytes) || !fileSystem.GetDiskTotalSpace(packageUtils.RootDirectory, out var totalNumberOfBytes)) { log.Info("Unable to determine disk space. Skipping free space package retention."); return new PackageIdentity[0]; } var percentFreeDiskSpaceDesired = variables.GetInt32(PackageRetentionPercentFreeDiskSpace) ?? DefaultPercentFreeDiskSpace; var desiredSpaceInBytes = totalNumberOfBytes * (ulong) percentFreeDiskSpaceDesired / 100; if (totalNumberOfFreeBytes > desiredSpaceInBytes) { log.VerboseFormat("Detected enough space for new packages. ({0}/{1})", totalNumberOfFreeBytes.ToFileSizeString(), totalNumberOfBytes.ToFileSizeString()); return new PackageIdentity[0]; } var spaceToFree = (desiredSpaceInBytes - totalNumberOfFreeBytes) * (100 + FreeSpacePercentBuffer) / 100; log.VerboseFormat("Cleaning {0} space from the package cache.", spaceToFree.ToFileSizeString()); ulong spaceFreed = 0L; var orderedJournalEntries = sortJournalEntries.Sort(journalEntries); return orderedJournalEntries.TakeWhile(entry => { var moreToClean = spaceFreed < spaceToFree; spaceFreed += entry.FileSizeBytes; return moreToClean; }) .Select(entry => entry.Package); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using Calamari.Aws.Deployment.Conventions; using Amazon.CloudFormation.Model; using Calamari.Common.Util; namespace Calamari.Aws.Integration.CloudFormation.Templates { public interface ICloudFormationRequestBuilder : ITemplateInputs<Parameter> { CreateStackRequest BuildCreateStackRequest(); UpdateStackRequest BuildUpdateStackRequest(); Task<CreateChangeSetRequest> BuildChangesetRequest(); } }<file_sep>namespace Calamari.Testing.Requirements { public class RequiresMonoVersion400OrAboveAttribute : RequiresMinimumMonoVersionAttribute { public RequiresMonoVersion400OrAboveAttribute() : base(4, 0, 0) { } } }<file_sep>using System; using System.Collections.Generic; using Serilog; namespace Calamari.ConsolidateCalamariPackages { interface IPackageReference { string Name { get; } string Version { get; } string PackagePath { get; } IReadOnlyList<SourceFile> GetSourceFiles(ILogger log); } }<file_sep>#if USE_NUGET_V3_LIBS using System; using NuGet.Versioning; using Octopus.Versioning; namespace Calamari.Common.Plumbing.Extensions { public static class VersionExtensions { /// <summary> /// Converts an IVersion to a NuGetVersion. /// </summary> /// <param name="version">The base version</param> /// <returns>The NuGet version</returns> public static NuGetVersion ToNuGetVersion(this IVersion version) { return new NuGetVersion( version.Major, version.Minor, version.Patch, version.Revision, version.ReleaseLabels, version.Metadata); } } } #endif<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Azure.Identity; using Azure.ResourceManager.Resources; using Azure.ResourceManager.Resources.Models; using Calamari.AzureAppService.Azure; using Calamari.AzureAppService.Behaviors; using Calamari.AzureAppService.Json; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.Helpers; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.Rest; using Newtonsoft.Json; using NUnit.Framework; using Polly.Retry; namespace Calamari.AzureAppService.Tests { [TestFixture] public class LegacyAppServiceSettingsBehaviorFixture { private string clientId; private string clientSecret; private string tenantId; private string subscriptionId; private string webappName; private string resourceGroupName; private string slotName; private StringDictionary existingSettings; private ConnectionStringDictionary existingConnectionStrings; private ResourceGroupsOperations resourceGroupClient; private string authToken; private WebSiteManagementClient webMgmtClient; private Site site; private RetryPolicy retryPolicy; [OneTimeSetUp] public async Task Setup() { retryPolicy = RetryPolicyFactory.CreateForHttp429(); var resourceManagementEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ResourceManagementEndPoint) ?? DefaultVariables.ResourceManagementEndpoint; var activeDirectoryEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ActiveDirectoryEndPoint) ?? DefaultVariables.ActiveDirectoryEndpoint; resourceGroupName = Guid.NewGuid().ToString(); clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); var resourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? "eastus"; authToken = await Auth.GetAuthTokenAsync(tenantId, clientId, clientSecret, resourceManagementEndpointBaseUri, activeDirectoryEndpointBaseUri); var resourcesClient = new ResourcesManagementClient(subscriptionId, new ClientSecretCredential(tenantId, clientId, clientSecret)); resourceGroupClient = resourcesClient.ResourceGroups; var resourceGroup = new ResourceGroup(resourceGroupLocation); resourceGroup = await resourceGroupClient.CreateOrUpdateAsync(resourceGroupName, resourceGroup); webMgmtClient = new WebSiteManagementClient(new TokenCredentials(authToken)) { SubscriptionId = subscriptionId, HttpClient = { BaseAddress = new Uri(DefaultVariables.ResourceManagementEndpoint) }, }; var svcPlan = await retryPolicy.ExecuteAsync(async () => await webMgmtClient.AppServicePlans.BeginCreateOrUpdateAsync(resourceGroup.Name, resourceGroup.Name, new AppServicePlan(resourceGroup.Location))); site = await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.BeginCreateOrUpdateAsync(resourceGroup.Name, resourceGroup.Name, new Site(resourceGroup.Location) { ServerFarmId = svcPlan.Id })); existingSettings = new StringDictionary { Properties = new Dictionary<string, string> { { "ExistingSetting", "Foo" }, { "ReplaceSetting", "Foo" } } }; existingConnectionStrings = new ConnectionStringDictionary { Properties = new Dictionary<string, ConnStringValueTypePair> { { "ExistingConnectionString", new ConnStringValueTypePair("ConnectionStringValue", ConnectionStringType.SQLAzure) }, { "ReplaceConnectionString", new ConnStringValueTypePair("originalConnectionStringValue", ConnectionStringType.Custom) } } }; await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.UpdateConnectionStringsAsync(resourceGroupName, site.Name, existingConnectionStrings)); webappName = site.Name; } [OneTimeTearDown] public async Task CleanupCode() { await resourceGroupClient.StartDeleteAsync(resourceGroupName); } [Test] public async Task TestSiteAppSettings() { await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.UpdateApplicationSettingsWithHttpMessagesAsync(resourceGroupName, site.Name, existingSettings)); await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.UpdateConnectionStringsAsync(resourceGroupName, site.Name, existingConnectionStrings)); var iVars = new CalamariVariables(); AddVariables(iVars); var runningContext = new RunningDeployment("", iVars); iVars.Add("Greeting", "Calamari"); var appSettings = BuildAppSettingsJson(new[] { ("MyFirstAppSetting", "Foo", true), ("MySecondAppSetting", "bar", false), ("ReplaceSetting", "Bar", false) }); iVars.Add(SpecialVariables.Action.Azure.AppSettings, appSettings.json); await new LegacyAzureAppServiceSettingsBehaviour(new InMemoryLog()).Execute(runningContext); await AssertAppSettings(appSettings.setting, new ConnectionStringDictionary()); } [Test] public async Task TestSiteConnectionStrings() { await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.UpdateApplicationSettingsWithHttpMessagesAsync(resourceGroupName, site.Name, existingSettings)); await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.UpdateConnectionStringsAsync(resourceGroupName, site.Name, existingConnectionStrings)); var iVars = new CalamariVariables(); AddVariables(iVars); var runningContext = new RunningDeployment("", iVars); iVars.Add("Greeting", "Calamari"); var connectionStrings = BuildConnectionStringJson(new[] { ("ReplaceConnectionString", "replacedConnectionStringValue", ConnectionStringType.SQLServer, false), ("NewConnectionString", "newValue", ConnectionStringType.SQLAzure, false), ("ReplaceSlotConnectionString", "replacedSlotConnectionStringValue", ConnectionStringType.MySql, true) }); iVars.Add(SpecialVariables.Action.Azure.ConnectionStrings, connectionStrings.json); await new LegacyAzureAppServiceSettingsBehaviour(new InMemoryLog()).Execute(runningContext); await AssertAppSettings(new AppSetting[] { }, connectionStrings.connStrings); } [Test] public async Task TestSlotSettings() { var slotName = "stage"; this.slotName = slotName; await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.BeginCreateOrUpdateSlotAsync(resourceGroupName, resourceGroupName, site, slotName)); var existingSettingsTask = retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.UpdateApplicationSettingsSlotWithHttpMessagesAsync(resourceGroupName, site.Name, existingSettings, slotName)); var iVars = new CalamariVariables(); AddVariables(iVars); var runningContext = new RunningDeployment("", iVars); iVars.Add("Greeting", slotName); iVars.Add("Octopus.Action.Azure.DeploymentSlot", slotName); var settings = BuildAppSettingsJson(new[] { ("FirstSetting", "Foo", true), ("MySecondAppSetting", "Baz", false), ("MyDeploySlotSetting", slotName, false), ("ReplaceSetting", "Foo", false) }); var connectionStrings = BuildConnectionStringJson(new[] { ("NewKey", "newConnStringValue", ConnectionStringType.Custom, false), ("ReplaceConnectionString", "ChangedConnectionStringValue", ConnectionStringType.SQLServer, false), ("newSlotConnectionString", "ChangedConnectionStringValue", ConnectionStringType.SQLServer, true), ("ReplaceSlotConnectionString", "ChangedSlotConnectionStringValue", ConnectionStringType.Custom, true) }); iVars.Add(SpecialVariables.Action.Azure.AppSettings, settings.json); iVars.Add(SpecialVariables.Action.Azure.ConnectionStrings, connectionStrings.json); await existingSettingsTask; await new LegacyAzureAppServiceSettingsBehaviour(new InMemoryLog()).Execute(runningContext); await AssertAppSettings(settings.setting, connectionStrings.connStrings); } private void AddVariables(CalamariVariables vars) { vars.Add(AccountVariables.ClientId, clientId); vars.Add(AccountVariables.Password, clientSecret); vars.Add(AccountVariables.TenantId, tenantId); vars.Add(AccountVariables.SubscriptionId, subscriptionId); vars.Add("Octopus.Action.Azure.ResourceGroupName", resourceGroupName); vars.Add("Octopus.Action.Azure.WebAppName", webappName); } private (string json, IEnumerable<AppSetting> setting) BuildAppSettingsJson(IEnumerable<(string name, string value, bool isSlotSetting)> settings) { var appSettings = settings.Select(setting => new AppSetting { Name = setting.name, Value = setting.value, SlotSetting = setting.isSlotSetting }); return (JsonConvert.SerializeObject(appSettings), appSettings); } private (string json, ConnectionStringDictionary connStrings) BuildConnectionStringJson( IEnumerable<(string name, string value, ConnectionStringType type, bool isSlotSetting)> connStrings) { var connections = connStrings.Select(connstring => new LegacyConnectionStringSetting { Name = connstring.name, Value = connstring.value, Type = connstring.type, SlotSetting = connstring.isSlotSetting }); var connectionsDict = new ConnectionStringDictionary { Properties = new Dictionary<string, ConnStringValueTypePair>() }; foreach (var item in connStrings) { connectionsDict.Properties[item.name] = new ConnStringValueTypePair(item.value, item.type); } return (JsonConvert.SerializeObject(connections), connectionsDict); } async Task AssertAppSettings(IEnumerable<AppSetting> expectedAppSettings, ConnectionStringDictionary expectedConnStrings) { // Update existing settings with new replacement values var expectedSettingsArray = expectedAppSettings as AppSetting[] ?? expectedAppSettings.ToArray(); foreach (var (name, value, _) in expectedSettingsArray.Where(x => existingSettings.Properties.ContainsKey(x.Name))) { existingSettings.Properties[name] = value; } if (expectedConnStrings?.Properties != null && expectedConnStrings.Properties.Any()) { foreach (var item in expectedConnStrings.Properties) { existingConnectionStrings.Properties[item.Key] = item.Value; } } // for each existing setting that isn't defined in the expected settings object, add it var expectedSettingsList = expectedSettingsArray.ToList(); expectedSettingsList.AddRange(existingSettings.Properties .Where(x => expectedSettingsArray.All(y => y.Name != x.Key)) .Select(kvp => new AppSetting { Name = kvp.Key, Value = kvp.Value, SlotSetting = false })); // Get the settings from the webapp var targetSite = new AzureTargetSite(subscriptionId, resourceGroupName, webappName, slotName); var settings = await AppSettingsManagement.GetAppSettingsAsync(webMgmtClient, authToken, targetSite); var connStrings = await AppSettingsManagement.GetConnectionStringsAsync(webMgmtClient, targetSite); CollectionAssert.AreEquivalent(expectedSettingsList, settings); foreach (var item in connStrings.Properties) { var existingItem = existingConnectionStrings.Properties[item.Key]; Assert.AreEqual(existingItem.Value, item.Value.Value); Assert.AreEqual(existingItem.Type, item.Value.Type); } //CollectionAssert.AreEquivalent(existingConnectionStrings.Properties, connStrings.Properties); } } }<file_sep>using System; Console.WriteLine("Hello " + Octopus.Parameters["Name"]); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calamari.Integration.Nginx { public static class NginxDirectives { public static string Include = "include"; public static class Server { public static string Listen = "listen"; public static string HostName = "server_name"; public static string Certificate = "ssl_certificate"; public static string CertificateKey = "ssl_certificate_key"; public static string SecurityProtocols = "ssl_protocols"; public static string SslCiphers = "ssl_ciphers"; } public static class Location { public static class Proxy { public static string Url = "proxy_pass"; public static string SetHeader = "proxy_set_header"; } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Calamari.Common.Plumbing.ServiceMessages; using Octopus.Diagnostics; namespace Calamari.Testing.LogParser { public enum TestExecutionOutcome { Successful = 1, Cancelled = 2, TimeOut = 3, Unsuccessful = 4 } public class TestOutputVariable { public TestOutputVariable(string name, string? value, bool isSensitive = false) { Name = name; Value = value; IsSensitive = isSensitive; } public string Name { get; } public string? Value { get; } public bool IsSensitive { get; } } public class TestOutputVariableCollection : ICollection<TestOutputVariable>, IReadOnlyDictionary<string, TestOutputVariable> { readonly Dictionary<string, TestOutputVariable> items = new Dictionary<string, TestOutputVariable>(StringComparer.OrdinalIgnoreCase); public int Count => items.Count; public void Add(TestOutputVariable item) { items.Add(item.Name, item); } public bool ContainsKey(string name) { return items.ContainsKey(name); } public bool TryGetValue(string name, out TestOutputVariable value) { return items.TryGetValue(name, out value); } public TestOutputVariable this[string name] { get => items[name]; set => items[name] = value; } public IEnumerable<string> Keys => items.Keys; public IEnumerable<TestOutputVariable> Values => items.Values; public void Clear() { items.Clear(); } bool ICollection<TestOutputVariable>.Contains(TestOutputVariable item) { return items.ContainsKey(item.Name); } public void CopyTo(TestOutputVariable[] array, int arrayIndex) { throw new System.NotImplementedException(); } bool ICollection<TestOutputVariable>.Remove(TestOutputVariable item) { return items.Remove(item.Name); } IEnumerator<TestOutputVariable> IEnumerable<TestOutputVariable>.GetEnumerator() { return GetEnumerator(); } IEnumerator<KeyValuePair<string, TestOutputVariable>> IEnumerable<KeyValuePair<string, TestOutputVariable>>.GetEnumerator() { return items.GetEnumerator(); } IEnumerator<TestOutputVariable> GetEnumerator() { return items.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } bool ICollection<TestOutputVariable>.IsReadOnly => false; } public class TestScriptOutputAction { public TestScriptOutputAction(string name, IDictionary<string, string> properties) { Name = name; Properties = properties; } public string Name { get; } public IDictionary<string, string> Properties { get; } public bool ContainsPropertyWithValue(string propertyName) { return Properties.ContainsKey(propertyName) && !string.IsNullOrEmpty(Properties[propertyName]); } public bool ContainsPropertyWithGuid(string propertyName) { return ContainsPropertyWithValue(propertyName) && IsGuid(propertyName); } bool IsGuid(string propertyName) { return Guid.TryParse(Properties[propertyName], out _); } public string[] GetStrings(params string[] propertyNames) { var values = Properties.Where(x => propertyNames.Contains(x.Key)) .Select(x => x.Value) .ToList(); if (!values.Any()) { return new string[0]; } var allValues = new List<string>(); foreach (var v in values.Where(v => !string.IsNullOrWhiteSpace(v))) { allValues.AddRange(v.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries).Select(_ => _.Trim())); } return allValues.ToArray(); } } public class ScriptOutputFilter { readonly CalamariInMemoryTaskLog log; readonly ServiceMessageParser parser; readonly Action<string> nullTarget = s => { }; readonly TestOutputVariableCollection testOutputVariables = new TestOutputVariableCollection(); readonly List<CollectedArtifact> artifacts = new List<CollectedArtifact>(); readonly List<FoundPackage> foundPackages = new List<FoundPackage>(); readonly List<ServiceMessage> serviceMessages = new List<ServiceMessage>(); readonly Action<string> debugTarget; Action<string> outputTarget; Action<string> errorTarget; readonly List<TestScriptOutputAction> actions = new List<TestScriptOutputAction>(); readonly List<string> supportedScriptActionNames = new List<string>(); readonly Action<int, string> progressTarget; public ScriptOutputFilter(CalamariInMemoryTaskLog log) { this.log = log; DeltaPackageVerifcation = null; DeltaPackageError = null; ResultMessage = null; parser = new ServiceMessageParser(WritePlainText, ServiceMessage); debugTarget = log.Verbose; outputTarget = log.Info; errorTarget = log.Error; PopulateSupportedScriptActionNames(); progressTarget = log.UpdateProgress; } /// <summary> /// A copy of the collection of service messages that were recorded as part of the /// script execution. /// </summary> public List<ServiceMessage> ServiceMessages => new List<ServiceMessage>(serviceMessages); public bool CalamariFoundPackage { get; set; } public TestOutputVariableCollection TestOutputVariables => testOutputVariables; public List<CollectedArtifact> Artifacts => artifacts; public List<FoundPackage> FoundPackages => foundPackages; public List<TestScriptOutputAction> Actions => actions; public DeltaPackage? DeltaPackageVerifcation { get; set; } public string? DeltaPackageError { get; set; } public string? ResultMessage { get; private set; } public void Write(IEnumerable<ProcessOutput> output) { foreach (var line in output) { parser.Append(line.Source, line.Text); parser.Finish(); } } public void Write(ProcessOutputSource source, string text) { parser.Append(source, text); parser.Finish(); } void WritePlainText(ProcessOutputSource source, string text) { switch (source) { case ProcessOutputSource.Debug: debugTarget(text); break; case ProcessOutputSource.StdOut: outputTarget(text); break; case ProcessOutputSource.StdErr: errorTarget(text); break; } } void ServiceMessage(ServiceMessage serviceMessage) { serviceMessages.Add(serviceMessage); switch (serviceMessage.Name) { case ScriptServiceMessageNames.StdErrBehavior.Ignore: errorTarget = nullTarget; break; case ScriptServiceMessageNames.StdErrBehavior.Default: case ScriptServiceMessageNames.StdErrBehavior.Error: errorTarget = log.Error; break; case ScriptServiceMessageNames.StdErrBehavior.Progress: errorTarget = log.Verbose; break; case ScriptServiceMessageNames.SetVariable.Name: { var name = serviceMessage.GetValue(ScriptServiceMessageNames.SetVariable.NameAttribute); var value = serviceMessage.GetValue(ScriptServiceMessageNames.SetVariable.ValueAttribute); bool.TryParse(serviceMessage.GetValue(ScriptServiceMessageNames.SetVariable.SensitiveAttribute), out var isSensitive); if (name != null && value != null) { testOutputVariables[name] = new TestOutputVariable(name, value, isSensitive); if (isSensitive) { // If we're adding a sensitive output-variable we need to add it to the log-context // so it will be masked. log.WithSensitiveValue(value); } } break; } case ScriptServiceMessageNames.Progress.Name: { var message = serviceMessage.GetValue(ScriptServiceMessageNames.Progress.Message); if (message != null && int.TryParse(serviceMessage.GetValue(ScriptServiceMessageNames.Progress.Percentage), out int percentage)) progressTarget(percentage, message); break; } case ScriptServiceMessageNames.CreateArtifact.Name: { var name = serviceMessage.GetValue(ScriptServiceMessageNames.CreateArtifact.NameAttribute); var path = serviceMessage.GetValue(ScriptServiceMessageNames.CreateArtifact.PathAttribute); long.TryParse(serviceMessage.GetValue(ScriptServiceMessageNames.CreateArtifact.LengthAttribute), out long length); if (name != null) { artifacts.Add(new CollectedArtifact(name, path) {Length = length}); } break; } case ScriptServiceMessageNames.ResultMessage.Name: ResultMessage = serviceMessage.GetValue(ScriptServiceMessageNames.ResultMessage.MessageAttribute); break; case ScriptServiceMessageNames.CalamariFoundPackage.Name: CalamariFoundPackage = true; break; case ScriptServiceMessageNames.FoundPackage.Name: var id = serviceMessage.GetValue(ScriptServiceMessageNames.FoundPackage.IdAttribute); var version = serviceMessage.GetValue(ScriptServiceMessageNames.FoundPackage.VersionAttribute); var versionFormat = serviceMessage.GetValue(ScriptServiceMessageNames.FoundPackage.VersionFormat); var hash = serviceMessage.GetValue(ScriptServiceMessageNames.FoundPackage.HashAttribute); var remotePath = serviceMessage.GetValue(ScriptServiceMessageNames.FoundPackage.RemotePathAttribute); var fileExtension = serviceMessage.GetValue(ScriptServiceMessageNames.FoundPackage.FileExtensionAttribute); if (id != null && version != null) { foundPackages.Add(new FoundPackage(id, version, versionFormat, remotePath, hash, fileExtension)); } break; case ScriptServiceMessageNames.PackageDeltaVerification.Name: var deltaVerificationRemotePath = serviceMessage.GetValue(ScriptServiceMessageNames.PackageDeltaVerification.RemotePathAttribute); var deltaVerificationHash = serviceMessage.GetValue(ScriptServiceMessageNames.PackageDeltaVerification.HashAttribute); var deltaVerificationSize = serviceMessage.GetValue(ScriptServiceMessageNames.PackageDeltaVerification.SizeAttribute); DeltaPackageError = serviceMessage.GetValue(ScriptServiceMessageNames.PackageDeltaVerification.Error); if (deltaVerificationRemotePath != null && deltaVerificationHash != null) { DeltaPackageVerifcation = new DeltaPackage(deltaVerificationRemotePath, deltaVerificationHash, long.Parse(deltaVerificationSize)); } break; case ScriptServiceMessageNames.StdOutBehaviour.Default: outputTarget = log.Info; break; case ScriptServiceMessageNames.StdOutBehaviour.Error: outputTarget = log.Error; break; case ScriptServiceMessageNames.StdOutBehaviour.Ignore: outputTarget = nullTarget; break; case ScriptServiceMessageNames.StdOutBehaviour.Verbose: outputTarget = log.Verbose; break; case ScriptServiceMessageNames.StdOutBehaviour.Warning: outputTarget = log.Warn; break; case ScriptServiceMessageNames.StdOutBehaviour.Highlight: outputTarget = s => log.Write(LogCategory.Highlight, s); break; case ScriptServiceMessageNames.StdOutBehaviour.Wait: outputTarget = s => log.Write(LogCategory.Wait, s); break; default: // check to see if it is a support action name if (supportedScriptActionNames.Contains(serviceMessage.Name)) { actions.Add(new TestScriptOutputAction(serviceMessage.Name, serviceMessage.Properties)); } break; } } public void Finish() { parser.Finish(); } void PopulateSupportedScriptActionNames() { if (supportedScriptActionNames.Any()) return; var actionNames = GetAllFieldValues( typeof(ScriptServiceMessageNames.ScriptOutputActions), x => Attribute.IsDefined(x, typeof(ServiceMessageNameAttribute))) .Select(x => x.ToString()); supportedScriptActionNames.AddRange(actionNames); } static IEnumerable<object> GetAllFieldValues(Type t, Func<FieldInfo, bool> filter) { var values = new List<object>(); var fields = t.GetFields(); values.AddRange(fields.Where(filter).Select(x => x.GetValue(null))); var nestedTypes = t.GetNestedTypes(); foreach (var nestedType in nestedTypes) { values.AddRange(GetAllFieldValues(nestedType, filter)); } return values; } } }<file_sep>using System.IO; using System.Xml.Linq; using System.Xml.XPath; using Calamari.Common.Features.ConfigurationVariables; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.ConfigurationVariables { [TestFixture] public class ConfigurationVariablesFixture : CalamariFixture { ConfigurationVariablesReplacer configurationVariablesReplacer; CalamariVariables variables; [SetUp] public void SetUp() { variables = new CalamariVariables(); configurationVariablesReplacer = new ConfigurationVariablesReplacer(variables, new InMemoryLog()); } [Test] public void DoesNotAddXmlHeader() { variables.Set("WelcomeMessage", "Hello world"); variables.Set("LogFile", "C:\\Log.txt"); variables.Set("DatabaseConnection", null); var text = PerformTest(GetFixtureResource("Samples", "NoHeader.config"), variables); Assert.That(text, Does.StartWith("<configuration")); } [Test] public void SupportsNamespaces() { variables.Set("WelcomeMessage", "Hello world"); variables.Set("LogFile", "C:\\Log.txt"); variables.Set("DatabaseConnection", null); var text = PerformTest(GetFixtureResource("Samples","CrazyNamespace.config"), variables); var contents = XDocument.Parse(text); Assert.AreEqual("Hello world", contents.XPathSelectElement("//*[local-name()='appSettings']/*[local-name()='add'][@key='WelcomeMessage']").Attribute("value").Value); Assert.AreEqual("C:\\Log.txt", contents.XPathSelectElement("//*[local-name()='appSettings']/*[local-name()='add'][@key='LogFile']").Attribute("value").Value); Assert.AreEqual("", contents.XPathSelectElement("//*[local-name()='appSettings']/*[local-name()='add'][@key='DatabaseConnection']").Attribute("value").Value); } [Test] public void ReplacesAppSettings() { variables.Set("WelcomeMessage", "Hello world"); variables.Set("LogFile", "C:\\Log.txt"); variables.Set("DatabaseConnection", null); var text = PerformTest(GetFixtureResource("Samples", "App.config"), variables); var contents = XDocument.Parse(text); Assert.AreEqual("Hello world", contents.XPathSelectElement("//appSettings/add[@key='WelcomeMessage']").Attribute("value").Value); Assert.AreEqual("C:\\Log.txt", contents.XPathSelectElement("//appSettings/add[@key='LogFile']").Attribute("value").Value); Assert.AreEqual("", contents.XPathSelectElement("//appSettings/add[@key='DatabaseConnection']").Attribute("value").Value); } [Test] public void ReplacesStronglyTypedAppSettings() { variables.Set("WelcomeMessage", "Hello world"); variables.Set("LogFile", "C:\\Log.txt"); variables.Set("DatabaseConnection", null); var text = PerformTest(GetFixtureResource("Samples", "StrongTyped.config"), variables); var contents = XDocument.Parse(text); Assert.AreEqual("Hello world", contents.XPathSelectElement("//AppSettings.Properties.Settings/setting[@name='WelcomeMessage']/value").Value); } [Test] public void ReplacesConnectionStrings() { variables.Set("MyDb1", "Server=foo"); variables.Set("MyDb2", "Server=bar&bar=123"); var text = PerformTest(GetFixtureResource("Samples", "App.config"), variables); var contents = XDocument.Parse(text); Assert.AreEqual("Server=foo", contents.XPathSelectElement("//connectionStrings/add[@name='MyDb1']").Attribute("connectionString").Value); Assert.AreEqual("Server=bar&bar=123", contents.XPathSelectElement("//connectionStrings/add[@name='MyDb2']").Attribute("connectionString").Value); } [Test] [ExpectedException(typeof (System.Xml.XmlException))] public void ShouldThrowExceptionForBadConfig() { PerformTest(GetFixtureResource("Samples", "Bad.config"), variables); } [Test] public void ShouldSuppressExceptionForBadConfig_WhenFlagIsSet() { variables.AddFlag(KnownVariables.Package.IgnoreVariableReplacementErrors, true); configurationVariablesReplacer = new ConfigurationVariablesReplacer(variables, new InMemoryLog()); PerformTest(GetFixtureResource("Samples", "Bad.config"), variables); } string PerformTest(string sampleFile, IVariables variables) { var temp = Path.GetTempFileName(); File.Copy(sampleFile, temp, true); using (new TemporaryFile(temp)) { configurationVariablesReplacer.ModifyConfigurationFile(temp, variables); return File.ReadAllText(temp); } } } } <file_sep>using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Model; namespace Calamari.Deployment.PackageRetention.Caching { public class LeastFrequentlyUsedJournalEntry { public JournalEntry Entry { get; } public CacheAge Age { get; } public int HitCount { get; } public int NewerVersionCount { get; } public LeastFrequentlyUsedJournalEntry(JournalEntry entry, CacheAge age, int hitCount, int newerVersionCount) { Entry = entry; Age = age; HitCount = hitCount; NewerVersionCount = newerVersionCount; } } }<file_sep>using System; using System.Collections.Generic; using System.IO.Compression; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Calamari.ConsolidateCalamariPackages { class Hasher : IDisposable { private readonly MD5 md5 = MD5.Create(); public string GetPackageCombinationHash(string assemblyVersion, IReadOnlyList<IPackageReference> packagesToScan) { var uniqueString = string.Join(",", packagesToScan.OrderBy(p => p.Name).Select(p => p.Name + p.Version)); uniqueString += assemblyVersion; return Hash(uniqueString); } public string Hash(ZipArchiveEntry entry) { using (var entryStream = entry.Open()) return BitConverter.ToString(md5.ComputeHash(entryStream)).Replace("-", "").ToLower(); } public string Hash(string str) => Hash(Encoding.UTF8.GetBytes(str)); public string Hash(byte[] bytes) => BitConverter.ToString(md5.ComputeHash(bytes)).Replace("-", "").ToLower(); public void Dispose() => md5?.Dispose(); } }<file_sep>using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class Deployment : Resource { public override string ChildKind => "ReplicaSet"; public int UpToDate { get; } public string Ready { get; } public int Available { get; } [JsonIgnore] public int Desired { get; } [JsonIgnore] public int TotalReplicas { get; } [JsonIgnore] public int ReadyReplicas { get; } public Deployment(JObject json, Options options) : base(json, options) { ReadyReplicas = FieldOrDefault("$.status.readyReplicas", 0); Desired = FieldOrDefault("$.spec.replicas", 0); TotalReplicas = FieldOrDefault("$.status.replicas", 0); Ready = $"{ReadyReplicas}/{Desired}"; Available = FieldOrDefault("$.status.availableReplicas", 0); UpToDate = FieldOrDefault("$.status.updatedReplicas", 0); ResourceStatus = TotalReplicas == Desired && UpToDate == Desired && Available == Desired && ReadyReplicas == Desired ? ResourceStatus.Successful : ResourceStatus.InProgress; } public override void UpdateChildren(IEnumerable<Resource> children) { base.UpdateChildren(children); var foundReplicas = Children ?.SelectMany(child => child?.Children ?? Enumerable.Empty<Resource>()) .Count() ?? 0; ResourceStatus = foundReplicas != Desired ? ResourceStatus.InProgress : ResourceStatus; } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<Deployment>(lastStatus); return last.ResourceStatus != ResourceStatus || last.UpToDate != UpToDate || last.Ready != Ready || last.Available != Available; } } }<file_sep>#!/bin/bash Octopus_Azure_Environment=$(get_octopusvariable "Octopus.Action.Azure.Environment") Octopus_Azure_ADClientId=$(get_octopusvariable "Octopus.Action.Azure.ClientId") Octopus_Azure_ADPassword=$(get_octopusvariable "Octopus.Action.Azure.Password") Octopus_Azure_ADTenantId=$(get_octopusvariable "Octopus.Action.Azure.TenantId") Octopus_Azure_SubscriptionId=$(get_octopusvariable "Octopus.Action.Azure.SubscriptionId") function check_app_exists { command -v $1 > /dev/null 2>&1 if [[ $? -ne 0 ]]; then echo >&2 "The executable $1 does not exist, or is not on the PATH." echo >&2 "See https://g.octopushq.com/TBD for more information." exit 1 fi } function setup_context { { # Config directory is set to make sure that our security is right for the step running it # and not using the one in the default config dir to avoid issues with user defined ones export AZURE_CONFIG_DIR="$OctopusCalamariWorkingDirectory/azure-cli" mkdir -p $AZURE_CONFIG_DIR # The azure extensions directory is getting overridden above when we set the azure config dir (undocumented behavior). # Set the azure extensions directory to the value of $OctopusAzureExtensionsDirectory if specified, # otherwise, back to the default value of $HOME/.azure/cliextension. if [ -n "$OctopusAzureExtensionsDirectory" ] then echo "Setting Azure CLI extensions directory to $OctopusAzureExtensionsDirectory" export AZURE_EXTENSION_DIR="$OctopusAzureExtensionsDirectory" else export AZURE_EXTENSION_DIR="$HOME/.azure/cliextensions" fi # authenticate with the Azure CLI echo "##octopus[stdout-verbose]" az cloud set --name ${Octopus_Azure_Environment:-"AzureCloud"} 2>null 3>null echo "Azure CLI: Authenticating with Service Principal" loginArgs=() # Use the full argument because of https://github.com/Azure/azure-cli/issues/12105 loginArgs+=("--username=$Octopus_Azure_ADClientId") loginArgs+=("--password=$<PASSWORD>") loginArgs+=("--tenant=$Octopus_Azure_ADTenantId") echo az login --service-principal ${loginArgs[@]} # Note: Need to double quote the loginArgs here to ensure that spaces aren't treated as separate arguments # It also seems like putting double quotes around each individual argument makes az cli include the " # character as part of the input causing issues... az login --service-principal "${loginArgs[@]}" echo "Azure CLI: Setting active subscription to $Octopus_Azure_SubscriptionId" az account set --subscription $Octopus_Azure_SubscriptionId echo "##octopus[stdout-default]" write_verbose "Successfully authenticated with the Azure CLI" } || { # failed to authenticate with Azure CLI echo "Failed to authenticate with Azure CLI" exit 1 } } echo "##octopus[stdout-verbose]" check_app_exists az setup_context OctopusAzureTargetScript=$(get_octopusvariable "OctopusAzureTargetScript") OctopusAzureTargetScriptParameters=$(get_octopusvariable "OctopusAzureTargetScriptParameters") echo "Invoking target script \"$OctopusAzureTargetScript\" with $OctopusAzureTargetScriptParameters parameters" echo "##octopus[stdout-default]" source "$OctopusAzureTargetScript" $OctopusAzureTargetScriptParameters || exit 1 : { az logout 2>null 3>null }<file_sep>using System.IO; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Conventions { public class ExecuteScriptConvention : IInstallConvention { private readonly IScriptEngine scriptEngine; private readonly ICommandLineRunner commandLineRunner; public ExecuteScriptConvention(IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) { this.scriptEngine = scriptEngine; this.commandLineRunner = commandLineRunner; } public void Install(RunningDeployment deployment) { var variables = deployment.Variables; var scriptFile = Path.Combine(deployment.CurrentDirectory, variables.Get(ScriptVariables.ScriptFileName)); var scriptParameters = variables.Get(SpecialVariables.Action.Script.ScriptParameters); Log.VerboseFormat("Executing '{0}'", scriptFile); var result = scriptEngine.Execute(new Script(scriptFile, scriptParameters), variables, commandLineRunner, deployment.EnvironmentVariables); var exitCode = result.ExitCode == 0 && result.HasErrors && variables.GetFlag(SpecialVariables.Action.FailScriptOnErrorOutput) ? -1 : result.ExitCode; Log.SetOutputVariable(SpecialVariables.Action.Script.ExitCode, exitCode.ToString(), variables); } } }<file_sep>#nullable enable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Calamari.AzureAppService.Json; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.Rest; using Newtonsoft.Json; namespace Calamari.AzureAppService { public static class AppSettingsManagement { public static async Task<IEnumerable<AppSetting>> GetAppSettingsAsync(WebSiteManagementClient webAppClient, string authToken, AzureTargetSite targetSite) { var webAppSettings = await webAppClient.WebApps.ListApplicationSettingsAsync(targetSite); var slotSettings = (await GetSlotSettingsListAsync(webAppClient, authToken, targetSite)).ToArray(); return webAppSettings.Properties.Select( setting => new AppSetting { Name = setting.Key, Value = setting.Value, SlotSetting = slotSettings.Any(x => x == setting.Key) }).ToList(); } /// <summary> /// Patches (add or update) the app settings for a web app or slot using the website management client library extensions. /// If any setting needs to be marked sticky (slot setting), update it via <see cref="PutSlotSettingsListAsync"/>. /// </summary> /// <param name="webAppClient">A <see cref="WebSiteManagementClient"/> that is directly used to update app settings.<seealso cref="WebSiteManagementClientExtensions"/></param> /// <param name="targetSite">The target site containing the resource group name, site and (optional) site name</param> /// <param name="appSettings">A <see cref="StringDictionary"/> containing the app settings to set</param> /// <returns>Awaitable <see cref="Task"/></returns> public static async Task PutAppSettingsAsync(WebSiteManagementClient webAppClient, StringDictionary appSettings, AzureTargetSite targetSite) { await webAppClient.WebApps.UpdateApplicationSettingsAsync(targetSite, appSettings); } /// <summary> /// Puts (overwrite) List of setting names who's values should be sticky (slot settings). /// </summary> /// <param name="webAppClient">The <see cref="WebSiteManagementClient"/> that will be used to submit the new list</param> /// <param name="targetSite">The target site containing the resource group name, site and (optional) site name</param> /// <param name="slotConfigNames">collection of setting names to be marked as sticky (slot setting)</param> /// <param name="authToken">The authorization token used to authenticate the request</param> /// <returns>Awaitable <see cref="Task"/></returns> public static async Task PutSlotSettingsListAsync(WebSiteManagementClient webAppClient, AzureTargetSite targetSite, IEnumerable<string> slotConfigNames, string authToken) { var client = webAppClient.HttpClient; client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var targetUrl = $"https://management.azure.com/subscriptions/{webAppClient.SubscriptionId}/resourceGroups/{targetSite.ResourceGroupName}/providers/Microsoft.Web/sites/{targetSite.Site}/config/slotconfignames?api-version=2018-11-01"; var slotSettingsJson = new appSettingNamesRoot {properties = new properties {appSettingNames = slotConfigNames}, name = targetSite.Site}; var postBody = JsonConvert.SerializeObject(slotSettingsJson); //var body = new StringContent(postBody); var body = new StringContent(postBody, Encoding.UTF8, "application/json"); var response = await client.PutAsync(targetUrl, body); if (!response.IsSuccessStatusCode) { throw new HttpRequestException(response.ReasonPhrase); } } /// <summary> /// Gets list of existing sticky (slot settings) /// </summary> /// <param name="webAppClient">The <see cref="WebSiteManagementClient"/> that will be used to submit the get request</param> /// <param name="targetSite">The <see cref="AzureTargetSite"/> that will represents the web app's resource group, name and (optionally) slot that is being deployed to</param> /// <returns>Collection of setting names that are sticky (slot setting)</returns> public static async Task<IEnumerable<string>> GetSlotSettingsListAsync(WebSiteManagementClient webAppClient, string authToken, AzureTargetSite targetSite) { var client = webAppClient.HttpClient; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); var targetUrl = $"{client.BaseAddress}/subscriptions/{webAppClient.SubscriptionId}/resourceGroups/{targetSite.ResourceGroupName}/providers/Microsoft.Web/sites/{targetSite.Site}/config/slotconfignames?api-version=2018-11-01"; var results = await client.GetStringAsync(targetUrl); var output = JsonConvert.DeserializeObject<appSettingNamesRoot>(results).properties.appSettingNames ?? new List<string>(); return output; } public static async Task<ConnectionStringDictionary> GetConnectionStringsAsync( WebSiteManagementClient webAppClient, AzureTargetSite targetSite) { var conStringDict = await webAppClient.WebApps.ListConnectionStringsAsync(targetSite); return conStringDict; } } } <file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Calamari.Common.Util; namespace Calamari.AzureServiceFabric.Behaviours { class DeployAzureServiceFabricAppBehaviour : IDeployBehaviour { readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly ICalamariEmbeddedResources embeddedResources; readonly IScriptEngine scriptEngine; readonly ICommandLineRunner commandLineRunner; public DeployAzureServiceFabricAppBehaviour( ILog log, ICalamariFileSystem fileSystem, ICalamariEmbeddedResources embeddedResources, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) { this.log = log; this.fileSystem = fileSystem; this.embeddedResources = embeddedResources; this.scriptEngine = scriptEngine; this.commandLineRunner = commandLineRunner; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var variables = context.Variables; // Set output variables for our script to access. log.SetOutputVariable("PublishProfileFile", variables.Get(SpecialVariables.Action.ServiceFabric.PublishProfileFile, "PublishProfiles\\Cloud.xml"), variables); log.SetOutputVariable("DeployOnly", variables.Get(SpecialVariables.Action.ServiceFabric.DeployOnly, defaultValue: false.ToString()), variables); log.SetOutputVariable("UnregisterUnusedApplicationVersionsAfterUpgrade", variables.Get(SpecialVariables.Action.ServiceFabric.UnregisterUnusedApplicationVersionsAfterUpgrade, defaultValue: false.ToString()), variables); log.SetOutputVariable("OverrideUpgradeBehavior", variables.Get(SpecialVariables.Action.ServiceFabric.OverrideUpgradeBehavior, defaultValue: "None"), variables); log.SetOutputVariable("OverwriteBehavior", variables.Get(SpecialVariables.Action.ServiceFabric.OverwriteBehavior, defaultValue: "SameAppTypeAndVersion"), variables); log.SetOutputVariable("SkipPackageValidation", variables.Get(SpecialVariables.Action.ServiceFabric.SkipPackageValidation, defaultValue: false.ToString()), variables); log.SetOutputVariable("CopyPackageTimeoutSec", variables.Get(SpecialVariables.Action.ServiceFabric.CopyPackageTimeoutSec, defaultValue: 0.ToString()), variables); SetRegisterApplicationTypeTimeout(variables); // Package should have been extracted to the staging dir (as per the ExtractPackageToStagingDirectoryConvention). var targetPath = Path.Combine(Environment.CurrentDirectory, "staging"); log.SetOutputVariable("ApplicationPackagePath", targetPath, variables); if (context.Variables.GetFlag(SpecialVariables.Action.ServiceFabric.LogExtractedApplicationPackage)) LogExtractedPackage(context.CurrentDirectory); // The user may supply the script, to override behaviour. var scriptFile = Path.Combine(context.CurrentDirectory, "DeployToServiceFabric.ps1"); if (!fileSystem.FileExists(scriptFile)) { // Use our bundled version. fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText(GetType().Assembly, $"{GetType().Assembly.GetName().Name}.Scripts.DeployAzureServiceFabricApplication.ps1")); } var result = scriptEngine.Execute(new Script(scriptFile), context.Variables, commandLineRunner); fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure); if (result.ExitCode != 0) { throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile, result.ExitCode)); } return this.CompletedTask(); } void SetRegisterApplicationTypeTimeout(IVariables variables) { var registerAppTypeTimeout = variables.Get(SpecialVariables.Action.ServiceFabric.RegisterApplicationTypeTimeoutSec); if (registerAppTypeTimeout != null) { log.SetOutputVariable("RegisterApplicationTypeTimeoutSec", registerAppTypeTimeout, variables); } } void LogExtractedPackage(string workingDirectory) { log.Verbose("Service Fabric extracted. Working directory contents:"); DirectoryLoggingHelper.LogDirectoryContents(log, fileSystem, workingDirectory, "", 0); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class AlreadyInstalledConventionFixture { JournalEntry previous; IDeploymentJournal journal; IVariables variables; [SetUp] public void SetUp() { journal = Substitute.For<IDeploymentJournal>(); journal.GetLatestInstallation(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).Returns(_ => previous); variables = new CalamariVariables(); } [Test] public void ShouldSkipIfInstalled() { variables.Set(KnownVariables.Package.SkipIfAlreadyInstalled, true.ToString()); previous = new JournalEntry("123", "tenant", "env", "proj", "rp01", DateTime.Now, "C:\\App", "C:\\MyApp", true, new List<DeployedPackage>{new DeployedPackage("pkg", "0.0.9", "C:\\PackageOld.nupkg")}); RunConvention(); Assert.That(variables.Get(KnownVariables.Action.SkipJournal), Is.EqualTo("true")); } [Test] public void ShouldOnlySkipIfSpecified() { previous = new JournalEntry("123", "tenant", "env", "proj", "rp01", DateTime.Now, "C:\\App", "C:\\MyApp", true, new List<DeployedPackage>{new DeployedPackage("pkg", "0.0.9", "C:\\PackageOld.nupkg")}); RunConvention(); Assert.That(variables.Get(KnownVariables.Action.SkipJournal), Is.Null); } [Test] public void ShouldNotSkipIfPreviouslyFailed() { variables.Set(KnownVariables.Package.SkipIfAlreadyInstalled, true.ToString()); previous = new JournalEntry("123", "tenant", "env", "proj", "rp01", DateTime.Now, "C:\\App", "C:\\MyApp", false, new List<DeployedPackage>{new DeployedPackage("pkg", "0.0.9", "C:\\PackageOld.nupkg")}); RunConvention(); Assert.That(variables.Get(KnownVariables.Action.SkipJournal), Is.Null); } void RunConvention() { var convention = new AlreadyInstalledConvention(new InMemoryLog(), journal); convention.Install(new RunningDeployment("C:\\Package.nupkg", variables)); } } }<file_sep>using Calamari.Common.Plumbing.FileSystem; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class DeployPackageWithScriptsFixture : DeployPackageFixture { private const string ServiceName = "Acme.Package"; [SetUp] public override void SetUp() { base.SetUp(); } [Test] public void ShouldSkipRemainingConventions() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, "1.0.0"))) { var result = DeployPackage(file.FilePath); result.AssertSuccess(); //Post Deploy should not run. result.AssertNoOutput("hello from post-deploy"); } } [TearDown] public override void CleanUp() { base.CleanUp(); } } }<file_sep>using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; namespace Calamari.Tests.Fixtures.Integration.Scripting { public abstract class ScriptEngineFixtureBase { protected CalamariVariables GetVariables() { var cd = new CalamariVariables(); cd.Set("foo", "bar"); cd.Set("mysecrect", "KingKong"); return cd; } protected CalamariResult ExecuteScript(IScriptExecutor psse, string scriptName, IVariables variables) { var runner = new TestCommandLineRunner(new InMemoryLog(), variables); var result = psse.Execute(new Script(scriptName), variables, runner); return new CalamariResult(result.ExitCode, runner.Output); } } } <file_sep>using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo("Calamari.AzureResourceGroup.Tests")]<file_sep>using System; using System.Globalization; using System.IO; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Testing; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; using Octopus.Versioning; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.PackageDownload { [TestFixture] public class PackageDownloadFixture : CalamariFixture { static readonly string TentacleHome = TestEnvironment.GetTestPath("Fixtures", "PackageDownload"); static readonly string DownloadPath = TestEnvironment.GetTestPath(TentacleHome, "Files"); static readonly string PublicFeedUri = "https://f.feedz.io/octopus-deploy/integration-tests/nuget/index.json"; static readonly string NuGetFeedUri = "https://www.nuget.org/api/v2/"; private static readonly string AuthFeedUri = ExternalVariables.Get(ExternalVariable.MyGetFeedUrl); private static readonly string AuthFeedUsername = ExternalVariables.Get(ExternalVariable.MyGetFeedUsername); private static readonly string AuthFeedPassword = ExternalVariables.Get(ExternalVariable.MyGetFeedPassword); static readonly string ExpectedPackageHash = "1e0856338eb5ada3b30903b980cef9892ebf7201"; static readonly long ExpectedPackageSize = 3749; static readonly SampleFeedPackage FeedzPackage = new SampleFeedPackage() { Id = "feeds-feedz", Version = new SemanticVersion("1.0.0"), PackageId = "OctoConsole" }; static readonly SampleFeedPackage FileShare = new SampleFeedPackage() { Id = "feeds-local", Version = new SemanticVersion(1, 0, 0), PackageId = "Acme.Web" }; static readonly SampleFeedPackage NuGetFeed = new SampleFeedPackage() { Id = "feeds-nuget", Version = new SemanticVersion(2, 1, 0), PackageId = "abp.castle.log4net" }; static readonly string ExpectedMavenPackageHash = "3564ef3803de51fb0530a8377ec6100b33b0d073"; static readonly long ExpectedMavenPackageSize = 2575022; static readonly string MavenPublicFeedUri = "https://repo.maven.apache.org/maven2/"; static readonly SampleFeedPackage MavenPublicFeed = new SampleFeedPackage("#") { Id = "feeds-maven", Version = VersionFactory.CreateMavenVersion("22.0"), PackageId = "com.google.guava:guava" }; static readonly string MavenSnapshotPublicFeedUri = "https://oss.sonatype.org/content/repositories/snapshots/"; // If this version is no longer available go to https://oss.sonatype.org/#view-repositories;releases~browseindex // In the bottom panel, expand Releases -> com -> google -> guava and find whatever the latest Snapshot version is // Also update the hash and size static readonly SampleFeedPackage MavenSnapshotPublicFeed = new SampleFeedPackage("#") { Id = "feeds-maven", Version = VersionFactory.CreateMavenVersion("24.0-SNAPSHOT"), PackageId = "com.google.guava:guava" }; static readonly string ExpectedMavenSnapshotPackageHash = "425932eacd1450c4c4c32b9ed8a1d9b397f20082"; static readonly long ExpectedMavenSnapshotPackageSize = 2621686; [SetUp] public void SetUp() { if (!Directory.Exists(TentacleHome)) Directory.CreateDirectory(TentacleHome); Directory.SetCurrentDirectory(TentacleHome); Environment.SetEnvironmentVariable("TentacleHome", TentacleHome); Console.WriteLine("TentacleHome is set to: " + TentacleHome); } [TearDown] public void TearDown() { if (Directory.Exists(DownloadPath)) Directory.Delete(DownloadPath, true); Environment.SetEnvironmentVariable("TentacleHome", null); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void ShouldDownloadPackage() { var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri); result.AssertSuccess(); result.AssertOutput("Downloading NuGet package {0} v{1} from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, PublicFeedUri); result.AssertOutput("Downloaded package will be stored in: '{0}'", FeedzPackage.DownloadFolder); AssertPackageHashMatchesExpected(result, ExpectedPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedPackageSize); AssertStagePackageOutputVariableSet(result, FeedzPackage); result.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, PublicFeedUri); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresNonFreeBSDPlatform] public void ShouldDownloadMavenPackage() { if (CalamariEnvironment.IsRunningOnMac && TestEnvironment.IsCI && !CalamariEnvironment.IsRunningOnMono) Assert.Inconclusive("As of November 2018, this test is failing under dotnet core on the cloudmac under teamcity - we were getting an error 'SSL connect error' when trying to download from 'https://repo.maven.apache.org/maven2/'. Marking as inconclusive so we can re-enable the build - it had been disabled for months :("); var result = DownloadPackage( MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven); result.AssertSuccess(); result.AssertOutput("Downloading Maven package {0} v{1} from feed: '{2}'", MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeedUri); result.AssertOutput("Downloaded package will be stored in: '{0}'", MavenPublicFeed.DownloadFolder); result.AssertOutput("Found package {0} v{1}", MavenPublicFeed.PackageId, MavenPublicFeed.Version); AssertPackageHashMatchesExpected(result, ExpectedMavenPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedMavenPackageSize); AssertStagePackageOutputVariableSet(result, MavenPublicFeed); result.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeedUri); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresNonFreeBSDPlatform] public void ShouldDownloadMavenSnapshotPackage() { if (CalamariEnvironment.IsRunningOnMac && TestEnvironment.IsCI && !CalamariEnvironment.IsRunningOnMono) Assert.Inconclusive("As of November 2018, this test is failing under dotnet core on the cloudmac under teamcity - we were getting an error 'SSL connect error' when trying to download from 'https://repo.maven.apache.org/maven2/'. Marking as inconclusive so we can re-enable the build - it had been disabled for months :("); var result = DownloadPackage( MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven); result.AssertSuccess(); result.AssertOutput("Downloading Maven package {0} v{1} from feed: '{2}'", MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeedUri); result.AssertOutput("Downloaded package will be stored in: '{0}'", MavenPublicFeed.DownloadFolder); result.AssertOutput("Found package {0} v{1}", MavenPublicFeed.PackageId, MavenPublicFeed.Version); AssertPackageHashMatchesExpected(result, ExpectedMavenPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedMavenPackageSize); AssertStagePackageOutputVariableSet(result, MavenPublicFeed); result.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeedUri); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void ShouldDownloadPackageWithRepositoryMetadata() { var result = DownloadPackage(NuGetFeed.PackageId, NuGetFeed.Version.ToString(), NuGetFeed.Id, NuGetFeedUri); result.AssertSuccess(); result.AssertOutput( $"Downloading NuGet package {NuGetFeed.PackageId} v{NuGetFeed.Version} from feed: '{NuGetFeedUri}'"); result.AssertOutput($"Downloaded package will be stored in: '{NuGetFeed.DownloadFolder}"); AssertStagePackageOutputVariableSet(result, NuGetFeed); result.AssertOutput($"Package {NuGetFeed.PackageId} v{NuGetFeed.Version} successfully downloaded from feed: '{NuGetFeedUri}'"); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void ShouldUsePackageFromCache() { DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri) .AssertSuccess(); var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", FeedzPackage.PackageId, FeedzPackage.Version); result.AssertOutputMatches(string.Format("Package was found in cache\\. No need to download. Using file: '{0}'", PackageName.ToRegexPattern(FeedzPackage.PackageId, FeedzPackage.Version, FeedzPackage.DownloadFolder))); AssertPackageHashMatchesExpected(result, ExpectedPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedPackageSize); AssertStagePackageOutputVariableSet(result, FeedzPackage); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresNonFreeBSDPlatform] public void ShouldUseMavenPackageFromCache() { if (CalamariEnvironment.IsRunningOnMac && TestEnvironment.IsCI && !CalamariEnvironment.IsRunningOnMono) Assert.Inconclusive("As of November 2018, this test is failing under dotnet core on the cloudmac under teamcity - we were getting an error 'SSL connect error' when trying to download from 'https://repo.maven.apache.org/maven2/'. Marking as inconclusive so we can re-enable the build - it had been disabled for months :("); DownloadPackage(MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven) .AssertSuccess(); var result = DownloadPackage(MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", MavenPublicFeed.PackageId, MavenPublicFeed.Version); result.AssertOutputMatches(string.Format("Package was found in cache\\. No need to download. Using file: '{0}'", PackageName.ToRegexPattern(MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeed.DownloadFolder))); AssertPackageHashMatchesExpected(result, ExpectedMavenPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedMavenPackageSize); AssertStagePackageOutputVariableSet(result, MavenPublicFeed); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresNonFreeBSDPlatform] public void ShouldUseMavenSnapshotPackageFromCache() { if (CalamariEnvironment.IsRunningOnMac && TestEnvironment.IsCI && !CalamariEnvironment.IsRunningOnMono) Assert.Inconclusive("As of November 2018, this test is failing under dotnet core on the cloudmac under teamcity - we were getting an error 'SSL connect error' when trying to download from 'https://repo.maven.apache.org/maven2/'. Marking as inconclusive so we can re-enable the build - it had been disabled for months :("); DownloadPackage(MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven) .AssertSuccess(); var result = DownloadPackage(MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", MavenPublicFeed.PackageId, MavenPublicFeed.Version); result.AssertOutputMatches($"Package was found in cache\\. No need to download. Using file: '{PackageName.ToRegexPattern(MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeed.DownloadFolder)}'"); AssertPackageHashMatchesExpected(result, ExpectedMavenPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedMavenPackageSize); AssertStagePackageOutputVariableSet(result, MavenPublicFeed); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void ShouldByPassCacheAndDownloadPackage() { DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri).AssertSuccess(); var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri, forcePackageDownload: true); result.AssertSuccess(); result.AssertOutput("Downloading NuGet package {0} v{1} from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, PublicFeedUri); result.AssertOutput("Downloaded package will be stored in: '{0}'", FeedzPackage.DownloadFolder); AssertPackageHashMatchesExpected(result, ExpectedPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedPackageSize); AssertStagePackageOutputVariableSet(result, FeedzPackage); result.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, PublicFeedUri); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresNonFreeBSDPlatform] public void ShouldByPassCacheAndDownloadMavenPackage() { if (CalamariEnvironment.IsRunningOnMac && TestEnvironment.IsCI && !CalamariEnvironment.IsRunningOnMono) Assert.Inconclusive("As of November 2018, this test is failing under dotnet core on the cloudmac under teamcity - we were getting an error 'SSL connect error' when trying to download from 'https://repo.maven.apache.org/maven2/'. Marking as inconclusive so we can re-enable the build - it had been disabled for months :("); var firstDownload = DownloadPackage( MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, versionFormat: VersionFormat.Maven, feedType: FeedType.Maven); firstDownload.AssertSuccess(); var secondDownload = DownloadPackage( MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven, forcePackageDownload: true); secondDownload.AssertSuccess(); secondDownload.AssertOutput("Downloading Maven package {0} v{1} from feed: '{2}'", MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeedUri); secondDownload.AssertOutput("Downloaded package will be stored in: '{0}'", MavenPublicFeed.DownloadFolder); secondDownload.AssertOutput("Found package {0} v{1}", MavenPublicFeed.PackageId, MavenPublicFeed.Version); AssertPackageHashMatchesExpected(secondDownload, ExpectedMavenPackageHash); AssertPackageSizeMatchesExpected(secondDownload, ExpectedMavenPackageSize); AssertStagePackageOutputVariableSet(secondDownload, MavenPublicFeed); secondDownload.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeedUri); } [Test] [RequiresMonoVersion480OrAboveForTls12] [RequiresNonFreeBSDPlatform] public void ShouldByPassCacheAndDownloadMavenSnapshotPackage() { var firstDownload = DownloadPackage( MavenSnapshotPublicFeed.PackageId, MavenSnapshotPublicFeed.Version.ToString(), MavenSnapshotPublicFeed.Id, MavenSnapshotPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven); firstDownload.AssertSuccess(); var secondDownload = DownloadPackage( MavenSnapshotPublicFeed.PackageId, MavenSnapshotPublicFeed.Version.ToString(), MavenSnapshotPublicFeed.Id, MavenSnapshotPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven, forcePackageDownload: true); secondDownload.AssertSuccess(); secondDownload.AssertOutput("Downloading Maven package {0} v{1} from feed: '{2}'", MavenSnapshotPublicFeed.PackageId, MavenSnapshotPublicFeed.Version, MavenSnapshotPublicFeedUri); secondDownload.AssertOutput("Downloaded package will be stored in: '{0}'", MavenSnapshotPublicFeed.DownloadFolder); secondDownload.AssertOutput("Found package {0} v{1}", MavenSnapshotPublicFeed.PackageId, MavenSnapshotPublicFeed.Version); AssertPackageHashMatchesExpected(secondDownload, ExpectedMavenSnapshotPackageHash); AssertPackageSizeMatchesExpected(secondDownload, ExpectedMavenSnapshotPackageSize); AssertStagePackageOutputVariableSet(secondDownload, MavenSnapshotPublicFeed); secondDownload.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", MavenSnapshotPublicFeed.PackageId, MavenSnapshotPublicFeed.Version, MavenSnapshotPublicFeedUri); } [Test] [Ignore("Auth Feed Failing On Mono")] public void PrivateNuGetFeedShouldDownloadPackage() { var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, AuthFeedUri, AuthFeedUsername, AuthFeedPassword); result.AssertSuccess(); result.AssertOutput("Downloading NuGet package {0} v{1} from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, AuthFeedUri); result.AssertOutput("Downloaded package will be stored in: '{0}'", FeedzPackage.DownloadFolder); #if USE_NUGET_V2_LIBS result.AssertOutput("Found package {0} v{1}", FeedzPackage.PackageId, FeedzPackage.Version); #endif AssertPackageHashMatchesExpected(result, ExpectedPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedPackageSize); AssertStagePackageOutputVariableSet(result, FeedzPackage); result.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, AuthFeedUri); } [Test] [Ignore("Auth Feed Failing On Mono")] public void PrivateNuGetFeedShouldUsePackageFromCache() { DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, AuthFeedUri, AuthFeedUsername, AuthFeedPassword) .AssertSuccess(); var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, AuthFeedUri, AuthFeedUsername, AuthFeedPassword); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", FeedzPackage.PackageId, FeedzPackage.Version); result.AssertOutputMatches($"Package was found in cache\\. No need to download. Using file: '{PackageName.ToRegexPattern(FeedzPackage.PackageId, FeedzPackage.Version, FeedzPackage.DownloadFolder)}'"); AssertPackageHashMatchesExpected(result, ExpectedPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedPackageSize); AssertStagePackageOutputVariableSet(result, FeedzPackage); } [Test] [Ignore("Auth Feed Failing On Mono")] public void PrivateNuGetFeedShouldByPassCacheAndDownloadPackage() { DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, AuthFeedUri, AuthFeedUsername, AuthFeedPassword).AssertSuccess(); var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, AuthFeedUri, AuthFeedUsername, AuthFeedPassword, forcePackageDownload: true); result.AssertSuccess(); result.AssertOutput("Downloading NuGet package {0} v{1} from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, AuthFeedUri); result.AssertOutput("Downloaded package will be stored in: '{0}'", FeedzPackage.DownloadFolder); #if USE_NUGET_V2_LIBS result.AssertOutput("Found package {0} v{1}", FeedzPackage.PackageId, FeedzPackage.Version); #endif AssertPackageHashMatchesExpected(result, ExpectedPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedPackageSize); AssertStagePackageOutputVariableSet(result, FeedzPackage); result.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, AuthFeedUri); } [Test] [Ignore("Auth Feed Failing On Mono")] public void PrivateNuGetFeedShouldFailDownloadPackageWhenInvalidCredentials() { var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, AuthFeedUri, "fake-feed-username", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); result.AssertFailure(); result.AssertOutput("Downloading NuGet package {0} v{1} from feed: '{2}'", FeedzPackage.PackageId, FeedzPackage.Version, AuthFeedUri); result.AssertOutput("Downloaded package will be stored in: '{0}'", FeedzPackage.DownloadFolder); result.AssertErrorOutput("Unable to download package: The remote server returned an error: (401) Unauthorized."); } [Test] public void FileShareFeedShouldDownloadPackage() { using (var acmeWeb = CreateSamplePackage()) { var result = DownloadPackage(FileShare.PackageId, FileShare.Version.ToString(), FileShare.Id, acmeWeb.DirectoryPath); result.AssertSuccess(); result.AssertOutput("Downloading NuGet package {0} v{1} from feed: '{2}'", FileShare.PackageId, FileShare.Version, new Uri(acmeWeb.DirectoryPath)); result.AssertOutput("Downloaded package will be stored in: '{0}'", FileShare.DownloadFolder); result.AssertOutput("Found package {0} v{1}", FileShare.PackageId, FileShare.Version); AssertPackageHashMatchesExpected(result, acmeWeb.Hash); AssertPackageSizeMatchesExpected(result, acmeWeb.Size); AssertStagePackageOutputVariableSet(result, FileShare); result.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", FileShare.PackageId, FileShare.Version, acmeWeb.DirectoryPath); } } [Test] public void FileShareFeedShouldUsePackageFromCache() { using (var acmeWeb = CreateSamplePackage()) { DownloadPackage(FileShare.PackageId, FileShare.Version.ToString(), FileShare.Id, acmeWeb.DirectoryPath).AssertSuccess(); var result = DownloadPackage(FileShare.PackageId, FileShare.Version.ToString(), FileShare.Id, acmeWeb.DirectoryPath); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", FileShare.PackageId, FileShare.Version); result.AssertOutputMatches($"Package was found in cache\\. No need to download. Using file: '{PackageName.ToRegexPattern(FileShare.PackageId, FileShare.Version, FileShare.DownloadFolder)}'"); AssertPackageHashMatchesExpected(result, acmeWeb.Hash); AssertPackageSizeMatchesExpected(result, acmeWeb.Size); AssertStagePackageOutputVariableSet(result, FileShare); } } [Test] public void FileShareFeedShouldByPassCacheAndDownloadPackage() { using (var acmeWeb = CreateSamplePackage()) { DownloadPackage(FileShare.PackageId, FileShare.Version.ToString(), FileShare.Id, acmeWeb.DirectoryPath) .AssertSuccess(); var result = DownloadPackage(FileShare.PackageId, FileShare.Version.ToString(), FileShare.Id, acmeWeb.DirectoryPath, forcePackageDownload: true); result.AssertSuccess(); result.AssertOutput("Downloading NuGet package {0} v{1} from feed: '{2}'", FileShare.PackageId, FileShare.Version, new Uri(acmeWeb.DirectoryPath)); result.AssertOutput("Downloaded package will be stored in: '{0}'", FileShare.DownloadFolder); result.AssertOutput("Found package {0} v{1}", FileShare.PackageId, FileShare.Version); AssertPackageHashMatchesExpected(result, acmeWeb.Hash); AssertPackageSizeMatchesExpected(result, acmeWeb.Size); AssertStagePackageOutputVariableSet(result, FileShare); result.AssertOutput("Package {0} v{1} successfully downloaded from feed: '{2}'", FileShare.PackageId, FileShare.Version, acmeWeb.DirectoryPath); } } [Test] public void FileShareFeedShouldFailDownloadPackageWhenInvalidFileShare() { using (var acmeWeb = CreateSamplePackage()) { var invalidFileShareUri = new Uri(Path.Combine(acmeWeb.DirectoryPath, "InvalidPath")); var result = DownloadPackage(FileShare.PackageId, FileShare.Version.ToString(), FileShare.Id, invalidFileShareUri.ToString()); result.AssertFailure(); result.AssertOutput("Downloading NuGet package {0} v{1} from feed: '{2}'", FileShare.PackageId, FileShare.Version, invalidFileShareUri); result.AssertErrorOutput("Failed to download package Acme.Web v1.0.0 from feed: '{0}'", invalidFileShareUri); result.AssertErrorOutput("Failed to download package {0} v{1} from feed: '{2}'", FileShare.PackageId, FileShare.Version, invalidFileShareUri); } } [Test] public void ShouldFailWhenNoPackageId() { var result = DownloadPackage("", FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri); result.AssertFailure(); result.AssertErrorOutput("No package ID was specified"); } [Test] public void ShouldFailWhenInvalidPackageId() { var invalidPackageId = string.Format("X{0}X", FeedzPackage.PackageId); var result = DownloadPackage(invalidPackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri); result.AssertFailure(); result.AssertErrorOutput("Failed to download package {0} v{1} from feed: '{2}'", invalidPackageId, FeedzPackage.Version, PublicFeedUri); } [Test] public void ShouldFailWhenNoFeedVersion() { var result = DownloadPackage(FeedzPackage.PackageId, "", FeedzPackage.Id, PublicFeedUri); result.AssertFailure(); result.AssertErrorOutput("No package version was specified"); } [Test] public void ShouldFailWhenInvalidFeedVersion() { const string invalidFeedVersion = "1.0.x"; var result = DownloadPackage(FeedzPackage.PackageId, invalidFeedVersion, FeedzPackage.Id, PublicFeedUri); result.AssertFailure(); result.AssertErrorOutput("Package version '{0}' specified is not a valid Semver version string", invalidFeedVersion); } [Test] public void ShouldFailWhenNoFeedId() { var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), "", PublicFeedUri); result.AssertFailure(); result.AssertErrorOutput("No feed ID was specified"); } [Test] public void ShouldFailWhenNoFeedUri() { var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, ""); result.AssertFailure(); result.AssertErrorOutput("No feed URI was specified"); } [Test] public void ShouldFailWhenInvalidFeedUri() { var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, "www.myget.org/F/octopusdeploy-tests"); result.AssertFailure(); result.AssertErrorOutput("URI specified 'www.myget.org/F/octopusdeploy-tests' is not a valid URI"); } [Test] [Ignore("for now, runs fine locally...not sure why it's not failing in TC, will investigate")] public void ShouldFailWhenUsernameIsSpecifiedButNoPassword() { var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri, AuthFeedUsername); result.AssertFailure(); result.AssertErrorOutput("A username was specified but no password was provided"); } CalamariResult DownloadPackage(string packageId, string packageVersion, string feedId, string feedUri, string feedUsername = "", string feedPassword = "", FeedType feedType = FeedType.NuGet, VersionFormat versionFormat = VersionFormat.Semver, bool forcePackageDownload = false, int attempts = 5, int attemptBackoffSeconds = 0) { var calamari = Calamari() .Action("download-package") .Argument("packageId", packageId) .Argument("packageVersion", packageVersion) .Argument("packageVersionFormat", versionFormat) .Argument("feedId", feedId) .Argument("feedUri", feedUri) .Argument("feedType", feedType) .Argument("attempts", attempts.ToString()) .Argument("attemptBackoffSeconds", attemptBackoffSeconds.ToString()); if (!String.IsNullOrWhiteSpace(feedUsername)) calamari.Argument("feedUsername", feedUsername); if (!String.IsNullOrWhiteSpace(feedPassword)) calamari.Argument("feedPassword", feedPassword); if (forcePackageDownload) calamari.Flag("forcePackageDownload"); return Invoke(calamari); } static void AssertPackageHashMatchesExpected(CalamariResult result, string expectedHash) { result.AssertOutputVariable("StagedPackage.Hash", Is.EqualTo(expectedHash)); } static void AssertPackageSizeMatchesExpected(CalamariResult result, long expectedSize) { result.AssertOutputVariable("StagedPackage.Size", Is.EqualTo(expectedSize.ToString(CultureInfo.InvariantCulture))); } static void AssertStagePackageOutputVariableSet(CalamariResult result, SampleFeedPackage testFeed) { var newPacakgeRegex = PackageName.ToRegexPattern(testFeed.PackageId, testFeed.Version, testFeed.DownloadFolder); result.AssertOutputVariable("StagedPackage.FullPathOnRemoteMachine", Does.Match(newPacakgeRegex + ".*")); } private TemporaryFile CreateSamplePackage() { return new TemporaryFile(PackageBuilder.BuildSamplePackage(FileShare.PackageId, FileShare.Version.ToString())); } class SampleFeedPackage { public SampleFeedPackage() { Delimiter = "."; } public SampleFeedPackage(string delimiter) { Delimiter = delimiter; } private string Delimiter { get; set; } public string Id { get; set; } public string PackageId { get; set; } public IVersion Version { get; set; } public string DownloadFolder => Path.Combine(DownloadPath, Id); } } } <file_sep>using System; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; using Calamari.Scripting; namespace Calamari.Commands { class ThrowScriptErrorIfNeededBehaviour : IOnFinishBehaviour { public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var exitCode = context.Variables.GetInt32(SpecialVariables.Action.Script.ExitCode); if (exitCode != 0) throw new CommandException($"Script returned non-zero exit code: {exitCode}."); return this.CompletedTask(); } } }<file_sep>using Autofac; using Calamari.Commands.Support; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using Autofac.Features.Metadata; using Calamari.Commands; using Calamari.Common; using Calamari.Common.Commands; using Calamari.Common.Features.Discovery; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment.PackageRetention; using Calamari.Integration.Certificates; using Calamari.Integration.FileSystem; using Calamari.Kubernetes.Commands.Discovery; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus; using Calamari.LaunchTools; using IContainer = Autofac.IContainer; #if !NET40 using Calamari.Aws.Deployment; using Calamari.Azure; using Calamari.Kubernetes.Commands.Executors; #endif namespace Calamari { public class Program : CalamariFlavourProgram { protected Program(ILog log) : base(log) { } public static int Main(string[] args) { return new Program(ConsoleLog.Instance).Execute(args); } public int Execute(params string[] args) { return Run(args); } protected override int ResolveAndExecuteCommand(IContainer container, CommonOptions options) { var commands = container.Resolve<IEnumerable<Meta<Lazy<ICommandWithArgs>, CommandMeta>>>(); var commandCandidates = commands.Where(x => x.Metadata.Name.Equals(options.Command, StringComparison.OrdinalIgnoreCase)).ToArray(); if (commandCandidates.Length == 0) throw new CommandException($"Could not find the command {options.Command}"); if (commandCandidates.Length > 1) throw new CommandException($"Multiple commands found with the name {options.Command}"); return commandCandidates[0].Value.Value.Execute(options.RemainingArguments.ToArray()); } protected override void ConfigureContainer(ContainerBuilder builder, CommonOptions options) { base.ConfigureContainer(builder, options); builder.RegisterType<CalamariCertificateStore>().As<ICertificateStore>().SingleInstance(); builder.RegisterType<DeploymentJournalWriter>().As<IDeploymentJournalWriter>().SingleInstance(); builder.RegisterType<PackageStore>().As<IPackageStore>().SingleInstance(); #if !NET40 builder.RegisterType<ResourceRetriever>().As<IResourceRetriever>().SingleInstance(); builder.RegisterType<RunningResourceStatusCheck>().As<IRunningResourceStatusCheck>().SingleInstance(); builder.RegisterType<ResourceStatusCheckTask>().AsSelf(); builder.RegisterType<ResourceUpdateReporter>().As<IResourceUpdateReporter>().SingleInstance(); builder.RegisterType<ResourceStatusReportExecutor>().As<IResourceStatusReportExecutor>(); builder.RegisterType<GatherAndApplyRawYamlExecutor>().As<IGatherAndApplyRawYamlExecutor>(); builder.RegisterType<Timer>().As<ITimer>(); #endif builder.RegisterType<Kubectl>().AsSelf().As<IKubectl>().InstancePerLifetimeScope(); builder.RegisterType<KubectlGet>().As<IKubectlGet>().SingleInstance(); builder.RegisterType<KubernetesDiscovererFactory>() .As<IKubernetesDiscovererFactory>() .SingleInstance(); builder.RegisterInstance(SemaphoreFactory.Get()).As<ISemaphoreFactory>(); builder.RegisterModule<PackageRetentionModule>(); TypeDescriptor.AddAttributes(typeof(ServerTaskId), new TypeConverterAttribute(typeof(TinyTypeTypeConverter<ServerTaskId>))); //Add decorator to commands with the RetentionLockingCommand attribute. Also need to include commands defined in external assemblies. var assembliesToRegister = GetAllAssembliesToRegister().ToArray(); builder.RegisterAssemblyModules(assembliesToRegister); builder.RegisterAssemblyTypes(assembliesToRegister) .AssignableTo<IKubernetesDiscoverer>() .As<IKubernetesDiscoverer>(); //Register the non-decorated commands builder.RegisterAssemblyTypes(assembliesToRegister) .AssignableTo<ICommandWithArgs>() .WithMetadataFrom<CommandAttribute>() .As<ICommandWithArgs>(); builder.RegisterAssemblyTypes(assembliesToRegister) .AssignableTo<ICommandWithInputs>() .WithMetadataFrom<CommandAttribute>() .As<ICommandWithInputs>(); builder.RegisterAssemblyTypes(GetProgramAssemblyToRegister()) .Where(x => typeof(ILaunchTool).IsAssignableFrom(x) && !x.IsAbstract && !x.IsInterface) .WithMetadataFrom<LaunchToolAttribute>() .As<ILaunchTool>(); } IEnumerable<Assembly> GetExtensionAssemblies() { #if !NET40 //Calamari.Aws yield return typeof(AwsSpecialVariables).Assembly; //Calamari.Azure yield return typeof(ServicePrincipalAccount).Assembly; #else return Enumerable.Empty<Assembly>(); #endif } protected override IEnumerable<Assembly> GetAllAssembliesToRegister() { var assemblies = base.GetAllAssembliesToRegister(); foreach (var assembly in assemblies) { yield return assembly; } yield return typeof(ApplyDeltaCommand).Assembly; // Calamari.Shared var extensionAssemblies = GetExtensionAssemblies(); foreach (var extensionAssembly in extensionAssemblies) { yield return extensionAssembly; } } } }<file_sep>using System; namespace Calamari.Common.Plumbing.Proxies { public static class EnvironmentVariables { public const string TentacleProxyUsername = "TentacleProxyUsername"; public const string TentacleProxyPassword = "<PASSWORD>"; public const string TentacleProxyHost = "TentacleProxyHost"; public const string TentacleProxyPort = "TentacleProxyPort"; public const string TentacleUseDefaultProxy = "TentacleUseDefaultProxy"; } }<file_sep>using System; using Calamari.Common.Plumbing.Deployment; namespace Calamari.Common.Features.Packages { public interface IExtractPackage { void ExtractToCustomDirectory(PathToPackage? pathToPackage, string directory); void ExtractToStagingDirectory(PathToPackage? pathToPackage, IPackageExtractor? customPackageExtractor = null); void ExtractToStagingDirectory(PathToPackage? pathToPackage, string extractedToPathOutputVariableName); void ExtractToEnvironmentCurrentDirectory(PathToPackage pathToPackage); void ExtractToApplicationDirectory(PathToPackage pathToPackage, IPackageExtractor? customPackageExtractor = null); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Amazon.S3.Model; using Calamari.Aws.Integration.S3; using NUnit.Framework; using Octopus.CoreUtilities.Extensions; namespace Calamari.Tests.AWS.S3 { [TestFixture] public class S3ObjectExtensionsFixture { [Test] public void MetadataComparisonIsTrueWhenHeadersMatch() { var useHeaderValues = GetKnownSpecialKeyApplier(); PutObjectRequest request = new PutObjectRequest().Tee(r => { useHeaderValues(r.Headers); }); GetObjectMetadataResponse response = new GetObjectMetadataResponse().Tee(r => { useHeaderValues(r.Headers); }); var result = S3ObjectExtensions.MetadataEq(request.ToCombinedMetadata(), response.ToCombinedMetadata()); Assert.IsTrue(result, "Metadata was found to be not equal, but should match."); } [Test] public void MetadataComparisonPicksUpDifferencesInSpecialHeaders() { var useHeaderValues = GetKnownSpecialKeyApplier(); var useDifferentHeaderValues = GetKnownSpecialKeyApplier(); PutObjectRequest request = new PutObjectRequest().Tee(r => { useHeaderValues(r.Headers); }); GetObjectMetadataResponse response = new GetObjectMetadataResponse().Tee(r => { useDifferentHeaderValues(r.Headers); }); var result = S3ObjectExtensions.MetadataEq(request.ToCombinedMetadata(), response.ToCombinedMetadata()); Assert.IsFalse(result, "The comparison was found to be equal, however the special headers differ."); } [Test] public void MetadataComparisonIsPicksUpDifferenceInMetadataValues() { var useHeaderValues = GetKnownSpecialKeyApplier(); PutObjectRequest request = new PutObjectRequest().Tee(r => { useHeaderValues(r.Headers); r.Metadata.Add("Cowabunga", "Baby"); }); GetObjectMetadataResponse response = new GetObjectMetadataResponse().Tee(r => { useHeaderValues(r.Headers); r.Metadata.Add("Cowabunga", "Baby2"); }); var result = S3ObjectExtensions.MetadataEq(request.ToCombinedMetadata(), response.ToCombinedMetadata()); Assert.IsFalse(result, "Metadata comparison was found to be match, but should differ"); } [Test] public void MetadataComparisonIsPicksUpDifferenceInMetadataKeys() { var useHeaderValues = GetKnownSpecialKeyApplier(); PutObjectRequest request = new PutObjectRequest().Tee(r => { useHeaderValues(r.Headers); r.Metadata.Add("Meep Meep", "Baby2"); }); GetObjectMetadataResponse response = new GetObjectMetadataResponse().Tee(r => { useHeaderValues(r.Headers); r.Metadata.Add("Cowabunga", "Baby2"); }); var result = S3ObjectExtensions.MetadataEq(request.ToCombinedMetadata(), response.ToCombinedMetadata()); Assert.IsFalse(result, "Metadata comparison was found to be match, but should differ"); } [Test] public void MetadataComparisonIgnoresUnknownSpecialHeaders() { PutObjectRequest request = new PutObjectRequest().Tee(r => { r.Headers["Geppetto"] = "Pinocchio "; r.Metadata.Add("Cowabunga", "Baby"); }); GetObjectMetadataResponse response = new GetObjectMetadataResponse().Tee(r => { r.Headers["Crazy"] = "Town"; r.Metadata.Add("Cowabunga", "Baby"); }); var result = S3ObjectExtensions.MetadataEq(request.ToCombinedMetadata(), response.ToCombinedMetadata()); Assert.IsTrue(result, "Metadata was found to be equal, but should differ"); } private Action<HeadersCollection> GetKnownSpecialKeyApplier() { var keys = S3ObjectExtensions.GetKnownSpecialHeaderKeys().Select((x) => new KeyValuePair<string, string>(x, $"value-{Guid.NewGuid()}" )).ToList(); return (collection) => { foreach (var keyValuePair in keys) { collection[keyValuePair.Key] = keyValuePair.Value; } }; } } } <file_sep>using System.Threading.Tasks; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Fixtures; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] public class Helm3UpgradeFixture : HelmUpgradeFixture { [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void Upgrade_Succeeds() { var result = DeployPackage(); result.AssertSuccess(); result.AssertOutputMatches($"NAMESPACE: {Namespace}"); result.AssertOutputMatches("STATUS: deployed"); result.AssertOutputMatches($"release \"{ReleaseName}\" uninstalled"); result.AssertOutput("Using custom helm executable at " + HelmExePath); Assert.AreEqual(ReleaseName.ToLower(), result.CapturedOutput.OutputVariables["ReleaseName"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public async Task CustomHelmExeInPackage_RelativePath() { await TestCustomHelmExeInPackage_RelativePath("3.0.1"); } protected override string ExplicitExeVersion => "3.0.2"; } }<file_sep>using System; namespace Calamari.Common.Plumbing.Proxies { public static class ProxySettingsInitializer { public static IProxySettings GetProxySettingsFromEnvironment() { var proxyUsername = Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername); var proxyPassword = Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword); var proxyHost = Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost); var proxyPortText = Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort); int.TryParse(proxyPortText, out var proxyPort); var useCustomProxy = !string.IsNullOrWhiteSpace(proxyHost); if (useCustomProxy) return new UseCustomProxySettings( proxyHost, proxyPort, proxyUsername, proxyPassword ); if (!bool.TryParse(Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy), out var useDefaultProxy)) useDefaultProxy = true; if (useDefaultProxy) return new UseSystemProxySettings( proxyUsername, proxyPassword); return new BypassProxySettings(); } } }<file_sep>using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.Management.WebSites.Models; using Polly; using Polly.Retry; namespace Calamari.AzureAppService.Tests { public static class RetryPolicyFactory { public static RetryPolicy CreateForHttp429() { return Policy .Handle<DefaultErrorResponseException>(ex => (int)ex.Response.StatusCode == 429) .WaitAndRetryAsync(5, CalculateRetryDelay, (ex, ts, i, ctx) => Task.CompletedTask); } static TimeSpan CalculateRetryDelay(int retryAttempt, Exception ex, Context ctx) { //the azure API returns a Retry-After header that contains the number of seconds because you should try again //so we try and read that header if (ex is DefaultErrorResponseException responseException && responseException.Response.Headers.TryGetValue("Retry-After", out var values)) { var retryAfterValue = values.FirstOrDefault(); if (int.TryParse(retryAfterValue, out var secondsToRetryAfter)) return TimeSpan.FromSeconds(secondsToRetryAfter); } //fall back on just an exponential increase based on the retry attempt return TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)); } } }<file_sep>using System; Console.WriteLine("Parameters " + Env.ScriptArgs[0] + Env.ScriptArgs[1]); <file_sep>using System; namespace Calamari.Common.Features.Processes.Semaphores { public interface ICreateSemaphores { ISemaphore Create(string name, TimeSpan lockTimeout); } }<file_sep>using System; using System.Runtime.InteropServices; namespace Calamari.Common.Plumbing { public static class CalamariEnvironment { /// <summary> /// If/When we try executing this on another runtime we can 'tweak' this logic. /// The reccomended way to determine at runtime if executing within the mono framework /// http://www.mono-project.com/docs/gui/winforms/porting-winforms-applications/#runtime-conditionals /// </summary> public static readonly bool IsRunningOnMono = Type.GetType("Mono.Runtime") != null; /// <summary> /// Based on some internal methods used my mono itself /// https://github.com/mono/mono/blob/master/mcs/class/corlib/System/Environment.cs /// </summary> public static bool IsRunningOnNix => Environment.OSVersion.Platform == PlatformID.Unix && !IsRunningOnMac; public static bool IsRunningOnWindows => Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE; public static bool IsRunningOnMac { get { if (Environment.OSVersion.Platform == PlatformID.MacOSX) return true; if (Environment.OSVersion.Platform != PlatformID.Unix) return false; var buf = IntPtr.Zero; try { buf = Marshal.AllocHGlobal(8192); // Get sysname from uname () if (uname(buf) == 0) { var os = Marshal.PtrToStringAnsi(buf); if (os == "Darwin") return true; } } catch { // ignored } finally { if (buf != IntPtr.Zero) Marshal.FreeHGlobal(buf); } return false; } } //from https://github.com/jpobst/Pinta/blob/master/Pinta.Core/Managers/SystemManager.cs#L162 //(MIT license) [DllImport("libc")] //From Managed.Windows.Forms/XplatUI static extern int uname(IntPtr buf); } }<file_sep>using Azure.Identity; using Azure.ResourceManager.Resources; using Azure.ResourceManager.Resources.Models; using Calamari.AzureAppService.Behaviors; using Calamari.Common.Commands; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.Helpers; using FluentAssertions; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.Rest; using NUnit.Framework; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Polly.Retry; namespace Calamari.AzureAppService.Tests { [TestFixture] public class LegacyTargetDiscoveryBehaviourIntegrationTestFixture { private string clientId; private string clientSecret; private string tenantId; private string subscriptionId; private string resourceGroupName; private string authToken; private ResourceGroupsOperations resourceGroupClient; private WebSiteManagementClient webMgmtClient; private ResourceGroup resourceGroup; private AppServicePlan svcPlan; private string appName = Guid.NewGuid().ToString(); private List<string> slotNames = new List<string> { "blue", "green" }; private static readonly string Type = "Azure"; private static readonly string AccountId = "Accounts-1"; private static readonly string Role = "my-azure-app-role"; private static readonly string EnvironmentName = "dev"; private RetryPolicy retryPolicy; [OneTimeSetUp] public async Task Setup() { retryPolicy = RetryPolicyFactory.CreateForHttp429(); var resourceManagementEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ResourceManagementEndPoint) ?? DefaultVariables.ResourceManagementEndpoint; var activeDirectoryEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ActiveDirectoryEndPoint) ?? DefaultVariables.ActiveDirectoryEndpoint; resourceGroupName = Guid.NewGuid().ToString(); clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); var resourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? "eastus"; authToken = await Auth.GetAuthTokenAsync(tenantId, clientId, clientSecret, resourceManagementEndpointBaseUri, activeDirectoryEndpointBaseUri); var resourcesClient = new ResourcesManagementClient(subscriptionId, new ClientSecretCredential(tenantId, clientId, clientSecret)); resourceGroupClient = resourcesClient.ResourceGroups; resourceGroup = new ResourceGroup(resourceGroupLocation); resourceGroup = await resourceGroupClient.CreateOrUpdateAsync(resourceGroupName, resourceGroup); webMgmtClient = new WebSiteManagementClient(new TokenCredentials(authToken)) { SubscriptionId = subscriptionId, HttpClient = { BaseAddress = new Uri(DefaultVariables.ResourceManagementEndpoint), Timeout = TimeSpan.FromMinutes(5) }, }; svcPlan = await retryPolicy.ExecuteAsync(async () => await webMgmtClient.AppServicePlans.CreateOrUpdateAsync(resourceGroup.Name, resourceGroup.Name, new AppServicePlan(resourceGroup.Location) { Sku = new SkuDescription("S1", "Standard") } )); } [OneTimeTearDown] public async Task Cleanup() { if (resourceGroupClient != null) await resourceGroupClient.StartDeleteAsync(resourceGroupName); } [SetUp] public async Task CreateOrResetWebAppAndSlots() { // Call update on the web app and each slot without and tags // to reset it for each test. await CreateOrUpdateTestWebApp(); await CreateOrUpdateTestWebAppSlots(); } [Test] public async Task Execute_WebAppWithMatchingTags_CreatesCorrectTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); this.CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set expected tags on our web app var tags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, { TargetTags.RoleTagName, Role }, }; await CreateOrUpdateTestWebApp(tags); await Eventually.ShouldEventually(async () => { // Act await sut.Execute(context); // Assert var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(resourceGroupName, appName, AccountId, Role, null, null); var serviceMessageString = serviceMessageToCreateWebAppTarget.ToString(); log.StandardOut.Should().Contain(serviceMessageString); }, log, CancellationToken.None); } [Test] public async Task Execute_WebAppWithNonMatchingTags_CreatesNoTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); this.CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set expected tags on our web app var tags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, { TargetTags.RoleTagName, Role }, }; await CreateOrUpdateTestWebApp(tags); // Act await sut.Execute(context); // Assert var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(resourceGroupName, appName, AccountId, "a-different-role", null, null); log.StandardOut.Should().NotContain(serviceMessageToCreateWebAppTarget.ToString(), "The web app target should not be created as the role tag did not match"); } [Test] public async Task Execute_MultipleWebAppSlotsWithTags_WebAppHasNoTags_CreatesCorrectTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set expected tags on each slot of the web app but not the web app itself var tags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, { TargetTags.RoleTagName, Role }, }; await CreateOrUpdateTestWebAppSlots(tags); await Eventually.ShouldEventually(async () => { // Act await sut.Execute(context); var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(resourceGroupName, appName, AccountId, Role, null, null); log.StandardOut.Should().NotContain(serviceMessageToCreateWebAppTarget.ToString(), "A target should not be created for the web app itself, only for slots within the web app"); // Assert foreach (var slotName in slotNames) { var serviceMessageToCreateTargetForSlot = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(resourceGroupName, appName, AccountId, Role, null, slotName); log.StandardOut.Should().Contain(serviceMessageToCreateTargetForSlot.ToString()); } }, log, CancellationToken.None); } [Test] public async Task Execute_MultipleWebAppSlotsWithTags_WebAppWithTags_CreatesCorrectTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set expected tags on each slot of the web app AND the web app itself var tags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, { TargetTags.RoleTagName, Role }, }; await CreateOrUpdateTestWebApp(tags); await CreateOrUpdateTestWebAppSlots(tags); await Eventually.ShouldEventually(async () => { // Act await sut.Execute(context); var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(resourceGroupName, appName, AccountId, Role, null, null); log.StandardOut.Should().Contain(serviceMessageToCreateWebAppTarget.ToString(), "A target should be created for the web app itself as well as for the slots"); // Assert foreach (var slotName in slotNames) { var serviceMessageToCreateTargetForSlot = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(resourceGroupName, appName, AccountId, Role, null, slotName); log.StandardOut.Should().Contain(serviceMessageToCreateTargetForSlot.ToString()); } }, log, CancellationToken.None); } [Test] public async Task Execute_MultipleWebAppSlotsWithPartialTags_WebAppWithPartialTags_CreatesNoTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set partial tags on each slot of the web app AND the remaining ones on the web app itself var webAppTags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, }; var slotTags = new Dictionary<string, string> { { TargetTags.RoleTagName, Role }, }; await CreateOrUpdateTestWebApp(webAppTags); await CreateOrUpdateTestWebAppSlots(slotTags); await Eventually.ShouldEventually(async () => { // Act await sut.Execute(context); var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(resourceGroupName, appName, AccountId, Role, null, null); log.StandardOut.Should().NotContain(serviceMessageToCreateWebAppTarget.ToString(), "A target should not be created for the web app as the tags directly on the web app do not match, even though when combined with the slot tags they do"); // Assert foreach (var slotName in slotNames) { var serviceMessageToCreateTargetForSlot = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(resourceGroupName, appName, AccountId, Role, null, slotName); log.StandardOut.Should().NotContain(serviceMessageToCreateTargetForSlot.ToString(), "A target should not be created for the web app slot as the tags directly on the slot do not match, even though when combined with the web app tags they do"); } }, log, CancellationToken.None); } private async Task CreateOrUpdateTestWebApp(Dictionary<string, string> tags = null) { await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.CreateOrUpdateAsync( resourceGroupName, appName, new Site(resourceGroup.Location, tags: tags) { ServerFarmId = svcPlan.Id })); } private async Task CreateOrUpdateTestWebAppSlots(Dictionary<string, string> tags = null) { foreach (var slotName in slotNames) { await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.CreateOrUpdateSlotAsync( resourceGroup.Name, appName, new Site(resourceGroup.Location, tags: tags) { ServerFarmId = svcPlan.Id }, slotName)); } } private void CreateVariables(RunningDeployment context) { string targetDiscoveryContext = $@"{{ ""scope"": {{ ""spaceName"": ""default"", ""environmentName"": ""{EnvironmentName}"", ""projectName"": ""my-test-project"", ""tenantName"": null, ""roles"": [""{Role}""] }}, ""authentication"": {{ ""type"": ""{Type}"", ""accountId"": ""{AccountId}"", ""accountDetails"": {{ ""subscriptionNumber"": ""{subscriptionId}"", ""clientId"": ""{clientId}"", ""tenantId"": ""{tenantId}"", ""password"": ""{<PASSWORD>}"", ""azureEnvironment"": """", ""resourceManagementEndpointBaseUri"": """", ""activeDirectoryEndpointBaseUri"": """" }} }} }} "; context.Variables.Add("Octopus.TargetDiscovery.Context", targetDiscoveryContext); } } }<file_sep>using System; using System.Net; using Calamari.Common.Plumbing.Logging; namespace Calamari.Common.Plumbing { public static class SecurityProtocols { public static void EnableAllSecurityProtocols() { // TLS1.2 was required to access GitHub apis as of 22 Feb 2018. // https://developer.github.com/changes/2018-02-01-weak-crypto-removal-notice/ // TLS1.1 and below was discontinued on MavenCentral as of 18 June 2018 //https://central.sonatype.org/articles/2018/May/04/discontinue-support-for-tlsv11-and-below/ var securityProcotolTypes = #if HAS_SSL3 SecurityProtocolType.Ssl3 | #endif SecurityProtocolType.Tls; // Enum.IsDefined is used as even though it may be compiled against net40 which does not have the flag // if at runtime it runs on say net475 the flags are present if (Enum.IsDefined(typeof(SecurityProtocolType), 768)) securityProcotolTypes = securityProcotolTypes | (SecurityProtocolType)768; if (Enum.IsDefined(typeof(SecurityProtocolType), 3072)) securityProcotolTypes = securityProcotolTypes | (SecurityProtocolType)3072; else Log.Verbose($"TLS1.2 is not supported, this means that some outgoing connections to third party endpoints will not work as they now only support TLS1.2.{Environment.NewLine}This includes GitHub feeds and Maven feeds."); ServicePointManager.SecurityProtocol = securityProcotolTypes; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using Calamari.Aws.Deployment.Conventions; using Calamari.Aws.Integration.S3; using Calamari.CloudAccounts; using Calamari.Commands; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; namespace Calamari.Aws.Commands { [Command("upload-aws-s3", Description = "Uploads a package or package file(s) to an AWS s3 bucket")] public class UploadAwsS3Command : Command { readonly ILog log; readonly IVariables variables; readonly ICalamariFileSystem fileSystem; readonly ISubstituteInFiles substituteInFiles; readonly IExtractPackage extractPackage; readonly IStructuredConfigVariablesService structuredConfigVariablesService; PathToPackage pathToPackage; string bucket; string targetMode; public UploadAwsS3Command( ILog log, IVariables variables, ICalamariFileSystem fileSystem, ISubstituteInFiles substituteInFiles, IExtractPackage extractPackage, IStructuredConfigVariablesService structuredConfigVariablesService ) { this.log = log; this.variables = variables; this.fileSystem = fileSystem; this.substituteInFiles = substituteInFiles; this.extractPackage = extractPackage; this.structuredConfigVariablesService = structuredConfigVariablesService; Options.Add("package=", "Path to the package to extract that contains the package.", v => pathToPackage = new PathToPackage(Path.GetFullPath(v))); Options.Add("bucket=", "The bucket to use", v => bucket = v); Options.Add("targetMode=", "Whether the entire package or files within the package should be uploaded to the s3 bucket", v => targetMode = v); } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); if (string.IsNullOrEmpty(pathToPackage)) { throw new CommandException($"No package file was specified. Please provide `{TentacleVariables.CurrentDeployment.PackageFilePath}` variable"); } if (!fileSystem.FileExists(pathToPackage)) throw new CommandException("Could not find package file: " + pathToPackage); var environment = AwsEnvironmentGeneration.Create(log, variables).GetAwaiter().GetResult(); var bucketKeyProvider = new BucketKeyProvider(); var targetType = GetTargetMode(targetMode); var conventions = new List<IConvention> { new DelegateInstallConvention(d => extractPackage.ExtractToStagingDirectory(pathToPackage)), new LogAwsUserInfoConvention(environment), new CreateS3BucketConvention(environment, _ => bucket), new UploadAwsS3Convention( log, fileSystem, environment, bucket, targetType, new VariableS3TargetOptionsProvider(variables), bucketKeyProvider, substituteInFiles, structuredConfigVariablesService ) }; var deployment = new RunningDeployment(pathToPackage, variables); var conventionRunner = new ConventionProcessor(deployment, conventions, log); conventionRunner.RunConventions(); return 0; } private static S3TargetMode GetTargetMode(string value) { return Enum.TryParse<S3TargetMode>(value, out var result) ? result : S3TargetMode.EntirePackage; } } } <file_sep>using System; using System.Linq; using Newtonsoft.Json.Linq; namespace Calamari.Tests.Helpers { public static class KubernetesJsonResourceScrubber { public static string ScrubRawJson(string json, Func<JProperty, bool> propertiesToRemovePredicate) { var jObject = JObject.Parse(json); jObject.Descendants() .OfType<JProperty>() .Where(propertiesToRemovePredicate) .ToList() .ForEach(p => p.Remove()); return jObject.ToString(); } } }<file_sep>using System.Collections.Generic; using Calamari.Commands.Java; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; namespace Calamari.Deployment.Features.Java.Actions { public class JavaKeystoreAction: JavaAction { public JavaKeystoreAction(JavaRunner runner): base(runner) { } public override void Execute(RunningDeployment deployment) { var variables = deployment.Variables; Log.Info("Adding certificate to Java Keystore"); var certificateId = variables.Get(SpecialVariables.Action.Java.JavaKeystore.Variable); var envVariables = new Dictionary<string, string>(){ {"OctopusEnvironment_Java_Certificate_Variable", certificateId}, {"OctopusEnvironment_Java_Certificate_Password", variables.Get(SpecialVariables.Action.Java.JavaKeystore.Password)}, {"OctopusEnvironment_Java_Certificate_KeystoreFilename", variables.Get(SpecialVariables.Action.Java.JavaKeystore.KeystoreFilename)}, {"OctopusEnvironment_Java_Certificate_KeystoreAlias", variables.Get(SpecialVariables.Action.Java.JavaKeystore.KeystoreAlias)}, {"OctopusEnvironment_Java_Certificate_Private_Key", variables.Get(SpecialVariables.Certificate.PrivateKeyPem(certificateId))}, {"OctopusEnvironment_Java_Certificate_Public_Key", variables.Get(SpecialVariables.Certificate.CertificatePem(certificateId))}, {"OctopusEnvironment_Java_Certificate_Public_Key_Subject", variables.Get(SpecialVariables.Certificate.Subject(certificateId))}, }; runner.Run("com.octopus.calamari.keystore.KeystoreConfig", envVariables); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Integration.FileSystem; using Calamari.Tests.Fixtures.Util; using Calamari.Util; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; using Octostache; namespace Calamari.Tests.Fixtures.Variables { [TestFixture] public class VariableFactoryFixture { string tempDirectory; string firstInsensitiveVariablesFileName; string firstSensitiveVariablesFileName; string secondSensitiveVariablesFileName; ICalamariFileSystem fileSystem; CommonOptions options; const string encryptionPassword = "<PASSWORD>!"; [SetUp] public void SetUp() { tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); firstSensitiveVariablesFileName = Path.Combine(tempDirectory, "firstVariableSet.secret"); secondSensitiveVariablesFileName = Path.Combine(tempDirectory, "secondVariableSet.secret"); firstInsensitiveVariablesFileName = Path.ChangeExtension(firstSensitiveVariablesFileName, "json"); fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); fileSystem.EnsureDirectoryExists(tempDirectory); CreateSensitiveVariableFile(); CreateInSensitiveVariableFile(); options = CommonOptions.Parse(new[] { "Test", "--variables", firstInsensitiveVariablesFileName, "--sensitiveVariables", firstSensitiveVariablesFileName, "--sensitiveVariables", secondSensitiveVariablesFileName, "--sensitiveVariablesPassword", encryptionPassword }); } [TearDown] public void CleanUp() { if (fileSystem.DirectoryExists(tempDirectory)) fileSystem.DeleteDirectory(tempDirectory, FailureOptions.IgnoreFailure); } [Test] public void ShouldIncludeEncryptedSensitiveVariables() { var result = new VariablesFactory(fileSystem).Create(options); Assert.AreEqual("firstSensitiveVariableValue", result.Get("firstSensitiveVariableName")); Assert.AreEqual("secondSensitiveVariableValue", result.Get("secondSensitiveVariableName")); Assert.AreEqual("firstInsensitiveVariableValue", result.Get("firstInsensitiveVariableName")); } [Test] public void ShouldIncludeCleartextSensitiveVariables() { options.InputVariables.SensitiveVariablesPassword = null; var sensitiveVariables = new Dictionary<string, string> { { "firstSensitiveVariableName", "firstSensitiveVariableValue"} }; File.WriteAllText(firstSensitiveVariablesFileName, JsonConvert.SerializeObject(sensitiveVariables)); File.WriteAllText(secondSensitiveVariablesFileName, "{}"); var result = new VariablesFactory(fileSystem).Create(options); Assert.AreEqual("firstSensitiveVariableValue", result.Get("firstSensitiveVariableName")); Assert.AreEqual("firstInsensitiveVariableValue", result.Get("firstInsensitiveVariableName")); } [Test] [ExpectedException(typeof(CommandException), ExpectedMessage = "Cannot decrypt sensitive-variables. Check your password is correct.")] public void ThrowsCommandExceptionIfUnableToDecrypt() { options.InputVariables.SensitiveVariablesPassword = "<PASSWORD>"; CreateSensitiveVariableFile(); new VariablesFactory(fileSystem).Create(options); } [Test] [ExpectedException(typeof(CommandException), ExpectedMessage = "Unable to parse sensitive-variables as valid JSON.")] public void ThrowsCommandExceptionIfUnableToParseAsJson() { options.InputVariables.SensitiveVariablesPassword = null; File.WriteAllText(firstSensitiveVariablesFileName, "I Am Not JSON"); new VariablesFactory(fileSystem).Create(options); } void CreateInSensitiveVariableFile() { var firstInsensitiveVariableSet = new VariableDictionary(firstInsensitiveVariablesFileName); firstInsensitiveVariableSet.Set("firstInsensitiveVariableName", "firstInsensitiveVariableValue"); firstInsensitiveVariableSet.Save(); } void CreateSensitiveVariableFile() { var firstSensitiveVariablesSet = new Dictionary<string, string> { {"firstSensitiveVariableName", "firstSensitiveVariableValue"} }; File.WriteAllBytes(firstSensitiveVariablesFileName, new AesEncryption(encryptionPassword).Encrypt(JsonConvert.SerializeObject(firstSensitiveVariablesSet))); var secondSensitiveVariablesSet = new Dictionary<string, string> { {"secondSensitiveVariableName", "secondSensitiveVariableValue"} }; File.WriteAllBytes(secondSensitiveVariablesFileName, new AesEncryption(encryptionPassword).Encrypt(JsonConvert.SerializeObject(secondSensitiveVariablesSet))); } [Test] public void ShouldCheckVariableIsSet() { var variables = new VariablesFactory(fileSystem).Create(options); Assert.That(variables.IsSet("thisIsBogus"), Is.False); Assert.That(variables.IsSet("firstSensitiveVariableName"), Is.True); } [Test] public void VariablesInAdditionalVariablesPathAreContributed() { try { using (var varFile = new TemporaryFile(Path.GetTempFileName())) { new CalamariVariables { { "new.key", "new.value" } }.Save(varFile.FilePath); Environment.SetEnvironmentVariable(VariablesFactory.AdditionalVariablesPathVariable, varFile.FilePath); var variables = new VariablesFactory(CalamariPhysicalFileSystem.GetPhysicalFileSystem()) .Create(new CommonOptions("test")); variables.Get("new.key").Should().Be("new.value"); } } finally { Environment.SetEnvironmentVariable(VariablesFactory.AdditionalVariablesPathVariable, null); } } [Test] public void IfAdditionalVariablesPathDoesNotExistAnExceptionIsThrown() { try { const string filePath = "c:/assuming/that/this/file/doesnt/exist.json"; Environment.SetEnvironmentVariable(VariablesFactory.AdditionalVariablesPathVariable, filePath); new VariablesFactory(CalamariPhysicalFileSystem.GetPhysicalFileSystem()) .Invoking(c => c.Create(new CommonOptions("test"))) .Should() .Throw<CommandException>() // Make sure that the message says how to turn this feature off. .Where(e => e.Message.Contains(VariablesFactory.AdditionalVariablesPathVariable)) // Make sure that the message says where it looked for the file. .Where(e => e.Message.Contains(filePath)); } finally { Environment.SetEnvironmentVariable(VariablesFactory.AdditionalVariablesPathVariable, null); } } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.FileSystem { public class FreeSpaceChecker : IFreeSpaceChecker { readonly ICalamariFileSystem fileSystem; readonly IVariables variables; const string SkipFreeDiskSpaceCheckVariable = "OctopusSkipFreeDiskSpaceCheck"; const string FreeDiskSpaceOverrideInMegaBytesVariable = "OctopusFreeDiskSpaceOverrideInMegaBytes"; const ulong DefaultRequiredSpaceInBytes = 500 * 1024 * 1024; public FreeSpaceChecker(ICalamariFileSystem fileSystem, IVariables variables) { this.fileSystem = fileSystem; this.variables = variables; } public ulong GetRequiredSpaceInBytes() { return GetRequiredSpaceInBytes(out _); } ulong GetRequiredSpaceInBytes(out bool spaceOverrideSpecified) { spaceOverrideSpecified = false; var freeSpaceOverrideInMegaBytes = variables.GetInt32(FreeDiskSpaceOverrideInMegaBytesVariable); if (!freeSpaceOverrideInMegaBytes.HasValue) return DefaultRequiredSpaceInBytes; spaceOverrideSpecified = true; return (ulong)freeSpaceOverrideInMegaBytes * 1024 * 1024; } public ulong GetSpaceRequiredToBeFreed(string directoryPath) { if (CalamariEnvironment.IsRunningOnMono && CalamariEnvironment.IsRunningOnMac) { Log.Verbose("Unable to determine disk free space under Mono on macOS. Assuming there's enough."); return 0; } var requiredSpaceInBytes = GetRequiredSpaceInBytes(out var spaceOverrideSpecified); if (spaceOverrideSpecified) { Log.Verbose($"{FreeDiskSpaceOverrideInMegaBytesVariable} has been specified. We will check and ensure that the drive containing the directory '{directoryPath}' on machine '{Environment.MachineName}' has {((ulong)requiredSpaceInBytes).ToFileSizeString()} free disk space."); } var success = fileSystem.GetDiskFreeSpace(directoryPath, out ulong totalNumberOfFreeBytes); if (!success) { Log.Verbose("Unable to determine disk free space. Assuming there's enough."); return 0; } if (totalNumberOfFreeBytes < requiredSpaceInBytes) return requiredSpaceInBytes - totalNumberOfFreeBytes; return 0; } public void EnsureDiskHasEnoughFreeSpace(string directoryPath) { if (CalamariEnvironment.IsRunningOnMono && CalamariEnvironment.IsRunningOnMac) { //After upgrading to macOS 10.15.2, and mono 5.14.0, drive.TotalFreeSpace and drive.AvailableFreeSpace both started returning 0. //see https://github.com/mono/mono/issues/17151, which was fixed in mono 6.4.xx //Rock and a hard place. Log.Verbose("Unable to determine disk free space under Mono on macOS. Assuming there's enough."); return; } if (variables.GetFlag(SkipFreeDiskSpaceCheckVariable)) { Log.Verbose($"{SkipFreeDiskSpaceCheckVariable} is enabled. The check to ensure that the drive containing the directory '{directoryPath}' on machine '{Environment.MachineName}' has enough free space will be skipped."); return; } ulong requiredSpaceInBytes = 500L * 1024 * 1024; var freeSpaceOverrideInMegaBytes = variables.GetInt32(FreeDiskSpaceOverrideInMegaBytesVariable); if (freeSpaceOverrideInMegaBytes.HasValue) { requiredSpaceInBytes = (ulong)freeSpaceOverrideInMegaBytes * 1024 * 1024; Log.Verbose($"{FreeDiskSpaceOverrideInMegaBytesVariable} has been specified. We will check and ensure that the drive containing the directory '{directoryPath}' on machine '{Environment.MachineName}' has {requiredSpaceInBytes.ToFileSizeString()} free disk space."); } var success = fileSystem.GetDiskFreeSpace(directoryPath, out var totalNumberOfFreeBytes); if (!success) return; if (totalNumberOfFreeBytes < requiredSpaceInBytes) throw new CommandException($"The drive containing the directory '{directoryPath}' on machine '{Environment.MachineName}' does not have enough free disk space available for this operation to proceed. The disk only has {totalNumberOfFreeBytes.ToFileSizeString()} available; please free up at least {requiredSpaceInBytes.ToFileSizeString()}."); } } }<file_sep>using System.IO; using System.Threading.Tasks; using SharpCompress.Archives; using SharpCompress.Archives.Zip; using SharpCompress.Common; namespace Calamari.AzureAppService { class NugetPackageProvider : IPackageProvider { public string UploadUrlPath => @"/api/zipdeploy"; public async Task<FileInfo> PackageArchive(string sourceDirectory, string targetDirectory) { await Task.Run(() => { using var archive = ZipArchive.Create(); archive.AddAllFromDirectory( $"{sourceDirectory}"); archive.SaveTo($"{targetDirectory}/app.zip", CompressionType.Deflate); }); return new FileInfo($"{targetDirectory}/app.zip"); } public async Task<FileInfo> ConvertToAzureSupportedFile(FileInfo sourceFile) { var newFilePath = sourceFile.FullName.Replace(".nupkg", ".zip"); await Task.Run(() => File.Move(sourceFile.FullName, newFilePath)); return new FileInfo(newFilePath); } } } <file_sep>namespace Calamari.Kubernetes.ResourceStatus.Resources { /// <summary> /// Identifies a unique resource in a kubernetes cluster /// </summary> public struct ResourceIdentifier : IResourceIdentity { // API version is irrelevant for identifying a resource, // since the resource name must be unique across all api versions. // https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names public string Kind { get; } public string Name { get; } public string Namespace { get; } public ResourceIdentifier(string kind, string name, string @namespace) { Kind = kind; Name = name; Namespace = @namespace; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.PackageRetention.Caching; using Calamari.Deployment.PackageRetention.Model; using Calamari.Testing.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.PackageRetention { [TestFixture] public class PercentFreeDiskSpacePackageCleanerFixture { [OneTimeSetUp] public void TestFixtureSetUp() { Environment.SetEnvironmentVariable("TentacleHome", TestEnvironment.GetTestPath()); } [OneTimeTearDown] public void TestFixtureTearDown() { Environment.SetEnvironmentVariable("TentacleHome", null); } [Test] public void WhenThereIsEnoughFreeSpace_NothingIsRemoved() { var fileSystem = new FileSystemThatHasSpace(1000, 1000); var log = new InMemoryLog(); var subject = new PercentFreeDiskSpacePackageCleaner(fileSystem, new FirstInFirstOutJournalEntrySort(), Substitute.For<IVariables>(), log); var result = subject.GetPackagesToRemove(MakeSomeJournalEntries()); result.Should().BeEmpty(); } [Test] public void WhenFreeingUpAPackageWorthOfSpace_OnePackageIsMarkedForRemoval() { var fileSystem = new FileSystemThatHasSpace(500, 5000); var log = new InMemoryLog(); var subject = new PercentFreeDiskSpacePackageCleaner(fileSystem, new FirstInFirstOutJournalEntrySort(), Substitute.For<IVariables>(), log); var result = subject.GetPackagesToRemove(MakeSomeJournalEntries()); result.Count().Should().Be(1); } [Test] public void WhenFreeingUpTwoPackagesWorthOfSpace_TwoPackagesAreMarkedForRemoval() { var fileSystem = new FileSystemThatHasSpace(1000, 10000); var log = new InMemoryLog(); var subject = new PercentFreeDiskSpacePackageCleaner(fileSystem, new FirstInFirstOutJournalEntrySort(), Substitute.For<IVariables>(), log); var result = subject.GetPackagesToRemove(MakeSomeJournalEntries()); result.Count().Should().Be(2); } static IEnumerable<JournalEntry> MakeSomeJournalEntries() { for (var i = 0; i < 10; i++) { var packageIdentity = new PackageIdentity(new PackageId("HelloWorld"), new SemanticVersion(1, 0, i), new PackagePath($"C:\\{i}.zip")); yield return new JournalEntry(packageIdentity, 1000); } } } }<file_sep>namespace Calamari.Common.FeatureToggles { /// <summary> /// This list of toggles should be a subset of the toggles supported by the current Octopus Server version in which it is published with. /// When a FeatureToggle no longer exists in server, it should be removed (along with relevant code) from this class /// </summary> public enum FeatureToggle { SkunkworksFeatureToggle, KubernetesAksKubeloginFeatureToggle, GlobPathsGroupSupportInvertedFeatureToggle, ModernAzureAppServiceSdkFeatureToggle, OidcAccountsFeatureToggle } }<file_sep>using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class Ingress : Resource { public string Class { get; } public IEnumerable<string> Hosts { get; } public string Address { get; set; } public Ingress(JObject json, Options options) : base(json, options) { Class = Field("$.spec.ingressClassName"); var rules = data.SelectToken("$.spec.rules") ?.ToObject<IngressRule[]>() ?? new IngressRule[] { }; Hosts = FormatHosts(rules); var loadBalancerIngresses = data.SelectToken("$.status.loadBalancer.ingress") ?.ToObject<LoadBalancerIngress[]>() ?? new LoadBalancerIngress[] { }; Address = FormatAddress(loadBalancerIngresses); } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<Ingress>(lastStatus); return last.Class != Class || !last.Hosts.SequenceEqual(Hosts) || last.Address != Address; } private static string FormatAddress(IEnumerable<LoadBalancerIngress> loadBalancerIngresses) { return string.Join(",", loadBalancerIngresses.Select(ingress => ingress.Ip)); } private static IEnumerable<string> FormatHosts(IEnumerable<IngressRule> rules) { return rules.Select(rule => rule.Host); } } } <file_sep>#!/bin/bash >&2 echo "hello"<file_sep>using System.IO; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.PackageRetention.Repositories { public class VariableJsonJournalPathProvider : IJsonJournalPathProvider { const string DefaultJournalName = "PackageRetentionJournal.json"; readonly IVariables variables; public VariableJsonJournalPathProvider(IVariables variables) { this.variables = variables; } public string GetJournalPath() { var packageRetentionJournalPath = variables.Get(KnownVariables.Calamari.PackageRetentionJournalPath); if (packageRetentionJournalPath != null) return packageRetentionJournalPath; var tentacleHome = variables.Get(TentacleVariables.Agent.TentacleHome) ?? string.Empty; return Path.Combine(tentacleHome, DefaultJournalName); } } }<file_sep>using System; using System.Collections.Generic; namespace Calamari.Common.Features.Substitutions { public interface ISubstituteInFiles { void SubstituteBasedSettingsInSuppliedVariables(string currentDirectory); void Substitute(string currentDirectory, IList<string> filesToTarget, bool warnIfFileNotFound = true); } }<file_sep>using System; using System.Collections.Generic; using System.Threading; using Calamari.Common.Features.Processes.Semaphores; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { public abstract class SemaphoreFixtureBase { protected void ShouldIsolate(ISemaphoreFactory semaphore) { var result = 0; var threads = new List<Thread>(); for (var i = 0; i < 4; i++) { threads.Add(new Thread(new ThreadStart(delegate { using (semaphore.Acquire("CalamariTest", "Another process is performing arithmetic, please wait")) { result = 1; Thread.Sleep(200); result = result + 1; Thread.Sleep(200); result = result + 1; } }))); } foreach (var thread in threads) thread.Start(); foreach (var thread in threads) thread.Join(); Assert.That(result, Is.EqualTo(3)); } protected void SecondSemaphoreWaitsUntilFirstSemaphoreIsReleased(ISemaphoreFactory semaphore) { AutoResetEvent autoEvent = new AutoResetEvent(false); var threadTwoShouldGetSemaphore = true; var threadOne = new Thread(() => { using (semaphore.Acquire("Octopus.Calamari.TestSemaphore", "Another process has the semaphore...")) { threadTwoShouldGetSemaphore = false; autoEvent.Set(); Thread.Sleep(200); threadTwoShouldGetSemaphore = true; } }); var threadTwo = new Thread(() => { autoEvent.WaitOne(); using (semaphore.Acquire("Octopus.Calamari.TestSemaphore", "Another process has the semaphore...")) { Assert.That(threadTwoShouldGetSemaphore, Is.True); } }); threadOne.Start(); threadTwo.Start(); threadOne.Join(); threadTwo.Join(); } } } <file_sep>using System.IO; using Calamari.Commands; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment; using Calamari.LaunchTools; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; using Octostache; namespace Calamari.Tests.Fixtures.Manifest { [TestFixture] [RequiresDotNetCore] public class ExecuteManifestCommandFixture : CalamariFixture { [Test] public void NoManifestFile() { var variables = new VariableDictionary(); var result = ExecuteCommand(variables); result.AssertFailure(); result.AssertErrorOutput("Execution manifest not found in variables."); } [Test] public void NoInstructions() { var variables = new VariableDictionary { { SpecialVariables.Execution.Manifest, "[]" } }; var result = ExecuteCommand(variables); result.AssertFailure(); result.AssertErrorOutput("The execution manifest must have at least one instruction."); } [Test] public void WithInstructions() { var instructions = InstructionBuilder .Create() .WithCalamariInstruction("test-calamari-instruction", new { Greeting = "Hello" }) .WithNodeInstruction() .AsString(); using (var temporaryDirectory = TemporaryDirectory.Create()) { var generatedApplicationPath = CodeGenerator.GenerateConsoleApplication("node", temporaryDirectory.DirectoryPath); var toolRoot = Path.Combine(temporaryDirectory.DirectoryPath, "app"); var destinationPath = CalamariEnvironment.IsRunningOnWindows ? toolRoot : Path.Combine(toolRoot, "bin"); DirectoryEx.Copy(generatedApplicationPath, destinationPath); var variables = new VariableDictionary { { SpecialVariables.Execution.Manifest, instructions }, { nameof(NodeInstructions.BootstrapperPathVariable), "BootstrapperPathVariable_Value" }, { nameof(NodeInstructions.NodePathVariable), toolRoot }, { nameof(NodeInstructions.TargetPathVariable), "TargetPathVariable_Value" }, { nameof(NodeInstructions.InputsVariable), "no_empty" }, { nameof(NodeInstructions.DeploymentTargetInputsVariable), "deploymentTargetInputs" }, }; var result = ExecuteCommand(variables); result.AssertSuccess(); result.AssertOutput("Hello from TestCommand"); result.AssertOutput("Hello from my custom node!"); result.AssertOutput(Path.Combine("BootstrapperPathVariable_Value", "bootstrapper.js")); result.AssertOutput("TargetPathVariable_Value"); result.AssertOutput(nameof(NodeInstructions.DeploymentTargetInputsVariable)); } } CalamariResult ExecuteCommand(VariableDictionary variables) { using (var variablesFile = new TemporaryFile(Path.GetTempFileName())) { variables.Save(variablesFile.FilePath); return Invoke(Calamari() .Action("execute-manifest") .Argument("variables", variablesFile.FilePath) .Argument("sensitiveVariablesPassword", "<PASSWORD>==")); } } } [Command("test-calamari-instruction")] public class TestCommand : Command<TestCommandInputs> { readonly ILog log; public TestCommand(ILog log) { this.log = log; } protected override void Execute(TestCommandInputs inputs) { log.Info($"{inputs.Greeting} from TestCommand"); } } public class TestCommandInputs { public string Greeting { get; set; } } }<file_sep>using System; using System.IO; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Integration.Iis; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class LegacyIisWebSiteConventionFixture { ICalamariFileSystem fileSystem; IInternetInformationServer iis; IVariables variables; RunningDeployment deployment; const string stagingDirectory = "C:\\Applications\\Acme\\1.0.0"; [SetUp] public void SetUp() { variables = new CalamariVariables(); fileSystem = Substitute.For<ICalamariFileSystem>(); iis = Substitute.For<IInternetInformationServer>(); deployment = new RunningDeployment("C:\\packages", variables) { StagingDirectory = stagingDirectory }; } [Test] public void ShouldUpdatePath() { const string websiteName = "AcmeOnline"; variables.Set(SpecialVariables.Package.UpdateIisWebsite, true.ToString()); variables.Set(SpecialVariables.Package.UpdateIisWebsiteName, websiteName); fileSystem.FileExists(Path.Combine(stagingDirectory, "Web.config")).Returns(true); iis.OverwriteHomeDirectory(websiteName, stagingDirectory, false).Returns(true); CreateConvention().Install(deployment); iis.Received().OverwriteHomeDirectory(websiteName, stagingDirectory, false); } [Test] public void ShouldUsePackageNameIfWebsiteNameVariableNotSupplied() { const string packageId = "Acme.1.1.1"; variables.Set(SpecialVariables.Package.UpdateIisWebsite, true.ToString()); variables.Set(PackageVariables.PackageId, packageId); fileSystem.FileExists(Path.Combine(stagingDirectory, "Web.config")).Returns(true); iis.OverwriteHomeDirectory(packageId, stagingDirectory, false).Returns(true); CreateConvention().Install(deployment); iis.Received().OverwriteHomeDirectory(packageId, stagingDirectory, false); } [Test] public void ShouldForceIis6CompatibilityIfFlagSet() { const string websiteName = "AcmeOnline"; variables.Set(SpecialVariables.Package.UpdateIisWebsite, true.ToString()); variables.Set(SpecialVariables.Package.UpdateIisWebsiteName, websiteName); variables.Set(SpecialVariables.UseLegacyIisSupport, true.ToString()); fileSystem.FileExists(Path.Combine(stagingDirectory, "Web.config")).Returns(true); iis.OverwriteHomeDirectory(websiteName, stagingDirectory, true).Returns(true); CreateConvention().Install(deployment); iis.Received().OverwriteHomeDirectory(websiteName, stagingDirectory, true); } [Test] public void ShouldNotUpdatePathIfFlagNotSet() { const string websiteName = "AcmeOnline"; variables.Set(SpecialVariables.Package.UpdateIisWebsite, false.ToString()); variables.Set(SpecialVariables.Package.UpdateIisWebsiteName, websiteName); fileSystem.FileExists(Path.Combine(stagingDirectory, "Web.config")).Returns(true); iis.OverwriteHomeDirectory(websiteName, stagingDirectory, false).Returns(true); CreateConvention().Install(deployment); iis.DidNotReceive().OverwriteHomeDirectory(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>()); } private LegacyIisWebSiteConvention CreateConvention() { return new LegacyIisWebSiteConvention(fileSystem, iis); } } }<file_sep>using System; using System.IO; using System.Net; using Calamari.Common.Plumbing.FileSystem; using Calamari.Integration.Packages.Download; using Calamari.Testing; using Calamari.Testing.Requirements; using FluentAssertions; using NUnit.Framework; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class HelmChartPackageDownloaderFixture { static readonly string AuthFeedUri = "https://octopusdeploy.jfrog.io/octopusdeploy/helm-testing/"; static readonly string FeedUsername = "e2e-reader"; static readonly string FeedPassword = ExternalVariables.Get(ExternalVariable.HelmPassword); static string home = Path.GetTempPath(); HelmChartPackageDownloader downloader; [OneTimeSetUp] public void TestFixtureSetUp() { Environment.SetEnvironmentVariable("TentacleHome", home); } [OneTimeTearDown] public void TestFixtureTearDown() { Environment.SetEnvironmentVariable("TentacleHome", null); } [SetUp] public void Setup() { downloader = new HelmChartPackageDownloader(CalamariPhysicalFileSystem.GetPhysicalFileSystem()); } [Test] [RequiresMonoVersion480OrAboveForTls12(Description = "This test requires TLS 1.2, which doesn't work with mono prior to 4.8")] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void PackageWithCredentials_Loads() { var pkg = downloader.DownloadPackage("mychart", new SemanticVersion("0.3.7"), "helm-feed", new Uri(AuthFeedUri), FeedUsername, FeedPassword, true, 1, TimeSpan.FromSeconds(3)); pkg.PackageId.Should().Be("mychart"); pkg.Version.Should().Be(new SemanticVersion("0.3.7")); } [Test] [RequiresMonoVersion480OrAboveForTls12(Description = "This test requires TLS 1.2, which doesn't work with mono prior to 4.8")] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void PackageWithInvalidUrl_Throws() { var badUrl = new Uri($"https://octopusdeploy.jfrog.io/gobbelygook/{Guid.NewGuid().ToString("N")}"); var badEndpointDownloader = new HelmChartPackageDownloader(CalamariPhysicalFileSystem.GetPhysicalFileSystem()); Action action = () => badEndpointDownloader.DownloadPackage("something", new SemanticVersion("99.9.7"), "gobbely", new Uri(badUrl, "something.99.9.7"), FeedUsername, FeedPassword, true, 1, TimeSpan.FromSeconds(3)); action.Should().Throw<Exception>().And.Message.Should().Contain("Unable to read Helm index file").And.Contain("404"); } } }<file_sep>using System; using System.Net; using System.Net.Http; using System.Net.Sockets; using Polly; using Polly.Retry; namespace Calamari.AzureAppService { public static class RetryPolicies { static readonly Random Jitterer = new Random(); // Based on the logic in the Polly.Extensions.Http package, but without having to include the package // We add a small amount of random jitter to just offset the retries public static RetryPolicy<HttpResponseMessage> TransientHttpErrorsPolicy { get; } = Policy.Handle<HttpRequestException>() .Or<SocketException>() .OrResult<HttpResponseMessage>(r => (int)r.StatusCode >= 500 || r.StatusCode == HttpStatusCode.RequestTimeout) .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) + TimeSpan.FromMilliseconds(Jitterer.Next(0, 1000))); } }<file_sep> using System; using System.Diagnostics; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Runtime; using Calamari.Aws.Exceptions; using Calamari.Aws.Integration.CloudFormation; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Octopus.CoreUtilities; namespace Calamari.Aws.Deployment.Conventions { public class ExecuteCloudFormationChangeSetConvention : CloudFormationInstallationConventionBase { private readonly Func<IAmazonCloudFormation> clientFactory; private readonly Func<RunningDeployment, StackArn> stackProvider; private readonly Func<RunningDeployment, ChangeSetArn> changeSetProvider; private readonly bool waitForComplete; public ExecuteCloudFormationChangeSetConvention( Func<IAmazonCloudFormation> clientFactory, StackEventLogger logger, Func<RunningDeployment, StackArn> stackProvider, Func<RunningDeployment, ChangeSetArn> changeSetProvider, bool waitForComplete): base(logger) { Guard.NotNull(stackProvider, "Stack provider must not be null"); Guard.NotNull(changeSetProvider, "Change set provider must nobe null"); Guard.NotNull(clientFactory, "Client factory should not be null"); this.clientFactory = clientFactory; this.stackProvider = stackProvider; this.changeSetProvider = changeSetProvider; this.waitForComplete = waitForComplete; } public override void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private async Task InstallAsync(RunningDeployment deployment) { var stack = stackProvider(deployment); var changeSet = changeSetProvider(deployment); Guard.NotNull(stack, "The provided stack identifer or name may not be null"); Guard.NotNull(changeSet, "The provided change set identifier or name may not be null"); var deploymentStartTime = DateTime.Now; var response = await clientFactory.DescribeChangeSetAsync(stack, changeSet); if (response.Changes.Count == 0) { await clientFactory().DeleteChangeSetAsync(new DeleteChangeSetRequest { ChangeSetName = changeSet.Value, StackName = stack.Value }); Log.Info("No changes need to be performed."); return; } await ExecuteChangeset(clientFactory, stack, changeSet); if (waitForComplete) { await WithAmazonServiceExceptionHandling(() => clientFactory.WaitForStackToComplete(CloudFormationDefaults.StatusWaitPeriod, stack, LogAndThrowRollbacks(clientFactory, stack, filter: FilterStackEventsSince(deploymentStartTime))) ); } } private async Task<RunningChangeSet> ExecuteChangeset(Func<IAmazonCloudFormation> factory, StackArn stack, ChangeSetArn changeSet) { try { var changes = await factory.WaitForChangeSetCompletion(CloudFormationDefaults.StatusWaitPeriod, new RunningChangeSet(stack, changeSet)); if (changes.Status == ChangeSetStatus.FAILED) { throw new UnknownException($"The changeset failed to create.\n{changes.StatusReason}"); } await factory().ExecuteChangeSetAsync(new ExecuteChangeSetRequest { ChangeSetName = changeSet.Value, StackName = stack.Value }); return new RunningChangeSet(stack, changeSet); } catch (AmazonCloudFormationException exception) when (exception.ErrorCode == "AccessDenied") { throw new PermissionException( "The AWS account used to perform the operation does not have the required permission to execute the changeset.\n" + "Please ensure the current account has permission to perfrom action 'cloudformation:ExecuteChangeSet'.\n" + exception.Message + "\n"); } catch (AmazonServiceException exception) { LogAmazonServiceException(exception); throw; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; namespace Calamari.Testing.Helpers { public class InMemoryLog : AbstractLog { public List<Message> Messages { get; } = new List<Message>(); public List<string> StandardOut { get; } = new List<string>(); public List<string> StandardError { get; }= new List<string>(); public List<ServiceMessage> ServiceMessages { get; } = new List<ServiceMessage>(); public IEnumerable<string> MessagesVerboseFormatted => Messages.Where(m => m.Level == Level.Verbose).Select(m => m.FormattedMessage); public IEnumerable<string> MessagesInfoFormatted => Messages.Where(m => m.Level == Level.Info).Select(m => m.FormattedMessage); public IEnumerable<string> MessagesWarnFormatted => Messages.Where(m => m.Level == Level.Warn).Select(m => m.FormattedMessage); public IEnumerable<string> MessagesErrorFormatted => Messages.Where(m => m.Level == Level.Error).Select(m => m.FormattedMessage); protected override void StdOut(string message) { Console.WriteLine(message); // Write to console for the test output StandardOut.Add(message); } protected override void StdErr(string message) { Console.Error.WriteLine(message); StandardError.Add(message); } public override void Verbose(string message) { Messages.Add(new Message(Level.Verbose, ProcessRedactions(message))); base.Verbose(message); } public override void VerboseFormat(string messageFormat, params object[] args) { var message = ProcessRedactions(string.Format(messageFormat, args)); Messages.Add(new Message(Level.Verbose, message, messageFormat, args)); base.VerboseFormat(messageFormat, args); } public override void Info(string message) { Messages.Add(new Message(Level.Info, ProcessRedactions(message))); base.Info(message); } public override void InfoFormat(string messageFormat, params object[] args) { var message = ProcessRedactions(string.Format(messageFormat, args)); Messages.Add(new Message(Level.Info, message, messageFormat, args)); base.InfoFormat(messageFormat, args); } public override void Warn(string message) { Messages.Add(new Message(Level.Warn, ProcessRedactions(message))); base.Warn(message); } public override void WarnFormat(string messageFormat, params object[] args) { var message = ProcessRedactions(string.Format(messageFormat, args)); Messages.Add(new Message(Level.Warn, message, messageFormat, args)); base.WarnFormat(messageFormat, args); } public override void Error(string message) { Messages.Add(new Message(Level.Error, ProcessRedactions(message))); base.Error(message); } public override void ErrorFormat(string messageFormat, params object[] args) { var message = ProcessRedactions(string.Format(messageFormat, args)); Messages.Add(new Message(Level.Error, message, messageFormat, args)); base.ErrorFormat(messageFormat, args); } public override void WriteServiceMessage(ServiceMessage serviceMessage) { ServiceMessages.Add(serviceMessage); base.WriteServiceMessage(serviceMessage); } public class Message { public Level Level { get; } public string? MessageFormat { get; } public object[]? Args { get; } public string FormattedMessage { get; } public Message(Level level, string message, string? messageFormat = null, params object[] args) { Level = level; MessageFormat = messageFormat; Args = args; FormattedMessage = message; } } public enum Level { Verbose, Info, Warn, Error } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { [TestFixture] public class LockFileBasedSemaphoreCreatorFixture { [Test] public void ReturnsInstanceOfLockFileBasedSemaphore() { var creator = new LockFileBasedSemaphoreCreator(new InMemoryLog()); var result = creator.Create("name", TimeSpan.FromSeconds(1)); Assert.That(result, Is.InstanceOf<LockFileBasedSemaphore>()); } } } <file_sep>using System; using Autofac; using Calamari.Common.Features.Behaviours; namespace Calamari.Common.Plumbing.Pipeline { public class AfterPackageExtractionResolver: Resolver<IAfterPackageExtractionBehaviour> { public AfterPackageExtractionResolver(ILifetimeScope lifetimeScope) : base(lifetimeScope) { } } }<file_sep>using System; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing.Logging; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { [TestFixture] public class FileBasedSempahoreManagerFixture : SemaphoreFixtureBase { [Test] public void FileBasedSempahoreWaitsUntilFirstSemaphoreIsReleased() { SecondSemaphoreWaitsUntilFirstSemaphoreIsReleased(new FileBasedSempahoreManager()); } [Test] public void FileBasedSempahoreShouldIsolate() { ShouldIsolate(new FileBasedSempahoreManager()); } [Test] public void WritesMessageToLogIfCannotGetSemaphore() { var log = new InMemoryLog(); var semaphoreCreator = Substitute.For<ICreateSemaphores>(); var name = Guid.NewGuid().ToString(); var semaphore = Substitute.For<ISemaphore>(); semaphore.WaitOne(200).Returns(false); semaphoreCreator.Create(name, TimeSpan.FromSeconds(60)).Returns(semaphore); var sempahoreManager = new FileBasedSempahoreManager(log, TimeSpan.FromMilliseconds(200), semaphoreCreator); using (sempahoreManager.Acquire(name, "wait message")) { } log.Messages.Should().Contain(m => m.Level == InMemoryLog.Level.Verbose && m.FormattedMessage == "wait message"); } [Test] public void ReleasesLockOnDispose() { var semaphoreCreator = Substitute.For<ICreateSemaphores>(); var name = Guid.NewGuid().ToString(); var semaphore = Substitute.For<ISemaphore>(); semaphoreCreator.Create(name, TimeSpan.FromMinutes(2)).Returns(semaphore); var sempahoreManager = new FileBasedSempahoreManager(Substitute.For<ILog>(), TimeSpan.FromMilliseconds(200), semaphoreCreator); using (sempahoreManager.Acquire(name, "wait message")) { } semaphore.Received().ReleaseLock(); } [Test] public void AttemptsToGetLockWithTimeoutThenWaitsIndefinitely() { var semaphoreCreator = Substitute.For<ICreateSemaphores>(); var name = Guid.NewGuid().ToString(); var semaphore = Substitute.For<ISemaphore>(); semaphore.WaitOne(200).Returns(false); semaphoreCreator.Create(name, TimeSpan.FromMinutes(2)).Returns(semaphore); var sempahoreManager = new FileBasedSempahoreManager(Substitute.For<ILog>(), TimeSpan.FromMilliseconds(200), semaphoreCreator); using (sempahoreManager.Acquire(name, "wait message")) { } semaphore.Received().WaitOne(200); semaphore.Received().WaitOne(); } } }<file_sep>using System; namespace Calamari.Common.Features.StructuredVariables { public interface IJsonFormatVariableReplacer : IFileFormatVariableReplacer { } }<file_sep>using System; namespace Calamari.Common.Plumbing.Pipeline { public interface IPreDeployBehaviour: IBehaviour { } }<file_sep>using Calamari.Deployment.PackageRetention; using NUnit.Framework; namespace Calamari.Tests.Fixtures.PackageRetention { [TestFixture] public class TinyTypeFixture { [Test] public void EquivalentValuesWithSameTypesAreEqualTinyTypes() { var tt1 = ATinyType.Create<ATinyType>(10); var tt2 = ATinyType.Create<ATinyType>(10); Assert.AreEqual(tt1, tt2); } [Test] public void EquivalentValuesWithDifferentTypesAreNotEqualTinyTypes() { var tt1 = ATinyType.Create<ATinyType>(10); var tt2 = AnotherTinyType.Create<AnotherTinyType>(10); Assert.AreNotEqual(tt1, tt2); } [Test] public void EquivalentValuesWithSameTypesHaveEqualHashCodes() { var tt1 = ATinyType.Create<ATinyType>(10); var tt2 = ATinyType.Create<ATinyType>(10); Assert.AreEqual(tt1.GetHashCode(), tt2.GetHashCode()); } [Test] public void EquivalentValuesWithDifferentTypesHaveUnequalHashCodes() { var tt1 = ATinyType.Create<ATinyType>(10); var tt2 = AnotherTinyType.Create<AnotherTinyType>(10); Assert.AreNotEqual(tt1.GetHashCode(), tt2.GetHashCode()); } class ATinyType : TinyType<int> { public ATinyType(int value) : base(value) { } } class AnotherTinyType : TinyType<int> { public AnotherTinyType(int value) : base(value) { } } } }<file_sep>using System; using System.Collections.Generic; using System.Text; using Calamari.Common.Commands; namespace Calamari.Deployment.Conventions { public static class ConventionExtensions { public static ConditionalInstallationConvention<T> When<T>(this T convention, Func<RunningDeployment, bool> predicate) where T: IInstallConvention { return new ConditionalInstallationConvention<T>(predicate, convention); } } } <file_sep>using System; using Octopus.Versioning; namespace Calamari.Tests.Helpers { // This file is a clone of how the server represents find package responses from Calamari public class FoundPackage { public string PackageId { get; } public IVersion Version { get; } public string RemotePath { get; } public string Hash { get; } public string FileExtension { get; } public FoundPackage(string packageId, string version, string versionFormat, string remotePath, string hash, string fileExtension) { PackageId = packageId; if (!Enum.TryParse(versionFormat, out VersionFormat realVersionFormat)) { realVersionFormat = VersionFormat.Semver; }; Version = VersionFactory.CreateVersion(version, realVersionFormat); RemotePath = remotePath; Hash = hash; FileExtension = fileExtension; } } }<file_sep>// Much of this class was based on code from https://github.com/NuGet/NuGet.Client. It was ported, as the NuGet libraries are .NET 4.5 and Calamari is .NET 4.0 // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.// #if USE_NUGET_V2_LIBS using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Octopus.CoreUtilities.Extensions; using Octopus.Versioning; using Octopus.Versioning.Semver; namespace Calamari.Integration.Packages.NuGet { internal static class NuGetV3Downloader { public static bool CanHandle(Uri feedUri, ICredentials feedCredentials, TimeSpan httpTimeout) { if (feedUri.ToString().EndsWith(".json", StringComparison.OrdinalIgnoreCase)) { return true; } return IsJsonEndpoint(feedUri, feedCredentials, httpTimeout); } static bool IsJsonEndpoint(Uri feedUri, ICredentials feedCredentials, TimeSpan httpTimeout) { #if NET40 var request = WebRequest.Create(feedUri); request.Credentials = feedCredentials; request.Timeout = (int)httpTimeout.TotalMilliseconds; using (var response = (HttpWebResponse)request.GetResponse()) { if (response.IsSuccessStatusCode()) { return response.ContentType == "application/json"; } throw new HttpException((int)response.StatusCode, $"Received status code that indicate not successful response. Uri:{feedUri}"); } #else var request = new HttpRequestMessage(HttpMethod.Get, feedUri); using (var httpClient = CreateHttpClient(feedCredentials, httpTimeout)) { var sending = httpClient.SendAsync(request); sending.Wait(); using (var response = sending.Result) { response.EnsureSuccessStatusCode(); return response.Content.Headers.ContentType.MediaType == "application/json"; } } #endif } class PackageIdentifier { public PackageIdentifier(string packageId, IVersion version) { Id = packageId.ToLowerInvariant(); Version = version.ToString().ToLowerInvariant(); SemanticVersion = version; SemanticVersionWithoutMetadata = new SemanticVersion(version.Major, version.Minor, version.Patch, version.Revision, version.Release, null); } public string Id { get; } public string Version { get; } public IVersion SemanticVersion { get; } public IVersion SemanticVersionWithoutMetadata { get; } } public static void DownloadPackage(string packageId, IVersion version, Uri feedUri, ICredentials feedCredentials, string targetFilePath, TimeSpan httpTimeout) { var packageIdentifier = new PackageIdentifier(packageId, version); var downloadUri = GetDownloadUri(packageIdentifier, feedUri, feedCredentials, httpTimeout); if (downloadUri == null) { throw new InvalidOperationException($"Unable to find url to download package: {version} with version: {version} from feed: {feedUri}"); } Log.Verbose($"Downloading package from '{downloadUri}'"); using (var nupkgFile = new FileStream(targetFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { GetHttp(downloadUri, feedCredentials, httpTimeout, pkgStream => { pkgStream.CopyTo(nupkgFile); }); } } static Uri? GetDownloadUri(PackageIdentifier packageIdentifier, Uri feedUri, ICredentials feedCredentials, TimeSpan httpTimeout) { var json = GetServiceIndexJson(feedUri, feedCredentials, httpTimeout); if (json == null) { throw new CommandException($"'{feedUri}' is not a valid NuGet v3 feed"); } var resources = GetServiceResources(json); var packageBaseDownloadUri = GetPackageBaseDownloadUri(resources, packageIdentifier); if (packageBaseDownloadUri != null) return packageBaseDownloadUri; return GetPackageRegistrationDownloadUri(feedCredentials, httpTimeout, resources, packageIdentifier); } static Uri? GetPackageRegistrationDownloadUri(ICredentials feedCredentials, TimeSpan httpTimeout, IDictionary<string, List<Uri>> resources, PackageIdentifier packageIdentifier) { var packageRegistrationUri = GetPackageRegistrationUri(resources, packageIdentifier.Id); var packageRegistrationResponse = GetJsonResponse(packageRegistrationUri, feedCredentials, httpTimeout); // Package Registration Response structure // https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#response var registrationPages = packageRegistrationResponse["items"]; // Registration Page structure // https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page-object foreach (var registrationPage in registrationPages) { var registrationLeaves = registrationPage["items"]; if (registrationLeaves == null) { // narrow version to specific page. var versionedRegistrationPage = registrationPages.FirstOrDefault(x => VersionComparer.Default.Compare(new SemanticVersion(x["lower"].ToString()), packageIdentifier.SemanticVersionWithoutMetadata) <= 0 && VersionComparer.Default.Compare(new SemanticVersion(x["upper"].ToString()), packageIdentifier.SemanticVersionWithoutMetadata) >= 0); // If we can't find a page for the version we are looking for, return null. if (versionedRegistrationPage == null) return null; var versionedRegistrationPageResponse = GetJsonResponse(new Uri(versionedRegistrationPage["@id"].ToString()), feedCredentials, httpTimeout); registrationLeaves = versionedRegistrationPageResponse["items"]; } // Leaf Structure // https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf-object-in-a-page var leaf = registrationLeaves.FirstOrDefault(x => string.Equals(x["catalogEntry"]["version"].ToString(), packageIdentifier.Version, StringComparison.OrdinalIgnoreCase)); // If we can't find the leaf registration for the version we are looking for, return null. if (leaf == null) return null; var contentUri = leaf["packageContent"].ToString(); // Note: We reformat the packageContent Uri here as Artifactory (and possibly others) does not include +metadata suffixes on its packageContent Uri's var downloadUri = new Uri($"{contentUri.Remove(contentUri.LastIndexOfAny("/".ToCharArray()) + 1)}{packageIdentifier.Version}"); return downloadUri; } return null; } static Uri? GetPackageBaseDownloadUri(IDictionary<string, List<Uri>> resources, PackageIdentifier packageIdentifier) { var packageBaseUri = GetPackageBaseUri(resources); if (packageBaseUri?.AbsoluteUri.TrimEnd('/') != null) { return new Uri($"{packageBaseUri}/{packageIdentifier.Id}/{packageIdentifier.Version}/{packageIdentifier.Id}.{packageIdentifier.Version}.nupkg"); } return null; } static Uri GetPackageRegistrationUri(IDictionary<string, List<Uri>> resources, string normalizedId) { var registrationUrl = NuGetServiceTypes.RegistrationsBaseUrl .Where(serviceType => resources.ContainsKey(serviceType)) .SelectMany(serviceType => resources[serviceType]) .First() .OriginalString.TrimEnd('/'); var packageRegistrationUri = new Uri($"{registrationUrl}/{normalizedId}/index.json"); return packageRegistrationUri; } static HttpClient CreateHttpClient(ICredentials credentials, TimeSpan httpTimeout) { var handler = new WebRequestHandler { Credentials = credentials, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; var httpClient = new HttpClient(handler) { Timeout = httpTimeout }; httpClient.DefaultRequestHeaders.Add("user-agent", "NuGet Client V3/3.4.3"); return httpClient; } static void GetHttp(Uri uri, ICredentials credentials, TimeSpan httpTimeout, Action<Stream> processContent) { #if NET40 var request = WebRequest.Create(uri); request.Credentials = credentials; request.Timeout = (int)httpTimeout.TotalMilliseconds; using (var response = (HttpWebResponse)request.GetResponse()) { if (response.IsSuccessStatusCode()) { using (var respStream = response.GetResponseStream()) { processContent(respStream); } } else { throw new HttpException((int)response.StatusCode, $"Received status code that indicate not successful response. Uri:{uri}"); } } #else var request = new HttpRequestMessage(HttpMethod.Get, uri); using (var httpClient = CreateHttpClient(credentials, httpTimeout)) { var sending = httpClient.SendAsync(request); sending.Wait(); using (var response = sending.Result) { response.EnsureSuccessStatusCode(); var readingStream = response.Content.ReadAsStreamAsync(); readingStream.Wait(); processContent(readingStream.Result); } } #endif } static Uri? GetPackageBaseUri(IDictionary<string, List<Uri>> resources) { // If index.json contains a flat container resource use that to directly // construct package download urls. if (resources.ContainsKey(NuGetServiceTypes.PackageBaseAddress)) return resources[NuGetServiceTypes.PackageBaseAddress].FirstOrDefault(); return null; } static JObject? GetServiceIndexJson(Uri feedUri, ICredentials feedCredentials, TimeSpan httpTimeout) { var json = GetJsonResponse(feedUri, feedCredentials, httpTimeout); if (!IsValidV3Json(json)) return null; return json; } static JObject GetJsonResponse(Uri feedUri, ICredentials feedCredentials, TimeSpan httpTimeout) { // Parse JSON for package base URL JObject json = null; GetHttp(feedUri, feedCredentials, httpTimeout, stream => { using (var streamReader = new StreamReader(stream)) using (var jsonReader = new JsonTextReader(streamReader)) { json = JObject.Load(jsonReader); } }); return json; } static bool IsValidV3Json(JObject json) { // Use SemVer instead of NuGetVersion, the service index should always be // in strict SemVer format JToken versionToken; if (json.TryGetValue("version", out versionToken) && versionToken.Type == JTokenType.String) { var version = VersionFactory.TryCreateSemanticVersion((string)versionToken); if (version != null && version.Major == 3) { return true; } } return false; } static IDictionary<string, List<Uri>> GetServiceResources(JObject index) { var result = new Dictionary<string, List<Uri>>(); JToken resources; if (index.TryGetValue("resources", out resources)) { foreach (var resource in resources) { JToken type = resource["@type"]; JToken id = resource["@id"]; if (type == null || id == null) { continue; } if (type.Type == JTokenType.Array) { foreach (var nType in type) { AddEndpoint(result, nType, id); } } else { AddEndpoint(result, type, id); } } } return result; } static void AddEndpoint(IDictionary<string, List<Uri>> result, JToken typeToken, JToken idToken) { string type = (string)typeToken; string id = (string)idToken; if (type == null || id == null) { return; } List<Uri> ids; if (!result.TryGetValue(type, out ids)) { ids = new List<Uri>(); result.Add(type, ids); } Uri uri; if (Uri.TryCreate(id, UriKind.Absolute, out uri)) { ids.Add(new Uri(id)); } } } } #endif<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Deployment.Journal { public class DeployedPackage { public DeployedPackage(string? packageId, string? packageVersion, string? deployedFrom) { Guard.NotNullOrWhiteSpace(packageId, "Deployed package must have an Id"); Guard.NotNullOrWhiteSpace(packageVersion, "Deployed package must have a version"); PackageId = packageId; PackageVersion = packageVersion; DeployedFrom = deployedFrom; } public DeployedPackage(XElement element) : this( element.Attribute("PackageId")?.Value, element.Attribute("PackageVersion")?.Value, element.Attribute("DeployedFrom")?.Value) { } public string PackageId { get; } public string PackageVersion { get; } public string? DeployedFrom { get; } public XElement ToXmlElement() { var attributes = new List<XAttribute> { new XAttribute("PackageId", PackageId), new XAttribute("PackageVersion", PackageVersion) }; if (!string.IsNullOrEmpty(DeployedFrom)) attributes.Add(new XAttribute("DeployedFrom", DeployedFrom)); return new XElement("Package", attributes); } public static IEnumerable<DeployedPackage> GetDeployedPackages(RunningDeployment deployment) { var variables = deployment.Variables; foreach (var packageReferenceName in variables.GetIndexes(PackageVariables.PackageCollection)) { yield return new DeployedPackage( variables.Get(PackageVariables.IndexedPackageId(packageReferenceName)), variables.Get(PackageVariables.IndexedPackageVersion(packageReferenceName)), variables.Get(PackageVariables.IndexedOriginalPath(packageReferenceName)) ); } } public static IEnumerable<DeployedPackage> FromJournalEntryElement(XElement deploymentElement) { // Originally journal entries were restricted to having one package (as deployment steps could // only have one package), and the properties were written as attributes on the <Deployment> element. // When the capability was added for deployment steps to have multiple packages, the package // details were moved to child <Package> elements. // We need to support reading both for backwards-compatibility with legacy journal entries. // If the deployment element has children, then we will read the packages from there. if (deploymentElement.HasElements) return deploymentElement.Elements("Package").Select(x => new DeployedPackage(x)); // Otherwise we try to read them from the legacy attributes var packageIdAttribute = deploymentElement.Attribute("PackageId"); if (packageIdAttribute != null && !string.IsNullOrEmpty(packageIdAttribute.Value)) return new[] { new DeployedPackage( packageIdAttribute.Value, deploymentElement.Attribute("PackageVersion")?.Value, deploymentElement.Attribute("ExtractedFrom")?.Value) }; return new List<DeployedPackage>(); } } }<file_sep>using System; using Calamari.Commands.Support; using Calamari.Common.Commands; namespace Calamari.Aws.Exceptions { /// <summary> /// Represents a failed attempt to query the AWS API /// </summary> public class PermissionException : CommandException { public PermissionException(string message) : base(message) { } public PermissionException(string message, Exception inner) : base(message, inner) { } } } <file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; namespace Calamari.Kubernetes.Integration { public class GkeGcloudAuthPlugin : CommandLineTool { public GkeGcloudAuthPlugin(ILog log, ICommandLineRunner commandLineRunner, string workingDirectory, Dictionary<string, string> environmentVars) : base(log, commandLineRunner, workingDirectory, environmentVars) { } public bool ExistsOnPath() { var result = CalamariEnvironment.IsRunningOnWindows ? ExecuteCommandAndReturnOutput("where", "gke-gcloud-auth-plugin.exe") : ExecuteCommandAndReturnOutput("which", "gke-gcloud-auth-plugin"); var foundExecutable = result.Output.InfoLogs.FirstOrDefault(); return !string.IsNullOrEmpty(foundExecutable); } } } <file_sep>using System; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Deployment { public static class SpecialVariables { public static readonly string AppliedXmlConfigTransforms = "OctopusAppliedXmlConfigTransforms"; public static string GetLibraryScriptModuleName(string variableName) { return variableName.Replace("Octopus.Script.Module[", "").TrimEnd(']'); } public static bool IsExcludedFromLocalVariables(string name) { return name.Contains("["); } public static bool IsLibraryScriptModule(string variableName) { return variableName.StartsWith("Octopus.Script.Module["); } public static string GetOutputVariableName(string actionName, string variableName) { return string.Format("Octopus.Action[{0}].Output.{1}", actionName, variableName); } public static string GetMachineIndexedOutputVariableName(string actionName, string machineName, string variableName) { return string.Format("Octopus.Action[{0}].Output[{1}].{2}", actionName, machineName, variableName); } public const string UseLegacyIisSupport = "OctopusUseLegacyIisSupport"; public static readonly string RetentionPolicyItemsToKeep = "OctopusRetentionPolicyItemsToKeep"; public static readonly string RetentionPolicyDaysToKeep = "OctopusRetentionPolicyDaysToKeep"; public static readonly string DeleteScriptsOnCleanup = "OctopusDeleteScriptsOnCleanup"; public static class Bootstrapper { public static string ModulePaths = "Octopus.Calamari.Bootstrapper.ModulePaths"; } public static class Tentacle { public static class CurrentDeployment { public static readonly string RetentionPolicySubset = "Octopus.Tentacle.CurrentDeployment.RetentionPolicySubset"; public static readonly string TargetedRoles = "Octopus.Tentacle.CurrentDeployment.TargetedRoles"; } public static class Agent { public static readonly string ProgramDirectoryPath = "Octopus.Tentacle.Agent.ProgramDirectoryPath"; } } public static class Package { public static readonly string ShouldDownloadOnTentacle = "Octopus.Action.Package.DownloadOnTentacle"; public static readonly string UpdateIisWebsite = "Octopus.Action.Package.UpdateIisWebsite"; public static readonly string UpdateIisWebsiteName = "Octopus.Action.Package.UpdateIisWebsiteName"; public static readonly string TreatConfigTransformationWarningsAsErrors = "Octopus.Action.Package.TreatConfigTransformationWarningsAsErrors"; public static readonly string IgnoreConfigTransformationErrors = "Octopus.Action.Package.IgnoreConfigTransformationErrors"; public static readonly string SuppressConfigTransformationLogging = "Octopus.Action.Package.SuppressConfigTransformationLogging"; public static readonly string EnableDiagnosticsConfigTransformationLogging = "Octopus.Action.Package.EnableDiagnosticsConfigTransformationLogging"; public static readonly string AdditionalXmlConfigurationTransforms = "Octopus.Action.Package.AdditionalXmlConfigurationTransforms"; public static readonly string IgnoreVariableReplacementErrors = "Octopus.Action.Package.IgnoreVariableReplacementErrors"; public static readonly string RunPackageScripts = "Octopus.Action.Package.RunScripts"; } public static class Packages { public static string ExtractedPath(string key) { return $"Octopus.Action.Package[{key}].ExtractedPath"; } public static string PackageFileName(string key) { return $"Octopus.Action.Package[{key}].PackageFileName"; } public static string PackageFilePath(string key) { return $"Octopus.Action.Package[{key}].PackageFilePath"; } } public static class Vhd { public static readonly string ApplicationPath = "Octopus.Action.Vhd.ApplicationPath"; public static readonly string VmName = "Octopus.Action.Vhd.VmName"; public static readonly string DeployVhdToVm = "Octopus.Action.Vhd.DeployVhdToVm"; } public static class Features { public const string Vhd = "Octopus.Features.Vhd"; } public static class Action { public const string FailScriptOnErrorOutput = "Octopus.Action.FailScriptOnErrorOutput"; public static class IisWebSite { public static readonly string DeployAsWebSite = "Octopus.Action.IISWebSite.CreateOrUpdateWebSite"; public static readonly string DeployAsWebApplication = "Octopus.Action.IISWebSite.WebApplication.CreateOrUpdate"; public static readonly string DeployAsVirtualDirectory = "Octopus.Action.IISWebSite.VirtualDirectory.CreateOrUpdate"; public static readonly string ApplicationPoolName = "Octopus.Action.IISWebSite.ApplicationPoolName"; public static readonly string ApplicationPoolUserName = "Octopus.Action.IISWebSite.ApplicationPoolUsername"; public static readonly string Bindings = "Octopus.Action.IISWebSite.Bindings"; public static readonly string ExistingBindings = "Octopus.Action.IISWebSite.ExistingBindings"; public static readonly string ApplicationPoolIdentityType = "Octopus.Action.IISWebSite.ApplicationPoolIdentityType"; public static class Output { public static readonly string CertificateStoreName = "Octopus.Action.IISWebSite.CertificateStoreName"; } } public static class ServiceFabric { public static readonly string ConnectionEndpoint = "Octopus.Action.ServiceFabric.ConnectionEndpoint"; } public static class Aws { public static readonly string CloudFormationStackName = "Octopus.Action.Aws.CloudFormationStackName"; public static readonly string CloudFormationTemplate = "Octopus.Action.Aws.CloudFormationTemplate"; public static readonly string CloudFormationProperties = "Octopus.Action.Aws.CloudFormationProperties"; public static readonly string AssumeRoleARN = "Octopus.Action.Aws.AssumedRoleArn"; public static readonly string AssumeRoleExternalId = "Octopus.Action.Aws.AssumeRoleExternalId"; public static readonly string AccountId = "Octopus.Action.AwsAccount.Variable"; public static readonly string CloudFormationAction = "Octopus.Action.Aws.CloudFormationAction"; } public static class Azure { public static readonly string UseBundledAzurePowerShellModules = "Octopus.Action.Azure.UseBundledAzurePowerShellModules"; public static readonly string AccountVariable = "Octopus.Action.AzureAccount.Variable"; public static readonly string SubscriptionId = "Octopus.Action.Azure.SubscriptionId"; public static readonly string ClientId = "Octopus.Action.Azure.ClientId"; public static readonly string TenantId = "Octopus.Action.Azure.TenantId"; public static readonly string Password = "<PASSWORD>"; public static readonly string CertificateBytes = "Octopus.Action.Azure.CertificateBytes"; public static readonly string CertificateThumbprint = "Octopus.Action.Azure.CertificateThumbprint"; public static readonly string WebAppName = "Octopus.Action.Azure.WebAppName"; public static readonly string WebAppSlot = "Octopus.Action.Azure.DeploymentSlot"; public static readonly string RemoveAdditionalFiles = "Octopus.Action.Azure.RemoveAdditionalFiles"; public static readonly string AppOffline = "Octopus.Action.Azure.AppOffline"; public static readonly string PreserveAppData = "Octopus.Action.Azure.PreserveAppData"; public static readonly string PreservePaths = "Octopus.Action.Azure.PreservePaths"; public static readonly string PhysicalPath = "Octopus.Action.Azure.PhysicalPath"; public static readonly string UseChecksum = "Octopus.Action.Azure.UseChecksum"; public static readonly string CloudServiceName = "Octopus.Action.Azure.CloudServiceName"; public static readonly string Slot = "Octopus.Action.Azure.Slot"; public static readonly string SwapIfPossible = "Octopus.Action.Azure.SwapIfPossible"; public static readonly string StorageAccountName = "Octopus.Action.Azure.StorageAccountName"; public static readonly string UseCurrentInstanceCount = "Octopus.Action.Azure.UseCurrentInstanceCount"; public static readonly string UploadedPackageUri = "Octopus.Action.Azure.UploadedPackageUri"; public static readonly string CloudServicePackagePath = "Octopus.Action.Azure.CloudServicePackagePath"; public static readonly string PackageExtractionPath = "Octopus.Action.Azure.PackageExtractionPath"; public static readonly string CloudServicePackageExtractionDisabled = "Octopus.Action.Azure.CloudServicePackageExtractionDisabled"; public static readonly string LogExtractedCspkg = "Octopus.Action.Azure.LogExtractedCspkg"; public static readonly string CloudServiceConfigurationFileRelativePath = "Octopus.Action.Azure.CloudServiceConfigurationFileRelativePath"; public static readonly string DeploymentLabel = "Octopus.Action.Azure.DeploymentLabel"; public static readonly string ExtensionsDirectory = "Octopus.Action.Azure.ExtensionsDirectory"; public static readonly string ResourceGroupName = "Octopus.Action.Azure.ResourceGroupName"; public static readonly string ResourceGroupDeploymentName = "Octopus.Action.Azure.ResourceGroupDeploymentName"; public static readonly string ResourceGroupDeploymentMode = "Octopus.Action.Azure.ResourceGroupDeploymentMode"; public static readonly string Environment = "Octopus.Action.Azure.Environment"; public static readonly string ResourceManagementEndPoint = "Octopus.Action.Azure.ResourceManagementEndPoint"; public static readonly string ServiceManagementEndPoint = "Octopus.Action.Azure.ServiceManagementEndPoint"; public static readonly string ActiveDirectoryEndPoint = "Octopus.Action.Azure.ActiveDirectoryEndPoint"; public static readonly string StorageEndPointSuffix = "Octopus.Action.Azure.StorageEndpointSuffix"; public static class Output { public static readonly string SubscriptionId = "OctopusAzureSubscriptionId"; public static readonly string ConfigurationFile = "OctopusAzureConfigurationFile"; public static readonly string CloudServiceDeploymentSwapped = "OctopusAzureCloudServiceDeploymentSwapped"; } } public class WindowsService { public const string Arguments = "Octopus.Action.WindowsService.Arguments"; public const string CustomAccountName = "Octopus.Action.WindowsService.CustomAccountName"; public const string CustomAccountPassword = "<PASSWORD>"; } public static class Certificate { public static readonly string CertificateVariable = "Octopus.Action.Certificate.Variable"; public static readonly string PrivateKeyExportable = "Octopus.Action.Certificate.PrivateKeyExportable"; public static readonly string StoreLocation = "Octopus.Action.Certificate.StoreLocation"; public static readonly string StoreName = "Octopus.Action.Certificate.StoreName"; public static readonly string StoreUser = "Octopus.Action.Certificate.StoreUser"; } public static class Script { public static readonly string ScriptParameters = "Octopus.Action.Script.ScriptParameters"; public static readonly string ScriptSource = "Octopus.Action.Script.ScriptSource"; public static readonly string ExitCode = "Octopus.Action.Script.ExitCode"; public static string ScriptBodyBySyntax(ScriptSyntax syntax) { return $"Octopus.Action.Script.ScriptBody[{syntax.ToString()}]"; } } public static class CustomScripts { public static readonly string Prefix = "Octopus.Action.CustomScripts."; public static string GetCustomScriptStage(string deploymentStage, ScriptSyntax scriptSyntax) { return $"{Prefix}{deploymentStage}.{scriptSyntax.FileExtension()}"; } } public static class Java { public static readonly string JavaLibraryEnvVar = "JavaIntegrationLibraryPackagePath"; public static readonly string JavaArchiveExtractionDisabled = "Octopus.Action.Java.JavaArchiveExtractionDisabled"; public static readonly string DeployExploded = "Octopus.Action.JavaArchive.DeployExploded"; public static class Tomcat { public static readonly string Feature = "Octopus.Features.TomcatDeployManager"; public static readonly string DeployName = "Tomcat.Deploy.Name"; public static readonly string Controller = "Tomcat.Deploy.Controller"; public static readonly string User = "Tomcat.Deploy.User"; public static readonly string Password = "<PASSWORD>"; public static readonly string Enabled = "Tomcat.Deploy.Enabled"; public static readonly string Version = "Tomcat.Deploy.Version"; public static readonly string StateActionTypeName = "Octopus.TomcatState"; } public static class TomcatDeployCertificate { public static readonly string CertificateActionTypeName = "Octopus.TomcatDeployCertificate"; public static readonly string CatalinaHome = "Tomcat.Certificate.CatalinaHome"; public static readonly string CatalinaBase = "Tomcat.Certificate.CatalinaBase"; public static readonly string Implementation = "Tomcat.Certificate.Implementation"; public static readonly string PrivateKeyFilename = "Tomcat.Certificate.PrivateKeyFilename"; public static readonly string PublicKeyFilename = "Tomcat.Certificate.PublicKeyFilename"; public static readonly string Service = "Tomcat.Certificate.Service"; public static readonly string Port = "Tomcat.Certificate.Port"; public static readonly string Hostname = "Tomcat.Certificate.Hostname"; public static readonly string Default = "Tomcat.Certificate.Default"; } public static class JavaKeystore { public static readonly string CertificateActionTypeName = "Octopus.JavaDeployCertificate"; public static readonly string Variable = "Java.Certificate.Variable"; public static readonly string Password = "<PASSWORD>"; public static readonly string KeystoreFilename = "Java.Certificate.KeystoreFilename"; public static readonly string KeystoreAlias = "Java.Certificate.KeystoreAlias"; } public static class WildFly { public static readonly string Feature = "Octopus.Features.WildflyDeployCLI"; public static readonly string StateFeature = "Octopus.Features.WildflyStateCLI"; public static readonly string DeployName = "WildFly.Deploy.Name"; public static readonly string Controller = "WildFly.Deploy.Controller"; public static readonly string Port = "WildFly.Deploy.Port"; public static readonly string User = "WildFly.Deploy.User"; public static readonly string Password = "<PASSWORD>"; public static readonly string Protocol = "WildFly.Deploy.Protocol"; public static readonly string Enabled = "WildFly.Deploy.Enabled"; public static readonly string EnabledServerGroup = "WildFly.Deploy.EnabledServerGroup"; public static readonly string DisabledServerGroup = "WildFly.Deploy.DisabledServerGroup"; public static readonly string ServerType = "WildFly.Deploy.ServerType"; public static readonly string DeployActionTypeName = "Octopus.WildFlyDeploy"; public static readonly string CertificateActionTypeName = "Octopus.WildFlyCertificateDeploy"; public static readonly string StateActionTypeName = "Octopus.WildFlyState"; public static readonly string CertificateProfiles = "WildFly.Deploy.CertificateProfiles"; public static readonly string DeployCertificate = "WildFly.Deploy.DeployCertificate"; public static readonly string CertificateRelativeTo = "WildFly.Deploy.CertificateRelativeTo"; public static readonly string HTTPSPortBindingName = "WildFly.Deploy.HTTPSPortBindingName"; public static readonly string SecurityRealmName = "WildFly.Deploy.SecurityRealmName"; public static readonly string ElytronKeystoreName = "WildFly.Deploy.ElytronKeystoreName"; public static readonly string ElytronKeymanagerName = "WildFly.Deploy.ElytronKeymanagerName"; public static readonly string ElytronSSLContextName = "WildFly.Deploy.ElytronSSLContextName"; } } public static class Nginx { public static readonly string ConfigRoot = "Octopus.Action.Nginx.ConfigurationsDirectory"; public static readonly string SslRoot = "Octopus.Action.Nginx.CertificatesDirectory"; public static class Server { public static readonly string HostName = "Octopus.Action.Nginx.Server.HostName"; public static readonly string Bindings = "Octopus.Action.Nginx.Server.Bindings"; public static readonly string Locations = "Octopus.Action.Nginx.Server.Locations"; public static readonly string ConfigName = "Octopus.Action.Nginx.Server.ConfigName"; } } } public static class Account { public const string Name = "Octopus.Account.Name"; public const string AccountType = "Octopus.Account.AccountType"; public const string Username = "Octopus.Account.Username"; public const string Password = "<PASSWORD>"; public const string Token = "Octopus.Account.Token"; } public static class Release { public static readonly string Number = "Octopus.Release.Number"; } public static class Certificate { public static readonly string PrivateKeyAccessRules = "Octopus.Action.Certificate.PrivateKeyAccessRules"; public static string Name(string variableName) { return $"{variableName}.Name"; } public static string CertificatePem(string variableName) { return $"{variableName}.CertificatePem"; } public static string PrivateKey(string variableName) { return $"{variableName}.PrivateKey"; } public static string PrivateKeyPem(string variableName) { return $"{variableName}.PrivateKeyPem"; } public static string Subject(string variableName) { return $"{variableName}.Subject"; } } public static class Execution { public static readonly string Manifest = "Octopus.Steps.Manifest"; } } } <file_sep>#if NETCORE using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using FluentAssertions; using Newtonsoft.Json.Linq; using NUnit.Framework; using Octopus.CoreUtilities.Extensions; namespace Calamari.Tests.KubernetesFixtures { public abstract class KubernetesContextScriptWrapperLiveFixture: KubernetesContextScriptWrapperLiveFixtureBase { protected const string KubeCtlExecutableVariableName = "Octopus.Action.Kubernetes.CustomKubectlExecutable"; protected const string KubeConfigFileName = "kubeconfig.tpl"; InstallTools installTools; string terraformWorkingFolder; protected abstract string KubernetesCloudProvider { get; } protected virtual Task PreInitialise() { return Task.CompletedTask; } protected virtual Task InstallOptionalTools(InstallTools tools) { return Task.CompletedTask; } [OneTimeSetUp] public async Task SetupInfrastructure() { await PreInitialise(); terraformWorkingFolder = InitialiseTerraformWorkingFolder($"terraform_working/{KubernetesCloudProvider}", $"KubernetesFixtures/Terraform/Clusters/{KubernetesCloudProvider}"); installTools = new InstallTools(TestContext.Progress.WriteLine); await installTools.Install(); await InstallOptionalTools(installTools); InitialiseInfrastructure(terraformWorkingFolder); } [OneTimeTearDown] public void TearDownInfrastructure() { RunTerraformDestroy(terraformWorkingFolder); } [SetUp] public void SetExtraVariables() { variables.Set(KubeCtlExecutableVariableName, installTools.KubectlExecutable); } protected override Dictionary<string, string> GetEnvironments() { var currentPath = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; var delimiter = CalamariEnvironment.IsRunningOnWindows ? ";" : ":"; var toolsToAdd = ToolsToAddToPath(installTools).ToList(); if (!toolsToAdd.IsNullOrEmpty()) { foreach (var tool in toolsToAdd) { if (currentPath.Length > 0 && !currentPath.EndsWith(delimiter)) { currentPath += delimiter; } currentPath += Path.GetDirectoryName(tool); } } return new Dictionary<string, string> { { "PATH", currentPath } }; } protected abstract IEnumerable<string> ToolsToAddToPath(InstallTools tools); protected abstract void ExtractVariablesFromTerraformOutput(JObject jsonOutput); void InitialiseInfrastructure(string terraformWorkingFolder) { RunTerraformInternal(terraformWorkingFolder, "init"); RunTerraformInternal(terraformWorkingFolder, "apply", "-auto-approve"); var jsonOutput = JObject.Parse(RunTerraformOutput(terraformWorkingFolder)); ExtractVariablesFromTerraformOutput(jsonOutput); } protected void RunTerraformDestroy(string terraformWorkingFolder, Dictionary<string, string> env = null) { RunTerraformInternal(terraformWorkingFolder, env ?? new Dictionary<string, string>(), "destroy", "-auto-approve"); } string RunTerraformOutput(string terraformWorkingFolder) { return RunTerraformInternal(terraformWorkingFolder, new Dictionary<string, string>(), false, "output", "-json"); } string RunTerraformInternal(string terraformWorkingFolder, params string[] args) { return RunTerraformInternal(terraformWorkingFolder, new Dictionary<string, string>(), args); } protected string RunTerraformInternal(string terraformWorkingFolder, Dictionary<string, string> env, params string[] args) { return RunTerraformInternal(terraformWorkingFolder, env, true, args); } protected abstract Dictionary<string, string> GetEnvironmentVars(); string RunTerraformInternal(string terraformWorkingFolder, Dictionary<string, string> env, bool printOut, params string[] args) { var stdOut = new StringBuilder(); var environmentVars = GetEnvironmentVars(); environmentVars["TF_IN_AUTOMATION"] = bool.TrueString; environmentVars.AddRange(env); var result = SilentProcessRunner.ExecuteCommand(installTools.TerraformExecutable, string.Join(" ", args.Concat(new[] { "-no-color" })), terraformWorkingFolder, environmentVars, s => { stdOut.AppendLine(s); if (printOut) { TestContext.Progress.WriteLine(s); } }, e => { TestContext.Error.WriteLine(e); }); result.ExitCode.Should().Be(0, because: $"`terraform {args[0]}` should run without error and exit cleanly during infrastructure setup"); return stdOut.ToString().Trim(Environment.NewLine.ToCharArray()); } protected string InitialiseTerraformWorkingFolder(string folderName, string filesSource) { var workingFolder = Path.Combine(testFolder, folderName); if (Directory.Exists(workingFolder)) Directory.Delete(workingFolder, true); Directory.CreateDirectory(workingFolder); foreach (var file in Directory.EnumerateFiles(Path.Combine(testFolder, filesSource))) { File.Copy(file, Path.Combine(workingFolder, Path.GetFileName(file)), overwrite: true); } return workingFolder; } } } #endif<file_sep>using System; namespace Calamari.Common.Features.Scripting { /// <summary> /// Defines some common priorities for script wrappers /// </summary> public static class ScriptWrapperPriorities { /// <summary> /// The priority for the script wrapper that checks deployed Kubernetes resources status /// </summary> public const int KubernetesStatusCheckPriority = 1002; /// <summary> /// The priority for script wrappers that configure kubernetes authentication /// </summary> public const int KubernetesContextPriority = 1001; /// <summary> /// The priority for script wrappers that configure cloud authentication /// </summary> public const int CloudAuthenticationPriority = 1000; /// <summary> /// The priority for tools that configure individual tools /// </summary> public const int ToolConfigPriority = 100; /// <summary> /// The priority for tools the terminal script wrapper, which should always /// be run last /// </summary> public const int TerminalScriptPriority = -1; } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.Deployment; using Calamari.Deployment.PackageRetention; namespace Calamari.Commands { [Command("extract-package")] public class ExtractPackageCommand : Command<ExtractPackageCommandInputs> { readonly IExtractPackage extractPackage; public ExtractPackageCommand(IExtractPackage extractPackage) { this.extractPackage = extractPackage; } protected override void Execute(ExtractPackageCommandInputs inputs) { extractPackage.ExtractToStagingDirectory(new PathToPackage(inputs.PathToPackage), inputs.ExtractedToPathOutputVariableName); } } public class ExtractPackageCommandInputs { public string PathToPackage { get; set; } public string ExtractedToPathOutputVariableName { get; set; } } }<file_sep>using System; using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureCloudService { class AzureAccount { public AzureAccount(IVariables variables) { SubscriptionNumber = variables.Get(SpecialVariables.Action.Azure.SubscriptionId); ServiceManagementEndpointBaseUri = variables.Get(SpecialVariables.Action.Azure.ServiceManagementEndPoint, DefaultVariables.ServiceManagementEndpoint); CertificateThumbprint = variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint); CertificateBytes = Convert.FromBase64String(variables.Get(SpecialVariables.Action.Azure.CertificateBytes)); } public string SubscriptionNumber { get; } public string CertificateThumbprint { get; } public string ServiceManagementEndpointBaseUri { get; } public byte[] CertificateBytes { get; } } }<file_sep>using System.IO; using Calamari.Common.Features.Scripting.DotnetScript; using Calamari.Common.Plumbing.FileSystem; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Scripting { [TestFixture] public class CSharpScriptEngineFixture : ScriptEngineFixtureBase { [Category(TestCategory.ScriptingSupport.DotnetScript)] [Test, RequiresDotNetCore] public void CSharpDecryptsVariables() { using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "cs"))) { File.WriteAllText(scriptFile.FilePath, "System.Console.WriteLine(Octopus.Parameters[\"mysecrect\"]);"); var result = ExecuteScript(new DotnetScriptExecutor(), scriptFile.FilePath, GetVariables()); result.AssertOutput("KingKong"); } } } } <file_sep>using System; using Calamari.Common.Plumbing.Logging; namespace Calamari.Common.Features.Processes.Semaphores { public class LockFileBasedSemaphoreCreator : ICreateSemaphores { readonly ILog log; public LockFileBasedSemaphoreCreator(ILog log) { this.log = log; } public ISemaphore Create(string name, TimeSpan lockTimeout) { return new LockFileBasedSemaphore(name, lockTimeout, log); } } }<file_sep>using System; using Octostache; namespace Calamari.Common.Plumbing.Variables { public class CalamariVariables : VariableDictionary, IVariables { public bool IsSet(string name) { return this[name] != null; } public void Merge(VariableDictionary other) { other.GetNames().ForEach(name => Set(name, other.GetRaw(name))); } public void AddFlag(string key, bool value) { Add(key, value.ToString()); } public IVariables Clone() { var dict = new CalamariVariables(); dict.Merge(this); return dict; } public IVariables CloneAndEvaluate() { var dict = new CalamariVariables(); GetNames().ForEach(name => dict.Set(name, Get(name))); return dict; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.Java; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.Packages; using Octopus.Versioning; namespace Calamari.Integration.FileSystem { public interface IPackageStore { PackagePhysicalFileMetadata? GetPackage(string packageId, IVersion version, string hash); IEnumerable<PackagePhysicalFileMetadata> GetNearestPackages(string packageId, IVersion version, int take = 5); } public class PackageStore : IPackageStore { readonly ICalamariFileSystem fileSystem; readonly string[] supportedExtensions; public PackageStore(ICombinedPackageExtractor packageExtractor, ICalamariFileSystem fileSystem) { this.supportedExtensions = packageExtractor.Extensions.Concat(JarPackageExtractor.SupportedExtensions).Distinct().ToArray(); this.fileSystem = fileSystem; } public static string GetPackagesDirectory() { var tentacleHome = Environment.GetEnvironmentVariable("TentacleHome"); if (tentacleHome == null) throw new Exception("Environment variable 'TentacleHome' has not been set."); return Path.Combine(tentacleHome, "Files"); } public PackagePhysicalFileMetadata? GetPackage(string packageId, IVersion version, string hash) { fileSystem.EnsureDirectoryExists(GetPackagesDirectory()); foreach (var file in PackageFiles(packageId, version)) { var packageNameMetadata = PackageMetadata(file); if (packageNameMetadata == null) continue; if (!string.Equals(packageNameMetadata.PackageId, packageId, StringComparison.OrdinalIgnoreCase)) continue; if (!packageNameMetadata.Version.Equals(version) && !packageNameMetadata.FileVersion.Equals(version)) continue; var physicalPackageMetadata = PackagePhysicalFileMetadata.Build(file, packageNameMetadata); if (string.IsNullOrWhiteSpace(hash) || hash == physicalPackageMetadata?.Hash) return physicalPackageMetadata; } return null; } IEnumerable<string> PackageFiles(string packageId, IVersion? version = null) { return fileSystem.EnumerateFilesRecursively(GetPackagesDirectory(), PackageName.ToSearchPatterns(packageId, version, supportedExtensions)); } public IEnumerable<PackagePhysicalFileMetadata> GetNearestPackages(string packageId, IVersion version, int take = 5) { fileSystem.EnsureDirectoryExists(GetPackagesDirectory()); var zipPackages = from filePath in PackageFiles(packageId) let zip = PackageMetadata(filePath) where zip != null && string.Equals(zip.PackageId, packageId, StringComparison.OrdinalIgnoreCase) && zip.Version.CompareTo(version) <= 0 orderby zip.Version descending select new {zip, filePath}; return from zipPackage in zipPackages.Take(take) let package = PackagePhysicalFileMetadata.Build(zipPackage.filePath, zipPackage.zip) where package != null select package; } PackageFileNameMetadata? PackageMetadata(string file) { try { return PackageName.FromFile(file); } catch (Exception) { Log.Verbose($"Could not extract metadata for {file}. This file may be corrupt or not have a recognised filename."); return null; } } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.FileSystem; namespace Calamari.Tests.Fixtures.Integration.FileSystem { public class TestFile : IFile { private string BasePath { get; } public TestFile(string basePath) => BasePath = basePath; private string WithBase(string path) => path == null ? null : Path.Combine(BasePath, path); public bool Exists(string path) => File.Exists(WithBase(path)); public byte[] ReadAllBytes(string path) => File.ReadAllBytes(WithBase(path)); public DateTime GetCreationTime(string filePath) => File.GetCreationTime(WithBase(filePath)); public Stream Open(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare none) => File.Open(WithBase(filePath), fileMode, fileAccess, none); public void WriteAllBytes(string filePath, byte[] data) => throw new NotImplementedException("Only supports read-only operations"); public void Move(string sourceFile, string destination) => throw new NotImplementedException("Only supports read-only operations"); public void SetAttributes(string path, FileAttributes normal) => throw new NotImplementedException("Only supports read-only operations"); public void Copy(string temporaryReplacement, string originalFile, bool overwrite) => throw new NotImplementedException("Only supports read-only operations"); public void Delete(string path) => throw new NotImplementedException("Only supports read-only operations"); } } <file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Common.Commands; namespace Calamari.Deployment.Conventions { public class AggregateInstallationConvention: IInstallConvention { readonly IInstallConvention[] conventions; public AggregateInstallationConvention(params IInstallConvention[] conventions) { this.conventions = conventions; } public AggregateInstallationConvention(IEnumerable<IInstallConvention> conventions) { this.conventions = conventions?.ToArray() ?? new IInstallConvention[0]; } public void Install(RunningDeployment deployment) { foreach (var convention in conventions) { convention.Install(deployment); if (deployment.Variables.GetFlag(Common.Plumbing.Variables.KnownVariables.Action.SkipRemainingConventions)) { break; } } } } }<file_sep>using Calamari.AzureAppService; using FluentAssertions; using FluentAssertions.Execution; using NUnit.Framework; using System.Collections.Generic; using Calamari.AzureAppService.Azure; namespace Calamari.AzureAppService.Tests { [TestFixture] public class AzureWebAppTagHelperFixture { [Test] public void GetOctopusTags_FindsMatchingTags_RegardlessOfCase() { // Arrange var tags = new Dictionary<string, string> { { "oCtoPus-eNviRonMenT", "taggedEnvironment" }, { "ocTopUs-roLe", "taggedRole" }, { "OctOpuS-ProJecT", "taggedProject" }, { "oCtoPus-sPacE", "taggedSpace" }, { "ocTopUs-teNanT", "taggedTenant" }, }; // Act var foundTags = AzureWebAppTagHelper.GetOctopusTags(tags); // Assert using (new AssertionScope()) { foundTags.Environment.Should().Be("taggedEnvironment"); foundTags.Role.Should().Be("taggedRole"); foundTags.Project.Should().Be("taggedProject"); foundTags.Space.Should().Be("taggedSpace"); foundTags.Tenant.Should().Be("taggedTenant"); } } } } <file_sep>using System; using System.Linq; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Variables { public class VariablesFixture { [Test] public void ShouldLogVariables() { var variables = new CalamariVariables(); variables.Set(KnownVariables.PrintVariables, true.ToString()); variables.Set(KnownVariables.PrintEvaluatedVariables, true.ToString()); variables.Set(DeploymentEnvironment.Name, "Production"); const string variableName = "foo"; const string rawVariableValue = "The environment is #{Octopus.Environment.Name}"; variables.Set(variableName, rawVariableValue); var program = new TestProgram { VariablesOverride = variables }; program.RunStubCommand(); var messages = program.TestLog.Messages; var messagesAsString = string.Join(Environment.NewLine, program.TestLog.Messages.Select(m => m.FormattedMessage)); //Assert raw variables were output messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == $"{KnownVariables.PrintVariables} is enabled. This should only be used for debugging problems with variables, and then disabled again for normal deployments."); messagesAsString.Should().Contain("The following variables are available:"); messagesAsString.Should().Contain($"[{variableName}] = '{rawVariableValue}'"); //Assert evaluated variables were output messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == $"{KnownVariables.PrintEvaluatedVariables} is enabled. This should only be used for debugging problems with variables, and then disabled again for normal deployments."); messagesAsString.Should().Contain("The following evaluated variables are available:"); messagesAsString.Should().Contain($"[{variableName}] = 'The environment is Production'"); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Azure.Identity; using Azure.ResourceManager.Resources; using Azure.ResourceManager.Resources.Models; using Calamari.AzureAppService; using Calamari.AzureAppService.Azure; using Calamari.AzureAppService.Behaviors; using Calamari.AzureAppService.Json; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.Helpers; using FluentAssertions; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.Rest; using Newtonsoft.Json; using NUnit.Framework; using Octostache; using Polly.Retry; namespace Calamari.AzureAppService.Tests { [TestFixture] public class LegacyAzureAppServiceDeployContainerBehaviorFixture { private string clientId; private string clientSecret; private string tenantId; private string subscriptionId; private string webappName; private string resourceGroupName; private ResourceGroupsOperations resourceGroupClient; private string authToken; private WebSiteManagementClient webMgmtClient; private CalamariVariables newVariables; readonly HttpClient client = new HttpClient(); private Site site; private RetryPolicy retryPolicy; [OneTimeSetUp] public async Task Setup() { retryPolicy = RetryPolicyFactory.CreateForHttp429(); resourceGroupName = Guid.NewGuid().ToString(); clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); // For some reason we are having issues creating these linux resources on Standard in EastUS var resourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? "westus2"; authToken = await GetAuthToken(tenantId, clientId, clientSecret); var resourcesClient = new ResourcesManagementClient(subscriptionId, new ClientSecretCredential(tenantId, clientId, clientSecret)); resourceGroupClient = resourcesClient.ResourceGroups; var resourceGroup = new ResourceGroup(resourceGroupLocation); resourceGroup = await resourceGroupClient.CreateOrUpdateAsync(resourceGroupName, resourceGroup); webMgmtClient = new WebSiteManagementClient(new TokenCredentials(authToken)) { SubscriptionId = subscriptionId, HttpClient = { BaseAddress = new Uri(DefaultVariables.ResourceManagementEndpoint) }, }; var svcPlan = await retryPolicy.ExecuteAsync(async () => await webMgmtClient.AppServicePlans.BeginCreateOrUpdateAsync(resourceGroup.Name, resourceGroup.Name, new AppServicePlan(resourceGroup.Location) { Kind = "linux", Reserved = true, Sku = new SkuDescription { Name = "S1", Tier = "Standard" } })); site = await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.BeginCreateOrUpdateAsync(resourceGroup.Name, resourceGroup.Name, new Site(resourceGroup.Location) { ServerFarmId = svcPlan.Id, SiteConfig = new SiteConfig { LinuxFxVersion = @"DOCKER|mcr.microsoft.com/azuredocs/aci-helloworld", AppSettings = new List<NameValuePair> { new NameValuePair("DOCKER_REGISTRY_SERVER_URL", "https://index.docker.io"), new NameValuePair("WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false") }, AlwaysOn = true } })); webappName = site.Name; await AssertSetupSuccessAsync(); } [OneTimeTearDown] public async Task CleanupCode() { if (resourceGroupClient != null) await resourceGroupClient.StartDeleteAsync(resourceGroupName); //foreach (var tempDir in _tempDirs) //{ // if(tempDir.Exists) // tempDir.Delete(true); //} } [Test] public async Task AzureLinuxContainerDeploy() { newVariables = new CalamariVariables(); AddVariables(newVariables); var runningContext = new RunningDeployment("", newVariables); await new LegacyAzureAppServiceDeployContainerBehavior(new InMemoryLog()).Execute(runningContext); var targetSite = new AzureTargetSite(subscriptionId, resourceGroupName, site.Name); await AssertDeploySuccessAsync(targetSite); } [Test] public async Task AzureLinuxContainerSlotDeploy() { var slotName = "stage"; newVariables = new CalamariVariables(); AddVariables(newVariables); newVariables.Add("Octopus.Action.Azure.DeploymentSlot", slotName); await retryPolicy.ExecuteAsync(async () => await webMgmtClient.WebApps.BeginCreateOrUpdateSlotAsync(resourceGroupName, webappName, site, slotName)); var runningContext = new RunningDeployment("", newVariables); await new LegacyAzureAppServiceDeployContainerBehavior(new InMemoryLog()).Execute(runningContext); var targetSite = new AzureTargetSite(subscriptionId, resourceGroupName, site.Name, slotName); await AssertDeploySuccessAsync(targetSite); } async Task AssertSetupSuccessAsync() { var response = await RetryPolicies.TransientHttpErrorsPolicy.ExecuteAsync(async () => { var r = await client.GetAsync($@"https://{site.DefaultHostName}"); r.EnsureSuccessStatusCode(); return r; }); var receivedContent = await response.Content.ReadAsStringAsync(); receivedContent.Should().Contain(@"<title>Welcome to Azure Container Instances!</title>"); Assert.IsTrue(response.IsSuccessStatusCode); } async Task AssertDeploySuccessAsync(AzureTargetSite targetSite) { var imageName = newVariables.Get(SpecialVariables.Action.Package.PackageId); var registryUrl = newVariables.Get(SpecialVariables.Action.Package.Registry); var imageVersion = newVariables.Get(SpecialVariables.Action.Package.PackageVersion) ?? "latest"; var config = await webMgmtClient.WebApps.GetConfigurationAsync(targetSite); Assert.AreEqual($@"DOCKER|{imageName}:{imageVersion}", config.LinuxFxVersion); var appSettings = await webMgmtClient.WebApps.ListApplicationSettingsAsync(targetSite); Assert.AreEqual("https://" + registryUrl, appSettings.Properties["DOCKER_REGISTRY_SERVER_URL"]); } void AddVariables(CalamariVariables vars) { vars.Add(AccountVariables.ClientId, clientId); vars.Add(AccountVariables.Password, clientSecret); vars.Add(AccountVariables.TenantId, tenantId); vars.Add(AccountVariables.SubscriptionId, subscriptionId); vars.Add("Octopus.Action.Azure.ResourceGroupName", resourceGroupName); vars.Add("Octopus.Action.Azure.WebAppName", webappName); vars.Add(SpecialVariables.Action.Package.FeedId, "Feeds-42"); vars.Add(SpecialVariables.Action.Package.Registry, "index.docker.io"); vars.Add(SpecialVariables.Action.Package.PackageId, "nginx"); vars.Add(SpecialVariables.Action.Package.Image, "nginx:latest"); vars.Add(SpecialVariables.Action.Package.PackageVersion, "latest"); vars.Add(SpecialVariables.Action.Azure.DeploymentType, "Container"); //vars.Add(SpecialVariables.Action.Azure.ContainerSettings, BuildContainerConfigJson()); } private async Task<string> GetAuthToken(string tenantId, string applicationId, string password) { var resourceManagementEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ResourceManagementEndPoint) ?? DefaultVariables.ResourceManagementEndpoint; var activeDirectoryEndpointBaseUri = Environment.GetEnvironmentVariable(AccountVariables.ActiveDirectoryEndPoint) ?? DefaultVariables.ActiveDirectoryEndpoint; return await Auth.GetAuthTokenAsync(tenantId, applicationId, password, resourceManagementEndpointBaseUri, activeDirectoryEndpointBaseUri); } } }<file_sep>#!/bin/bash echo "Parameters (\$1='$1' \$2='$2')"<file_sep>using System; using Calamari.Common.Features.Scripts; namespace Calamari.Terraform { static class TerraformSpecialVariables { public const string JsonTemplateFile = "template.tf.json"; public const string HclTemplateFile = "template.tf"; public const string JsonVariablesFile = "terraform.tfvars.json"; public const string HclVariablesFile = "terraform.tfvars"; public static class Action { public static class Terraform { public const string GoogleCloudAccount = "Octopus.Action.Terraform.GoogleCloudAccount"; public const string PlanJsonOutput = "Octopus.Action.Terraform.PlanJsonOutput"; public const string PlanJsonChangesAdd = "TerraformPlanJsonAdd"; public const string PlanJsonChangesChange = "TerraformPlanJsonChange"; public const string PlanJsonChangesRemove = "TerraformPlanJsonRemove"; public const string Template = "Octopus.Action.Terraform.Template"; public const string TemplateParameters = "Octopus.Action.Terraform.TemplateParameters"; public const string RunAutomaticFileSubstitution = "Octopus.Action.Terraform.RunAutomaticFileSubstitution"; public const string ManagedAccount = "Octopus.Action.Terraform.ManagedAccount"; public const string AzureAccount = "Octopus.Action.Terraform.AzureAccount"; public const string AllowPluginDownloads = "Octopus.Action.Terraform.AllowPluginDownloads"; public const string PluginsDirectory = "Octopus.Action.Terraform.PluginsDirectory"; public const string TemplateDirectory = "Octopus.Action.Terraform.TemplateDirectory"; public const string FileSubstitution = "Octopus.Action.Terraform.FileSubstitution"; public const string Workspace = "Octopus.Action.Terraform.Workspace"; public const string CustomTerraformExecutable = "Octopus.Action.Terraform.CustomTerraformExecutable"; public const string AttachLogFile = "Octopus.Action.Terraform.AttachLogFile"; public const string AdditionalInitParams = "Octopus.Action.Terraform.AdditionalInitParams"; public const string AdditionalActionParams = "Octopus.Action.Terraform.AdditionalActionParams"; public const string VarFiles = "Octopus.Action.Terraform.VarFiles"; public const string AWSManagedAccount = "Octopus.Action.Terraform.ManagedAccount"; public const string AzureManagedAccount = "Octopus.Action.Terraform.AzureAccount"; public const string PlanOutput = "TerraformPlanOutput"; public const string PlanDetailedExitCode = "TerraformPlanDetailedExitCode"; public const string EnvironmentVariables = "Octopus.Action.Terraform.EnvVariables"; } } public static class Calamari { public static readonly string TerraformCliPath = "Octopus.Calamari.TerraformCliPath"; } public static class Packages { public static readonly string PackageId = "Octopus.Action.Package.PackageId"; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calamari.Common.Features.Discovery { public class TargetTags { public const string EnvironmentTagName = "octopus-environment"; public const string RoleTagName = "octopus-role"; public const string ProjectTagName = "octopus-project"; public const string SpaceTagName = "octopus-space"; public const string TenantTagName = "octopus-tenant"; public TargetTags( string? environment, string? role, string? project, string? space, string? tenant) { this.Environment = environment; this.Role = role; this.Project = project; this.Space = space; this.Tenant = tenant; } public string? Environment { get; } public string? Role { get; } public string? Project { get; } public string? Space { get; } public string? Tenant { get; } } } <file_sep>using System.Security.Principal; using Calamari.Common.Plumbing; using NUnit.Framework; using NUnit.Framework.Interfaces; namespace Calamari.Testing.Requirements { public class RequiresAdminAttribute : TestAttribute, ITestAction { public void BeforeTest(ITest testDetails) { var isAdmin = (new WindowsPrincipal(WindowsIdentity.GetCurrent())).IsInRole(WindowsBuiltInRole.Administrator); if (!isAdmin) { Assert.Ignore("Requires Admin Rights"); } } public void AfterTest(ITest testDetails) { } public ActionTargets Targets { get; set; } } public class RequiresWindowsServer2012OrAboveAttribute : TestAttribute, ITestAction { public void BeforeTest(ITest testDetails) { if (!CalamariEnvironment.IsRunningOnWindows) { Assert.Ignore("Requires Windows"); } #if NETFX var decimalVersion = Environment.OSVersion.Version.Major + Environment.OSVersion.Version.Minor * 0.1; if(decimalVersion < 6.2) { Assert.Ignore("Requires Windows Server 2012 or above"); } #else // .NET Core will be new enough. #endif } public void AfterTest(ITest testDetails) { } public ActionTargets Targets { get; set; } } }<file_sep>using Calamari.Common.Features.Packages; using Calamari.Common.Features.Processes; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes; using Calamari.Kubernetes.Commands; using Calamari.Kubernetes.Commands.Executors; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Integration.FileSystem; using FluentAssertions; using NUnit.Framework; using NSubstitute; namespace Calamari.Tests.KubernetesFixtures.Commands { [TestFixture] public class KubernetesApplyRawYamlCommandFixture { [Test] public void WhenResourceStatusIsDisabled_ShouldNotRunStatusChecks() { var variables = new CalamariVariables() { [KnownVariables.EnabledFeatureToggles] = "MultiGlobPathsForRawYamlFeatureToggle", [SpecialVariables.ResourceStatusCheck] = "False" }; var resourceStatusCheck = Substitute.For<IResourceStatusReportExecutor>(); var command = CreateCommand(variables, resourceStatusCheck); command.Execute(new string[]{ }); resourceStatusCheck.ReceivedCalls().Should().BeEmpty(); } [Test] public void WhenResourceStatusIsEnabled_ShouldRunStatusChecks() { var variables = new CalamariVariables() { [KnownVariables.EnabledFeatureToggles] = "MultiGlobPathsForRawYamlFeatureToggle", [SpecialVariables.ResourceStatusCheck] = "True" }; var resourceStatusCheck = Substitute.For<IResourceStatusReportExecutor>(); var command = CreateCommand(variables, resourceStatusCheck); command.Execute(new string[]{ }); resourceStatusCheck.ReceivedCalls().Should().HaveCount(1); } private KubernetesApplyRawYamlCommand CreateCommand(IVariables variables, IResourceStatusReportExecutor resourceStatusCheck) { var log = new InMemoryLog(); var fs = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, Substitute.For<ICommandLineRunner>()); return new KubernetesApplyRawYamlCommand( log, Substitute.For<IDeploymentJournalWriter>(), variables, fs, Substitute.For<IExtractPackage>(), Substitute.For<ISubstituteInFiles>(), Substitute.For<IStructuredConfigVariablesService>(), Substitute.For<IGatherAndApplyRawYamlExecutor>(), resourceStatusCheck, kubectl); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Discovery; #nullable enable namespace Calamari.AzureAppService.Azure { static class AzureWebAppTagHelper { public static TargetTags GetOctopusTags(IReadOnlyDictionary<string, string> tags) { var caseInsensitiveTagDictionary = tags.ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.OrdinalIgnoreCase); caseInsensitiveTagDictionary.TryGetValue(TargetTags.EnvironmentTagName, out string? environment); caseInsensitiveTagDictionary.TryGetValue(TargetTags.RoleTagName, out string? role); caseInsensitiveTagDictionary.TryGetValue(TargetTags.ProjectTagName, out string? project); caseInsensitiveTagDictionary.TryGetValue(TargetTags.SpaceTagName, out string? space); caseInsensitiveTagDictionary.TryGetValue(TargetTags.TenantTagName, out string? tenant); return new TargetTags( environment: environment, role: role, project: project, space: space, tenant: tenant); } } } #nullable restore<file_sep>using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Processes; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process { [TestFixture] public class CommandLineRunnerFixture { [Test] public void ScriptShouldFailIfExecutableDoesNotExist() { const string executable = "TestingCalamariThisExecutableShouldNeverExist"; var subject = new TestCommandLineRunner(new InMemoryLog(), new CalamariVariables()); var result = subject.Execute(new CommandLineInvocation(executable, "--version")); result.HasErrors.Should().BeTrue(); subject.Output.Errors.Should().Contain(CommandLineRunner.ConstructWin32ExceptionMessage(executable)); } } }<file_sep>using System; using System.Dynamic; using YamlDotNet.Core.Tokens; namespace Calamari.Deployment.PackageRetention { public abstract class CaseInsensitiveTinyType : TinyType<string> { protected CaseInsensitiveTinyType(string value) : base(value) { } public override bool Equals(object? obj) { if (obj == null) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; if (obj is CaseInsensitiveTinyType ciTinyT) return string.Equals(ciTinyT.Value, Value, StringComparison.OrdinalIgnoreCase);; return false; } public override int GetHashCode() { return GetType().GetHashCode() ^ (Value != null ? Value.ToLowerInvariant().GetHashCode() : 0); } public static bool operator ==(CaseInsensitiveTinyType? first, CaseInsensitiveTinyType? second) { if (first is null || second is null) return false; return first.Equals(second); } public static bool operator !=(CaseInsensitiveTinyType? first, CaseInsensitiveTinyType? second) { return !(first == second); } } }<file_sep>namespace Calamari.Integration.Certificates { public enum PrivateKeyAccess { ReadOnly, FullControl } }<file_sep>using System; using Calamari.Common.Features.Packages.Decorators.ArchiveLimits; using Calamari.Common.Features.Packages.Decorators.Logging; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Packages.Decorators { public static class ArchiveLimitsExtensions { public static IPackageExtractor WithExtractionLimits(this IPackageExtractor extractor, ILog log, IVariables variables) { var enforceLimits = variables.GetFlag(KnownVariables.Package.ArchiveLimits.Enabled); var logMetrics = variables.GetFlag(KnownVariables.Package.ArchiveLimits.MetricsEnabled); var result = extractor; if (enforceLimits) result = result.WithUncompressedSizeProtection(variables); if (enforceLimits) result = result.WithCompressionRatioProtection(variables); if (logMetrics) result = result.WithMetricLogging(log); return result; } static IPackageExtractor WithUncompressedSizeProtection(this IPackageExtractor extractor, IVariables variables) { try { if (!variables.IsSet(KnownVariables.Package.ArchiveLimits.MaximumUncompressedSize)) return extractor; var maximumUncompressedSize = Convert.ToInt64(variables.Get(KnownVariables.Package.ArchiveLimits.MaximumUncompressedSize)); return new EnforceDecompressionLimitDecorator(extractor, maximumUncompressedSize); } catch { return extractor; } } static IPackageExtractor WithCompressionRatioProtection(this IPackageExtractor extractor, IVariables variables) { try { if (!variables.IsSet(KnownVariables.Package.ArchiveLimits.MaximumCompressionRatio)) return extractor; var maximumCompressionRatio = Convert.ToInt32(variables.Get(KnownVariables.Package.ArchiveLimits.MaximumCompressionRatio)); return new EnforceCompressionRatioDecorator(extractor, maximumCompressionRatio); } catch { return extractor; } } static IPackageExtractor WithMetricLogging(this IPackageExtractor extractor, ILog log) { return new LogArchiveMetricsDecorator(extractor, log); } } } <file_sep>using Newtonsoft.Json.Linq; namespace Calamari.Tests.KubernetesFixtures { public static class JObjectExtensionMethods { public static T Get<T>(this JObject jsonOutput, params string[] paths) { JToken result = jsonOutput; foreach (var path in paths) { result = result[path]; if (result is null) { return default; } } return result.Value<T>(); } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Deployment.Conventions { public class ConfiguredScriptConvention : IInstallConvention { readonly ConfiguredScriptBehaviour configuredScriptBehaviour; public ConfiguredScriptConvention(ConfiguredScriptBehaviour configuredScriptBehaviour) { this.configuredScriptBehaviour = configuredScriptBehaviour; } public void Install(RunningDeployment deployment) { if (configuredScriptBehaviour.IsEnabled(deployment)) { configuredScriptBehaviour.Execute(deployment).Wait();; } } public static string GetScriptName(string deploymentStage, ScriptSyntax scriptSyntax) { return $"Octopus.Action.CustomScripts.{deploymentStage}.{scriptSyntax.FileExtension()}"; } } }<file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; namespace Calamari.Testing.Helpers; public static class MessageExtensionMethods { public static ServiceMessage[] GetServiceMessagesOfType(this IEnumerable<InMemoryLog.Message> messages, string serviceMessageType) { return messages.Where(m => m.FormattedMessage.StartsWith($"{ServiceMessage.ServiceMessageLabel}[{serviceMessageType}")) .Select(m => m.ParseRawServiceMessage()) .ToArray(); } static ServiceMessage ParseRawServiceMessage(this InMemoryLog.Message message) { var serviceMessageLog = message.FormattedMessage; serviceMessageLog = serviceMessageLog.Split('[')[1].Split(']')[0]; var parts = serviceMessageLog.Split(' '); var serviceMessageType = parts[0]; var properties = parts.Skip(1).Select(s => { var key = s.Substring(0, s.IndexOf('=')); var value = s.Substring(s.IndexOf('=') + 1).Trim('\'', '\"'); return (Key: key, Value: value); }); return new ServiceMessage(serviceMessageType, properties.ToDictionary(x => x.Key, x => AbstractLog.UnconvertServiceMessageValue(x.Value))); } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; namespace Calamari.Tests.Fixtures.PowerShell { public enum PowerShellEdition { Desktop, Core } public abstract class PowerShellFixtureBase : CalamariFixture { protected abstract PowerShellEdition PowerShellEdition { get; } void AssertPowerShellEdition(CalamariResult output) { const string powerShellCoreEdition = "PSEdition Core"; var trimmedOutput = output.CapturedOutput.AllMessages.Select(i => i.TrimEnd()); if (PowerShellEdition == PowerShellEdition.Core) trimmedOutput.Should().Contain(powerShellCoreEdition); else { // Checking for not containing 'Core' as Build Servers run on // PowerShell 3 which does not have PSEdition in the output trimmedOutput.Should().NotContain(powerShellCoreEdition); } } [Test] [TestCase("true", true)] [TestCase("false", false)] [TestCase("", false)] [TestCase(null, false)] public void ShouldCallWithNoProfileWhenVariableSet(string executeWithoutProfile, bool calledWithNoProfile) { var variables = new CalamariVariables(); if (executeWithoutProfile != null) variables.Set(PowerShellVariables.ExecuteWithoutProfile, executeWithoutProfile); var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script") .Argument("script", GetFixtureResource("Scripts", ProfileScript)), variables); output.AssertSuccess(); // Need to check for "-NoProfile -NoLogo" not just "-NoProfile" because when // run via Cake we end up with the outer Powershell call included in the // output too, which has a -NoProfile flag. output.CapturedOutput.Infos .Any(line => line.Contains("-NoLo") && line.Contains("-NoProfile")) .Should().Be(calledWithNoProfile); AssertPowerShellEdition(output); } [Test] public void ShouldNotCallWithNoProfileWhenVariableNotSet() { var (output, _) = RunPowerShellScript(ProfileScript, new Dictionary<string, string>() { [PowerShellVariables.ExecuteWithoutProfile] = "true" }); output.AssertSuccess(); output.AssertOutput("-NoProfile"); AssertPowerShellEdition(output); } string ProfileScript => IsRunningOnUnixLikeEnvironment ? "Profile.Nix.ps1" : "Profile.Windows.ps1"; [Test] public void ShouldCallHello() { var (output, _) = RunPowerShellScript("Hello.ps1"); output.AssertSuccess(); output.AssertOutput("Hello!"); AssertPowerShellEdition(output); output.AssertProcessNameAndId(PowerShellEdition == PowerShellEdition.Core ? "pwsh" : "powershell"); } [Test] public void ShouldLogWarningIfScriptArgumentUsed() { var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script") .Argument("script", GetFixtureResource("Scripts", "Hello.ps1"))); output.AssertSuccess(); output.AssertOutput($"##octopus[stdout-warning]{Environment.NewLine}The `--script` parameter is deprecated."); output.AssertOutput("Hello!"); AssertPowerShellEdition(output); } [Test] public void ShouldRetrieveCustomReturnValue() { var (output, _) = RunPowerShellScript("Exit2.ps1"); output.AssertFailure(2); output.AssertOutput("Hello!"); AssertPowerShellEdition(output); } [Test] public void ShouldCallHelloWithSensitiveVariable() { var variables = new CalamariVariables(); variables.Set("Name", "NameToEncrypt"); var (output, _) = RunPowerShellScript("HelloWithVariable.ps1", new Dictionary<string, string>() { ["Name"] = "NameToEncrypt" }, sensitiveVariablesPassword: "<PASSWORD>=="); output.AssertSuccess(); output.AssertOutput("Hello NameToEncrypt"); AssertPowerShellEdition(output); } [Test] public void ShouldCallHelloWithAdditionalOutputVariablesFileVariable() { if (IsRunningOnUnixLikeEnvironment) Assert.Inconclusive("outputVariables is provided for offline drops, and is only supported for windows deployments, since it uses DP-API to encrypt and decrypt the output variables"); var outputVariablesFile = Path.GetTempFileName(); var variables = new Dictionary<string, string>() { ["Octopus.Action[PreviousStep].Output.FirstName"] = "Steve" }; var serialized = JsonConvert.SerializeObject(variables); var bytes = ProtectedData.Protect(Encoding.UTF8.GetBytes(serialized), Convert.FromBase64String("5XETGOgqYR2bRhlfhDruEg=="), DataProtectionScope.CurrentUser); var encoded = Convert.ToBase64String(bytes); File.WriteAllText(outputVariablesFile, encoded); using (new TemporaryFile(outputVariablesFile)) { var (output, _) = RunPowerShellScript("OutputVariableFromPrevious.ps1", null, new Dictionary<string, string>() { ["outputVariables"] = outputVariablesFile, ["outputVariablesPassword"] = "<PASSWORD>==" }); output.AssertSuccess(); output.AssertOutput("Hello Steve"); AssertPowerShellEdition(output); } } [Test] public void ShouldConsumeParametersWithQuotesUsingDeprecatedArgument() { var (output, _) = RunPowerShellScript("Parameters.ps1", additionalParameters: new Dictionary<string, string>() { ["scriptParameters"] = "-Parameter0 \"Para meter0\" -Parameter1 'Para meter1'" }); output.AssertSuccess(); output.AssertOutput("Parameters Para meter0Para meter1"); AssertPowerShellEdition(output); } [Test] public void ShouldConsumeParametersWithQuotes() { var (output, _) = RunPowerShellScript("Parameters.ps1", new Dictionary<string, string>() { [SpecialVariables.Action.Script.ScriptParameters] = "-Parameter0 \"Para meter0\" -Parameter1 'Para meter1'" }); output.AssertSuccess(); output.AssertOutput("Parameters Para meter0Para meter1"); AssertPowerShellEdition(output); } [Test] public void ShouldCaptureAllOutput() { var (output, _) = RunPowerShellScript("Output.ps1"); output.AssertFailure(); output.AssertOutput("Hello, write-host!"); output.AssertOutput("Hello, write-output!"); output.AssertOutput("Hello, write-verbose!"); output.AssertOutput("Hello, write-warning!"); output.AssertErrorOutput("Hello-Error!"); output.AssertNoOutput("This warning should not appear in logs!"); AssertPowerShellEdition(output); } [Test] public void ShouldWriteServiceMessageForArtifacts() { var artifactPath = IsRunningOnUnixLikeEnvironment ? @"\tmp\calamari\File.txt" : @"C:\Path\File.txt"; var (output, _) = RunPowerShellScript("CanCreateArtifact.ps1", new Dictionary<string, string> {{"ArtifactPath", artifactPath}}); output.AssertSuccess(); var expectedArtifactServiceMessage = IsRunningOnUnixLikeEnvironment ? "##octopus[createArtifact path='L3RtcC9jYWxhbWFyaS9GaWxlLnR4dA==' name='XHRtcFxjYWxhbWFyaVxGaWxlLnR4dA==' length='MA==']" : "##octopus[createArtifact path='QzpcUGF0aFxGaWxlLnR4dA==' name='RmlsZS50eHQ=' length='MA==']"; output.AssertOutput(expectedArtifactServiceMessage); AssertPowerShellEdition(output); } [Test] public void ShouldWriteServiceMessageForUpdateProgress() { var (output, _) = RunPowerShellScript("UpdateProgress.ps1"); output.AssertSuccess(); output.AssertOutput("##octopus[progress percentage='NTA=' message='SGFsZiBXYXk=']"); AssertPowerShellEdition(output); } [Test] public void ShouldWriteServiceMessageForUpdateProgressFromPipeline() { var (output, _) = RunPowerShellScript("UpdateProgressFromPipeline.ps1"); output.AssertSuccess(); output.AssertOutput("##octopus[progress percentage='NTA=' message='SGFsZiBXYXk=']"); AssertPowerShellEdition(output); } [Test] public void ShouldWriteServiceMessageForPipedArtifacts() { var tempPath = Path.GetTempPath(); // There is no nice platform agnostic way to do this until powershell 7 ships and is on all our test agents (this introduces a new "TEMP" drive) var artifacts = Enumerable.Range(0, 3).Select(i => new Artifact(Path.Combine(tempPath, $"CanCreateArtifactPipedTestFile{i}.artifact"))).ToList(); foreach (var artifact in artifacts) { artifact.Create(); } try { var (output, _) = RunPowerShellScript("CanCreateArtifactPiped.ps1", new Dictionary<string, string> {{"TempDirectory", tempPath}}); output.AssertSuccess(); foreach (var artifact in artifacts) { var expectedPath = Convert.ToBase64String(Encoding.UTF8.GetBytes(artifact.Path)); var expectedName = Convert.ToBase64String(Encoding.UTF8.GetBytes(artifact.Name)); output.AssertOutput($"##octopus[createArtifact path='{expectedPath}' name='{expectedName}' length='MA==']"); } AssertPowerShellEdition(output); } finally { foreach (var artifact in artifacts) { artifact.Delete(); } } } class Artifact { public string Name => System.IO.Path.GetFileName(Path); public string Path { get; } public Artifact(string path) { Path = path; } public void Create() { if (!File.Exists(Path)) File.WriteAllText(Path, ""); } public void Delete() { File.Delete(Path); } } [Test] public void ShouldWriteVerboseMessageForArtifactsThatDoNotExist() { var nonExistantArtifactPath = IsRunningOnUnixLikeEnvironment ? @"\tmp\NonExistantPath\NonExistantFile.txt" : @"C:\NonExistantPath\NonExistantFile.txt"; var (output, _) = RunPowerShellScript("WarningForMissingArtifact.ps1", new Dictionary<string, string> {{"ArtifactPath", nonExistantArtifactPath}}); output.AssertSuccess(); output.AssertOutput($@"There is no file at '{nonExistantArtifactPath}' right now. Writing the service message just in case the file is available when the artifacts are collected at a later point in time."); var expectedArtifactServiceMessage = IsRunningOnUnixLikeEnvironment ? "##octopus[createArtifact path='L3RtcC9Ob25FeGlzdGFudFBhdGgvTm9uRXhpc3RhbnRGaWxlLnR4dA==' name='XHRtcFxOb25FeGlzdGFudFBhdGhcTm9uRXhpc3RhbnRGaWxlLnR4dA==' length='MA==']" : "##octopus[createArtifact path='QzpcTm9uRXhpc3RhbnRQYXRoXE5vbkV4aXN0YW50RmlsZS50eHQ=' name='Tm9uRXhpc3RhbnRGaWxlLnR4dA==' length='MA==']"; output.AssertOutput(expectedArtifactServiceMessage); AssertPowerShellEdition(output); } [Test] public void ShouldAllowDotSourcing() { var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script") .Argument("script", GetFixtureResource("Scripts", "CanDotSource.ps1"))); output.AssertSuccess(); output.AssertOutput("Hello!"); AssertPowerShellEdition(output); } [Test] public void ShouldSetVariables() { var (output, variables) = RunPowerShellScript("CanSetVariable.ps1"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='VGVzdEE=' value='V29ybGQh']"); Assert.AreEqual("World!", variables.Get("TestA")); AssertPowerShellEdition(output); } [Test] public void ShouldSetSensitiveVariables() { var (output, variables) = RunPowerShellScript("CanSetVariable.ps1"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='U2VjcmV0U3F1aXJyZWw=' value='WCBtYXJrcyB0aGUgc3BvdA==' sensitive='VHJ1ZQ==']"); Assert.AreEqual("X marks the spot", variables.Get("SecretSquirrel")); AssertPowerShellEdition(output); } [Test] public void ShouldSetActionIndexedOutputVariables() { var (output, variables) = RunPowerShellScript("CanSetVariable.ps1", new Dictionary<string, string> { [ActionVariables.Name] = "run-script" }); Assert.AreEqual("World!", variables.Get("Octopus.Action[run-script].Output.TestA")); AssertPowerShellEdition(output); } [Test] public void ShouldSetMachineIndexedOutputVariables() { var (output, variables) = RunPowerShellScript("CanSetVariable.ps1", new Dictionary<string, string> { [ActionVariables.Name] = "run-script", [MachineVariables.Name] = "App01" }); Assert.AreEqual("World!", variables.Get("Octopus.Action[run-script].Output[App01].TestA")); AssertPowerShellEdition(output); } [Test] public void ShouldFailOnInvalid() { var (output, _) = RunPowerShellScript("Invalid.ps1"); output.AssertFailure(); output.AssertErrorOutput("A positional parameter cannot be found that accepts"); AssertPowerShellEdition(output); } [Test] public void ShouldFailOnInvalidSyntax() { var (output, _) = RunPowerShellScript("InvalidSyntax.ps1"); output.AssertFailure(); //ensure it logs the type of error output.AssertErrorOutput("ParserError:"); //ensure it logs the error line in question output.AssertErrorOutput("+ $#FC(@UCJ@(#U"); //ensure it logs each of the errors output.AssertErrorOutput("Unexpected token '@(' in expression or statement."); output.AssertErrorOutput("Missing closing ')' in expression."); output.AssertErrorOutput("The splatting operator '@' cannot be used to reference variables in an expression. '@UCJ' can be used only as an argument to a command. To reference variables in an expression use '$UCJ'."); //ensure it logs the stack trace output.AssertErrorOutput("at <ScriptBlock>, "); AssertPowerShellEdition(output); } [Test] public void ShouldPrintVariables() { var (output, _) = RunPowerShellScript("PrintVariables.ps1", new Dictionary<string, string> { ["Variable1"] = "ABC", ["Variable2"] = "DEF", ["Variable3"] = "GHI", ["Foo_bar"] = "Hello", ["Host"] = "Never", }); output.AssertSuccess(); output.AssertOutput("V1= ABC"); output.AssertOutput("V2= DEF"); output.AssertOutput("V3= GHI"); output.AssertOutput("FooBar= Hello"); // Legacy - '_' used to be removed output.AssertOutput("Foo_Bar= Hello"); // Current - '_' is valid in PowerShell AssertPowerShellEdition(output); } [Test] public void ShouldSupportModulesInVariables() { var (output, _) = RunPowerShellScript("UseModule.ps1", new Dictionary<string, string> { ["Octopus.Script.Module[Foo]"] = "function SayHello() { Write-Host \"Hello from module!\" }", ["Variable2"] = "DEF", ["Variable3"] = "GHI", ["Foo_bar"] = "Hello", ["Host"] = "Never", }); output.AssertSuccess(); output.AssertOutput("Hello from module!"); AssertPowerShellEdition(output); } [Test] public void ShouldShowFriendlyErrorWithInvalidSyntaxInScriptModule() { var (output, _) = RunPowerShellScript("UseModule.ps1", new Dictionary<string, string>() { ["Octopus.Script.Module[Foo]"] = "function SayHello() { Write-Host \"Hello from module! }" }); output.AssertFailure(); //ensure it logs the script module name output.AssertErrorOutput("Failed to import Script Module 'Foo' from '"); //ensure it logs the type of error output.AssertErrorOutput("ParserError:"); //ensure it logs the error line in question output.AssertErrorOutput("+ function SayHello() { Write-Host \"Hello from module! }"); //ensure it logs each of the errors output.AssertErrorOutput("The string is missing the terminator: \"."); output.AssertErrorOutput("Missing closing '}' in statement block"); //ensure it logs the stack trace output.AssertErrorOutput("at Import-ScriptModule, "); output.AssertErrorOutput("at <ScriptBlock>, "); AssertPowerShellEdition(output); } [Test] public void ShouldFailIfAModuleHasASyntaxError() { var (output, _) = RunPowerShellScript("UseModule.ps1", new Dictionary<string, string>() { ["Octopus.Script.Module[Foo]"] = "function SayHello() { Write-Host \"Hello from module! }" }); output.AssertFailure(); output.AssertErrorOutput("ParserError", true); output.AssertErrorOutput("is missing the terminator", true); AssertPowerShellEdition(output); } [Test] public void ShouldNotSubstituteVariablesInNonPackagedScript() { // Use a temp file for the script to avoid mutating the script file for other tests var scriptFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".ps1"); File.WriteAllText(scriptFile, "Write-Host \"Hello #{Octopus.Environment.Name}!\""); var variables = new CalamariVariables(); variables.Set("Octopus.Environment.Name", "Production"); using (new TemporaryFile(scriptFile)) { var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script") .Argument("script", scriptFile), variables); output.AssertSuccess(); output.AssertOutput("Hello #{Octopus.Environment.Name}!"); AssertPowerShellEdition(output); } } [Test] [Description("Proves packaged scripts can have variables substituted into them before running")] public void ShouldSubstituteVariablesInPackagedScripts() { var variables = new CalamariVariables(); variables.Set("Octopus.Environment.Name", "Production"); variables.Set(ScriptVariables.ScriptFileName, "Deploy.ps1"); var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script") .Argument("package", GetFixtureResource("Packages", "PackagedScript.1.0.0.zip")), variables); output.AssertSuccess(); output.AssertOutput("Extracting package"); output.AssertOutput("Performing variable substitution"); output.AssertOutput("OctopusParameter: Production"); output.AssertOutput("InlineVariable: Production"); output.AssertOutput("VariableSubstitution: Production"); AssertPowerShellEdition(output); } [Test] public void ShouldPing() { var pingScriptName = IsRunningOnUnixLikeEnvironment ? "Ping.Nix.ps1" : "Ping.Win.ps1"; var (output, _) = RunPowerShellScript(pingScriptName); output.AssertSuccess(); var expectedPingingText = IsRunningOnUnixLikeEnvironment ? "PING " : "Pinging "; output.AssertOutput(expectedPingingText); AssertPowerShellEdition(output); } [Test] public void ShouldExecuteWhenPathContainsSingleQuote() { var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script") .Argument("script", GetFixtureResource(Path.Combine("Scripts", "Path With '"), "PathWithSingleQuote.ps1"))); output.AssertSuccess(); output.AssertOutput("Hello from a path containing a '"); AssertPowerShellEdition(output); } [Test] public void ShouldExecuteWhenPathContainsDollar() { var output = InvokeCalamariForPowerShell(calamari => calamari .Action("run-script") .Argument("script", GetFixtureResource(Path.Combine("Scripts", "Path With $"), "PathWithDollar.ps1"))); output.AssertSuccess(); output.AssertOutput("Hello from a path containing a $"); AssertPowerShellEdition(output); } [Test] public void ShouldNotFailOnStdErr() { var (output, _) = RunPowerShellScript("StdErr.ps1"); output.AssertSuccess(); output.AssertErrorOutput("error"); AssertPowerShellEdition(output); } [Test] public void ShouldFailOnStdErrWithTreatScriptWarningsAsErrors() { var (output, _) = RunPowerShellScript("StdErr.ps1", new Dictionary<string, string>() { ["Octopus.Action.FailScriptOnErrorOutput"] = "True" }); output.AssertFailure(); output.AssertErrorOutput("error"); AssertPowerShellEdition(output); } [Test] public void ShouldPassOnStdInfoWithTreatScriptWarningsAsErrors() { var (output, _) = RunPowerShellScript("Hello.ps1", new Dictionary<string, string>() { ["Octopus.Action.FailScriptOnErrorOutput"] = "True" }); output.AssertSuccess(); output.AssertOutput("Hello!"); AssertPowerShellEdition(output); } [Test] public void ShouldNotDoubleReplaceVariables() { var (output, _) = RunPowerShellScript("DontDoubleReplace.ps1", new Dictionary<string, string>() { ["Octopus.Machine.Name"] = "Foo" }); output.AssertSuccess(); output.AssertOutput("The Octopus variable for machine name is #{Octopus.Machine.Name}"); output.AssertOutput("An example of this evaluated is: 'Foo'"); AssertPowerShellEdition(output); } [Test] public void CharacterWithBomMarkCorrectlyEncoded() { var (output, _) = RunPowerShellScript("ScriptWithBOM.ps1"); output.AssertSuccess(); output.AssertOutput(string.Join(Environment.NewLine, "45", "226", "128", "147")); AssertPowerShellEdition(output); } static bool IsRunningOnUnixLikeEnvironment => CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac; protected CalamariResult InvokeCalamariForPowerShell(Action<CommandLine> buildCommand, CalamariVariables variables = null) { var variableDictionary = variables ?? new CalamariVariables(); variableDictionary.Add(PowerShellVariables.Edition, GetPowerShellEditionVariable()); using (var variablesFile = CreateVariablesFile(variableDictionary)) { var calamariCommand = Calamari(); buildCommand(calamariCommand); calamariCommand.Argument("variables", variablesFile.FilePath); return Invoke(calamariCommand); } } VariableFile CreateVariablesFile(CalamariVariables variables) { return new VariableFile(variables); } class VariableFile : IDisposable { readonly TemporaryFile tempFile; public string FilePath { get; } public VariableFile(CalamariVariables variables) { FilePath = Path.GetTempFileName(); tempFile = new TemporaryFile(FilePath); variables.Save(FilePath); } public void Dispose() { tempFile.Dispose(); } } (CalamariResult result, IVariables variables) RunPowerShellScript(string scriptName, Dictionary<string, string> additionalVariables = null, Dictionary<string, string> additionalParameters = null, string sensitiveVariablesPassword = null) { var variablesDictionary = additionalVariables ?? new Dictionary<string, string>(); variablesDictionary.Add(PowerShellVariables.Edition, GetPowerShellEditionVariable()); return RunScript(scriptName, variablesDictionary, additionalParameters, sensitiveVariablesPassword); } string GetPowerShellEditionVariable() { switch(PowerShellEdition) { case PowerShellEdition.Desktop: return "Desktop"; case PowerShellEdition.Core: return "Core"; default: throw new ArgumentOutOfRangeException(); } } } }<file_sep>using System.Security.Cryptography.X509Certificates; using Calamari.Common.Plumbing.Variables; using Octostache; namespace Calamari.Integration.Certificates { public interface ICertificateStore { X509Certificate2 GetOrAdd(string thumbprint, byte[] bytes); X509Certificate2 GetOrAdd(string thumbprint, byte[] bytes, StoreName storeName); X509Certificate2 GetOrAdd(IVariables variables, string certificateVariable, string storeName, string storeLocation = "CurrentUser"); X509Certificate2 GetOrAdd(IVariables variables, string certificateVariable, StoreName storeName, StoreLocation storeLocation = StoreLocation.CurrentUser); } }<file_sep>using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; namespace Calamari.Kubernetes.Integration { public class AzureCli : CommandLineTool { public AzureCli(ILog log, ICommandLineRunner commandLineRunner, string workingDirectory, Dictionary<string, string> environmentVars) : base(log, commandLineRunner, workingDirectory, environmentVars) { } public bool TrySetAz() { var result = CalamariEnvironment.IsRunningOnWindows ? ExecuteCommandAndReturnOutput("where", "az.cmd") : ExecuteCommandAndReturnOutput("which", "az"); var foundExecutable = result.Output.InfoLogs.FirstOrDefault(); if (string.IsNullOrEmpty(foundExecutable)) { log.Error("Could not find az. Make sure az is on the PATH."); return false; } ExecutableLocation = foundExecutable.Trim(); return true; } public void ConfigureAzAccount(string subscriptionId, string tenantId, string clientId, string password, string azEnvironment) { environmentVars.Add("AZURE_CONFIG_DIR", Path.Combine(workingDirectory, "azure-cli")); TryExecuteCommandAndLogOutput(ExecutableLocation, "cloud", "set", "--name", azEnvironment); log.Verbose("Azure CLI: Authenticating with Service Principal"); // Use the full argument with an '=' because of https://github.com/Azure/azure-cli/issues/12105 ExecuteCommandAndLogOutput(new CommandLineInvocation(ExecutableLocation, "login", "--service-principal", $"--username=\"{clientId}\"", $"--password=\"{<PASSWORD>}\"", $"--tenant=\"{tenantId}\"")); log.Verbose($"Azure CLI: Setting active subscription to {subscriptionId}"); ExecuteCommandAndLogOutput(new CommandLineInvocation(ExecutableLocation, "account", "set", "--subscription", subscriptionId)); log.Info("Successfully authenticated with the Azure CLI"); } public void ConfigureAksKubeCtlAuthentication(Kubectl kubectlCli, string clusterResourceGroup, string clusterName, string clusterNamespace, string kubeConfigPath, bool adminLogin) { log.Info($"Creating kubectl context to AKS Cluster in resource group {clusterResourceGroup} called {clusterName} (namespace {clusterNamespace}) using a AzureServicePrincipal"); var arguments = new List<string>(new[] { "aks", "get-credentials", "--resource-group", clusterResourceGroup, "--name", clusterName, "--file", $"\"{kubeConfigPath}\"", "--overwrite-existing" }); if (adminLogin) { arguments.Add("--admin"); clusterName += "-admin"; } var result = ExecuteCommandAndLogOutput(new CommandLineInvocation(ExecutableLocation, arguments.ToArray())); result.VerifySuccess(); kubectlCli.ExecuteCommandAndAssertSuccess("config", "set-context", clusterName, $"--namespace={@clusterNamespace}"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure.ResourceManager; using Azure.ResourceManager.ResourceGraph; using Azure.ResourceManager.ResourceGraph.Models; using Calamari.AzureAppService.Azure; using Calamari.Common.Commands; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; using JsonException = System.Text.Json.JsonException; using JsonSerializer = System.Text.Json.JsonSerializer; #nullable enable namespace Calamari.AzureAppService.Behaviors { public class TargetDiscoveryBehaviour : IDeployBehaviour { // These values are well-known resource types in Azure's API. // The format is {resource-provider}/{resource-type} // WebAppType refers to Azure Web Apps, Azure Functions Apps and Azure App Services // while WebAppSlotsType refers to Slots of any of the above resources. // More info about Azure Resource Providers and Types here: // https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/resource-providers-and-types private const string WebAppSlotsType = "microsoft.web/sites/slots"; private const string WebAppType = "microsoft.web/sites"; private ILog Log { get; } public TargetDiscoveryBehaviour(ILog log) { Log = log; } public bool IsEnabled(RunningDeployment context) => true; public async Task Execute(RunningDeployment runningDeployment) { var targetDiscoveryContext = GetTargetDiscoveryContext(runningDeployment.Variables); if (targetDiscoveryContext?.Authentication == null || targetDiscoveryContext.Scope == null) { Log.Warn("Aborting target discovery."); return; } var account = targetDiscoveryContext.Authentication.AccountDetails; Log.Verbose("Looking for Azure web apps using:"); Log.Verbose($" Subscription ID: {account.SubscriptionNumber}"); Log.Verbose($" Tenant ID: {account.TenantId}"); Log.Verbose($" Client ID: {account.ClientId}"); var armClient = account.CreateArmClient(retryOptions => { retryOptions.MaxDelay = TimeSpan.FromSeconds(10); retryOptions.MaxRetries = 5; }); try { var resources = await armClient.GetResourcesByType(WebAppType, WebAppSlotsType); var discoveredTargetCount = 0; Log.Verbose($"Found {resources.Length} candidate web app resources."); foreach (var resource in resources) { var tagValues = resource.Tags; if (tagValues == null) continue; var tags = AzureWebAppTagHelper.GetOctopusTags(tagValues); var matchResult = targetDiscoveryContext.Scope.Match(tags); if (matchResult.IsSuccess) { discoveredTargetCount++; Log.Info($"Discovered matching web app resource: {resource.Name}"); WriteTargetCreationServiceMessage( resource, targetDiscoveryContext, matchResult); } else { Log.Verbose($"Web app {resource.Name} does not match target requirements:"); foreach (var reason in matchResult.FailureReasons) { Log.Verbose($"- {reason}"); } } } if (discoveredTargetCount > 0) { Log.Info($"{discoveredTargetCount} target{(discoveredTargetCount > 1 ? "s" : "")} found."); } else { Log.Warn("Could not find any Azure web app targets."); } } catch (Exception ex) { Log.Warn("Error connecting to Azure to look for web apps:"); Log.Warn(ex.Message); Log.Warn("Aborting target discovery."); } } private void WriteTargetCreationServiceMessage( AzureResource resource, TargetDiscoveryContext<AccountAuthenticationDetails<ServicePrincipalAccount>> context, TargetMatchResult matchResult) { var resourceName = resource.Name; string? slotName = null; if (resource.IsSlot) { slotName = resource.SlotName; resourceName = resource.ParentName; } Log.WriteServiceMessage( TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage( resource.ResourceGroup, resourceName, context.Authentication!.AccountId, matchResult.Role, context.Scope!.WorkerPoolId, slotName)); } private TargetDiscoveryContext<AccountAuthenticationDetails<ServicePrincipalAccount>>? GetTargetDiscoveryContext( IVariables variables) { const string contextVariableName = "Octopus.TargetDiscovery.Context"; var json = variables.Get(contextVariableName); if (json == null) { Log.Warn($"Could not find target discovery context in variable {contextVariableName}."); return null; } var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; try { return JsonSerializer .Deserialize<TargetDiscoveryContext<AccountAuthenticationDetails<ServicePrincipalAccount>>>( json, options); } catch (JsonException ex) { Log.Warn($"Target discovery context from variable {contextVariableName} is in wrong format: {ex.Message}"); return null; } } } public static class TargetDiscoveryHelpers { public static ServiceMessage CreateWebAppTargetCreationServiceMessage(string? resourceGroupName, string webAppName, string accountId, string role, string? workerPoolId, string? slotName) { var parameters = new Dictionary<string, string?> { { "azureWebApp", webAppName }, { "name", $"azure-web-app/{resourceGroupName}/{webAppName}{(slotName == null ? "" : $"/{slotName}")}" }, { "azureWebAppSlot", slotName }, { "azureResourceGroupName", resourceGroupName }, { "octopusAccountIdOrName", accountId }, { "octopusRoles", role }, { "updateIfExisting", "True" }, { "octopusDefaultWorkerPoolIdOrName", workerPoolId }, { "isDynamic", "True" } }; return new ServiceMessage( "create-azurewebapptarget", parameters.Where(p => p.Value != null).ToDictionary(p => p.Key, p => p.Value!)); } public static async Task<AzureResource[]> GetResourcesByType(this ArmClient armClient, params string[] types) { var tenant = armClient.GetTenants().First(); var typesToRetrieveClause = string.Join(" or ", types.Select(t => $"type == '{t}'")); var typeCondition = types.Any() ? $"| where { typesToRetrieveClause } |" : string.Empty; var query = new ResourceQueryContent( $"Resources {typeCondition} project name, type, tags, resourceGroup"); var response = await tenant.GetResourcesAsync(query, CancellationToken.None); return JsonConvert.DeserializeObject<AzureResource[]>(response.Value.Data.ToString()); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Features.Scripts; namespace Calamari.Common.Features.FunctionScriptContributions { public interface ICodeGenFunctions { ScriptSyntax Syntax { get; } string Generate(IEnumerable<ScriptFunctionRegistration> registrations); } }<file_sep>namespace Calamari.AzureServiceFabric { static class SpecialVariables { public static class Action { public static class ServiceFabric { public static readonly string ConnectionEndpoint = "Octopus.Action.ServiceFabric.ConnectionEndpoint"; public static readonly string SecurityMode = "Octopus.Action.ServiceFabric.SecurityMode"; public static readonly string ServerCertThumbprint = "Octopus.Action.ServiceFabric.ServerCertThumbprint"; public static readonly string ClientCertVariable = "Octopus.Action.ServiceFabric.ClientCertVariable"; public static readonly string CertificateStoreLocation = "Octopus.Action.ServiceFabric.CertificateStoreLocation"; public static readonly string CertificateStoreName = "Octopus.Action.ServiceFabric.CertificateStoreName"; public static readonly string AadUserCredentialUsername = "Octopus.Action.ServiceFabric.AadUserCredentialUsername"; public static readonly string AadUserCredentialPassword = "<PASSWORD>"; public static readonly string CertificateFindType = "Octopus.Action.ServiceFabric.CertificateFindType"; public static readonly string CertificateFindValueOverride = "Octopus.Action.ServiceFabric.CertificateFindValueOverride"; public static readonly string AadCredentialType = "Octopus.Action.ServiceFabric.AadCredentialType"; public static readonly string AadClientCredentialSecret = "Octopus.Action.ServiceFabric.AadClientCredentialSecret"; public static readonly string PublishProfileFile = "Octopus.Action.ServiceFabric.PublishProfileFile"; public static readonly string DeployOnly = "Octopus.Action.ServiceFabric.DeployOnly"; public static readonly string UnregisterUnusedApplicationVersionsAfterUpgrade = "Octopus.Action.ServiceFabric.UnregisterUnusedApplicationVersionsAfterUpgrade"; public static readonly string OverrideUpgradeBehavior = "Octopus.Action.ServiceFabric.OverrideUpgradeBehavior"; public static readonly string OverwriteBehavior = "Octopus.Action.ServiceFabric.OverwriteBehavior"; public static readonly string SkipPackageValidation = "Octopus.Action.ServiceFabric.SkipPackageValidation"; public static readonly string CopyPackageTimeoutSec = "Octopus.Action.ServiceFabric.CopyPackageTimeoutSec"; public static readonly string RegisterApplicationTypeTimeoutSec = "Octopus.Action.ServiceFabric.RegisterApplicationTypeTimeoutSec"; public static readonly string LogExtractedApplicationPackage = "Octopus.Action.ServiceFabric.LogExtractedApplicationPackage"; } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Web; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Octopus.Versioning; namespace Calamari.Integration.Packages.Download { public class OciPackageDownloader : IPackageDownloader { const string VersionPath = "v2"; const string OciImageManifestAcceptHeader = "application/vnd.oci.image.manifest.v1+json"; const string ManifestImageTitleAnnotationKey = "org.opencontainers.image.title"; const string ManifestLayerPropertyName = "layers"; const string ManifestLayerDigestPropertyName = "digest"; const string ManifestLayerSizePropertyName = "size"; const string ManifestLayerAnnotationsPropertyName = "annotations"; const string ManifestLayerMediaTypePropertyName = "mediaType"; static Regex PackageDigestHashRegex = new Regex(@"[A-Za-z0-9_+.-]+:(?<hash>[A-Fa-f0-9]+)", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase); static readonly IPackageDownloaderUtils PackageDownloaderUtils = new PackageDownloaderUtils(); readonly ICalamariFileSystem fileSystem; readonly ICombinedPackageExtractor combinedPackageExtractor; readonly HttpClient client; public OciPackageDownloader( ICalamariFileSystem fileSystem, ICombinedPackageExtractor combinedPackageExtractor) { this.fileSystem = fileSystem; this.combinedPackageExtractor = combinedPackageExtractor; client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.None }); } public PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, string? feedUsername, string? feedPassword, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { var cacheDirectory = PackageDownloaderUtils.GetPackageRoot(feedId); fileSystem.EnsureDirectoryExists(cacheDirectory); if (!forcePackageDownload) { var downloaded = SourceFromCache(packageId, version, cacheDirectory); if (downloaded != null) { Log.VerboseFormat("Package was found in cache. No need to download. Using file: '{0}'", downloaded.FullFilePath); return downloaded; } } var tempDirectory = fileSystem.CreateTemporaryDirectory(); using (new TemporaryDirectory(tempDirectory)) { var homeDir = Path.Combine(tempDirectory, "oci"); if (!Directory.Exists(homeDir)) { Directory.CreateDirectory(homeDir); } var stagingDir = Path.Combine(homeDir, "staging"); if (!Directory.Exists(stagingDir)) { Directory.CreateDirectory(stagingDir); } var versionString = FixVersion(version); var apiUrl = GetApiUri(feedUri); var (digest, size, extension) = GetPackageDetails(apiUrl, packageId, versionString, feedUsername, feedPassword); var hash = GetPackageHashFromDigest(digest); var cachedFileName = PackageName.ToCachedFileName(packageId, version, extension); var downloadPath = Path.Combine(Path.Combine(stagingDir, cachedFileName)); DownloadPackage(apiUrl, packageId, digest, feedUsername, feedPassword, downloadPath); var localDownloadName = Path.Combine(cacheDirectory, cachedFileName); fileSystem.MoveFile(downloadPath, localDownloadName); return !string.IsNullOrEmpty(hash) ? new PackagePhysicalFileMetadata( PackageName.FromFile(localDownloadName), localDownloadName, hash, size) : PackagePhysicalFileMetadata.Build(localDownloadName) ?? throw new CommandException($"Unable to retrieve metadata for package {packageId}, version {version}"); } } // oci registries don't support the '+' tagging // https://helm.sh/docs/topics/registries/#oci-feature-deprecation-and-behavior-changes-with-v380 static string FixVersion(IVersion version) => version.ToString().Replace("+", "_"); static string? GetPackageHashFromDigest(string digest) => PackageDigestHashRegex.Match(digest).Groups["hash"]?.Value; (string digest, int size, string extension) GetPackageDetails( Uri url, string packageId, string version, string? feedUserName, string? feedPassword) { using var response = Get(new Uri($"{url}/{packageId}/manifests/{version}"), new NetworkCredential(feedUserName, feedPassword), ApplyAccept); var manifest = JsonConvert.DeserializeObject<JObject>(response.Content.ReadAsStringAsync().Result); var layer = manifest.Value<JArray>(ManifestLayerPropertyName)[0]; var digest = layer.Value<string>(ManifestLayerDigestPropertyName); var size = layer.Value<int>(ManifestLayerSizePropertyName); var extension = GetExtensionFromManifest(layer); return (digest, size, extension); } string GetExtensionFromManifest(JToken layer) { var artifactTitle = layer.Value<JObject>(ManifestLayerAnnotationsPropertyName)?[ManifestImageTitleAnnotationKey]?.Value<string>() ?? ""; var extension = combinedPackageExtractor .Extensions .FirstOrDefault(ext => Path.GetExtension(artifactTitle).Equals(ext, StringComparison.OrdinalIgnoreCase)); return extension ?? (layer.Value<string>(ManifestLayerMediaTypePropertyName).EndsWith("tar+gzip") ? ".tgz" : ".tar"); } void DownloadPackage( Uri url, string packageId, string digest, string? feedUsername, string? feedPassword, string downloadPath) { using var fileStream = fileSystem.OpenFile(downloadPath, FileAccess.Write); using var response = Get(new Uri($"{url}/{packageId}/blobs/{digest}"), new NetworkCredential(feedUsername, feedPassword)); if (!response.IsSuccessStatusCode) { throw new CommandException( $"Failed to download artifact (Status Code {(int)response.StatusCode}). Reason: {response.ReasonPhrase}"); } #if NET40 response.Content.CopyToAsync(fileStream).Wait(); #else response.Content.CopyToAsync(fileStream).GetAwaiter().GetResult(); #endif } static void ApplyAccept(HttpRequestMessage request) => request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(OciImageManifestAcceptHeader)); static Uri GetApiUri(Uri feedUri) { var httpScheme = BuildScheme(IsPlainHttp(feedUri)); var r = feedUri.ToString().Replace($"oci{Uri.SchemeDelimiter}", $"{httpScheme}{Uri.SchemeDelimiter}").TrimEnd('/'); var uri = new Uri(r); if (!r.EndsWith("/" + VersionPath)) { uri = new Uri(uri, VersionPath); } return uri; static bool IsPlainHttp(Uri uri) => uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase); static string BuildScheme(bool isPlainHttp) => isPlainHttp ? Uri.UriSchemeHttp : Uri.UriSchemeHttps; } PackagePhysicalFileMetadata? SourceFromCache(string packageId, IVersion version, string cacheDirectory) { Log.VerboseFormat("Checking package cache for package {0} v{1}", packageId, version.ToString()); var files = fileSystem.EnumerateFilesRecursively(cacheDirectory, PackageName.ToSearchPatterns(packageId, version, combinedPackageExtractor.Extensions)); foreach (var file in files) { var package = PackageName.FromFile(file); if (package == null) continue; if (string.Equals(package.PackageId, packageId, StringComparison.OrdinalIgnoreCase) && package.Version.Equals(version)) { var packagePhysicalFileMetadata = PackagePhysicalFileMetadata.Build(file, package) ?? throw new CommandException($"Unable to retrieve metadata for package {packageId}, version {version}"); return packagePhysicalFileMetadata; } } return null; } HttpResponseMessage Get(Uri url, ICredentials credentials, Action<HttpRequestMessage>? customAcceptHeader = null) { var request = new HttpRequestMessage(HttpMethod.Get, url); try { var networkCredential = credentials.GetCredential(url, "Basic"); if (!string.IsNullOrWhiteSpace(networkCredential?.UserName) || !string.IsNullOrWhiteSpace(networkCredential?.Password)) { request.Headers.Authorization = CreateAuthenticationHeader(networkCredential); } customAcceptHeader?.Invoke(request); var response = SendRequest(request); if (response.StatusCode == HttpStatusCode.Unauthorized) { var tokenFromAuthService = GetAuthRequestHeader(response, networkCredential); request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Authorization = tokenFromAuthService; customAcceptHeader?.Invoke(request); response = SendRequest(request); if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new CommandException($"Authorization to `{url}` failed."); } } if (response.StatusCode == HttpStatusCode.NotFound) { // Some registries do not support the Docker HTTP APIs // For example GitHub: https://github.community/t/ghcr-io-docker-http-api/130121 throw new CommandException($"Docker registry located at `{url}` does not support this action."); } if (!response.IsSuccessStatusCode) { var errorMessage = $"Request to Docker registry located at `{url}` failed with {response.StatusCode}:{response.ReasonPhrase}."; var responseBody = GetContent(response); if (!string.IsNullOrWhiteSpace(responseBody)) errorMessage += $" {responseBody}"; throw new CommandException(errorMessage); } return response; } finally { request.Dispose(); } } string RetrieveAuthenticationToken(string authUrl, NetworkCredential credential) { HttpResponseMessage? response = null; try { using (var msg = new HttpRequestMessage(HttpMethod.Get, authUrl)) { if (credential?.UserName != null) { msg.Headers.Authorization = CreateAuthenticationHeader(credential); } response = SendRequest(msg); } if (response.IsSuccessStatusCode) { return ExtractTokenFromResponse(response); } } finally { response?.Dispose(); } throw new CommandException("Unable to retrieve authentication token required to perform operation."); } AuthenticationHeaderValue GetAuthRequestHeader(HttpResponseMessage response, NetworkCredential credential) { var auth = response.Headers.WwwAuthenticate.FirstOrDefault(a => a.Scheme == "Bearer"); if (auth != null) { var authToken = RetrieveAuthenticationToken(GetOAuthServiceUrl(auth), credential); return new AuthenticationHeaderValue("Bearer", authToken); } if (response.Headers.WwwAuthenticate.Any(a => a.Scheme == "Basic")) { return CreateAuthenticationHeader(credential); } throw new CommandException($"Unknown Authentication scheme for Uri `{response.RequestMessage.RequestUri}`"); } static string GetOAuthServiceUrl(AuthenticationHeaderValue auth) { var details = auth.Parameter.Split(',').ToDictionary(x => x.Substring(0, x.IndexOf('=')), y => y.Substring(y.IndexOf('=') + 1, y.Length - y.IndexOf('=') - 1).Trim('"')); var oathUrl = new UriBuilder(details["realm"]); var queryStringValues = new Dictionary<string, string>(); if (details.TryGetValue("service", out var service)) { #if NET40 var encodedService = System.Web.HttpUtility.UrlEncode(service); #else var encodedService = WebUtility.UrlEncode(service); #endif queryStringValues.Add("service", encodedService); } if (details.TryGetValue("scope", out var scope)) { #if NET40 var encodedScope = System.Web.HttpUtility.UrlEncode(scope); #else var encodedScope = WebUtility.UrlEncode(scope); #endif queryStringValues.Add("scope", encodedScope); } oathUrl.Query = "?" + string.Join("&", queryStringValues.Select(kvp => $"{kvp.Key}={kvp.Value}").ToArray()); return oathUrl.ToString(); } static string ExtractTokenFromResponse(HttpResponseMessage response) { var token = GetContent(response); var lastItem = (string) JObject.Parse(token).SelectToken("token"); if (lastItem != null) { return lastItem; } throw new CommandException("Unable to retrieve authentication token required to perform operation."); } AuthenticationHeaderValue CreateAuthenticationHeader(NetworkCredential credential) { var byteArray = Encoding.ASCII.GetBytes($"{credential.UserName}:{credential.Password}"); return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); } HttpResponseMessage SendRequest(HttpRequestMessage request) { #if NET40 return client.SendAsync(request).Result; #else return client.SendAsync(request).GetAwaiter().GetResult(); #endif } static string? GetContent(HttpResponseMessage response) { #if NET40 return response.Content.ReadAsStringAsync().Result; #else return response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); #endif } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Integration.FileSystem; using Calamari.Integration.Processes; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using Octostache; namespace Calamari.Tests.Fixtures.Deployment { public abstract class DeployPackageFixture : CalamariFixture { protected ICalamariFileSystem FileSystem { get; private set; } protected IVariables Variables { get; private set; } protected string StagingDirectory { get; private set; } protected string CustomDirectory { get; private set; } public virtual void SetUp() { FileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); // Ensure staging directory exists and is empty StagingDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestStaging"); CustomDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestCustom"); FileSystem.EnsureDirectoryExists(StagingDirectory); FileSystem.PurgeDirectory(StagingDirectory, FailureOptions.ThrowOnFailure); Environment.SetEnvironmentVariable("TentacleJournal", Path.Combine(StagingDirectory, "DeploymentJournal.xml")); Variables = new VariablesFactory(FileSystem).Create(new CommonOptions("test")); Variables.Set(TentacleVariables.Agent.ApplicationDirectoryPath, StagingDirectory); Variables.Set("PreDeployGreeting", "Bonjour"); } public virtual void CleanUp() { CalamariPhysicalFileSystem.GetPhysicalFileSystem().PurgeDirectory(StagingDirectory, FailureOptions.IgnoreFailure); CalamariPhysicalFileSystem.GetPhysicalFileSystem().PurgeDirectory(CustomDirectory, FailureOptions.IgnoreFailure); } protected CalamariResult DeployPackage(string packageName) { using (var variablesFile = new TemporaryFile(Path.GetTempFileName())) { Variables.Save(variablesFile.FilePath); return Invoke(Calamari() .Action("deploy-package") .Argument("package", packageName) .Argument("variables", variablesFile.FilePath)); } } } }<file_sep>using System; using System.IO; namespace Calamari.Terraform.Tests.CommonTemplates { public static class TemplateLoader { private const string TemplatesFolder = "CommonTemplates"; public static string LoadTextTemplate(string templateName) { return File.ReadAllText(Path.Combine(TemplatesFolder, templateName)); } } } <file_sep>using System.Collections.Generic; using Octopus.CoreUtilities; namespace Calamari.Testing.Tools; public class BoostrapperModuleDeploymentTool : IDeploymentTool { private readonly IReadOnlyList<string> modulePaths; public BoostrapperModuleDeploymentTool( string id, IReadOnlyList<string> modulePaths, params string[] supportedPlatforms) { this.modulePaths = modulePaths; this.Id = id; this.SupportedPlatforms = supportedPlatforms ?? new string[0]; } public string Id { get; } public Maybe<string> SubFolder => Maybe<string>.None; public bool AddToPath => false; public Maybe<string> ToolPathVariableToSet => Maybe<string>.None; public string[] SupportedPlatforms { get; } public Maybe<DeploymentToolPackage> GetCompatiblePackage( string platform) { return platform != "win-x64" && platform != "netfx" ? Maybe<DeploymentToolPackage>.None : new DeploymentToolPackage((IDeploymentTool) this, this.Id, this.modulePaths).AsSome<DeploymentToolPackage>(); } }<file_sep>using Calamari.AzureAppService.Azure; using FluentAssertions; using NUnit.Framework; namespace Calamari.AzureAppService.Tests { public class AzureResourceFixture { private const string WebAppSlotsType = "microsoft.web/sites/slots"; private const string WebAppType = "microsoft.web/sites"; [Test] [TestCase(WebAppSlotsType, true)] [TestCase(WebAppType, false)] [TestCase("NotAValidType", false)] public void IsSlot_ReturnsCorrectValue_WhenTypeIsSetToDifferentValues(string type, bool expectedIsSlotValue) { var resource = new AzureResource { Type = type }; resource.IsSlot.Should().Be(expectedIsSlotValue); } [Test] [TestCase("SomeParentName/MySlotName", true, "MySlotName")] [TestCase("SomeCrazy/ParentName", false, null)] [TestCase("SomeCrazyParentNameWithNoSlot", true, "")] [TestCase("SomeCrazyParentNameWithNoSlot", false, null)] public void SlotName_ShouldReturnCorrectName_IfResourceIsSlot(string name, bool isSlot, string expectedSlotName) { var resource = new AzureResource { Type = isSlot ? WebAppSlotsType : WebAppType, Name = name }; resource.SlotName.Should().Be(expectedSlotName); } [Test] [TestCase("SomeParentName/MySlotName", true, "SomeParentName")] [TestCase("SomeCrazy/ParentName", false, null)] [TestCase("SomeCrazyParentNameWithNoSlot", true, "SomeCrazyParentNameWithNoSlot")] [TestCase("SomeCrazyParentNameWithNoSlot", false, null)] public void ParentName_ShouldReturnCorrectName_IfResourceIsSlot(string name, bool isSlot, string expectedParentName) { var resource = new AzureResource { Type = isSlot ? WebAppSlotsType : WebAppType, Name = name }; resource.ParentName.Should().Be(expectedParentName); } } }<file_sep>using System; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureServiceFabric.Behaviours { class EnsureCertificateInstalledInStoreBehaviour : IDeployBehaviour { readonly string certificateIdVariableName = SpecialVariables.Action.ServiceFabric.ClientCertVariable; readonly string storeLocationVariableName = SpecialVariables.Action.ServiceFabric.CertificateStoreLocation; readonly string storeNameVariableName = SpecialVariables.Action.ServiceFabric.CertificateStoreName; public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var variables = context.Variables; var clientCertVariable = variables.Get(certificateIdVariableName); if (!string.IsNullOrEmpty(clientCertVariable)) { EnsureCertificateInStore(variables, clientCertVariable); } return this.CompletedTask(); } void EnsureCertificateInStore(IVariables variables, string certificateVariable) { var storeLocation = StoreLocation.LocalMachine; if (!string.IsNullOrWhiteSpace(storeLocationVariableName) && Enum.TryParse(variables.Get(storeLocationVariableName, StoreLocation.LocalMachine.ToString()), out StoreLocation storeLocationOverride)) storeLocation = storeLocationOverride; var storeName = StoreName.My; if (!string.IsNullOrWhiteSpace(storeNameVariableName) && Enum.TryParse(variables.Get(storeNameVariableName, StoreName.My.ToString()), out StoreName storeNameOverride)) storeName = storeNameOverride; CalamariCertificateStore.GetOrAdd(variables, certificateVariable, storeName, storeLocation); } } }<file_sep>using System; using Calamari.Common.Plumbing; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace Calamari.Testing.Requirements { public class RequiresNon32BitWindowsAttribute : NUnitAttribute, IApplyToTest { public void ApplyToTest(Test test) { if (CalamariEnvironment.IsRunningOnWindows && !Environment.Is64BitOperatingSystem) { test.RunState = RunState.Skipped; test.Properties.Set(PropertyNames.SkipReason, "This test does not run on 32Bit Windows"); } } } }<file_sep>using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; using Octostache; using Octostache.Templates; namespace Calamari.Util { public static class InputSubstitution { public static string SubstituteAndEscapeAllVariablesInJson(string jsonInputs, IVariables variables, ILog log) { if (!TemplateParser.TryParseTemplate(jsonInputs, out var template, out string error)) { throw new CommandException($"Variable expression could not be parsed. Error: {error}"); } jsonInputs = template.ToString(); // we parse the template back to string to have a consistent representation of Octostache expressions foreach (var templateToken in template.Tokens) { string evaluated = variables.Evaluate(templateToken.ToString()); if (templateToken.GetArguments().Any() && evaluated == templateToken.ToString()) log.Warn($"Expression {templateToken.ToString()} could not be evaluated, check that the referenced variables exist."); jsonInputs = jsonInputs.Replace($"\"{templateToken.ToString()}\"", JsonConvert.ToString(evaluated)); } return jsonInputs; } } }<file_sep>using System; using System.Collections.Generic; namespace Calamari.ConsolidateCalamariPackages { public class ConsolidatedPackageIndex { public ConsolidatedPackageIndex(Dictionary<string, Package> packages) { Packages = new Dictionary<string, Package>(packages, StringComparer.OrdinalIgnoreCase); } public IReadOnlyDictionary<string, Package> Packages { get; } public class Package { public Package(string packageId, string version, bool isNupkg, Dictionary<string, string[]> platformHashes) { PackageId = packageId; Version = version; IsNupkg = isNupkg; PlatformHashes = new Dictionary<string, string[]>(platformHashes, StringComparer.OrdinalIgnoreCase); } public string PackageId { get; } public string Version { get; } public bool IsNupkg { get; } public Dictionary<string, string[]> PlatformHashes { get; } } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.NuGet; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using NUnit.Framework; using TestCommandLineRunner = Calamari.Testing.Helpers.TestCommandLineRunner; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class CombinedPackageExtractorFixture : CalamariFixture { [Test] [TestCaseSource(nameof(PackageNameTestCases))] public void GettingFileByExtension(string filename, Type expectedType) { var combinedExtractor = CreateCombinedPackageExtractor(); var specificExtractor = combinedExtractor.GetExtractor(filename); Assert.AreEqual(expectedType, specificExtractor.GetType()); } static IEnumerable<object> PackageNameTestCases() { var fileNames = new[] { "foo.1.0.0", "foo.1.0.0-tag", "foo.1.0.0-tag-release.tag", "foo.1.0.0+buildmeta", "foo.1.0.0-tag-release.tag+buildmeta", }; var extractorMapping = new (string extension, Type extractor)[] { ("zip", typeof(ZipPackageExtractor)), ("nupkg", typeof(NupkgExtractor)), ("tar", typeof(TarPackageExtractor)), ("tar.gz", typeof(TarGzipPackageExtractor)), ("tar.bz2", typeof(TarBzipPackageExtractor)), }; foreach (var filename in fileNames) { foreach (var (extension, type) in extractorMapping) { yield return new TestCaseData($"{filename}.{extension}", type); } } } [Test] [ExpectedException(typeof(CommandException), ExpectedMessage = "Package is missing file extension. This is needed to select the correct extraction algorithm.")] public void FileWithNoExtensionThrowsError() { CreateCombinedPackageExtractor().GetExtractor("blah"); } [Test] [ExpectedException(typeof(CommandException), ExpectedMessage = "Unsupported file extension `.7z`")] public void FileWithUnsupportedExtensionThrowsError() { CreateCombinedPackageExtractor().GetExtractor("blah.1.0.0.7z"); } static CombinedPackageExtractor CreateCombinedPackageExtractor() { var log = new InMemoryLog(); var variables = new CalamariVariables(); var combinedExtractor = new CombinedPackageExtractor(log, variables, new TestCommandLineRunner(log, variables)); return combinedExtractor; } } } <file_sep>namespace Calamari.AzureServiceFabric { enum AzureServiceFabricSecurityMode { Unsecure, SecureClientCertificate, SecureAzureAD, SecureAD, } }<file_sep>using System; using System.Linq; using System.Text; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.Logging { public class VariableLogger { readonly IVariables variables; readonly ILog log; public VariableLogger(IVariables variables, ILog log) { this.variables = variables; this.log = log; } public void LogVariables() { string ToString(bool useRawValue) { var text = new StringBuilder(); var namesToPrint = variables.GetNames().Where(name => !name.Contains("CustomScripts.")).OrderBy(name => name); foreach (var name in namesToPrint) { var value = useRawValue ? variables.GetRaw(name) : variables.Get(name); text.AppendLine($"[{name}] = '{value}'"); } return text.ToString(); } if (variables.GetFlag(KnownVariables.PrintVariables)) { log.Warn($"{KnownVariables.PrintVariables} is enabled. This should only be used for debugging problems with variables, and then disabled again for normal deployments."); log.Verbose("The following variables are available:" + Environment.NewLine + ToString(true)); } if (variables.GetFlag(KnownVariables.PrintEvaluatedVariables)) { log.Warn($"{KnownVariables.PrintEvaluatedVariables} is enabled. This should only be used for debugging problems with variables, and then disabled again for normal deployments."); log.Verbose("The following evaluated variables are available:" + Environment.NewLine + ToString(false)); } } } }<file_sep>#if !NET40 using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus.Resources; using Octopus.CoreUtilities.Extensions; namespace Calamari.Kubernetes.ResourceStatus { public class ResourceStatusCheckTask { private const int PollingIntervalSeconds = 2; private readonly IResourceRetriever resourceRetriever; private readonly IResourceUpdateReporter reporter; private readonly IKubectl kubectl; private readonly Timer.Factory timerFactory; public ResourceStatusCheckTask( IResourceRetriever resourceRetriever, IResourceUpdateReporter reporter, IKubectl kubectl, Timer.Factory timerFactory) { this.resourceRetriever = resourceRetriever; this.reporter = reporter; this.kubectl = kubectl; this.timerFactory = timerFactory; } public async Task<Result> Run(IEnumerable<ResourceIdentifier> resources, Options options, TimeSpan timeout, CancellationToken cancellationToken) { if (!kubectl.TrySetKubectl()) { throw new Exception("Unable to set KubeCtl"); } var timer = timerFactory(TimeSpan.FromSeconds(PollingIntervalSeconds), timeout); var definedResources = resources.ToArray(); var checkCount = 0; return await Task.Run(async () => { timer.Start(); var result = new Result(); do { if (cancellationToken.IsCancellationRequested) { return result; } if (!definedResources.Any()) { return new Result(DeploymentStatus.Succeeded); } var definedResourceStatuses = resourceRetriever .GetAllOwnedResources(definedResources, kubectl, options) .ToArray(); var resourceStatuses = definedResourceStatuses .SelectMany(IterateResourceTree) .ToDictionary(resource => resource.Uid, resource => resource); var deploymentStatus = GetDeploymentStatus(definedResourceStatuses, definedResources); reporter.ReportUpdatedResources(result.ResourceStatuses, resourceStatuses, ++checkCount); result = new Result( deploymentStatus, definedResources, definedResourceStatuses, resourceStatuses); await timer.WaitForInterval(); } while (!timer.HasCompleted() && result.DeploymentStatus == DeploymentStatus.InProgress); return result; }, cancellationToken); } private static DeploymentStatus GetDeploymentStatus(Resource[] resources, ResourceIdentifier[] definedResources) { if (resources.All(resource => resource.ResourceStatus == ResourceStatus.Resources.ResourceStatus.Successful) && resources.Length == definedResources.Length) { return DeploymentStatus.Succeeded; } if (resources .Any(resource => resource.ResourceStatus == ResourceStatus.Resources.ResourceStatus.Failed)) { return DeploymentStatus.Failed; } return DeploymentStatus.InProgress; } private static IEnumerable<Resource> IterateResourceTree(Resource root) { foreach (var resource in root.Children ?? Enumerable.Empty<Resource>()) { foreach (var child in IterateResourceTree(resource)) { yield return child; } } yield return root; } public class Result { public Result() : this(DeploymentStatus.InProgress) { } public Result(DeploymentStatus deploymentStatus) : this( deploymentStatus, new ResourceIdentifier[0], new Resource[0], new Dictionary<string, Resource>()) { } public Result( DeploymentStatus deploymentStatus, ResourceIdentifier[] definedResources, Resource[] definedResourceStatuses, Dictionary<string, Resource> resourceStatuses) { DefiniedResources = definedResources; DefinedResourceStatuses = definedResourceStatuses; ResourceStatuses = resourceStatuses; DeploymentStatus = deploymentStatus; } public ResourceIdentifier[] DefiniedResources { get; } public Resource[] DefinedResourceStatuses { get; } public Dictionary<string, Resource> ResourceStatuses { get; } public DeploymentStatus DeploymentStatus { get; } } } } #endif<file_sep>using System; using Calamari.Common.Features.Discovery; namespace Calamari.Kubernetes.Commands.Discovery { public interface IKubernetesDiscovererFactory { bool TryGetKubernetesDiscoverer(string type, out IKubernetesDiscoverer discoverer); } }<file_sep>using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus.Resources { [TestFixture] public class EndpointSliceTests { [Test] public void ShouldCollectCorrectProperties() { const string input = @"{ ""kind"": ""EndpointSlice"", ""metadata"": { ""name"": ""my-svc-abcde"", ""namespace"": ""default"", ""uid"": ""01695a39-5865-4eea-b4bf-1a4783cbce62"" }, ""addressType"": ""IPv4"", ""ports"": [ { ""name"": """", ""port"": 8080, ""protocol"": ""TCP"" } ], ""endpoints"": [ { ""addresses"": [ ""10.244.19.164"" ], }, { ""addresses"": [ ""10.244.19.165"" ], }, { ""addresses"": [ ""10.244.19.166"", ""10.244.19.167"" ], } ] }"; var service = ResourceFactory.FromJson(input, new Options()); service.Should().BeEquivalentTo(new { Kind = "EndpointSlice", Name = "my-svc-abcde", Namespace = "default", Uid = "01695a39-5865-4eea-b4bf-1a4783cbce62", AddressType = "IPv4", Ports = new string[] { "8080", }, Endpoints = new string[] { "10.244.19.164", "10.244.19.165", "10.244.19.166", "10.244.19.167" }, ResourceStatus = Kubernetes.ResourceStatus.Resources.ResourceStatus.Successful }); } } } <file_sep>using System; using System.IO; using System.Text.RegularExpressions; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Integration.FileSystem; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using Calamari.Util; using NUnit.Framework; namespace Calamari.Tests.Fixtures.ApplyDelta { [TestFixture] public class ApplyDeltaFixture : CalamariFixture { static readonly string TentacleHome = TestEnvironment.GetTestPath("Fixtures", "ApplyDelta"); static readonly string DownloadPath = Path.Combine(TentacleHome, "Files"); const string NewFileName = "Acme.Web.1.0.1.nupkg"; CalamariResult ApplyDelta(string basisFile, string fileHash, string deltaFile, string newFile, bool messageOnError = false) { var command = Calamari() .Action("apply-delta") .Argument("basisFileName", basisFile) .Argument("fileHash", fileHash) .Argument("deltaFileName", deltaFile) .Argument("newFileName", newFile); if (messageOnError) command = command.Flag("serviceMessageOnError"); return Invoke(command); } [OneTimeSetUp] public void TestFixtureSetUp() { Environment.SetEnvironmentVariable("TentacleHome", TentacleHome); } [OneTimeTearDown] public void TestFixtureTearDown() { Environment.SetEnvironmentVariable("TentacleHome", null); } [SetUp] public void SetUp() { if (!Directory.Exists(DownloadPath)) Directory.CreateDirectory(DownloadPath); } [TearDown] public void TearDown() { if (Directory.Exists(DownloadPath)) Directory.Delete(DownloadPath, true); } [Test] public void ShouldApplyDeltaToPreviousPackageToCreateNewPackage() { using (var basisFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0"))) using (var signatureFile = new TemporaryFile(basisFile.FilePath + ".octosig")) { #if USE_OCTODIFF_EXE var signatureResult = Invoke(OctoDiff() .Action("signature") .PositionalArgument(basisFile.FilePath) .PositionalArgument(signatureFile.FilePath)); signatureResult.AssertSuccess(); #else var exitCode = Octodiff.Program.Main(new[] {"signature", basisFile.FilePath, signatureFile.FilePath}); Assert.That(exitCode, Is.EqualTo(0), string.Format("Expected command to return exit code 0, received {0}", exitCode)); #endif Assert.That(File.Exists(signatureFile.FilePath)); using (var newFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.1", true))) using (var deltaFile = new TemporaryFile(basisFile.FilePath + "_to_" + NewFileName + ".octodelta")) { #if USE_OCTODIFF_EXE var deltaResult = Invoke(OctoDiff() .Action("delta") .PositionalArgument(signatureFile.FilePath) .PositionalArgument(newFile.FilePath) .PositionalArgument(deltaFile.FilePath)); deltaResult.AssertSuccess(); #else var deltaExitCode = Octodiff.Program.Main(new[] { "delta", signatureFile.FilePath, newFile.FilePath, deltaFile.FilePath }); Assert.That(deltaExitCode, Is.EqualTo(0), string.Format("Expected command to return exit code 0, received {0}", exitCode)); #endif Assert.That(File.Exists(deltaFile.FilePath)); var patchResult = ApplyDelta(basisFile.FilePath, basisFile.Hash, deltaFile.FilePath, NewFileName); patchResult.AssertSuccess(); patchResult.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name); patchResult.AssertOutput("Applying delta to {0} with hash {1} and storing as {2}", basisFile.FilePath, basisFile.Hash, patchResult.CapturedOutput.DeltaVerification.FullPathOnRemoteMachine); Assert.AreEqual(newFile.Hash, patchResult.CapturedOutput.DeltaVerification.Hash); Assert.AreEqual(newFile.Hash, HashCalculator.Hash(patchResult.CapturedOutput.DeltaVerification.FullPathOnRemoteMachine)); } } } [Test] public void ShouldWriteErrorWhenNoBasisFileIsSpecified() { var result = ApplyDelta("", "Hash", "Delta", "New"); result.AssertSuccess(); result.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name, message: "No basis file was specified. Please pass --basisFileName MyPackage.1.0.0.0.nupkg"); } [Test] public void ShouldWriteErrorWhenNoFileHashIsSpecified() { var result = ApplyDelta("Basis", "", "Delta", "New"); result.AssertSuccess(); result.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name, message: "No file hash was specified. Please pass --fileHash MyFileHash"); } [Test] public void ShouldWriteErrorWhenNoDeltaFileIsSpecified() { var result = ApplyDelta("Basis", "Hash", "", "New"); result.AssertSuccess(); result.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name, message: $"No delta file was specified. Please pass --deltaFileName MyPackage.1.0.0.0_to_1.0.0.1.octodelta"); } [Test] public void ShouldWriteErrorWhenNoNewFileIsSpecified() { var result = ApplyDelta("Basis", "Hash", "Delta", ""); result.AssertSuccess(); result.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name, message: "No new file name was specified. Please pass --newFileName MyPackage.1.0.0.1.nupkg"); } [Test] public void ShouldWriteErrorWhenBasisFileCannotBeFound() { var basisFile = Path.Combine(DownloadPath, "MyPackage.1.0.0.nupkg"); var result = ApplyDelta(basisFile, "Hash", "Delta", "New"); result.AssertSuccess(); result.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name, message: "Could not find basis file: " + basisFile); } [Test] public void ShouldWriteErrorWhenDeltaFileCannotBeFound() { using (var basisFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0"))) { var deltaFilePath = Path.Combine(DownloadPath, "Acme.Web.1.0.0_to_1.0.1.octodelta"); var result = ApplyDelta(basisFile.FilePath, basisFile.Hash, deltaFilePath, "New"); result.AssertSuccess(); result.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name, message: "Could not find delta file: " + deltaFilePath); } } [Test] public void ShouldWriteErrorWhenBasisFileHashDoesNotMatchSpecifiedFileHash() { var otherBasisFileHash = "2e9407c9eae20ffa94bf050283f9b4292a48504c"; using (var basisFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0"))) { var deltaFilePath = Path.Combine(DownloadPath, "Acme.Web.1.0.0_to_1.0.1.octodelta"); using (var deltaFile = File.CreateText(deltaFilePath)) { deltaFile.WriteLine("This is a delta file!"); deltaFile.Flush(); } var result = ApplyDelta(basisFile.FilePath, otherBasisFileHash, deltaFilePath, NewFileName, messageOnError: true); result.AssertSuccess(); result.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name, message: $"Basis file hash `{basisFile.Hash}` does not match the file hash specified `{otherBasisFileHash}`"); } } [Test] public void ShouldWriteErrorWhenDeltaFileIsInvalid() { using (var basisFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0"))) { var deltaFilePath = Path.Combine(DownloadPath, "Acme.Web.1.0.0_to_1.0.1.octodelta"); using (var deltaFile = File.CreateText(deltaFilePath)) { deltaFile.WriteLine("This is a delta file!"); deltaFile.Flush(); } var result = ApplyDelta(basisFile.FilePath, basisFile.Hash, deltaFilePath, NewFileName); result.AssertSuccess(); result.AssertOutputMatches( $".*\nApplying delta to {Regex.Escape(basisFile.FilePath)} with hash {basisFile.Hash} and storing as {Regex.Escape(DownloadPath)}.*"); result.AssertOutput("The delta file appears to be corrupt."); result.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name, message: "The following command: OctoDiff\nFailed with exit code: 2\n"); } } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting.DotnetScript; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.DotnetScript { public class DotnetScriptExecutor : ScriptExecutor { protected override IEnumerable<ScriptExecution> PrepareExecution(Script script, IVariables variables, Dictionary<string, string>? environmentVars = null) { var workingDirectory = Path.GetDirectoryName(script.File); var executable = DotnetScriptBootstrapper.FindExecutable(); var configurationFile = DotnetScriptBootstrapper.PrepareConfigurationFile(workingDirectory, variables); var (bootstrapFile, otherTemporaryFiles) = DotnetScriptBootstrapper.PrepareBootstrapFile(script.File, configurationFile, workingDirectory, variables); var arguments = DotnetScriptBootstrapper.FormatCommandArguments(bootstrapFile, script.Parameters); var cli = CalamariEnvironment.IsRunningOnWindows ? new CommandLineInvocation(executable, arguments) : new CommandLineInvocation("dotnet", $"\"{executable}\"", arguments); cli.WorkingDirectory = workingDirectory; cli.EnvironmentVars = environmentVars; yield return new ScriptExecution( cli, otherTemporaryFiles.Concat(new[] { bootstrapFile, configurationFile }) ); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment.Conventions; using Octostache.Templates; namespace Calamari.Deployment { public class ConventionProcessor { readonly RunningDeployment deployment; readonly List<IConvention> conventions; readonly ILog log; public ConventionProcessor(RunningDeployment deployment, List<IConvention> conventions, ILog log) { this.deployment = deployment; this.conventions = conventions; this.log = log; } public void RunConventions(bool logExceptions = true) { var installConventions = conventions.OfType<IInstallConvention>(); var rollbackConventions = conventions.OfType<IRollbackConvention>().ToList(); try { // Now run the "conventions", for example: Deploy.ps1 scripts, XML configuration, and so on RunInstallConventions(installConventions); // Run cleanup for rollback conventions, for example: delete DeployFailed.ps1 script RunRollbackCleanup(rollbackConventions); } catch (Exception installException) { if (logExceptions) { if (installException is CommandException || installException is RecursiveDefinitionException) log.Verbose(installException.ToString()); else Console.Error.WriteLine(installException); } deployment.Error(installException); if (rollbackConventions.Any()) { Console.Error.WriteLine("Running rollback conventions..."); try { // Rollback conventions include tasks like DeployFailed.ps1 RunRollbackConventions(rollbackConventions); // Run cleanup for rollback conventions, for example: delete DeployFailed.ps1 script RunRollbackCleanup(rollbackConventions); } catch (Exception rollbackException) { //if the "rollback" exception message is identical to the exception we got during "install", dont log it if (rollbackException.Message != installException.Message) { if (rollbackException is CommandException || rollbackException is RecursiveDefinitionException) log.Verbose(installException.ToString()); else Console.Error.WriteLine(rollbackException); } } } throw; } } void RunInstallConventions(IEnumerable<IInstallConvention> installConventions) { foreach (var convention in installConventions) { convention.Install(deployment); if (deployment.Variables.GetFlag(Common.Plumbing.Variables.KnownVariables.Action.SkipRemainingConventions)) { break; } } } void RunRollbackConventions(IEnumerable<IRollbackConvention> rollbackConventions) { foreach (var convention in rollbackConventions) { convention.Rollback(deployment); } } void RunRollbackCleanup(IEnumerable<IRollbackConvention> rollbackConventions) { foreach (var convention in rollbackConventions) { if (deployment.Variables.GetFlag(Common.Plumbing.Variables.KnownVariables.Action.SkipRemainingConventions)) { break; } convention.Cleanup(deployment); } } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Runtime; using Calamari.Aws.Exceptions; using Calamari.Aws.Integration; using Calamari.Aws.Integration.CloudFormation; using Calamari.Aws.Integration.CloudFormation.Templates; using Calamari.Aws.Util; using Calamari.CloudAccounts; using Calamari.Common.Commands; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment; using Calamari.Util; using Octopus.CoreUtilities; using Octopus.CoreUtilities.Extensions; namespace Calamari.Aws.Deployment.Conventions { /// <summary> /// Describes the state of the stack /// </summary> public enum StackStatus { DoesNotExist, Completed, InProgress } public class DeployAwsCloudFormationConvention : CloudFormationInstallationConventionBase { readonly Func<IAmazonCloudFormation> clientFactory; readonly Func<ICloudFormationRequestBuilder> templateFactory; readonly Func<RunningDeployment, StackArn> stackProvider; readonly Func<RunningDeployment, string> roleArnProvider; readonly bool waitForComplete; readonly string stackName; readonly AwsEnvironmentGeneration awsEnvironmentGeneration; public DeployAwsCloudFormationConvention( Func<IAmazonCloudFormation> clientFactory, Func<ICloudFormationRequestBuilder> templateFactory, StackEventLogger logger, Func<RunningDeployment, StackArn> stackProvider, Func<RunningDeployment, string> roleArnProvider, bool waitForComplete, string stackName, AwsEnvironmentGeneration awsEnvironmentGeneration) : base(logger) { this.clientFactory = clientFactory; this.templateFactory = templateFactory; this.stackProvider = stackProvider; this.roleArnProvider = roleArnProvider; this.waitForComplete = waitForComplete; this.stackName = stackName; this.awsEnvironmentGeneration = awsEnvironmentGeneration; } public override void Install(RunningDeployment deployment) { InstallAsync(deployment).GetAwaiter().GetResult(); } private async Task InstallAsync(RunningDeployment deployment) { Guard.NotNull(deployment, "deployment can not be null"); var stack = stackProvider(deployment); Guard.NotNull(stack, "Stack can not be null"); var template = templateFactory(); Guard.NotNull(template, "CloudFormation template can not be null."); await DeployCloudFormation(deployment, stack, template); } private async Task DeployCloudFormation(RunningDeployment deployment, StackArn stack, ICloudFormationRequestBuilder template) { Guard.NotNull(deployment, "deployment can not be null"); var deploymentStartTime = DateTime.Now; await clientFactory.WaitForStackToComplete(CloudFormationDefaults.StatusWaitPeriod, stack, LogAndThrowRollbacks(clientFactory, stack, false, filter: FilterStackEventsSince(deploymentStartTime))); await DeployStack(deployment, stack, template, deploymentStartTime); } /// <summary> /// Update or create the stack /// </summary> /// <param name="deployment">The current deployment</param> /// <param name="stack"></param> /// <param name="template"></param> private async Task DeployStack(RunningDeployment deployment, StackArn stack, ICloudFormationRequestBuilder template, DateTime deploymentStartTime) { Guard.NotNull(deployment, "deployment can not be null"); var stackId = await template.Inputs // Use the parameters to either create or update the stack .Map(async parameters => await StackExists(stack, StackStatus.DoesNotExist) != StackStatus.DoesNotExist ? await UpdateCloudFormation(deployment, stack, template) : await CreateCloudFormation(deployment, template)); if (waitForComplete) { await clientFactory.WaitForStackToComplete(CloudFormationDefaults.StatusWaitPeriod, stack, LogAndThrowRollbacks(clientFactory, stack, filter: FilterStackEventsSince(deploymentStartTime))); } // Take the stack ID returned by the create or update events, and save it as an output variable Log.SetOutputVariable("AwsOutputs[StackId]", stackId ?? "", deployment.Variables); Log.Info( $"Saving variable \"Octopus.Action[{deployment.Variables["Octopus.Action.Name"]}].Output.AwsOutputs[StackId]\""); } /// <summary> /// Gets the last stack event by timestamp, optionally filtered by a predicate /// </summary> /// <param name="predicate">The optional predicate used to filter events</param> /// <returns>The stack event</returns> private Task<Maybe<StackEvent>> StackEvent(StackArn stack, Func<StackEvent, bool> predicate = null) { return WithAmazonServiceExceptionHandling( async () => await clientFactory.GetLastStackEvent(stack, predicate)); } /// <summary> /// Check to see if the stack name exists. /// </summary> /// <param name="defaultValue">The return value when the user does not have the permissions to query the stacks</param> /// <returns>The current status of the stack</returns> async Task<StackStatus> StackExists(StackArn stack, StackStatus defaultValue) { return await WithAmazonServiceExceptionHandling(async () => await clientFactory.StackExistsAsync(stack, defaultValue)); } /// <summary> /// Creates the stack and returns the stack ID /// </summary> /// <param name="deployment">The running deployment</param> /// <returns>The stack id</returns> private Task<string> CreateCloudFormation(RunningDeployment deployment, ICloudFormationRequestBuilder template) { Guard.NotNull(template, "template can not be null"); return WithAmazonServiceExceptionHandling(async () => { var stackId = await clientFactory.CreateStackAsync(template.BuildCreateStackRequest()); Log.Info($"Created stack {stackId} in region {awsEnvironmentGeneration.AwsRegion.SystemName}"); return stackId; }); } /// <summary> /// Deletes the stack /// </summary> private Task DeleteCloudFormation(StackArn stack) { return WithAmazonServiceExceptionHandling(async () => { await clientFactory.DeleteStackAsync(stack); Log.Info($"Deleted stack called {stackName} in region {awsEnvironmentGeneration.AwsRegion.SystemName}"); }); } /// <summary> /// Updates the stack and returns the stack ID /// </summary> /// <param name="stack">The stack name or id</param> /// <param name="deployment">The current deployment</param> /// <param name="template">The CloudFormation template</param> /// <returns>stackId</returns> private async Task<string> UpdateCloudFormation( RunningDeployment deployment, StackArn stack, ICloudFormationRequestBuilder template) { Guard.NotNull(deployment, "deployment can not be null"); var deploymentStartTime = DateTime.Now; try { var result = await ClientHelpers.CreateCloudFormationClient(awsEnvironmentGeneration) .UpdateStackAsync(template.BuildUpdateStackRequest()); Log.Info( $"Updated stack with id {result.StackId} in region {awsEnvironmentGeneration.AwsRegion.SystemName}"); return result.StackId; } catch (AmazonCloudFormationException ex) { // Some stack states indicate that we can delete the stack and start again. Otherwise we have some other // exception that needs to be dealt with. if (!(await StackMustBeDeleted(stack)).SelectValueOrDefault(x => x)) { // Is this an unrecoverable state, or just a stack that has nothing to update? if (DealWithUpdateException(ex)) { // There was nothing to update, but we return the id for consistency anyway var result = await QueryStackAsync(clientFactory, stack); return result.StackId; } } // If the stack exists, is in a ROLLBACK_COMPLETE state, and was never successfully // created in the first place, we can end up here. In this case we try to create // the stack from scratch. await DeleteCloudFormation(stack); await clientFactory.WaitForStackToComplete(CloudFormationDefaults.StatusWaitPeriod, stack, LogAndThrowRollbacks(clientFactory, stack, false, filter: FilterStackEventsSince(deploymentStartTime))); return await CreateCloudFormation(deployment, template); } catch (AmazonServiceException ex) { LogAmazonServiceException(ex); throw; } } /// <summary> /// Not all exceptions are bad. Some just mean there is nothing to do, which is fine. /// This method will ignore expected exceptions, and rethrow any that are really issues. /// </summary> /// <param name="ex">The exception we need to deal with</param> /// <exception cref="AmazonCloudFormationException">The supplied exception if it really is an error</exception> private bool DealWithUpdateException(AmazonCloudFormationException ex) { Guard.NotNull(ex, "ex can not be null"); // Unfortunately there are no better fields in the exception to use to determine the // kind of error than the message. We are forced to match message strings. if (ex.Message.Contains("No updates are to be performed")) { Log.Info("No updates are to be performed"); return true; } if (ex.ErrorCode == "AccessDenied") { throw new PermissionException( "The AWS account used to perform the operation does not have the required permissions to update the stack.\n" + "Please ensure the current account has permission to perfrom action 'cloudformation:UpdateStack'.\n" + ex.Message); } throw new UnknownException("An unrecognised exception was thrown while updating a CloudFormation stack.\n", ex); } /// <summary> /// Check whether the stack must be deleted in order to recover. /// </summary> /// <param name="stack">The stack id or name</param> /// <returns>true if this status indicates that the stack has to be deleted, and false otherwise</returns> private async Task<Maybe<bool>> StackMustBeDeleted(StackArn stack) { try { return (await StackEvent(stack)).Select(x => x.StackIsUnrecoverable()); } catch (PermissionException) { // If we can't get the stack status, assume it is not in a state that we can recover from return Maybe<bool>.None; } } } }<file_sep>using System; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Substitutions { public interface IFileSubstituter { void PerformSubstitution(string sourceFile, IVariables variables); void PerformSubstitution(string sourceFile, IVariables variables, string targetFile); } }<file_sep>using System; using System.Collections.Generic; using System.IO; using Calamari.Common.Features.StructuredVariables; using NUnit.Framework; using YamlDotNet.Core; using YamlDotNet.Core.Events; namespace Calamari.Tests.Fixtures.StructuredVariables { [TestFixture] public class YamlEventStreamClassifierFixture { [Test] public void YamlEventPathMonitorCalculatesValuePaths() { var input = @" key: val key2: val2 mapA: keyA: vAA keyB: vAB seqC: - C0 - F: vC1F G: vC1G - - vC20 - vC21 - C3 key3: val3"; var expectedScalarValues = new List<(string path, string value)> { ("key", "val"), ("key2", "val2"), ("mapA:keyA", "vAA"), ("mapA:keyB", "vAB"), ("seqC:0", "C0"), ("seqC:1:F", "vC1F"), ("seqC:1:G", "vC1G"), ("seqC:2:0", "vC20"), ("seqC:2:1", "vC21"), ("seqC:3", "C3"), ("key3", "val3") }; CollectionAssert.AreEqual(expectedScalarValues, GetScalarValues(input)); } List<(string path, string value)> GetScalarValues(string input) { var result = new List<(string path, string value)>(); using (var textReader = new StringReader(input)) { var parser = new Parser(textReader); var classifier = new YamlEventStreamClassifier(); while (parser.MoveNext()) { var found = classifier.Process(parser.Current); if (found is YamlNode<Scalar> scalarValue) result.Add((scalarValue.Path, scalarValue.Event.Value)); } } return result; } } }<file_sep>using System; using Autofac; namespace Calamari.Common.Plumbing.Pipeline { public class OnFinishResolver: Resolver<IOnFinishBehaviour> { public OnFinishResolver(ILifetimeScope lifetimeScope) : base(lifetimeScope) { } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Deployment.Journal; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using Calamari.Kubernetes.Commands; using Calamari.Kubernetes.Integration; namespace Calamari.Tests.KubernetesFixtures { [Command(Name, Description = "used for tests")] public class TestableKubernetesDeploymentCommand : KubernetesDeploymentCommandBase { public const string Name = "test-kubernetes-command"; private readonly Kubectl kubectl; public TestableKubernetesDeploymentCommand( ILog log, IDeploymentJournalWriter deploymentJournalWriter, IVariables variables, ICalamariFileSystem fileSystem, IExtractPackage extractPackage, ISubstituteInFiles substituteInFiles, IStructuredConfigVariablesService structuredConfigVariablesService, Kubectl kubectl) : base(log, deploymentJournalWriter, variables, fileSystem, extractPackage, substituteInFiles, structuredConfigVariablesService, kubectl) { this.kubectl = kubectl; } protected override IEnumerable<IInstallConvention> CommandSpecificInstallConventions() { yield return new TestKubectlAuthConvention(kubectl); } private class TestKubectlAuthConvention : IInstallConvention { private readonly Kubectl kubectl; public TestKubectlAuthConvention(Kubectl kubectl) { this.kubectl = kubectl; } public void Install(RunningDeployment deployment) { if (!kubectl.TrySetKubectl()) { throw new InvalidOperationException("Unable to set KubeCtl"); } kubectl.ExecuteCommand("cluster-info"); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting.Bash; using Calamari.Common.Features.Scripting.DotnetScript; using Calamari.Common.Features.Scripting.FSharp; using Calamari.Common.Features.Scripting.Python; using Calamari.Common.Features.Scripting.WindowsPowerShell; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting { public interface IScriptEngine { ScriptSyntax[] GetSupportedTypes(); CommandResult Execute( Script script, IVariables variables, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars = null); } public class ScriptEngine : IScriptEngine { readonly IEnumerable<IScriptWrapper> scriptWrapperHooks; public ScriptEngine(IEnumerable<IScriptWrapper> scriptWrapperHooks) { this.scriptWrapperHooks = scriptWrapperHooks; } public ScriptSyntax[] GetSupportedTypes() { return ScriptSyntaxHelper.GetPreferenceOrderedScriptSyntaxesForEnvironment(); } public CommandResult Execute( Script script, IVariables variables, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars = null) { var syntax = script.File.ToScriptType(); return BuildWrapperChain(syntax, variables) .ExecuteScript(script, syntax, commandLineRunner, environmentVars); } /// <summary> /// Script wrappers form a chain, with one wrapper calling the next, much like /// a linked list. The last wrapper to be called is the TerminalScriptWrapper, /// which simply executes a ScriptEngine without any additional processing. /// In this way TerminalScriptWrapper is what actually executes the script /// that is to be run, with all other wrappers contributing to the script /// context. /// </summary> /// <param name="scriptSyntax">The type of the script being run</param> /// <param name="variables"></param> /// <returns> /// The start of the wrapper chain. Because each IScriptWrapper is expected to call its NextWrapper, /// calling ExecuteScript() on the start of the chain will result in every part of the chain being /// executed, down to the final TerminalScriptWrapper. /// </returns> IScriptWrapper BuildWrapperChain(ScriptSyntax scriptSyntax, IVariables variables) { // get the type of script return scriptWrapperHooks .Where(hook => hook.IsEnabled(scriptSyntax)) /* * Sort the list in descending order of priority to ensure that * authentication script wrappers are called before any tool * script wrapper that might rely on the auth having being performed */ .OrderByDescending(hook => hook.Priority) .Aggregate( // The last wrapper is always the TerminalScriptWrapper new TerminalScriptWrapper(GetScriptExecutor(scriptSyntax), variables), (IScriptWrapper current, IScriptWrapper next) => { // the next wrapper is pointed to the current one next.NextWrapper = current; /* * The next wrapper is carried across to the next aggregate call, * or is returned as the result of the aggregate call. This means * the last item in the list is the return value. */ return next; }); } IScriptExecutor GetScriptExecutor(ScriptSyntax scriptSyntax) { switch (scriptSyntax) { case ScriptSyntax.PowerShell: return new PowerShellScriptExecutor(); case ScriptSyntax.CSharp: return new DotnetScriptExecutor(); case ScriptSyntax.Bash: return new BashScriptExecutor(); case ScriptSyntax.FSharp: return new FSharpExecutor(); case ScriptSyntax.Python: return new PythonScriptExecutor(); default: throw new NotSupportedException($"{scriptSyntax} script are not supported for execution"); } } } }<file_sep>using Newtonsoft.Json; namespace Calamari.Kubernetes.ResourceStatus.Resources { // Subset of: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.26/#portstatus-v1-core public class PortStatus { [JsonProperty("port")] public string Port { get; set; } [JsonProperty("protocol")] public string Protocol { get; set; } } } <file_sep>using System; namespace Calamari.Common.Plumbing.Variables { public static class TentacleVariables { public static class CurrentDeployment { public static readonly string PackageFilePath = "Octopus.Tentacle.CurrentDeployment.PackageFilePath"; } public static class Agent { public static readonly string InstanceName = "Octopus.Tentacle.Agent.InstanceName"; public static readonly string ApplicationDirectoryPath = "Octopus.Tentacle.Agent.ApplicationDirectoryPath"; public static readonly string JournalPath = "env:TentacleJournal"; public static readonly string TentacleHome = "env:TentacleHome"; } public static class PreviousInstallation { public static readonly string PackageVersion = "Octopus.Tentacle.PreviousInstallation.PackageVersion"; public static readonly string PackageFilePath = "Octopus.Tentacle.PreviousInstallation.PackageFilePath"; public static readonly string OriginalInstalledPath = "Octopus.Tentacle.PreviousInstallation.OriginalInstalledPath"; public static readonly string CustomInstallationDirectory = "Octopus.Tentacle.PreviousInstallation.CustomInstallationDirectory"; } public static class PreviousSuccessfulInstallation { public static readonly string PackageVersion = "Octopus.Tentacle.PreviousSuccessfulInstallation.PackageVersion"; public static readonly string PackageFilePath = "Octopus.Tentacle.PreviousSuccessfulInstallation.PackageFilePath"; public static readonly string OriginalInstalledPath = "Octopus.Tentacle.PreviousSuccessfulInstallation.OriginalInstalledPath"; public static readonly string CustomInstallationDirectory = "Octopus.Tentacle.PreviousSuccessfulInstallation.CustomInstallationDirectory"; } } }<file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Microsoft.WindowsAzure.Management.Compute.Models; using Microsoft.WindowsAzure.Management.Compute; using Hyak.Common; namespace Calamari.AzureCloudService { public class SwapAzureDeploymentBehaviour : IBeforePackageExtractionBehaviour { readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly IScriptEngine scriptEngine; readonly ICommandLineRunner commandLineRunner; public SwapAzureDeploymentBehaviour(ILog log, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner) { this.log = log; this.fileSystem = fileSystem; this.scriptEngine = scriptEngine; this.commandLineRunner = commandLineRunner; } public bool IsEnabled(RunningDeployment context) { return true; } public async Task Execute(RunningDeployment context) { static async Task<DeploymentGetResponse> GetStagingDeployment(IComputeManagementClient azureClient, string serviceName) { try { var deployment = await azureClient.Deployments.GetBySlotAsync(serviceName, DeploymentSlot.Staging); return deployment; } catch (CloudException e) { if (e.Error.Code == "ResourceNotFound") { return null; } throw; } } var cloudServiceName = context.Variables.Get(SpecialVariables.Action.Azure.CloudServiceName); var slot = context.Variables.Get(SpecialVariables.Action.Azure.Slot, DeploymentSlot.Staging.ToString()); var deploymentSlot = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), slot); var swapIfPossible = context.Variables.GetFlag(SpecialVariables.Action.Azure.SwapIfPossible); var deploymentLabel = context.Variables.Get(SpecialVariables.Action.Azure.DeploymentLabel, $"{context.Variables.Get(ActionVariables.Name)} v{context.Variables.Get(KnownVariables.Release.Number)}"); log.SetOutputVariable("OctopusAzureServiceName", cloudServiceName, context.Variables); log.SetOutputVariable("OctopusAzureStorageAccountName", context.Variables.Get(SpecialVariables.Action.Azure.StorageAccountName), context.Variables); log.SetOutputVariable("OctopusAzureSlot", slot, context.Variables); log.SetOutputVariable("OctopusAzureDeploymentLabel", deploymentLabel, context.Variables); log.SetOutputVariable("OctopusAzureSwapIfPossible", swapIfPossible.ToString(), context.Variables); var tempDirectory = fileSystem.CreateTemporaryDirectory(); var scriptFile = Path.Combine(tempDirectory, "SwapAzureCloudServiceDeployment.ps1"); // The user may supply the script, to override behaviour if (fileSystem.FileExists(scriptFile)) { var result = scriptEngine.Execute(new Script(scriptFile), context.Variables, commandLineRunner); fileSystem.DeleteDirectory(tempDirectory, FailureOptions.IgnoreFailure); if (result.ExitCode != 0) { throw new CommandException($"Script '{scriptFile}' returned non-zero exit code: {result.ExitCode}"); } } else if (swapIfPossible && deploymentSlot == DeploymentSlot.Production) { log.Verbose("Checking whether a swap is possible"); var account = new AzureAccount(context.Variables); var certificate = CalamariCertificateStore.GetOrAdd(account.CertificateThumbprint, account.CertificateBytes); using var azureClient = account.CreateComputeManagementClient(certificate); var deployment = await GetStagingDeployment(azureClient, cloudServiceName); if (deployment == null) { log.Verbose("Nothing is deployed in staging"); } else { log.Verbose($"Current staging deployment: {deployment.Label}"); if (deployment.Label == deploymentLabel) { log.Verbose("Swapping the staging environment to production"); await azureClient.Deployments.SwapAsync(cloudServiceName, new DeploymentSwapParameters { SourceDeployment = deployment.PrivateId }); log.SetOutputVariable(SpecialVariables.Action.Azure.Output.CloudServiceDeploymentSwapped, bool.TrueString, context.Variables); } } } var swapped = context.Variables.GetFlag(SpecialVariables.Action.Azure.Output.CloudServiceDeploymentSwapped); if (swapped) { context.Variables.Set(KnownVariables.Action.SkipRemainingConventions, bool.TrueString); } } } }<file_sep>#!/bin/bash nginxTempDir=$(get_octopusvariable "OctopusNginxFeatureTempDirectory") if [ -d "${nginxTempDir}" ]; then echo "Removing temporary folder ${nginxTempDir}..." sudo rm -rf $nginxTempDir fi<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Deployment.PackageRetention.Model; using Newtonsoft.Json; namespace Calamari.Deployment.PackageRetention.Repositories { public class JsonJournalRepository : JournalRepositoryBase { readonly ICalamariFileSystem fileSystem; readonly string journalPath; readonly ILog log; public JsonJournalRepository(ICalamariFileSystem fileSystem, IJsonJournalPathProvider pathProvider, ILog log) { this.fileSystem = fileSystem; journalPath = pathProvider.GetJournalPath(); this.log = log; } public override void Commit() { Save(); } public override void Load() { if (File.Exists(journalPath)) { var json = fileSystem.ReadFile(journalPath); if (TryDeserializeJournal(json, out var journalContents)) { journalEntries = journalContents ?.JournalEntries ?.ToDictionary(entry => entry.Package, entry => entry) ?? new Dictionary<PackageIdentity, JournalEntry>(); Cache = journalContents?.Cache ?? new PackageCache(0); } else { var journalFileName = Path.GetFileNameWithoutExtension(journalPath); var backupJournalFileName = $"{journalFileName}_{DateTimeOffset.UtcNow:yyyyMMddTHHmmss}.json"; // eg. PackageRetentionJournal_20210101T120000.json log.Warn($"The existing package retention journal file {journalPath} could not be read. The file will be renamed to {backupJournalFileName}. A new journal will be created."); // NET Framework 4.0 doesn't have File.Move(source, dest, overwrite) so we use Copy and Delete to replicate this File.Copy(journalPath, Path.Combine(Path.GetDirectoryName(journalPath), backupJournalFileName), true); File.Delete(journalPath); journalEntries = new Dictionary<PackageIdentity, JournalEntry>(); Cache = new PackageCache(0); } } else { journalEntries = new Dictionary<PackageIdentity, JournalEntry>(); Cache = new PackageCache(0); } } void Save() { var onlyJournalEntries = journalEntries.Select(p => p.Value); var json = JsonConvert.SerializeObject(new PackageData(onlyJournalEntries, Cache)); fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(journalPath)); //save to temp file first var tempFilePath = $"{journalPath}.temp.{Guid.NewGuid()}.json"; fileSystem.WriteAllText(tempFilePath, json, Encoding.UTF8); fileSystem.OverwriteAndDelete(journalPath, tempFilePath); } class PackageData { public IEnumerable<JournalEntry> JournalEntries { get; } public PackageCache Cache { get; } [JsonConstructor] public PackageData(IEnumerable<JournalEntry> journalEntries, PackageCache cache) { JournalEntries = journalEntries; Cache = cache; } public PackageData() { JournalEntries = new List<JournalEntry>(); Cache = new PackageCache(0); } } static bool TryDeserializeJournal(string json, out PackageData result) { try { result = JsonConvert.DeserializeObject<PackageData>(json); return true; } catch (Exception e) { Log.Verbose($"Unable to deserialize entries in the package retention journal file. Error message: {e.ToString()}"); result = new PackageData(); return false; } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.Packages.Download.Helm; using Octopus.Versioning; using HttpClient = System.Net.Http.HttpClient; using PackageName = Calamari.Common.Features.Packages.PackageName; #if SUPPORTS_POLLY using Polly; #endif namespace Calamari.Integration.Packages.Download { public class HelmChartPackageDownloader: IPackageDownloader { static readonly IPackageDownloaderUtils PackageDownloaderUtils = new PackageDownloaderUtils(); const string Extension = ".tgz"; readonly ICalamariFileSystem fileSystem; readonly IHelmEndpointProxy endpointProxy; readonly HttpClient client; public HelmChartPackageDownloader(ICalamariFileSystem fileSystem) { this.fileSystem = fileSystem; client = new HttpClient(new HttpClientHandler{ AutomaticDecompression = DecompressionMethods.None }); endpointProxy = new HelmEndpointProxy(client); } public PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, string? feedUsername, string? feedPassword, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { var cacheDirectory = PackageDownloaderUtils.GetPackageRoot(feedId); fileSystem.EnsureDirectoryExists(cacheDirectory); if (!forcePackageDownload) { var downloaded = SourceFromCache(packageId, version, cacheDirectory); if (downloaded != null) { Log.VerboseFormat("Package was found in cache. No need to download. Using file: '{0}'", downloaded.FullFilePath); return downloaded; } } var feedCredentials = GetFeedCredentials(feedUsername, feedPassword); var package = GetChartDetails(feedUri, feedCredentials, packageId, CancellationToken.None); if (string.IsNullOrEmpty(package.PackageId)) { throw new CommandException($"There was an error fetching the chart from the provided repository. The package id was not valid ({package.PackageId})"); } var packageVersion = package.Versions.FirstOrDefault(v => version.Equals(v.Version)); var foundUrl = packageVersion?.Urls.FirstOrDefault(); if (foundUrl == null) { throw new CommandException("Could not determine download url from chart repository. Please check associated index.yaml is correct."); } var packageUrl = foundUrl.IsValidUrl() ? new Uri(foundUrl, UriKind.Absolute) : new Uri(feedUri, foundUrl); return DownloadChart(packageUrl, packageId, version, feedCredentials, cacheDirectory); } (string PackageId, IEnumerable<HelmIndexYamlReader.ChartData> Versions) GetChartDetails(Uri feedUri, ICredentials credentials, string packageId, CancellationToken cancellationToken) { var cred = credentials.GetCredential(feedUri, "basic"); var yaml = endpointProxy.Get(feedUri, cred.UserName, cred.Password, cancellationToken); var package = HelmIndexYamlReader.Read(yaml).FirstOrDefault(p => p.PackageId.Equals(packageId, StringComparison.OrdinalIgnoreCase)); return package; } PackagePhysicalFileMetadata DownloadChart(Uri url, string packageId, IVersion version, ICredentials feedCredentials, string cacheDirectory) { var cred = feedCredentials.GetCredential(url, "basic"); var tempDirectory = fileSystem.CreateTemporaryDirectory(); using (new TemporaryDirectory(tempDirectory)) { var homeDir = Path.Combine(tempDirectory, "helm"); if (!Directory.Exists(homeDir)) { Directory.CreateDirectory(homeDir); } var stagingDir = Path.Combine(tempDirectory, "staging"); if (!Directory.Exists(stagingDir)) { Directory.CreateDirectory(stagingDir); } string cachedFileName = PackageName.ToCachedFileName(packageId, version, Extension); var downloadPath = Path.Combine(Path.Combine(stagingDir, cachedFileName)); InvokeWithRetry(() => { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.AddAuthenticationHeader(cred.UserName, cred.Password); using (var fileStream = fileSystem.OpenFile(downloadPath, FileAccess.Write)) using (var response = client.SendAsync(request).Result) { if (!response.IsSuccessStatusCode) { throw new CommandException( $"Helm failed to download the chart (Status Code {(int) response.StatusCode}). Reason: {response.ReasonPhrase}"); } #if NET40 response.Content.CopyToAsync(fileStream).Wait(); #else response.Content.CopyToAsync(fileStream).GetAwaiter().GetResult(); #endif } }); var localDownloadName = Path.Combine(cacheDirectory, cachedFileName); fileSystem.MoveFile(downloadPath, localDownloadName); var packagePhysicalFileMetadata = PackagePhysicalFileMetadata.Build(localDownloadName); return packagePhysicalFileMetadata ?? throw new CommandException($"Unable to retrieve metadata for package {packageId}, version {version}"); } } #if SUPPORTS_POLLY void InvokeWithRetry(Action action) { Policy.Handle<Exception>() .WaitAndRetry(4, retry => TimeSpan.FromSeconds(retry), (ex, timespan) => { Console.WriteLine($"Command failed. Retrying in {timespan}."); }) .Execute(action); } #else //net40 doesn't support polly... usage is low enough to skip the effort to implement nice retries void InvokeWithRetry(Action action) => action(); #endif PackagePhysicalFileMetadata? SourceFromCache(string packageId, IVersion version, string cacheDirectory) { Log.VerboseFormat("Checking package cache for package {0} v{1}", packageId, version.ToString()); var files = fileSystem.EnumerateFilesRecursively(cacheDirectory, PackageName.ToSearchPatterns(packageId, version, new [] { Extension })); foreach (var file in files) { var package = PackageName.FromFile(file); if (package == null) continue; if (string.Equals(package.PackageId, packageId, StringComparison.OrdinalIgnoreCase) && package.Version.Equals(version)) return PackagePhysicalFileMetadata.Build(file, package); } return null; } static ICredentials GetFeedCredentials(string? feedUsername, string? feedPassword) { ICredentials credentials = CredentialCache.DefaultNetworkCredentials; if (!String.IsNullOrWhiteSpace(feedUsername)) { credentials = new NetworkCredential(feedUsername, feedPassword); } return credentials; } } }<file_sep>using System; namespace Calamari.Common.Features.Deployment { public static class DeploymentStages { public const string BeforePreDeploy = "BeforePreDeploy"; public const string PreDeploy = "PreDeploy"; public const string AfterPreDeploy = "AfterPreDeploy"; public const string BeforeDeploy = "BeforeDeploy"; public const string Deploy = "Deploy"; public const string AfterDeploy = "AfterDeploy"; public const string BeforePostDeploy = "BeforePostDeploy"; public const string PostDeploy = "PostDeploy"; public const string AfterPostDeploy = "AfterPostDeploy"; public const string DeployFailed = "DeployFailed"; } }<file_sep>#if NETCORE using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Calamari.Testing; using Calamari.Testing.Helpers; using Newtonsoft.Json.Linq; using NUnit.Framework; using SpecialVariables = Calamari.Kubernetes.SpecialVariables; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class KubernetesContextScriptWrapperLiveFixtureGke : KubernetesContextScriptWrapperLiveFixture { string gkeToken; string gkeProject; string gkeLocation; string gkeClusterCaCertificate; string gkeClusterEndpoint; string gkeClusterName; protected override string KubernetesCloudProvider => "GKE"; protected override IEnumerable<string> ToolsToAddToPath(InstallTools tools) { yield return tools.GcloudExecutable; } protected override async Task InstallOptionalTools(InstallTools tools) { await tools.InstallGCloud(); } protected override void ExtractVariablesFromTerraformOutput(JObject jsonOutput) { gkeClusterEndpoint = jsonOutput["gke_cluster_endpoint"]["value"].Value<string>(); gkeClusterCaCertificate = jsonOutput["gke_cluster_ca_certificate"]["value"].Value<string>(); gkeToken = jsonOutput["gke_token"]["value"].Value<string>(); gkeClusterName = jsonOutput["gke_cluster_name"]["value"].Value<string>(); gkeProject = jsonOutput["gke_cluster_project"]["value"].Value<string>(); gkeLocation = jsonOutput["gke_cluster_location"]["value"].Value<string>(); } protected override Dictionary<string, string> GetEnvironmentVars() { return new Dictionary<string, string> { { "GOOGLE_CLOUD_KEYFILE_JSON", ExternalVariables.Get(ExternalVariable.GoogleCloudJsonKeyfile) }, { "USE_GKE_GCLOUD_AUTH_PLUGIN", "True" } }; } [Test] [TestCase(true)] [TestCase(false)] public void AuthorisingWithToken(bool runAsScript) { variables.Set(SpecialVariables.ClusterUrl, $"https://{gkeClusterEndpoint}"); variables.Set(Deployment.SpecialVariables.Account.AccountType, "Token"); variables.Set(Deployment.SpecialVariables.Account.Token, gkeToken); var certificateAuthority = "myauthority"; variables.Set("Octopus.Action.Kubernetes.CertificateAuthority", certificateAuthority); variables.Set($"{certificateAuthority}.CertificatePem", gkeClusterCaCertificate); if (runAsScript) { DeployWithKubectlTestScriptAndVerifyResult(); } else { ExecuteCommandAndVerifyResult(TestableKubernetesDeploymentCommand.Name); } } [Test] [TestCase(true)] [TestCase(false)] public void AuthorisingWithGoogleCloudAccount(bool runAsScript) { variables.Set(Deployment.SpecialVariables.Account.AccountType, "GoogleCloudAccount"); variables.Set(SpecialVariables.GkeClusterName, gkeClusterName); var account = "gke_account"; variables.Set("Octopus.Action.GoogleCloudAccount.Variable", account); var jsonKey = ExternalVariables.Get(ExternalVariable.GoogleCloudJsonKeyfile); variables.Set($"{account}.JsonKey", Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonKey))); variables.Set("Octopus.Action.GoogleCloud.Project", gkeProject); variables.Set("Octopus.Action.GoogleCloud.Zone", gkeLocation); if (runAsScript) { DeployWithKubectlTestScriptAndVerifyResult(); } else { ExecuteCommandAndVerifyResult(TestableKubernetesDeploymentCommand.Name); } } [Test] public void UsingInternalIpForPrivateCluster() { variables.Set(Deployment.SpecialVariables.Account.AccountType, "GoogleCloudAccount"); variables.Set(SpecialVariables.GkeClusterName, gkeClusterName); variables.Set(SpecialVariables.GkeUseClusterInternalIp, bool.TrueString); var account = "gke_account"; variables.Set("Octopus.Action.GoogleCloudAccount.Variable", account); var jsonKey = ExternalVariables.Get(ExternalVariable.GoogleCloudJsonKeyfile); variables.Set($"{account}.JsonKey", Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonKey))); variables.Set("Octopus.Action.GoogleCloud.Project", gkeProject); variables.Set("Octopus.Action.GoogleCloud.Zone", gkeLocation); ExecuteCommandAndVerifyResult(TestableKubernetesDeploymentCommand.Name); } [Test] public void UnreachableK8Cluster_ShouldExecuteTargetScript() { const string unreachableClusterUrl = "https://example.kubernetes.com"; const string certificateAuthority = "myauthority"; variables.Set(SpecialVariables.ClusterUrl, unreachableClusterUrl); variables.Set(Deployment.SpecialVariables.Account.AccountType, "Token"); variables.Set(Deployment.SpecialVariables.Account.Token, gkeToken); variables.Set("Octopus.Action.Kubernetes.CertificateAuthority", certificateAuthority); variables.Set($"{certificateAuthority}.CertificatePem", gkeClusterCaCertificate); DeployWithNonKubectlTestScriptAndVerifyResult(); } } } #endif<file_sep>using System.IO; using Calamari.Common.Plumbing.Extensions; using Calamari.Util; using Octostache; namespace Calamari.Tests { public static class VariableDictionaryExtensions { public static void SaveEncrypted(this VariableDictionary variables, string key, string file) { var encryptedContent = new AesEncryption(key).Encrypt(variables.SaveAsString()); File.WriteAllBytes(file, encryptedContent); } } } <file_sep>namespace Calamari.Aws.Deployment { public static class AwsSpecialVariables { public const string IamCapabilities = "Octopus.Action.Aws.IamCapabilities"; public static class Authentication { public static readonly string UseInstanceRole = "Octopus.Action.AwsAccount.UseInstanceRole"; public static readonly string AwsAccountVariable = "Octopus.Action.AwsAccount.Variable"; } public static class S3 { public const string FileSelections = "Octopus.Action.Aws.S3.FileSelections"; public const string PackageOptions = "Octopus.Action.Aws.S3.PackageOptions"; } public static class CloudFormation { public const string Action = "Octopus.Action.Aws.CloudFormationAction"; public const string StackName = "Octopus.Action.Aws.CloudFormationStackName"; public const string Template = "Octopus.Action.Aws.CloudFormationTemplate"; public const string TemplateParameters = "Octopus.Action.Aws.CloudFormationTemplateParameters"; public const string TemplateParametersRaw = "Octopus.Action.Aws.CloudFormationTemplateParametersRaw"; public const string RoleArn = "Octopus.Action.Aws.CloudFormation.RoleArn"; public const string Tags = "Octopus.Action.Aws.CloudFormation.Tags"; public static class Changesets { public const string Feature = "Octopus.Features.CloudFormation.ChangeSet.Feature"; //The Name is generally used when the user doesn't want octopus to generate the change set name public const string Name = "Octopus.Action.Aws.CloudFormation.ChangeSet.Name"; public const string Defer = "Octopus.Action.Aws.CloudFormation.ChangeSet.Defer"; public const string Generate = "Octopus.Action.Aws.CloudFormation.ChangeSet.GenerateName"; //The ARN is either specified or dynamically provided when the change set is created public const string Arn = "Octopus.Action.Aws.CloudFormation.ChangeSet.Arn"; } } } } <file_sep>using System; using Calamari.Common.Plumbing.Logging; using Microsoft.Web.XmlTransform; namespace Calamari.Common.Features.ConfigurationTransforms { public class VerboseTransformLogger : IXmlTransformationLogger { public event LogDelegate? Error; readonly TransformLoggingOptions transformLoggingOptions; readonly ILog log; public VerboseTransformLogger(TransformLoggingOptions transformLoggingOptions, ILog log) { this.transformLoggingOptions = transformLoggingOptions; this.log = log; } public void LogMessage(string message, params object[] messageArgs) { if (transformLoggingOptions.HasFlag(TransformLoggingOptions.DoNotLogVerbose)) { return; } log.VerboseFormat(message, messageArgs); } public void LogMessage(MessageType type, string message, params object[] messageArgs) { LogMessage(message, messageArgs); } public void LogWarning(string message, params object[] messageArgs) { LogWarn(message, messageArgs); } public void LogWarning(string file, string message, params object[] messageArgs) { LogWarn("File {0}:", file); LogWarn(message, messageArgs); } public void LogWarning(string file, int lineNumber, int linePosition, string message, params object[] messageArgs) { LogWarn("File {0}, line {1}, position {2}: ", file, lineNumber, linePosition); LogWarning(message, messageArgs); } void LogWarn(string message, params object[] messageArgs) { if (transformLoggingOptions.HasFlag(TransformLoggingOptions.LogWarningsAsErrors)) { log.ErrorFormat(message, messageArgs); Error?.Invoke(this); } else if (transformLoggingOptions.HasFlag(TransformLoggingOptions.LogWarningsAsInfo)) { log.InfoFormat(message, messageArgs); } else { log.WarnFormat(message, messageArgs); } } public void LogError(string message, params object[] messageArgs) { LogErr(message, messageArgs); } public void LogError(string file, string message, params object[] messageArgs) { LogErr("File {0}: ", file); LogErr(message, messageArgs); } public void LogError(string file, int lineNumber, int linePosition, string message, params object[] messageArgs) { LogErr("File {0}, line {1}, position {2}:", file, lineNumber, linePosition); LogErr(message, messageArgs); } public void LogErrorFromException(Exception ex) { LogErr(ex.ToString()); } public void LogErrorFromException(Exception ex, string file) { LogErr("File {0}:", file); LogErr(ex.ToString()); } public void LogErrorFromException(Exception ex, string file, int lineNumber, int linePosition) { LogErr("File {0}, line {1}, position {2}:", file, lineNumber, linePosition); LogErr(ex.ToString()); } void LogErr(string message, params object[] messageArgs) { if (transformLoggingOptions.HasFlag(TransformLoggingOptions.LogExceptionsAsWarnings)) { log.WarnFormat(message, messageArgs); } else { log.ErrorFormat(message, messageArgs); Error?.Invoke(this); } } public void StartSection(string message, params object[] messageArgs) { if (transformLoggingOptions.HasFlag(TransformLoggingOptions.DoNotLogVerbose)) { return; } log.VerboseFormat(message, messageArgs); } public void StartSection(MessageType type, string message, params object[] messageArgs) { StartSection(message, messageArgs); } public void EndSection(string message, params object[] messageArgs) { if (transformLoggingOptions.HasFlag(TransformLoggingOptions.DoNotLogVerbose)) { return; } log.VerboseFormat(message, messageArgs); } public void EndSection(MessageType type, string message, params object[] messageArgs) { EndSection(message, messageArgs); } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Logging; using SharpCompress.Archives; using SharpCompress.Archives.Zip; using SharpCompress.Common; #if !NET40 using Polly; #endif namespace Calamari.Common.Features.Packages { public class ZipPackageExtractor : IPackageEntryExtractor { readonly ILog log; public ZipPackageExtractor(ILog log) { this.log = log; } public string[] Extensions => new[] { ".zip" }; public int Extract(string packageFile, string directory) { var filesExtracted = 0; using (var inStream = new FileStream(packageFile, FileMode.Open, FileAccess.Read)) using (var archive = ZipArchive.Open(inStream)) { foreach (var entry in archive.Entries) { ProcessEvent(ref filesExtracted, entry); ExtractEntry(directory, entry); } } return filesExtracted; } public void ExtractEntry(string directory, IArchiveEntry entry) { #if NET40 entry.WriteToDirectory(directory, new PackageExtractionOptions(log)); #else var extractAttempts = 10; Policy.Handle<IOException>() .WaitAndRetry( extractAttempts, i => TimeSpan.FromMilliseconds(50), (ex, retry) => { log.Verbose($"Failed to extract: {ex.Message}. Retry in {retry.Milliseconds} milliseconds."); }) .Execute(() => { entry.WriteToDirectory(directory, new PackageExtractionOptions(log)); }); #endif } protected void ProcessEvent(ref int filesExtracted, IEntry entry) { if (entry.IsDirectory) return; filesExtracted++; } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Packages { public class ExtractPackage : IExtractPackage { public const string StagingDirectoryName = "staging"; readonly ICombinedPackageExtractor combinedPackageExtractor; readonly ICalamariFileSystem fileSystem; readonly IVariables variables; readonly ILog log; public ExtractPackage(ICombinedPackageExtractor combinedPackageExtractor, ICalamariFileSystem fileSystem, IVariables variables, ILog log) { this.combinedPackageExtractor = combinedPackageExtractor; this.fileSystem = fileSystem; this.variables = variables; this.log = log; } public void ExtractToCustomDirectory(PathToPackage? pathToPackage, string directory) { ExtractToCustomSubDirectory(pathToPackage, directory, null, null); } public void ExtractToStagingDirectory(PathToPackage? pathToPackage, IPackageExtractor? customPackageExtractor = null) { ExtractToCustomSubDirectory(pathToPackage, Path.Combine(Environment.CurrentDirectory, StagingDirectoryName), customPackageExtractor, null); } public void ExtractToStagingDirectory(PathToPackage? pathToPackage, string extractedToPathOutputVariableName) { ExtractToCustomSubDirectory( pathToPackage, Path.Combine(Environment.CurrentDirectory, StagingDirectoryName), null, extractedToPathOutputVariableName); } public void ExtractToEnvironmentCurrentDirectory(PathToPackage pathToPackage) { var targetPath = Environment.CurrentDirectory; Extract(pathToPackage, targetPath, PackageVariables.Output.InstallationDirectoryPath, null); } public void ExtractToApplicationDirectory(PathToPackage pathToPackage, IPackageExtractor? customPackageExtractor = null) { var metadata = PackageName.FromFile(pathToPackage); var targetPath = ApplicationDirectory.GetApplicationDirectory(metadata, variables, fileSystem); Extract(pathToPackage, targetPath, PackageVariables.Output.InstallationDirectoryPath, customPackageExtractor); } void ExtractToCustomSubDirectory(PathToPackage? pathToPackage, string directory, IPackageExtractor? customPackageExtractor, string? extractedToPathOutputVariableName) { fileSystem.EnsureDirectoryExists(directory); Extract(pathToPackage, directory, extractedToPathOutputVariableName ?? PackageVariables.Output.InstallationDirectoryPath, customPackageExtractor); } void Extract(PathToPackage? pathToPackage, string targetPath, string extractedToPathOutputVariableName, IPackageExtractor? customPackageExtractor) { try { var path = (string?)pathToPackage; if (string.IsNullOrWhiteSpace(path)) { log.Verbose("No package path defined. Skipping package extraction."); return; } log.Verbose("Extracting package to: " + targetPath); var extractorToUse = customPackageExtractor ?? combinedPackageExtractor; var filesExtracted = extractorToUse.Extract(path, targetPath); log.Verbose("Extracted " + filesExtracted + " files"); variables.Set(KnownVariables.OriginalPackageDirectoryPath, targetPath); log.SetOutputVariable(extractedToPathOutputVariableName, targetPath, variables); log.SetOutputVariable(PackageVariables.Output.DeprecatedInstallationDirectoryPath, targetPath, variables); log.SetOutputVariable(PackageVariables.Output.ExtractedFileCount, filesExtracted.ToString(), variables); } catch (UnauthorizedAccessException) { LogAccessDenied(); throw; } catch (Exception ex) when (ex.Message.ContainsIgnoreCase("Access is denied")) { LogAccessDenied(); throw; } } void LogAccessDenied() { log.Error("Failed to extract the package because access to the package was denied. This may have happened because anti-virus software is scanning the file. Try disabling your anti-virus software in order to rule this out."); } } }<file_sep>namespace Calamari.Integration.Iis { public enum ApplicationPoolIdentityType { ApplicationPoolIdentity, LocalService, LocalSystem, NetworkService, SpecificUser } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.Bash { public class BashScriptBootstrapper { public const string WindowsNewLine = "\r\n"; public const string LinuxNewLine = "\n"; static readonly string BootstrapScriptTemplate; static readonly string SensitiveVariablePassword = <PASSWORD>.RandomString(16); static readonly AesEncryption VariableEncryptor = new AesEncryption(SensitiveVariablePassword); static readonly ICalamariFileSystem CalamariFileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); static BashScriptBootstrapper() { BootstrapScriptTemplate = EmbeddedResource.ReadEmbeddedText(typeof(BashScriptBootstrapper).Namespace + ".Bootstrap.sh"); } public static string FormatCommandArguments(string bootstrapFile) { var encryptionKey = ToHex(AesEncryption.GetEncryptionKey(SensitiveVariablePassword)); var commandArguments = new StringBuilder(); commandArguments.AppendFormat("\"{0}\" \"{1}\"", bootstrapFile, encryptionKey); return commandArguments.ToString(); } public static string PrepareConfigurationFile(string workingDirectory, IVariables variables) { var configurationFile = Path.Combine(workingDirectory, "Configure." + Guid.NewGuid().ToString().Substring(10) + ".sh"); var builder = new StringBuilder(BootstrapScriptTemplate); var encryptedVariables = EncryptVariables(variables); builder.Replace("#### VariableDeclarations ####", string.Join(LinuxNewLine, GetVariableSwitchConditions(encryptedVariables))); using (var file = new FileStream(configurationFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.ASCII)) { writer.Write(builder.Replace(WindowsNewLine, LinuxNewLine)); writer.Flush(); } File.SetAttributes(configurationFile, FileAttributes.Hidden); return configurationFile; } static IList<EncryptedVariable> EncryptVariables(IVariables variables) { return variables.GetNames() .Select(name => { var encryptedValue = VariableEncryptor.Encrypt(variables.Get(name) ?? ""); var raw = AesEncryption.ExtractIV(encryptedValue, out var iv); return new EncryptedVariable(name, Convert.ToBase64String(raw), ToHex(iv)); }).ToList(); } static IEnumerable<string> GetVariableSwitchConditions(IEnumerable<EncryptedVariable> variables) { return variables .Select(variable => { var variableValue = $@"decrypt_variable ""{variable.EncryptedValue}"" ""{variable.Iv}"""; return string.Format(" \"{1}\"){0} {2} ;;{0}", Environment.NewLine, EncodeValue(variable.Name), variableValue); }); } static string ToHex(byte[] bytes) { return BitConverter.ToString(bytes).Replace("-", ""); } static string EncodeValue(string value) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(value ?? "")); } public static string FindBashExecutable() { if (CalamariEnvironment.IsRunningOnWindows) { var systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System); return Path.Combine(systemFolder, "bash.exe"); } return "bash"; } static void EnsureValidUnixFile(string scriptFilePath) { var text = File.ReadAllText(scriptFilePath); text = text.Replace(WindowsNewLine, LinuxNewLine); File.WriteAllText(scriptFilePath, text); } public static (string bootstrapFile, string[] temporaryFiles) PrepareBootstrapFile(Script script, string configurationFile, string workingDirectory, IVariables variables) { var bootstrapFile = Path.Combine(workingDirectory, "Bootstrap." + Guid.NewGuid().ToString().Substring(10) + "." + Path.GetFileName(script.File)); var scriptModulePaths = PrepareScriptModules(variables, workingDirectory).ToArray(); using (var file = new FileStream(bootstrapFile, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(file, Encoding.ASCII)) { writer.NewLine = LinuxNewLine; writer.WriteLine("#!/bin/bash"); writer.WriteLine("source \"$(pwd)/" + Path.GetFileName(configurationFile) + "\""); writer.WriteLine("shift"); // Shift the variable decryption key out of scope of the user script (see: https://github.com/OctopusDeploy/Calamari/pull/773) writer.WriteLine("source \"$(pwd)/" + Path.GetFileName(script.File) + "\" " + script.Parameters); writer.Flush(); } File.SetAttributes(bootstrapFile, FileAttributes.Hidden); EnsureValidUnixFile(script.File); return (bootstrapFile, scriptModulePaths); } static IEnumerable<string> PrepareScriptModules(IVariables variables, string workingDirectory) { foreach (var variableName in variables.GetNames().Where(ScriptVariables.IsLibraryScriptModule)) if (ScriptVariables.GetLibraryScriptModuleLanguage(variables, variableName) == ScriptSyntax.Bash) { var libraryScriptModuleName = ScriptVariables.GetLibraryScriptModuleName(variableName); var name = new string(libraryScriptModuleName.Where(char.IsLetterOrDigit).ToArray()); var moduleFileName = $"{name}.sh"; var moduleFilePath = Path.Combine(workingDirectory, moduleFileName); Log.VerboseFormat("Writing script module '{0}' as bash script {1}. Import this via `source {1}`.", libraryScriptModuleName, moduleFileName, name); Encoding utf8WithoutBom = new UTF8Encoding(false); var contents = variables.Get(variableName); if (contents == null) throw new InvalidOperationException($"Value for variable {variableName} could not be found."); CalamariFileSystem.OverwriteFile(moduleFilePath, contents, utf8WithoutBom); EnsureValidUnixFile(moduleFilePath); yield return moduleFilePath; } } class EncryptedVariable { public EncryptedVariable(string name, string encryptedValue, string iv) { Name = name; EncryptedValue = encryptedValue; Iv = iv; } public string Name { get; } public string EncryptedValue { get; } public string Iv { get; } } } } <file_sep>using Calamari.Common.Plumbing.Logging; namespace Calamari.Tests.Helpers { public class SilentLog : AbstractLog { protected override void StdOut(string message) { // Do nothing } protected override void StdErr(string message) { // Do nothing } } }<file_sep>#if !NET40 using System; using System.Collections.Generic; using System.IO; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Proxies; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus; namespace Calamari.Commands { [Command("kubernetes-object-status")] public class KubernetesObjectStatusReporterCommand: Command<KubernetesObjectStatusReporterCommandInput> { private readonly ILog log; private readonly IVariables variables; private readonly IResourceStatusReportExecutor statusReportExecutor; private readonly Kubectl kubectl; public KubernetesObjectStatusReporterCommand( ILog log, IVariables variables, IResourceStatusReportExecutor statusReportExecutor, Kubectl kubectl) { this.log = log; this.variables = variables; this.statusReportExecutor = statusReportExecutor; this.kubectl = kubectl; } protected override void Execute(KubernetesObjectStatusReporterCommandInput inputs) { if (!inputs.Enabled) { log.Info("Kubernetes Object Status reporting has been skipped."); return; } try { log.Info("Starting Kubernetes Object Status reporting."); ConfigureKubectl(); var manifestPath = variables.Get(SpecialVariables.KustomizeManifest); var defaultNamespace = variables.Get(SpecialVariables.Namespace, "default"); // When the namespace on a target was set and then cleared, it's going to be "" instead of null if (string.IsNullOrEmpty(defaultNamespace)) { defaultNamespace = "default"; } var resources = KubernetesYaml.GetDefinedResources(new[] {File.ReadAllText(manifestPath)}, defaultNamespace); var statusResult = statusReportExecutor.Start(inputs.Timeout, inputs.WaitForJobs, resources).WaitForCompletionOrTimeout() .GetAwaiter().GetResult(); if (!statusResult) { throw new CommandException("Unable to complete Kubernetes Report Status."); } } catch (Exception ex) { throw new CommandException("Failed to complete Kubernetes Report Status.", ex); } } private void ConfigureKubectl() { var kubeConfig = variables.Get(SpecialVariables.KubeConfig); var environmentVars = new Dictionary<string, string> {{"KUBECONFIG", kubeConfig}}; foreach (var proxyVariable in ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables()) { environmentVars[proxyVariable.Key] = proxyVariable.Value; } kubectl.SetEnvironmentVariables(environmentVars); } } public class KubernetesObjectStatusReporterCommandInput { public bool WaitForJobs { get; set; } public int Timeout { get; set; } public bool Enabled { get; set; } } } #endif<file_sep>using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureCloudService { [Command("deploy-azure-cloud-service", Description = "Extracts and installs an Azure Cloud-Service")] public class DeployAzureCloudServiceCommand : PipelineCommand { protected override IEnumerable<IBeforePackageExtractionBehaviour> BeforePackageExtraction(BeforePackageExtractionResolver resolver) { yield return resolver.Create<SwapAzureDeploymentBehaviour>(); } protected override IEnumerable<IAfterPackageExtractionBehaviour> AfterPackageExtraction(AfterPackageExtractionResolver resolver) { yield return resolver.Create<FindCloudServicePackageBehaviour>(); yield return resolver.Create<EnsureCloudServicePackageIsCtpFormatBehaviour>(); yield return resolver.Create<ExtractAzureCloudServicePackageBehaviour>(); yield return resolver.Create<ChooseCloudServiceConfigurationFileBehaviour>(); } protected override IEnumerable<IPreDeployBehaviour> PreDeploy(PreDeployResolver resolver) { yield return resolver.Create<ConfigureAzureCloudServiceBehaviour>(); } protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<RePackageCloudServiceBehaviour>(); yield return resolver.Create<UploadAzureCloudServicePackageBehaviour>(); yield return resolver.Create<DeployAzureCloudServicePackageBehaviour>(); } } }<file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Retry; using Globfish; namespace Calamari.Common.Plumbing.FileSystem { public abstract class CalamariPhysicalFileSystem : ICalamariFileSystem { /// <summary> /// For file operations, try again after 100ms and again every 200ms after that /// </summary> static readonly LimitedExponentialRetryInterval RetryIntervalForFileOperations = new LimitedExponentialRetryInterval(100, 200, 2); public static readonly ReadOnlyCollection<Encoding> DefaultInputEncodingPrecedence; static CalamariPhysicalFileSystem() { #if NETSTANDARD Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Required to use code pages in .NET Standard #endif DefaultInputEncodingPrecedence = new List<Encoding> { new UTF8Encoding(false, true), Encoding.GetEncoding("windows-1252", EncoderFallback.ExceptionFallback /* Detect problems if re-used for output */, DecoderFallback.ReplacementFallback) }.AsReadOnly(); } protected IFile File { get; set; } = new StandardFile(); protected IDirectory Directory { get; set; } = new StandardDirectory(); public static CalamariPhysicalFileSystem GetPhysicalFileSystem() { if (CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac) return new NixCalamariPhysicalFileSystem(); return new WindowsPhysicalFileSystem(); } /// <summary> /// For file operations, retry constantly up to one minute /// </summary> /// <remarks> /// Windows services can hang on to files for ~30s after the service has stopped as background /// threads shutdown or are killed for not shutting down in a timely fashion /// </remarks> protected static RetryTracker GetFileOperationRetryTracker() { return new RetryTracker(10000, TimeSpan.FromMinutes(1), RetryIntervalForFileOperations); } public bool FileExists(string? path) { return File.Exists(path); } public bool DirectoryExists(string? path) { return Directory.Exists(path); } public bool DirectoryIsEmpty(string path) { try { return !Directory.GetFileSystemEntries(path).Any(); } catch (Exception) { return false; } } public virtual void DeleteFile(string path, FailureOptions options = FailureOptions.ThrowOnFailure) { DeleteFile(path, options, GetFileOperationRetryTracker(), CancellationToken.None); } void DeleteFile(string path, FailureOptions options, RetryTracker retry, CancellationToken cancel) { if (string.IsNullOrWhiteSpace(path)) return; retry.Reset(); while (retry.Try()) { cancel.ThrowIfCancellationRequested(); try { if (File.Exists(path)) { if (retry.IsNotFirstAttempt) File.SetAttributes(path, FileAttributes.Normal); File.Delete(path); } break; } catch (Exception ex) { if (retry.CanRetry()) { if (retry.ShouldLogWarning()) Log.VerboseFormat("Retry #{0} on delete file '{1}'. Exception: {2}", retry.CurrentTry, path, ex.Message); Thread.Sleep(retry.Sleep()); } else { if (options == FailureOptions.ThrowOnFailure) throw; } } } } public void DeleteDirectory(string path) { Directory.Delete(path, true); } public void DeleteDirectory(string path, FailureOptions options) { if (string.IsNullOrWhiteSpace(path)) return; var retry = GetFileOperationRetryTracker(); while (retry.Try()) try { if (Directory.Exists(path)) { var dir = new DirectoryInfo(path); dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(true); EnsureDirectoryDeleted(path, options); } break; } catch (Exception ex) { if (retry.CanRetry()) { if (retry.ShouldLogWarning()) Log.VerboseFormat("Retry #{0} on delete directory '{1}'. Exception: {2}", retry.CurrentTry, path, ex.Message); Thread.Sleep(retry.Sleep()); } else { if (options == FailureOptions.ThrowOnFailure) throw; } } } void EnsureDirectoryDeleted(string path, FailureOptions failureOptions) { var retry = GetFileOperationRetryTracker(); while (retry.Try()) { if (!Directory.Exists(path)) return; if (retry.CanRetry() && retry.ShouldLogWarning()) Log.VerboseFormat("Waiting for directory '{0}' to be deleted", path); } var message = $"Directory '{path}' still exists, despite requested deletion"; if (failureOptions == FailureOptions.ThrowOnFailure) throw new Exception(message); Log.Verbose(message); } public virtual IEnumerable<string> EnumerateFilesWithGlob(string parentDirectoryPath, GlobMode globMode, params string[] globPattern) { return EnumerateWithGlob(parentDirectoryPath, globMode, globPattern).Select(fi => fi.FullName).Where(FileExists); } IEnumerable<FileSystemInfo> EnumerateWithGlob(string parentDirectoryPath, GlobMode globMode, params string[] globPattern) { IEnumerable<FileSystemInfo> Expand(string path) { return globMode switch { GlobMode.GroupExpansionMode => Glob.Expand(path), _ => LegacyGlob.Expand(path) }; } var results = globPattern.Length == 0 ? Expand(Path.Combine(parentDirectoryPath, "*")) : globPattern.SelectMany(pattern => Expand(Path.Combine(parentDirectoryPath, pattern))); return results .GroupBy(fi => fi.FullName) // use groupby + first to do .Distinct using fullname .Select(g => g.First()); } public virtual IEnumerable<string> EnumerateFiles( string parentDirectoryPath, params string[] searchPatterns) { return Directory.EnumerateFiles(parentDirectoryPath, searchPatterns); } public virtual IEnumerable<string> EnumerateFilesRecursively( string parentDirectoryPath, params string[] searchPatterns) { return Directory.EnumerateFilesRecursively(parentDirectoryPath, searchPatterns); } public IEnumerable<string> EnumerateDirectories(string parentDirectoryPath) { return Directory.EnumerateDirectories(parentDirectoryPath); } public IEnumerable<string> EnumerateDirectoriesRecursively(string parentDirectoryPath) { return Directory.EnumerateDirectoriesRecursively(parentDirectoryPath); } public long GetFileSize(string path) { return new FileInfo(path).Length; } public string ReadFile(string path) { return ReadFile(path, out _); } public string ReadFile(string path, out Encoding encoding) { return ReadAllText(ReadAllBytes(path), out encoding, DefaultInputEncodingPrecedence); } public string ReadAllText(byte[] bytes, out Encoding encoding, ICollection<Encoding> encodingPrecedence) { if (encodingPrecedence.Count < 1) throw new Exception("No encodings specified."); if (encodingPrecedence.Take(encodingPrecedence.Count - 1) .FirstOrDefault(DecoderDoesNotRaiseErrorsForUnsupportedCharacters) is { } e) throw new Exception($"The supplied encoding '{e}' does not raise errors for unsupported characters, so the subsequent " + "encoder will never be used. Please set DecoderFallback to ExceptionFallback or use Unicode."); Exception? lastException = null; foreach (var encodingToTry in encodingPrecedence) try { using (var stream = new MemoryStream(bytes)) using (var reader = new StreamReader(stream, encodingToTry)) { var text = reader.ReadToEnd(); encoding = reader.CurrentEncoding; return text; } } catch (DecoderFallbackException ex) { lastException = ex; } throw new Exception("Unable to decode file contents with the specified encodings.", lastException); } public static bool DecoderDoesNotRaiseErrorsForUnsupportedCharacters(Encoding encoding) { return encoding.DecoderFallback != DecoderFallback.ExceptionFallback && !encoding.WebName.StartsWith("utf-") && !encoding.WebName.StartsWith("unicode") && !encoding.WebName.StartsWith("ucs-"); } public byte[] ReadAllBytes(string path) { return File.ReadAllBytes(path); } public void OverwriteFile(string path, string contents, Encoding? encoding = null) { RetryTrackerFileAction(() => WriteAllText(path, contents, encoding), path, "overwrite"); } public void OverwriteFile(string path, Action<TextWriter> writeToWriter, Encoding? encoding = null) { RetryTrackerFileAction(() => WriteAllText(path, writeToWriter, encoding), path, "overwrite"); } public void OverwriteFile(string path, byte[] data) { RetryTrackerFileAction(() => WriteAllBytes(path, data), path, "overwrite"); } public void WriteAllText(string path, string contents, Encoding? encoding = null) { WriteAllText(path, writer => writer.Write(contents), encoding); } public void WriteAllText(string path, Action<TextWriter> writeToWriter, Encoding? encoding = null) { if (path.Length <= 0) throw new ArgumentException(path); var encodingsToTry = new List<Encoding> { new UTF8Encoding(false, true) }; if (encoding != null) encodingsToTry.Insert(0, encoding); if (encodingsToTry.Take(encodingsToTry.Count - 1) .FirstOrDefault(EncoderDoesNotRaiseErrorsForUnsupportedCharacters) is { } e) Log.Warn($"The supplied encoding '{e}' does not raise errors for unsupported characters, so the subsequent " + "encoder will never be used. Please set DecoderFallback to ExceptionFallback or use Unicode."); byte[]? bytes = null; (Encoding encoding, Exception exception)? lastFailure = null; foreach (var currentEncoding in encodingsToTry) { if (lastFailure != null) Log.Warn($"Unable to represent the output with encoding {lastFailure?.encoding.WebName}. Trying next the alternative: {currentEncoding.WebName}."); try { using (var memoryStream = new MemoryStream()) { using (var textWriter = new StreamWriter(memoryStream, currentEncoding)) { writeToWriter(textWriter); } bytes = memoryStream.ToArray(); } break; } catch (EncoderFallbackException ex) { lastFailure = (currentEncoding, ex); } } if (bytes == null) { throw new Exception("Unable to encode text with the specified encodings.", lastFailure?.exception); } WriteAllBytes(path, bytes); } public static bool EncoderDoesNotRaiseErrorsForUnsupportedCharacters(Encoding encoding) { return encoding.EncoderFallback != EncoderFallback.ExceptionFallback && !encoding.WebName.StartsWith("utf-") && !encoding.WebName.StartsWith("unicode") && !encoding.WebName.StartsWith("ucs-"); } public Stream OpenFile(string path, FileAccess access, FileShare share) { return OpenFile(path, FileMode.OpenOrCreate, access, share); } public Stream OpenFile(string path, FileMode mode, FileAccess access, FileShare share) { return new FileStream(path, mode, access, share); } public Stream CreateTemporaryFile(string extension, out string path) { if (!extension.StartsWith(".")) extension = "." + extension; path = Path.Combine(GetTempBasePath(), Guid.NewGuid() + extension); return OpenFile(path, FileAccess.ReadWrite, FileShare.Read); } string GetTempBasePath() { var path1 = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create); path1 = Path.Combine(path1, Assembly.GetEntryAssembly()?.GetName().Name ?? "Octopus.Calamari"); path1 = Path.Combine(path1, "Temp"); var path = path1; Directory.CreateDirectory(path); return Path.GetFullPath(path); } public string CreateTemporaryDirectory() { var path = Path.Combine(GetTempBasePath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(path); return path; } public void CreateDirectory(string directory) { Directory.CreateDirectory(directory); } public void PurgeDirectory(string targetDirectory, FailureOptions options) { PurgeDirectory(targetDirectory, fi => false, options); } public void PurgeDirectory(string targetDirectory, FailureOptions options, CancellationToken cancel) { PurgeDirectory(targetDirectory, fi => false, options, cancel); } public void PurgeDirectory(string targetDirectory, Predicate<FileSystemInfo> exclude, FailureOptions options) { PurgeDirectory(targetDirectory, exclude, options, CancellationToken.None); } public void PurgeDirectory(string targetDirectory, FailureOptions options, GlobMode globMode, params string[] globs) { Predicate<FileSystemInfo>? check = null; if (globs.Any()) { var keep = EnumerateWithGlob(targetDirectory, globMode, globs); check = fsi => { return keep.Any(k => k is DirectoryInfo && fsi.FullName.IsChildOf(k.FullName) || k.FullName == fsi.FullName); }; } PurgeDirectory(targetDirectory, check, options, CancellationToken.None); } void PurgeDirectory(string targetDirectory, Predicate<FileSystemInfo>? exclude, FailureOptions options, CancellationToken cancel, bool includeTarget = false, RetryTracker? retry = null) { exclude ??= (fi => false); if (!DirectoryExists(targetDirectory)) return; retry ??= GetFileOperationRetryTracker(); foreach (var file in EnumerateFiles(targetDirectory)) { cancel.ThrowIfCancellationRequested(); var includeInfo = new FileInfo(file); if (exclude(includeInfo)) continue; DeleteFile(file, options, retry, cancel); } foreach (var directory in EnumerateDirectories(targetDirectory)) { cancel.ThrowIfCancellationRequested(); var info = new DirectoryInfo(directory); if (exclude(info)) continue; if ((info.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) Directory.Delete(directory, false); else PurgeDirectory(directory, exclude, options, cancel, true, retry); } if (includeTarget && DirectoryIsEmpty(targetDirectory)) DeleteDirectory(targetDirectory, options); } public void OverwriteAndDelete(string originalFile, string temporaryReplacement) { var backup = originalFile + ".backup" + Guid.NewGuid(); try { if (!File.Exists(originalFile)) File.Copy(temporaryReplacement, originalFile, true); else System.IO.File.Replace(temporaryReplacement, originalFile, backup); } catch (UnauthorizedAccessException unauthorizedAccessException) { Log.VerboseFormat("Error attempting to copy or replace {0} with {1} Exception: {2}", originalFile, temporaryReplacement, unauthorizedAccessException.StackTrace); void LogFileAccess(string filePath) { try { Log.VerboseFormat("Attempting to access with OpenOrCreate file mode, Read/Write Access and No file share {0}", filePath); using (File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); Log.VerboseFormat("Succeeded accessing {0}", filePath); } catch (Exception fileAccessException) { Log.VerboseFormat("Failed to access filePath: {0}, Exception: {1}", filePath, fileAccessException.ToString()); } } LogFileAccess(originalFile); LogFileAccess(temporaryReplacement); LogFileAccess(backup); throw unauthorizedAccessException; } File.Delete(temporaryReplacement); if (File.Exists(backup)) File.Delete(backup); } // File.WriteAllBytes won't overwrite a hidden file, so implement our own. public void WriteAllBytes(string path, byte[] bytes) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length <= 0) throw new ArgumentException(path); // FileMode.Open causes an existing file to be truncated to the // length of our new data, but can't overwrite a hidden file, // so use FileMode.OpenOrCreate and set the new file length manually. using (var fs = new FileStream(path, FileMode.OpenOrCreate)) { fs.Write(bytes, 0, bytes.Length); fs.Flush(); fs.SetLength(fs.Position); } } public string RemoveInvalidFileNameChars(string path) { if (string.IsNullOrEmpty(path)) return path; var invalidPathChars = Path.GetInvalidPathChars(); var invalidFileChars = Path.GetInvalidFileNameChars(); var result = new StringBuilder(path.Length); for (var i = 0; i < path.Length; i++) { var c = path[i]; if (!invalidPathChars.Contains(c) && !invalidFileChars.Contains(c)) result.Append(c); } return result.ToString(); } public void MoveFile(string sourceFile, string destinationFile) { RetryTrackerFileAction(() => File.Move(sourceFile, destinationFile), destinationFile, "move"); } public void EnsureDirectoryExists(string directoryPath) { if (!DirectoryExists(directoryPath)) Directory.CreateDirectory(directoryPath); } // ReSharper disable AssignNullToNotNullAttribute public int CopyDirectory(string sourceDirectory, string targetDirectory) { return CopyDirectory(sourceDirectory, targetDirectory, CancellationToken.None); } public int CopyDirectory(string sourceDirectory, string targetDirectory, CancellationToken cancel) { if (!DirectoryExists(sourceDirectory)) return 0; if (!DirectoryExists(targetDirectory)) Directory.CreateDirectory(targetDirectory); var count = 0; var files = Directory.GetFiles(sourceDirectory, "*"); foreach (var sourceFile in files) { cancel.ThrowIfCancellationRequested(); var targetFile = Path.Combine(targetDirectory, Path.GetFileName(sourceFile)); CopyFile(sourceFile, targetFile); count++; } foreach (var childSourceDirectory in Directory.GetDirectories(sourceDirectory)) { var name = Path.GetFileName(childSourceDirectory); var childTargetDirectory = Path.Combine(targetDirectory, name); count += CopyDirectory(childSourceDirectory, childTargetDirectory, cancel); } return count; } public void CopyFile(string sourceFile, string targetFile) { RetryTrackerFileAction(() => File.Copy(sourceFile, targetFile, true), targetFile, "copy"); } static void RetryTrackerFileAction(Action fileAction, string target, string action) { var retry = GetFileOperationRetryTracker(); while (retry.Try()) try { fileAction(); return; } catch (Exception ex) { if (retry.CanRetry()) { if (retry.ShouldLogWarning()) Log.VerboseFormat("Retry #{0} on {1} '{2}'. Exception: {3}", retry.CurrentTry, action, target, ex.Message); Thread.Sleep(retry.Sleep()); } else { throw; } } } public string GetFullPath(string relativeOrAbsoluteFilePath) { if (!Path.IsPathRooted(relativeOrAbsoluteFilePath)) relativeOrAbsoluteFilePath = Path.Combine(Directory.GetCurrentDirectory(), relativeOrAbsoluteFilePath); relativeOrAbsoluteFilePath = Path.GetFullPath(relativeOrAbsoluteFilePath); return relativeOrAbsoluteFilePath; } public abstract bool GetDiskFreeSpace(string directoryPath, out ulong totalNumberOfFreeBytes); public abstract bool GetDiskTotalSpace(string directoryPath, out ulong totalNumberOfBytes); public string GetRelativePath(string fromFile, string toFile) { var fromPathTokens = fromFile.Split(Path.DirectorySeparatorChar); var toPathTokens = toFile.Split(Path.DirectorySeparatorChar); var matchingTokens = 0; for (; matchingTokens < fromPathTokens.Count() - 1; matchingTokens++) if (!fromPathTokens[matchingTokens].Equals(toPathTokens[matchingTokens], StringComparison.Ordinal)) break; var relativePath = new StringBuilder(); for (var i = matchingTokens; i < fromPathTokens.Length - 1; i++) relativePath.Append("..").Append(Path.DirectorySeparatorChar); for (var i = matchingTokens; i < toPathTokens.Length; i++) { relativePath.Append(toPathTokens[i]); if (i != toPathTokens.Length - 1) relativePath.Append(Path.DirectorySeparatorChar); } return relativePath.ToString(); } public DateTime GetCreationTime(string filePath) { return File.GetCreationTime(filePath); } public string GetFileName(string filePath) { return new FileInfo(filePath).Name; } public string GetDirectoryName(string directoryPath) { return new DirectoryInfo(directoryPath).Name; } public Stream OpenFileExclusively(string filePath, FileMode fileMode, FileAccess fileAccess) { return File.Open(filePath, fileMode, fileAccess, FileShare.None); } } } <file_sep>using System; using System.Collections.Generic; using Calamari.Commands; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.Scripting { [Command("run-script", Description = "Invokes a script")] public class RunScriptCommand : PipelineCommand { protected override bool IncludeConfiguredScriptBehaviour => false; protected override bool IncludePackagedScriptBehaviour => false; protected override IEnumerable<IBeforePackageExtractionBehaviour> BeforePackageExtraction(BeforePackageExtractionResolver resolver) { yield return resolver.Create<WriteVariablesToFileBehaviour>(); } protected override IEnumerable<IAfterPackageExtractionBehaviour> AfterPackageExtraction(AfterPackageExtractionResolver resolver) { yield return resolver.Create<StageScriptPackagesBehaviour>(); } protected override IEnumerable<IPreDeployBehaviour> PreDeploy(PreDeployResolver resolver) { yield return resolver.Create<SubstituteScriptSourceBehaviour>(); } protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<ExecuteScriptBehaviour>(); } protected override IEnumerable<IOnFinishBehaviour> OnFinish(OnFinishResolver resolver) { yield return resolver.Create<AddJournalEntryBehaviour>(); yield return resolver.Create<ThrowScriptErrorIfNeededBehaviour>(); } } }<file_sep>using Calamari.Common.Plumbing.Extensions; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace Calamari.Testing.Requirements { public class RequiresPowerShell5OrLowerAttribute : NUnitAttribute, IApplyToTest { public void ApplyToTest(Test test) { if (ScriptingEnvironment.SafelyGetPowerShellVersion().Major > 5) { test.RunState = RunState.Skipped; test.Properties.Set(PropertyNames.SkipReason, "This test requires PowerShell 5 or older."); } } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; namespace Calamari.Common.Features.FunctionScriptContributions { class FunctionAppenderScriptWrapper: IScriptWrapper { readonly IVariables variables; readonly ICalamariFileSystem fileSystem; readonly CodeGenFunctionsRegistry codeGenFunctionsRegistry; public FunctionAppenderScriptWrapper(IVariables variables, ICalamariFileSystem fileSystem, CodeGenFunctionsRegistry codeGenFunctionsRegistry) { this.variables = variables; this.fileSystem = fileSystem; this.codeGenFunctionsRegistry = codeGenFunctionsRegistry; } public int Priority { get; } = ScriptWrapperPriorities.ToolConfigPriority; public IScriptWrapper? NextWrapper { get; set; } public bool IsEnabled(ScriptSyntax syntax) { if (String.IsNullOrEmpty(variables.Get(ScriptFunctionsVariables.Registration))) { return false; } return codeGenFunctionsRegistry.SupportedScriptSyntax.Contains(syntax); } public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars) { if (NextWrapper == null) throw new InvalidOperationException("NextWrapper has not been set."); var workingDirectory = Path.GetDirectoryName(script.File); if (workingDirectory == null) throw new InvalidOperationException("Working directory has not been set correctly."); variables.Set("OctopusFunctionAppenderTargetScript", $"{script.File}"); variables.Set("OctopusFunctionAppenderTargetScriptParameters", script.Parameters); var copyScriptFile = variables.Get(ScriptFunctionsVariables.CopyScriptWrapper); var scriptFile = CreateContextScriptFile(workingDirectory, scriptSyntax); if (!String.IsNullOrEmpty(copyScriptFile)) { var destinationFile = copyScriptFile; if (!Path.IsPathRooted(copyScriptFile)) { destinationFile = Path.Combine(workingDirectory, copyScriptFile); } File.Copy(scriptFile, destinationFile, true); } using (var contextScriptFile = new TemporaryFile(scriptFile)) { return NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars); } } string CreateContextScriptFile(string workingDirectory, ScriptSyntax scriptSyntax) { var registrations = variables.Get(ScriptFunctionsVariables.Registration); var results = JsonConvert.DeserializeObject<IList<ScriptFunctionRegistration>>(registrations); var azureContextScriptFile = Path.Combine(workingDirectory, $"Octopus.FunctionAppenderContext.{scriptSyntax.FileExtension()}"); var contextScript = codeGenFunctionsRegistry.GetCodeGenerator(scriptSyntax).Generate(results); fileSystem.OverwriteFile(azureContextScriptFile, contextScript); return azureContextScriptFile; } } }<file_sep>using System.IO; using Assent; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { public class DeployPackageWithStructuredConfigurationFixture : DeployPackageFixture { const string ServiceName = "Acme.StructuredConfigFiles"; const string ServiceVersion = "1.0.0"; const string YamlFileName = "values.yaml"; const string JsonFileName = "values.json"; const string XmlFileName = "values.xml"; const string JsonFileNameWithAnXmlExtension = "json.xml"; const string ConfigFileName = "values.config"; const string PropertiesFileName = "config.properties"; const string MalformedFileName = "malformed.json"; const string XmlFileNameWithNonXmlExtension = "xml.config"; const string XmlFileNameWithJsonExtension = "xml.json"; const string YamlFileNameWithNonYamlExtension = "yaml.config"; const string PropertiesFileNameWithNonPropertiesExtension = "properties.config"; const string PropertiesFileNameWithYamlExtension = "properties.yaml"; const string YamlFileNameWithXmlExtension = "yaml.xml"; [SetUp] public override void SetUp() { base.SetUp(); } [Test] public void FailsAndWarnsIfAFileCannotBeParsedWhenFallbackFlagIsSet() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.AddFlag(ActionVariables.StructuredConfigurationFallbackFlag, true); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, MalformedFileName); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertFailure(); result.AssertErrorOutput("The file could not be parsed as Json"); } } [Test] public void ShouldNotTreatYamlFileAsYamlWhenFallbackFlagIsSet() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.AddFlag(ActionVariables.StructuredConfigurationFallbackFlag, true); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, YamlFileName); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertFailure(); // Indicates we tried to parse yaml as JSON. result.AssertErrorOutput("The file could not be parsed as Json"); } } [Test] public void ShouldPerformReplacementInYaml() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, YamlFileName); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedYamlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, YamlFileName)); this.Assent(extractedPackageUpdatedYamlFile, AssentConfiguration.Yaml); } } [Test] public void ShouldPerformReplacementInXml() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, XmlFileName); Variables.Set("/document/key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedXmlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, XmlFileName)); this.Assent(extractedPackageUpdatedXmlFile, AssentConfiguration.Xml); } } [Test] public void IfThereAreDuplicateNsPrefixesTheFirstOneIsUsedAndAWarningIsLogged() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, "duplicate-prefixes.xml"); Variables.Set("//parent/dupe:node", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutputMatches("You can avoid this by ensuring all namespaces in your document have unique prefixes\\."); var extractedPackageUpdatedXmlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, "duplicate-prefixes.xml")); this.Assent(extractedPackageUpdatedXmlFile, AssentConfiguration.Xml); } } [Test] public void LogsAWarningIfAVariableTreatedAsMarkupIsInvalid() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, "values.xml"); Variables.Set("/document", "<<<"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutputContains("Could not set the value of the XML element at XPath '/document' to '<<<'. Expected a valid XML fragment. Skipping replacement of this element."); var extractedPackageUpdatedXmlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, "values.xml")); this.Assent(extractedPackageUpdatedXmlFile, AssentConfiguration.Xml); } } [Test] public void ShouldPerformReplacementInProperties() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, PropertiesFileName); Variables.Set("debug", "false"); Variables.Set("port", "80"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedPropertiesFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, PropertiesFileName)); this.Assent(extractedPackageUpdatedPropertiesFile, AssentConfiguration.Properties); } } [Test] public void JsonShouldBeTriedBeforeOtherFormatsWhenGuessingTheBestFormat() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, YamlFileName); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutput("The file will be tried as Json first for backwards compatibility"); result.AssertOutputMatches("Structured variable replacement succeeded on file .+? with format Yaml"); } } [Test] public void SucceedsButWarnsIfNoFilesMatchTarget() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, "doesnt-exist.json"); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutputContains("No files were found that match the replacement target pattern 'doesnt-exist.json'"); } } [Test] public void CanPerformReplacementOnMultipleTargetFiles() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, $"{JsonFileName}\n{YamlFileName}"); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedJsonFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, JsonFileName)); var extractedPackageUpdatedYamlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, YamlFileName)); this.Assent(extractedPackageUpdatedJsonFile, AssentConfiguration.Json); this.Assent(extractedPackageUpdatedYamlFile, AssentConfiguration.Yaml); } } [Test] public void CanPerformReplacementOnAGlobThatMatchesFilesInDifferentFormats() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, "values.*"); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedJsonFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, JsonFileName)); var extractedPackageUpdatedYamlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, YamlFileName)); var extractedPackageUpdatedConfigFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, ConfigFileName)); this.Assent(extractedPackageUpdatedJsonFile, AssentConfiguration.Json); this.Assent(extractedPackageUpdatedYamlFile, AssentConfiguration.Yaml); this.Assent(extractedPackageUpdatedConfigFile, AssentConfiguration.Json); } } [Test] public void FailsIfAnyFileMatchingAGlobFailsToParse() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, "*.json"); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertFailure(); result.AssertErrorOutput("The file could not be parsed as Json"); } } [Test] public void FailsIfAFileFailsToParseWhenThereAreMultipleTargetFiles() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, $"{JsonFileName}\n{MalformedFileName}"); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertFailure(); result.AssertErrorOutput("The file could not be parsed as Json"); } } [Test] public void SucceedsButWarnsIfTargetIsADirectory() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, "."); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutputContains("Skipping structured variable replacement on '.' because it is a directory."); var unchangedJsonFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, JsonFileName)); var unchangedYamlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, YamlFileName)); this.Assent(unchangedJsonFile, AssentConfiguration.Json); this.Assent(unchangedYamlFile, AssentConfiguration.Yaml); } } [Test] public void FailsAndWarnsIfAFileCannotBeParsed() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, MalformedFileName); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertFailure(); result.AssertErrorOutput("The file could not be parsed as Json"); } } [Test] public void ShouldPerformReplacementInJsonFileWithANonJsonExtension() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, ConfigFileName); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedConfigFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, ConfigFileName)); this.Assent(extractedPackageUpdatedConfigFile, AssentConfiguration.Json); } } [Test] public void ShouldPerformReplacementInXmlFileWithANonXmlExtension() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, XmlFileNameWithNonXmlExtension); Variables.Set("/document/key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedXmlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, XmlFileNameWithNonXmlExtension)); result.AssertOutput("The file will be tried as multiple formats and will be treated as the first format that can be successfully parsed"); result.AssertOutput("couldn't be parsed as Json"); this.Assent(extractedPackageUpdatedXmlFile, AssentConfiguration.Xml); } } [Test] public void ShouldPerformReplacementInYamlFileWithANonYamlExtension() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, YamlFileNameWithNonYamlExtension); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedYamlFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, YamlFileNameWithNonYamlExtension)); result.AssertOutput("The file will be tried as multiple formats and will be treated as the first format that can be successfully parsed"); result.AssertOutput("couldn't be parsed as Json"); result.AssertOutput("couldn't be parsed as Xml"); this.Assent(extractedPackageUpdatedYamlFile, AssentConfiguration.Yaml); } } [Test] public void ShouldPerformReplacementInPropertiesFileWithANonPropertiesExtension() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, PropertiesFileNameWithNonPropertiesExtension); Variables.Set("debug", "false"); Variables.Set("port", "80"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedPropertiesFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, PropertiesFileNameWithNonPropertiesExtension)); result.AssertOutput("The file will be tried as multiple formats and will be treated as the first format that can be successfully parsed"); result.AssertOutput("couldn't be parsed as Json"); result.AssertOutput("couldn't be parsed as Xml"); result.AssertOutput("couldn't be parsed as Yaml"); this.Assent(extractedPackageUpdatedPropertiesFile, AssentConfiguration.Properties); } } [Test] public void FailsAndWarnsIfFileWithAnXmlExtensionContainsValidNonXmlContent() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, YamlFileNameWithXmlExtension); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertFailure(); result.AssertErrorOutput("The file could not be parsed as Xml"); } } [Test] public void FailsAndWarnsIfFileWithAYamlExtensionContainsValidNonYamlContent() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); // The content of this file can't be JSON (because JSON is a special case) // It also can't be XML because XML is valid yaml // We are left with making it a properties file that also happens to be invalid yaml Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, PropertiesFileNameWithYamlExtension); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertFailure(); result.AssertErrorOutput("The file could not be parsed as Yaml"); } } [Test] public void FailsAndWarnsIfFileWithAJsonExtensionContainsValidNonJsonContent() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, XmlFileNameWithJsonExtension); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertFailure(); result.AssertErrorOutput("The file could not be parsed as Json"); } } // This test case demonstrates that even though we usually try to determine file types // using file extensions first, Json is still a special case which takes precedence [Test] public void ShouldPerformReplacementInJsonFileWithFileExtForOtherSupportedConfigFormat() { using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(ServiceName, ServiceVersion))) { Variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables); Variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, JsonFileNameWithAnXmlExtension); Variables.Set("key", "new-value"); var result = DeployPackage(file.FilePath); result.AssertSuccess(); var extractedPackageUpdatedConfigFile = File.ReadAllText(Path.Combine(StagingDirectory, ServiceName, ServiceVersion, JsonFileNameWithAnXmlExtension)); this.Assent(extractedPackageUpdatedConfigFile, AssentConfiguration.Json); } } [TearDown] public override void CleanUp() { base.CleanUp(); } } }<file_sep>using System.Linq; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class Pod : Resource { public string Ready { get; } public int Restarts { get; } public string Status { get; } public Pod(JObject json, Options options) : base(json, options) { var phase = Field("$.status.phase"); var initContainerStatuses = data .SelectToken("$.status.initContainerStatuses") ?.ToObject<ContainerStatus[]>() ?? new ContainerStatus[] { }; var containerStatuses = data .SelectToken("$.status.containerStatuses") ?.ToObject<ContainerStatus[]>() ?? new ContainerStatus[] { }; var ready = data .SelectToken("$.status.conditions[?(@.type == 'Ready')].status") ?.Value<string>() ?? string.Empty; Status = GetStatus(phase, initContainerStatuses, containerStatuses); switch (phase) { case "Failed": case "Unknown": ResourceStatus = ResourceStatus.Failed; break; case "Succeeded": ResourceStatus = ResourceStatus.Successful; break; case "Pending": ResourceStatus = ResourceStatus.InProgress; break; default: ResourceStatus = ready == "True" ? ResourceStatus.Successful : ResourceStatus.InProgress; break; } var containers = containerStatuses.Length; var readyContainers = containerStatuses.Count(status => status.Ready); Ready = $"{readyContainers}/{containers}"; Restarts = containerStatuses.Select(status => status.RestartCount).Sum(); } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<Pod>(lastStatus); return last.ResourceStatus != ResourceStatus || last.Status != Status; } private static string GetStatus( string phase, ContainerStatus[] initContainerStatuses, ContainerStatus[] containerStatuses) { switch (phase) { case "Pending": if (!initContainerStatuses.Any() && !containerStatuses.Any()) { return "Pending"; } return initContainerStatuses.All(HasCompleted) ? GetStatus(containerStatuses) : GetInitializingStatus(initContainerStatuses); case "Failed": case "Succeeded": return GetReason(containerStatuses.FirstOrDefault()); default: return GetStatus(containerStatuses); } } private static string GetInitializingStatus(ContainerStatus[] initContainerStatuses) { var erroredContainer = initContainerStatuses.FirstOrDefault(HasError); if (erroredContainer != null) { return $"Init:{GetReason(erroredContainer)}"; } var totalInit = initContainerStatuses.Length; var readyInit = initContainerStatuses.Where(HasCompleted).Count(); return $"Init:{readyInit}/{totalInit}"; } private static string GetStatus(ContainerStatus[] containerStatuses) { var erroredContainer = containerStatuses.FirstOrDefault(HasError); if (erroredContainer != null) { return GetReason(erroredContainer); } var containerWithReason = containerStatuses.FirstOrDefault(HasReason); if (containerWithReason != null) { return GetReason(containerWithReason); } return "Running"; } private static string GetReason(ContainerStatus status) { // In real scenario this shouldn't happen, but we give it a default value just in case if (status == null) { return string.Empty; } if (status.State.Terminated != null) { return status.State.Terminated.Reason; } if (status.State.Waiting != null) { return status.State.Waiting.Reason; } return "Pending"; } private static bool HasError(ContainerStatus status) { if (status.State.Terminated != null) { return status.State.Terminated.Reason != "Completed"; } if (status.State.Waiting != null) { return status.State.Waiting.Reason != "PodInitializing" && status.State.Waiting.Reason != "ContainerCreating"; } return false; } private static bool HasReason(ContainerStatus status) { return status.State.Terminated != null || status.State.Waiting != null; } private static bool HasCompleted(ContainerStatus status) { return status.State.Terminated != null && status.State.Terminated.Reason == "Completed"; } } }<file_sep>using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Integration.Proxies; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.FSharp { [TestFixture] [Category(TestCategory.ScriptingSupport.FSharp)] public class FSharpProxyFixture : WindowsScriptProxyFixtureBase { protected override CalamariResult RunScript() { return RunScript("Proxy.fsx").result; } protected override bool TestWebRequestDefaultProxy => true; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Extensions; namespace Calamari.Common.Features.Processes { public class CommandLineInvocation { string? workingDirectory; public CommandLineInvocation(string executable, params string[] arguments) { Executable = executable; Arguments = arguments.Where(a => !string.IsNullOrWhiteSpace(a)).Join(" "); } public string Executable { get; } public string Arguments { get; } public string? UserName { get; set; } public SecureString? Password { get; set; } public Dictionary<string, string>? EnvironmentVars { get; set; } /// <summary> /// Prevent this execution from starting if another execution is running that also has this set to true. /// It does not isolate from executions that have this set to false. /// </summary> public bool Isolate { get; set; } /// <summary> /// Whether to output the execution output to the Calamari Log (i.e. it will be send back to Octopus) /// </summary> public bool OutputToLog { get; set; } = true; /// <summary> /// Start the logging as verbose. The executed command may change logging level itself via service messages. /// </summary> public bool OutputAsVerbose { get; set; } /// <summary> /// Add a non-standard output destination for the execution output /// </summary> public ICommandInvocationOutputSink? AdditionalInvocationOutputSink { get; set; } /// <summary> /// The initial working-directory for the invocation. /// Defaults to Environment.CurrentDirectory /// </summary> public string WorkingDirectory { get => workingDirectory ?? Environment.CurrentDirectory; set => workingDirectory = value; } public override string ToString() { return "\"" + Executable + "\" " + Arguments; } } }<file_sep>namespace Calamari.Kubernetes.ResourceStatus.Resources { public enum ResourceStatus { InProgress, Successful, Failed } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Testing.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.FileSystem { [TestFixture] public class CalamariPhysicalFileSystemFixture { static readonly string PurgeTestDirectory = TestEnvironment.GetTestPath("PurgeTestDirectory"); private CalamariPhysicalFileSystem fileSystem; private string rootPath; [SetUp] public void SetUp() { if (Directory.Exists(PurgeTestDirectory)) Directory.Delete(PurgeTestDirectory, true); fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); rootPath = Path.GetTempFileName(); File.Delete(rootPath); Directory.CreateDirectory(rootPath); } [TearDown] public void TearDown() { Directory.Delete(rootPath, true); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void WindowsUsesWindowsFileSystem() { var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); Assert.IsInstanceOf<WindowsPhysicalFileSystem>(fileSystem); } [Test] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public void NonWindowsUsesWindowsFileSystem() { var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); Assert.IsInstanceOf<NixCalamariPhysicalFileSystem>(fileSystem); } [Test] public void PurgeWithNoExcludeRemovesAll() { CreateFile("ImportantFile.txt"); CreateFile("MyDirectory", "SubDirectory", "WhoCaresFile.txt"); CollectionAssert.IsNotEmpty(Directory.EnumerateFileSystemEntries(PurgeTestDirectory).ToList(), "Expected all files to have been set up"); var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); fileSystem.PurgeDirectory(PurgeTestDirectory, FailureOptions.IgnoreFailure); CollectionAssert.IsEmpty(Directory.EnumerateFileSystemEntries(PurgeTestDirectory).ToList(), "Expected all items to be removed"); } [Test] public void PurgeCanExcludeFile() { var importantFile = CreateFile("ImportantFile.txt"); var purgableFile = CreateFile("WhoCaresFile.txt"); var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); fileSystem.PurgeDirectory(PurgeTestDirectory, (fsi) => fsi.Name.StartsWith("Important"), FailureOptions.IgnoreFailure); Assert.IsTrue(File.Exists(importantFile), $"Expected file `{importantFile}` to be preserved."); Assert.IsFalse(File.Exists(purgableFile), $"Expected file `{purgableFile}` to be removed."); } [Test] [TestCase("ImportantFolder", "WhoCaresFile", Description = "Purgable file in important folder should be kept", ExpectedResult = true)] [TestCase("ImportantFolder", "ImportantFile", Description = "Purgable file in important folder should still be kept", ExpectedResult = true)] [TestCase("WhoCaresFolder", "WhoCaresFile", Description = "Important file in purgable folder should still be removed", ExpectedResult = false)] [TestCase("WhoCaresFolder", "ImportantFile", Description = "Purgable file in purgable folder should be removed", ExpectedResult = false)] public bool PurgeDirectoryWithFolderExclusionWillNotCheckSubFiles(string folderName, string fileName) { var testFile = CreateFile(folderName, fileName); var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); fileSystem.PurgeDirectory(PurgeTestDirectory, (fsi) => fsi.Attributes.HasFlag(FileAttributes.Directory) && fsi.Name.StartsWith("Important"), FailureOptions.IgnoreFailure); return File.Exists(testFile); } [Test] [TestCase("SimilarFolder", "WhoCaresFile", "Similar*", Description = "Different file in Similar folder should be kept", ExpectedResult = true)] [TestCase("SimilarFolder", "SimilarFile", "Similar*", Description = "Similar file in Similar folder should still be kept", ExpectedResult = true)] [TestCase("WhoCaresFolder", "WhoCaresFile", "Similar*", Description = "Similar file in purgable folder should still be removed", ExpectedResult = false)] [TestCase("WhoCaresFolder", "SimilarFile", "Similar*", Description = "Similar file in purgable folder should be removed", ExpectedResult = false)] [TestCase("WhoCaresFolder", "WhoCaresFile", "**/Similar*", Description = "Different file in different folder should be removed", ExpectedResult = false)] [TestCase("WhoCaresFolder", "SimilarFile", "**/Similar*", Description = "Similar file in different folder should be kept", ExpectedResult = true)] [TestCase("ExactFolder", "WhoCaresFile", "ExactFolder", Description = "Different file in exact folder should be kept", ExpectedResult = true)] public bool PurgeDirectoryWithFolderUsingGlobs(string folderName, string fileName, string glob) { var testFile = CreateFile(folderName, fileName); var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem(); fileSystem.PurgeDirectory(PurgeTestDirectory, FailureOptions.IgnoreFailure, GlobMode.GroupExpansionMode, glob); return File.Exists(testFile); } string CreateFile(params string[] relativePath) { var filename = Path.Combine(PurgeTestDirectory, Path.Combine(relativePath)); var directory = Path.GetDirectoryName(filename); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); File.WriteAllBytes(filename, new byte[] { 0 }); return filename; } [Test] [TestCase(@"**/*.txt", "f1.txt", 2)] [TestCase(@"**/*.txt", "r.txt", 2)] [TestCase(@"*.txt", "r.txt")] [TestCase(@"**/*.config", "root.config", 6)] [TestCase(@"*.config", "root.config")] [TestCase(@"Config/*.config", "c.config")] [TestCase(@"Config/Feature1/*.config", "f1-a.config", 3)] [TestCase(@"Config/Feature1/*.config", "f1-b.config", 3)] [TestCase(@"Config/Feature1/*.config", "f1-c.config", 3)] [TestCase(@"Config/Feature2/*.config", "f2.config")] [TestCase(@"Config/Feature1/*-{a,b}.config", "f1-a.config", 2, 2)] [TestCase(@"Config/Feature1/*-{a,b}.config", "f1-b.config", 2, 2)] [TestCase(@"Config/Feature1/f1-{a,b}.config", "f1-a.config", 2, 0)] [TestCase(@"Config/Feature1/f1-{a,b}.config", "f1-b.config", 2, 0)] [TestCase(@"Config/Feature{1,2}/f{1,2}.{config,txt}", "f1.txt", 2, 0)] [TestCase(@"Config/Feature{1,2}/f{1,2}.{config,txt}", "f2.config", 2, 0)] [TestCase(@"Config/Feature1/*-[ab].config", "f1-a.config", 2, 0)] [TestCase(@"Config/Feature1/*-[ab].config", "f1-b.config", 2, 0)] [TestCase(@"Config/Feature1/f1-[ab].config", "f1-a.config", 2, 0)] [TestCase(@"Config/Feature1/f1-[ab].config", "f1-b.config", 2, 0)] [TestCase(@"Config/Feature[12]/f[12].{config,txt}", "f1.txt", 2, 0)] [TestCase(@"Config/Feature[12]/f[12].{config,txt}", "f2.config", 2, 0)] [TestCase(@"Config/Feature1/f1-[a-c].{config,txt}", "f1-b.config", 3, 0)] public void EnumerateFilesWithGlob(string pattern, string expectedFileMatchName, int expectedQty = 1, int? expectedQtyWithNoGrouping = null) { expectedQtyWithNoGrouping = expectedQtyWithNoGrouping ?? expectedQty; var content = "file-content" + Environment.NewLine; var configPath = Path.Combine(rootPath, "Config"); Directory.CreateDirectory(configPath); Directory.CreateDirectory(Path.Combine(configPath, "Feature1")); Directory.CreateDirectory(Path.Combine(configPath, "Feature2")); Action<string, string, string> writeFile = (p1, p2, p3) => fileSystem.OverwriteFile(p3 == null ? Path.Combine(p1, p2) : Path.Combine(p1, p2, p3), content); // NOTE: create all the files in *every case*, and TestCases help supply the assert expectations writeFile(rootPath, "root.config", null); writeFile(rootPath, "r.txt", null); writeFile(configPath, "c.config", null); writeFile(configPath, "Feature1", "f1.txt"); writeFile(configPath, "Feature1", "f1-a.config"); writeFile(configPath, "Feature1", "f1-b.config"); writeFile(configPath, "Feature1", "f1-c.config"); writeFile(configPath, "Feature2", "f2.config"); var result = fileSystem.EnumerateFilesWithGlob(rootPath, GlobMode.GroupExpansionMode, pattern).ToList(); var resultNoGrouping = fileSystem.EnumerateFilesWithGlob(rootPath, GlobMode.LegacyMode, pattern).ToList(); resultNoGrouping.Should() .HaveCount(expectedQtyWithNoGrouping.Value, $"{pattern} should have found {expectedQtyWithNoGrouping}, but found {result.Count}"); result.Should() .HaveCount(expectedQty, $"{pattern} should have found {expectedQty}, but found {result.Count}"); result.Should() .Contain(r => Path.GetFileName(r) == expectedFileMatchName, $"{pattern} should have found {expectedFileMatchName}, but didn't"); } [TestCase(@"*")] [TestCase(@"**")] [TestCase(@"**/*")] [TestCase(@"Dir/*")] [TestCase(@"Dir/**")] [TestCase(@"Dir/**/*")] public void EnumerateFilesWithGlobShouldNotReturnDirectories(string pattern) { Directory.CreateDirectory(Path.Combine(rootPath, "Dir")); Directory.CreateDirectory(Path.Combine(rootPath, "Dir", "Sub")); File.WriteAllText(Path.Combine(rootPath, "Dir", "File"), ""); File.WriteAllText(Path.Combine(rootPath, "Dir", "Sub", "File"), ""); var results = fileSystem.EnumerateFilesWithGlob(rootPath, GlobMode.GroupExpansionMode, pattern).ToArray(); if (results.Length > 0) results.Should().OnlyContain(f => f.EndsWith("File")); } [Test] public void EnumerateFilesWithGlobShouldNotReturnTheSameFileTwice() { File.WriteAllText(Path.Combine(rootPath, "File"), ""); var results = fileSystem.EnumerateFilesWithGlob(rootPath, GlobMode.GroupExpansionMode, "*", "**").ToList(); results.Should().HaveCount(1); } [TestCase(@"[Configuration]", @"[Configuration]\\*.txt")] [TestCase(@"Configuration]", @"Configuration]\\*.txt")] [TestCase(@"[Configuration", @"[Configuration\\*.txt")] [TestCase(@"{Configuration}", @"{Configuration}\\*.txt")] [TestCase(@"Configuration}", @"Configuration}\\*.txt")] [TestCase(@"{Configuration", @"{Configuration\\*.txt")] public void EnumerateFilesWithGlobShouldIgnoreGroups(string directory, string glob) { if (!CalamariEnvironment.IsRunningOnWindows) glob = glob.Replace("\\", "/"); Directory.CreateDirectory(Path.Combine(rootPath, directory)); File.WriteAllText(Path.Combine(rootPath, directory, "Foo.txt"), ""); var results = fileSystem.EnumerateFilesWithGlob(rootPath, GlobMode.GroupExpansionMode, glob).ToList(); var resultsWithNoGrouping = fileSystem.EnumerateFilesWithGlob(rootPath, GlobMode.LegacyMode, glob).ToList(); results.Should().ContainSingle(); resultsWithNoGrouping.Should().ContainSingle(); } [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void LongFilePathsShouldWork() { var paths = new Stack<string>(); var path = rootPath; for (var i = 0; i <= 15; i++) { path += @"\ZZZZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; fileSystem.EnsureDirectoryExists(path); paths.Push(path); } fileSystem.OverwriteFile("Some sample text", path + @"\test.txt"); fileSystem.DeleteFile(path + @"\test.txt"); while (paths.Any()) { var pathToRemove = paths.Pop(); fileSystem.DeleteDirectory(pathToRemove); } } [Test] public void WriteAllTextShouldOverwriteHiddenFileContent() { var path = Path.GetTempFileName(); File.WriteAllText(path, "hi there"); File.SetAttributes(path, FileAttributes.Hidden); fileSystem.WriteAllText(path, "hi"); Assert.AreEqual("hi", File.ReadAllText(path)); Assert.AreNotEqual(0, File.GetAttributes(path) & FileAttributes.Hidden); } [Test] public void WriteAllBytesShouldOverwriteHiddenFile() { var path = Path.GetTempFileName(); File.WriteAllText(path, "hi there"); File.SetAttributes(path, FileAttributes.Hidden); fileSystem.WriteAllBytes(path, Encoding.ASCII.GetBytes("hi")); Assert.AreEqual("hi", File.ReadAllText(path)); Assert.AreNotEqual(0, File.GetAttributes(path) & FileAttributes.Hidden); } } } <file_sep>createartifact("/home/file.txt") <file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using Serilog; namespace Calamari.ConsolidateCalamariPackages { class CalamariPackageReference : IPackageReference { private readonly Hasher hasher; public string Name { get; } public string Version { get; } public string PackagePath { get; } public CalamariPackageReference(Hasher hasher, BuildPackageReference packageReference) { this.hasher = hasher; Name = packageReference.Name; Version = packageReference.Version; PackagePath = packageReference.PackagePath; } public IReadOnlyList<SourceFile> GetSourceFiles(ILogger log) { var isNetFx = Name == "Calamari"; var isCloud = Name == "Calamari.Cloud"; var platform = isNetFx || isCloud ? "netfx" : Name.Split('.')[1]; if (!File.Exists(PackagePath)) throw new Exception($"Could not find the source NuGet package {PackagePath} does not exist"); using (var zip = ZipFile.OpenRead(PackagePath)) return zip.Entries .Where(e => !string.IsNullOrEmpty(e.Name)) .Where(e => e.FullName != "[Content_Types].xml") .Where(e => !e.FullName.StartsWith("_rels")) .Where(e => !e.FullName.StartsWith("package/services")) .Select(entry => new SourceFile { PackageId = isCloud ? "Calamari.Cloud" : "Calamari", Version = Version, Platform = platform, ArchivePath = PackagePath, IsNupkg = true, FullNameInDestinationArchive = entry.FullName, FullNameInSourceArchive = entry.FullName, Hash = hasher.Hash(entry) }) .ToArray(); } } }<file_sep>using System; using Calamari.Serialization; using Newtonsoft.Json; namespace Calamari.Commands { public interface ICommandWithInputs { void Execute(string inputs); } public abstract class Command<TInputs> : ICommandWithInputs { public void Execute(string inputs) { Execute(JsonConvert.DeserializeObject<TInputs>(inputs, JsonSerialization.GetDefaultSerializerSettings())); } protected abstract void Execute(TInputs inputs); } }<file_sep>using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Calamari.Common.Features.Packages; using Calamari.Integration.Packages; using NUnit.Framework; using Octopus.Versioning; using Octopus.Versioning.Semver; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class PackageNameFixture { [Test] public void ToCachedFileName_MavenEncodedChars() { var filename = PackageName.ToCachedFileName("My/Package", VersionFactory.CreateMavenVersion("12:8"), ".jar"); var scrubbedFilename = Regex.Replace(filename, "[0-9A-F]{32}", "<CACHE-GUID>"); Assert.AreEqual("My%2FPackage@M12%3A8@<CACHE-GUID>.jar", scrubbedFilename); } [Test] public void ToCachedFileName_Semver() { var filename = PackageName.ToCachedFileName("My/Package", VersionFactory.CreateSemanticVersion("12.32.1-meta+data"), ".zip"); var scrubbedFilename = Regex.Replace(filename, "[0-9A-F]{32}", "<CACHE-GUID>"); Assert.AreEqual("My%2FPackage@S12.32.1-meta+data@<CACHE-GUID>.zip", scrubbedFilename); } [Test] public void FromFile_SimpleConversion() { var details = PackageName.FromFile("blah/MyPackage@S1.0.0@XXXYYYZZZ.zip"); Assert.AreEqual("MyPackage", details.PackageId); Assert.AreEqual(new SemanticVersion("1.0.0"), details.Version); Assert.AreEqual(".zip", details.Extension); } [Test] public void FromFile_EncodedCharacters() { var details = PackageName.FromFile("blah/My%2FPackage@S1.0.0+CAT@XXXYYYZZZ.zip"); Assert.AreEqual("My/Package", details.PackageId); Assert.AreEqual(new SemanticVersion("1.0.0+CAT"), details.Version); Assert.AreEqual(".zip", details.Extension); } [Test] public void FromFile_MavenVersion() { var details = PackageName.FromFile("blah/pkg@M1.0.0%2BCAT@XXXYYYZZZ.jar"); Assert.AreEqual("pkg", details.PackageId); Assert.AreEqual(VersionFactory.CreateMavenVersion("1.0.0+CAT"), details.Version); Assert.AreEqual(".jar", details.Extension); } [Test] public void FromFile_OldSchoolFileType() { var details = PackageName.FromFile("blah/MyPackage.1.0.8-cat+jat.jar"); Assert.AreEqual("MyPackage", details.PackageId); Assert.AreEqual(VersionFactory.CreateSemanticVersion("1.0.8-cat+jat"), details.Version); Assert.AreEqual(".jar", details.Extension); } [Test] [TestCaseSource(nameof(PackageNameTestCases))] public void FromFile(string filename, string extension, string packageId, IVersion version) { var details = PackageName.FromFile($"blah/{filename}"); Assert.AreEqual(packageId, details.PackageId); Assert.AreEqual(version, details.Version); Assert.AreEqual(extension, details.Extension); } [Test] public void FromFile_InvalidVersionType() { Assert.Throws<Exception>(() => PackageName.FromFile("blah/pkg@1.0.0%2BCAT@XXXYYYZZZ.jar")); } [Test] public void FromFile_InvalidSemVer() { Assert.Throws<Exception>(() => PackageName.FromFile("blah/pkg@S1.D.0%2BCAT@XXXYYYZZZ.jar")); } [Test] public void FromFile_UnknownInvalidVersionType() { Assert.Throws<Exception>(() => PackageName.FromFile("blah/pkg@1.0.0%2BCAT@XXXYYYZZZ.jar")); } static IEnumerable<object> PackageNameTestCases() { var files = new (string filename, string version, string packageId)[] { ("foo.1.0.0", "1.0.0", "foo"), ("foo.1.0.0-tag", "1.0.0-tag", "foo"), ("foo.1.0.0-tag-release.tag", "1.0.0-tag-release.tag", "foo"), ("foo.1.0.0+buildmeta", "1.0.0+buildmeta", "foo"), ("foo.1.0.0-tag-release.tag+buildmeta", "1.0.0-tag-release.tag+buildmeta", "foo"), }; var extensions = new [] { ".zip", ".nupkg", ".tar", ".tar.gz", ".tar.bz2", }; foreach (var file in files) { foreach (var extension in extensions) { yield return new TestCaseData($"{file.filename}{extension}", extension, file.packageId, VersionFactory.CreateSemanticVersion(file.version)); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Calamari.Aws.Deployment; using Calamari.Common.Commands; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Common.Util; using Octopus.CoreUtilities; using StackStatus = Calamari.Aws.Deployment.Conventions.StackStatus; namespace Calamari.Aws.Integration.CloudFormation.Templates { public class CloudFormationTemplate : BaseTemplate, ITemplate { readonly Func<string> content; public CloudFormationTemplate(Func<string> content, ITemplateInputs<Parameter> parameters, string stackName, List<string> iamCapabilities, bool disableRollback, string roleArn, IEnumerable<KeyValuePair<string, string>> tags, StackArn stack, Func<IAmazonCloudFormation> clientFactory, IVariables variables) : base(parameters.Inputs, stackName, iamCapabilities, disableRollback, roleArn, tags, stack, clientFactory, variables) { this.content = content; } public static ICloudFormationRequestBuilder Create(ITemplateResolver templateResolver, string templateFile, string templateParameterFile, bool filesInPackage, ICalamariFileSystem fileSystem, IVariables variables, string stackName, List<string> capabilities, bool disableRollback, string roleArn, IEnumerable<KeyValuePair<string, string>> tags, StackArn stack, Func<IAmazonCloudFormation> clientFactory) { var resolvedTemplate = templateResolver.Resolve(templateFile, filesInPackage, variables); var resolvedParameters = templateResolver.MaybeResolve(templateParameterFile, filesInPackage, variables); if (!string.IsNullOrWhiteSpace(templateParameterFile) && !resolvedParameters.Some()) throw new CommandException("Could not find template parameters file: " + templateParameterFile); return new CloudFormationTemplate(() => variables.Evaluate(fileSystem.ReadFile(resolvedTemplate.Value)), CloudFormationParametersFile.Create(resolvedParameters, fileSystem, variables), stackName, capabilities, disableRollback, roleArn, tags, stack, clientFactory, variables); } public string Content => content(); public override CreateStackRequest BuildCreateStackRequest() { return new CreateStackRequest { StackName = stackName, TemplateBody = Content, Parameters = Inputs.ToList(), Capabilities = capabilities, DisableRollback = disableRollback, RoleARN = roleArn, Tags = tags }; } public override UpdateStackRequest BuildUpdateStackRequest() { return new UpdateStackRequest { StackName = stackName, TemplateBody = Content, Parameters = Inputs.ToList(), Capabilities = capabilities, RoleARN = roleArn, Tags = tags }; } public override async Task<CreateChangeSetRequest> BuildChangesetRequest() { return new CreateChangeSetRequest { StackName = stack.Value, TemplateBody = Content, Parameters = Inputs.ToList(), /* * The change set name might be passed down directly, or this variable may be * set as part of the deployment. Reading the value from the variables here * allows us to catch any deferred construction of the change stack name. */ ChangeSetName = variables[AwsSpecialVariables.CloudFormation.Changesets.Name], ChangeSetType = await GetStackStatus() == StackStatus.DoesNotExist ? ChangeSetType.CREATE : ChangeSetType.UPDATE, Capabilities = capabilities, RoleARN = roleArn }; } } }<file_sep>using System.IO; using System.Threading.Tasks; using SharpCompress.Archives; using SharpCompress.Archives.Zip; using SharpCompress.Common; namespace Calamari.AzureAppService { public class ZipPackageProvider : IPackageProvider { public string UploadUrlPath => @"/api/zipdeploy"; public async Task<FileInfo> PackageArchive(string sourceDirectory, string targetDirectory) { await Task.Run(() => { using var archive = ZipArchive.Create(); archive.AddAllFromDirectory( $"{sourceDirectory}"); archive.SaveTo($"{targetDirectory}/app.zip", CompressionType.Deflate); }); return new FileInfo($"{targetDirectory}/app.zip"); } public async Task<FileInfo> ConvertToAzureSupportedFile(FileInfo sourceFile) => await Task.Run(() => sourceFile); } }<file_sep>using Azure.ResourceManager.Resources; using Calamari.AzureAppService.Behaviors; using Calamari.Common.Commands; using Calamari.Common.Features.Discovery; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using FluentAssertions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.ResourceManager.AppService; using Azure.ResourceManager.AppService.Models; using Calamari.Common.Plumbing.Extensions; using Polly.Retry; namespace Calamari.AzureAppService.Tests { [TestFixture] public class TargetDiscoveryBehaviourIntegrationTestFixture : AppServiceIntegrationTest { private readonly string appName = Guid.NewGuid().ToString(); private readonly List<string> slotNames = new List<string> { "blue", "green" }; private static readonly string Type = "Azure"; private static readonly string AccountId = "Accounts-1"; private static readonly string Role = "my-azure-app-role"; private static readonly string EnvironmentName = "dev"; private RetryPolicy retryPolicy; private AppServicePlanResource appServicePlanResource; protected override async Task ConfigureTestResources(ResourceGroupResource resourceGroup) { var response = await resourceGroup.GetAppServicePlans() .CreateOrUpdateAsync(WaitUntil.Completed, ResourceGroupName, new AppServicePlanData(resourceGroup.Data.Location) { Sku = new AppServiceSkuDescription { Name = "S1", Tier = "Standard" } }); appServicePlanResource = response.Value; } [SetUp] public async Task CreateOrResetWebAppAndSlots() { // Call update on the web app and each slot without and tags // to reset it for each test. WebSiteResource = await CreateOrUpdateTestWebApp(); await CreateOrUpdateTestWebAppSlots(WebSiteResource); } [Test] public async Task Execute_WebAppWithMatchingTags_CreatesCorrectTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); this.CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set expected tags on our web app var tags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, { TargetTags.RoleTagName, Role }, }; await CreateOrUpdateTestWebApp(tags); await Eventually.ShouldEventually(async () => { // Act await sut.Execute(context); // Assert var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(ResourceGroupName, appName, AccountId, Role, null, null); var serviceMessageString = serviceMessageToCreateWebAppTarget.ToString(); log.StandardOut.Should().Contain(serviceMessageString); }, log, CancellationToken.None); } [Test] public async Task Execute_WebAppWithNonMatchingTags_CreatesNoTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); this.CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set expected tags on our web app var tags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, { TargetTags.RoleTagName, Role }, }; await CreateOrUpdateTestWebApp(tags); // Act await sut.Execute(context); // Assert var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(ResourceGroupName, appName, AccountId, "a-different-role", null, null); log.StandardOut.Should().NotContain(serviceMessageToCreateWebAppTarget.ToString(), "The web app target should not be created as the role tag did not match"); } [Test] public async Task Execute_MultipleWebAppSlotsWithTags_WebAppHasNoTags_CreatesCorrectTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set expected tags on each slot of the web app but not the web app itself var tags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, { TargetTags.RoleTagName, Role }, }; await CreateOrUpdateTestWebAppSlots(WebSiteResource, tags); await Eventually.ShouldEventually(async () => { // Act await sut.Execute(context); var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(ResourceGroupName, appName, AccountId, Role, null, null); log.StandardOut.Should().NotContain(serviceMessageToCreateWebAppTarget.ToString(), "A target should not be created for the web app itself, only for slots within the web app"); // Assert foreach (var slotName in slotNames) { var serviceMessageToCreateTargetForSlot = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(ResourceGroupName, appName, AccountId, Role, null, slotName); log.StandardOut.Should().Contain(serviceMessageToCreateTargetForSlot.ToString()); } }, log, CancellationToken.None); } [Test] public async Task Execute_MultipleWebAppSlotsWithTags_WebAppWithTags_CreatesCorrectTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set expected tags on each slot of the web app AND the web app itself var tags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, { TargetTags.RoleTagName, Role }, }; var webSiteResource =await CreateOrUpdateTestWebApp(tags); await CreateOrUpdateTestWebAppSlots(webSiteResource,tags); await Eventually.ShouldEventually(async () => { // Act await sut.Execute(context); var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(ResourceGroupName, appName, AccountId, Role, null, null); log.StandardOut.Should().Contain(serviceMessageToCreateWebAppTarget.ToString(), "A target should be created for the web app itself as well as for the slots"); // Assert foreach (var slotName in slotNames) { var serviceMessageToCreateTargetForSlot = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(ResourceGroupName, appName, AccountId, Role, null, slotName); log.StandardOut.Should().Contain(serviceMessageToCreateTargetForSlot.ToString()); } }, log, CancellationToken.None); } [Test] public async Task Execute_MultipleWebAppSlotsWithPartialTags_WebAppWithPartialTags_CreatesNoTargets() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); CreateVariables(context); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Set partial tags on each slot of the web app AND the remaining ones on the web app itself var webAppTags = new Dictionary<string, string> { { TargetTags.EnvironmentTagName, EnvironmentName }, }; var slotTags = new Dictionary<string, string> { { TargetTags.RoleTagName, Role }, }; var webSiteResource = await CreateOrUpdateTestWebApp(webAppTags); await CreateOrUpdateTestWebAppSlots(webSiteResource, slotTags); await Eventually.ShouldEventually(async () => { // Act await sut.Execute(context); var serviceMessageToCreateWebAppTarget = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(ResourceGroupName, appName, AccountId, Role, null, null); log.StandardOut.Should() .NotContain(serviceMessageToCreateWebAppTarget.ToString(), "A target should not be created for the web app as the tags directly on the web app do not match, even though when combined with the slot tags they do"); // Assert foreach (var slotName in slotNames) { var serviceMessageToCreateTargetForSlot = TargetDiscoveryHelpers.CreateWebAppTargetCreationServiceMessage(ResourceGroupName, appName, AccountId, Role, null, slotName); log.StandardOut.Should() .NotContain(serviceMessageToCreateTargetForSlot.ToString(), "A target should not be created for the web app slot as the tags directly on the slot do not match, even though when combined with the web app tags they do"); } }, log, CancellationToken.None); } private async Task<WebSiteResource> CreateOrUpdateTestWebApp(IDictionary<string, string> tags = null) { var data = new WebSiteData(ResourceGroupResource.Data.Location) { AppServicePlanId = appServicePlanResource.Id }; if (tags != null) data.Tags.AddRange(tags); var response = await ResourceGroupResource.GetWebSites() .CreateOrUpdateAsync(WaitUntil.Completed, appName, data); return response.Value; } private async Task CreateOrUpdateTestWebAppSlots(WebSiteResource webSiteResource, Dictionary<string, string> tags = null) { var webSiteData = webSiteResource.Data; if (tags != null) webSiteData.Tags.AddRange(tags); var slotTasks = new List<Task>(); foreach (var slotName in slotNames) { var task = webSiteResource.GetWebSiteSlots() .CreateOrUpdateAsync(WaitUntil.Completed, slotName, webSiteData ); slotTasks.Add(task); } await Task.WhenAll(slotTasks); } private void CreateVariables(RunningDeployment context) { string targetDiscoveryContext = $@"{{ ""scope"": {{ ""spaceName"": ""default"", ""environmentName"": ""{EnvironmentName}"", ""projectName"": ""my-test-project"", ""tenantName"": null, ""roles"": [""{Role}""] }}, ""authentication"": {{ ""type"": ""{Type}"", ""accountId"": ""{AccountId}"", ""accountDetails"": {{ ""subscriptionNumber"": ""{SubscriptionId}"", ""clientId"": ""{ClientId}"", ""tenantId"": ""{TenantId}"", ""password"": ""{<PASSWORD>}"", ""azureEnvironment"": """", ""resourceManagementEndpointBaseUri"": """", ""activeDirectoryEndpointBaseUri"": """" }} }} }} "; context.Variables.Add("Octopus.TargetDiscovery.Context", targetDiscoveryContext); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Discovery { public interface IKubernetesDiscoverer { string Type { get; } IEnumerable<KubernetesCluster> DiscoverClusters(string contextJson); } }<file_sep>namespace Calamari.Aws.Integration.S3 { public interface IHaveBucketKeyBehaviour { BucketKeyBehaviourType BucketKeyBehaviour { get; } string BucketKey { get; } string BucketKeyPrefix { get; } } }<file_sep>using System.IO; using System.Threading.Tasks; namespace Calamari.AzureAppService { public interface IPackageProvider { string UploadUrlPath { get; } Task<FileInfo> PackageArchive(string sourceDirectory, string targetDirectory); Task<FileInfo> ConvertToAzureSupportedFile(FileInfo sourceFile); } }<file_sep> using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.ConfigurationTransforms { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class TransformFileLocatorFixture { [Test] public void When_TransformIsFileNameOnly_And_TargetIsFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Transform and target are in the same directory") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\web.mytransform.config") .When.UsingTransform("web.mytransform.config => web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\web.mytransform.config") .Verify(this); } [Test] public void When_TransformIsFileNameOnly_And_TargetIsWildcardFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Transform and multiple targets are in the same directory") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\connstrings.mytransform.config") .When.UsingTransform("connstrings.mytransform.config => *.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\connstrings.mytransform.config") .And.SourceFile(@"c:\temp\app.config") .Should.BeTransFormedBy(@"c:\temp\connstrings.mytransform.config") .Verify(this); } [Test] public void When_TransformIsRelativePath_And_TargetIsFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform from a different directory") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\transforms\web.mytransform.config") .When.UsingTransform(@"transforms\web.mytransform.config => web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\web.mytransform.config") .Verify(this); } [Test] public void When_TransformIsRelativePath_And_TargetIsWildcardFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform from a different directory against multiple files") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\transforms\connstrings.mytransform.config") .When.UsingTransform(@"transforms\connstrings.mytransform.config => *.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\connstrings.mytransform.config") .Then.SourceFile(@"c:\temp\app.config") .Should.BeTransFormedBy(@"c:\temp\transforms\connstrings.mytransform.config") .Verify(this); } [Test] public void When_TransformIsFullPath_And_TargetIsFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Using an absolute path to the transform") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\subdir\web.config") .And.FileExists(@"c:\transforms\web.mytransform.config") .When.UsingTransform(@"c:\transforms\web.mytransform.config => web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\transforms\web.mytransform.config") .Then.SourceFile(@"c:\temp\subdir\web.config") .Should.BeTransFormedBy(@"c:\transforms\web.mytransform.config") .Verify(this); } [Test] public void When_TransformIsFullPath_And_TargetIsWildcardFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Using an absolute path to the transform, and applying it against multiple files") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\transforms\connstrings.mytransform.config") .When.UsingTransform(@"c:\transforms\connstrings.mytransform.config => *.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\transforms\connstrings.mytransform.config") .Then.SourceFile(@"c:\temp\app.config") .Should.BeTransFormedBy(@"c:\transforms\connstrings.mytransform.config") .Verify(this); } [Test] public void When_TransformIsFullPath_And_TargetIsWildcardFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Using an absolute path to the transform with an absolute path to multiple files") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\transforms\connstrings.mytransform.config") .When.UsingTransform(@"c:\transforms\connstrings.mytransform.config => c:\temp\*.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Then.SourceFile(@"c:\temp\app.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsWildcardFullPath_And_TargetIsFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying multiple absolute path transforms to the same target file") .Given.FileExists(@"c:\temp\web.config") .Given.FileExists(@"c:\temp\subdir\web.config") .And.FileExists(@"c:\transforms\connstrings.mytransform.config") .And.FileExists(@"c:\transforms\security.mytransform.config") .When.UsingTransform(@"c:\transforms\*.mytransform.config => web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\transforms\connstrings.mytransform.config", @"c:\transforms\security.mytransform.config") .Then.SourceFile(@"c:\temp\subdir\web.config") .Should.BeTransFormedBy(@"c:\transforms\connstrings.mytransform.config", @"c:\transforms\security.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardFullPath_And_TargetIsWildcardFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Using an absolute path wildcard transform and multiple targets") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\subdir\web.config") .And.FileExists(@"c:\temp\subdir\app.config") .And.FileExists(@"c:\transforms\web.mytransform.config") .And.FileExists(@"c:\transforms\app.mytransform.config") .When.UsingTransform(@"c:\transforms\*.mytransform.config => *.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\transforms\web.mytransform.config") .Then.SourceFile(@"c:\temp\app.config") .Should.BeTransFormedBy(@"c:\transforms\app.mytransform.config") .Then.SourceFile(@"c:\temp\subdir\web.config") .Should.BeTransFormedBy(@"c:\transforms\web.mytransform.config") .Then.SourceFile(@"c:\temp\subdir\app.config") .Should.BeTransFormedBy(@"c:\transforms\app.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardFullPath_And_TargetIsRelativePath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Using an absolute path to a transform against a target in a different directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\transforms\security.mytransform.config") .And.FileExists(@"c:\transforms\connstrings.mytransform.config") .When.UsingTransform(@"c:\transforms\*.mytransform.config => config\web.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsWildcardFullPath_And_TargetIsFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Using an absolute path wildcard transform against an absolute path target") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\transforms\security.mytransform.config") .And.FileExists(@"c:\transforms\connstrings.mytransform.config") .When.UsingTransform(@"c:\transforms\*.mytransform.config => c:\temp\web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsWildcardFullPath_And_TargetIsWildcardFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Using an absolute path wildcard transform against an absolute path wildcard target") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\transforms\security.mytransform.config") .And.FileExists(@"c:\transforms\connstrings.mytransform.config") .When.UsingTransform(@"c:\transforms\*.mytransform.config => c:\temp\*.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsWildcardFullPath_And_TargetIsWildcardRelativePath_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Using an absolute path for multiple transforms against multiple relative files") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\config\app.config") .And.FileExists(@"c:\transforms\web.mytransform.config") .And.FileExists(@"c:\transforms\app.mytransform.config") .When.UsingTransform(@"c:\transforms\*.mytransform.config => config\*.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\transforms\web.mytransform.config") .Then.SourceFile(@"c:\temp\config\app.config") .Should.BeTransFormedBy(@"c:\transforms\app.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardRelativePath_And_TargetIsFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying multiple relative transforms against a specific target") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\transforms\connstrings.mytransform.config") .And.FileExists(@"c:\temp\transforms\security.mytransform.config") .When.UsingTransform(@"transforms\*.mytransform.config => web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\connstrings.mytransform.config", @"c:\temp\transforms\security.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardRelativePath_And_TargetIsWildcardFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying transforms from a different directory to multiple targets") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\transforms\web.mytransform.config") .And.FileExists(@"c:\temp\transforms\app.mytransform.config") .When.UsingTransform(@"transforms\*.mytransform.config => *.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\web.mytransform.config") .Then.SourceFile(@"c:\temp\app.config") .Should.BeTransFormedBy(@"c:\temp\transforms\app.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardRelativePath_And_TargetIsRelativePath_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying multiple transforms in a different directory to a single target in a different directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\transforms\connstrings.mytransform.config") .And.FileExists(@"c:\temp\transforms\security.mytransform.config") .When.UsingTransform(@"transforms\*.mytransform.config => config\web.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\connstrings.mytransform.config", @"c:\temp\transforms\security.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardRelativePath_And_TargetIsWildcardRelativePath_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying transforms from a different directory to targets in a different directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\config\app.config") .And.FileExists(@"c:\temp\transforms\web.mytransform.config") .And.FileExists(@"c:\temp\transforms\app.mytransform.config") .When.UsingTransform(@"transforms\*.mytransform.config => config\*.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\web.mytransform.config") .Then.SourceFile(@"c:\temp\config\app.config") .Should.BeTransFormedBy(@"c:\temp\transforms\app.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardRelativePath_And_TargetIsWildcardFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying multiple transforms in a different directory to multiple targets with an absolute path") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\transforms\security.mytransform.config") .And.FileExists(@"c:\temp\transforms\connstrings.mytransform.config") .When.UsingTransform(@"transforms\*.mytransform.config => c:\temp\*.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Then.SourceFile(@"c:\temp\app.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsWildcardFileNameOnly_And_TargetIsWildcardFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying multiple transforms to multiple targets with an absolute path") .Given.FileExists(@"c:\temp\web.config") .Given.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\security.mytransform.config") .And.FileExists(@"c:\temp\connstrings.mytransform.config") .When.UsingTransform(@"*.mytransform.config => c:\temp\*.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Then.SourceFile(@"c:\temp\app.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsWildcardRelativePath_And_TargetIsFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying multiple transforms in a different directory to a target with an absolute path") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\transforms\security.mytransform.config") .And.FileExists(@"c:\temp\transforms\connstrings.mytransform.config") .When.UsingTransform(@"transforms\*.mytransform.config => c:\temp\web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsWildcardFileNameOnly_And_TargetIsFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying multiple transforms to a single target where both are in the same directory") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\security.mytransform.config") .And.FileExists(@"c:\temp\connstrings.mytransform.config") .When.UsingTransform(@"*.mytransform.config => web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\security.mytransform.config", @"c:\temp\connstrings.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardFileNameOnly_And_TargetIsFileNameOnly_2_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Wildcard transform with wildcard in the middle of the filename to a single target where both are in the same directory") .Given.FileExists(@"c:\temp\MyApp.connstrings.octopus.config") .And.FileExists(@"c:\temp\MyApp.nlog_octopus.config") .And.FileExists(@"c:\temp\MyApp.WinSvc.exe.config") .When.UsingTransform(@"MyApp.*.octopus.config => MyApp.WinSvc.exe.config") .Then.SourceFile(@"c:\temp\MyApp.WinSvc.exe.config") .Should.BeTransFormedBy(@"c:\temp\MyApp.connstrings.octopus.config") .Verify(this); } [Test] public void When_TransformIsWildcardFileNameOnly_And_TargetIsWildCardInsideFileNameOnly_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Using wildcard in the middle of target filename") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\web.mytransform.config") .When.UsingTransform(@"*.mytransform.config => w*.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsWildcardFileNameOnly_And_TargetIsWildcardFileNameOnly_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying multiple transforms against multiple targets") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\web.mytransform.config") .And.FileExists(@"c:\temp\app.mytransform.config") .When.UsingTransform(@"*.mytransform.config => *.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\web.mytransform.config") .And.SourceFile(@"c:\temp\app.config") .Should.BeTransFormedBy(@"c:\temp\app.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardFileNameOnly_And_TargetIsRelativePath_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying multiple transforms to a single target in a different directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\security.mytransform.config") .And.FileExists(@"c:\temp\connstrings.mytransform.config") .When.UsingTransform(@"*.mytransform.config => config\web.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\temp\security.mytransform.config", @"c:\temp\connstrings.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardFileNameOnly_And_TargetIsWildcardRelativePath_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying multiple transforms against multiple targets in a different directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\config\app.config") .And.FileExists(@"c:\temp\app.mytransform.config") .And.FileExists(@"c:\temp\web.mytransform.config") .When.UsingTransform(@"*.mytransform.config => config\*.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\temp\web.mytransform.config") .Then.SourceFile(@"c:\temp\config\app.config") .Should.BeTransFormedBy(@"c:\temp\app.mytransform.config") .Verify(this); } [Test] public void When_TransformIsWildcardFileNameOnly_And_TargetIsFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying multiple transforms against a target with an absolute path") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\security.mytransform.config") .And.FileExists(@"c:\temp\connstrings.mytransform.config") .When.UsingTransform(@"*.mytransform.config => c:\temp\web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsFileNameOnly_And_TargetIsRelative_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform against a target in a different folder") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\web.mytransform.config") .When.UsingTransform(@"web.mytransform.config => config\web.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\temp\web.mytransform.config") .Verify(this); } [Test] public void When_TransformIsFileNameOnly_And_TargetIsWildcardRelative_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform against multiple targets in a different directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\config\app.config") .And.FileExists(@"c:\temp\connstrings.mytransform.config") .When.UsingTransform(@"connstrings.mytransform.config => config\*.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\temp\connstrings.mytransform.config") .And.SourceFile(@"c:\temp\config\app.config") .Should.BeTransFormedBy(@"c:\temp\connstrings.mytransform.config") .Verify(this); } [Test] public void When_TransformIsRelativePath_And_TargetIsRelative_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform to a target in a sibling directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\transforms\web.mytransform.config") .When.UsingTransform(@"transforms\web.mytransform.config => config\web.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\web.mytransform.config") .Verify(this); } [Test] public void When_TransformIsRelativePath_And_TargetIsRelative_AndDirectoryRepeats_ItSucceeds() { // https://github.com/OctopusDeploy/Issues/issues/3152 ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform to a target in a sibling directory that repeats") .Given.FileExists(@"c:\temp\temp\web.config") .And.FileExists(@"c:\temp\transforms\web.mytransform.config") .When.UsingTransform(@"transforms\web.mytransform.config => temp\web.config") .Then.SourceFile(@"c:\temp\temp\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\web.mytransform.config") .Verify(this); } [Test] public void When_TransformIsRelativePath_And_TargetIsWildcardRelative_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform to multiple targets in a sibling directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\config\app.config") .And.FileExists(@"c:\temp\transforms\connstrings.mytransform.config") .When.UsingTransform(@"transforms\connstrings.mytransform.config => config\*.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\temp\transforms\connstrings.mytransform.config") .And.SourceFile(@"c:\temp\config\app.config") .Should.BeTransFormedBy(@"c:\temp\transforms\connstrings.mytransform.config") .Verify(this); } [Test] public void When_TransformIsFullPath_And_TargetIsRelative_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying a transform with an absolute path to target in a different directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\transforms\web.mytransform.config") .When.UsingTransform(@"c:\transforms\web.mytransform.config => config\web.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsFullPath_And_TargetIsRelativeWildcard_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform with an absolute path against multiple files in a different directory") .Given.FileExists(@"c:\temp\config\web.config") .And.FileExists(@"c:\temp\config\app.config") .And.FileExists(@"c:\transforms\connstrings.mytransform.config") .When.UsingTransform(@"c:\transforms\connstrings.mytransform.config => config\*.config") .Then.SourceFile(@"c:\temp\config\web.config") .Should.BeTransFormedBy(@"c:\transforms\connstrings.mytransform.config") .And.SourceFile(@"c:\temp\config\app.config") .Should.BeTransFormedBy(@"c:\transforms\connstrings.mytransform.config") .Verify(this); } [Test] public void When_TransformIsFileNameOnly_And_TargetIsFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying a transform against an absolute path target") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\web.mytransform.config") .When.UsingTransform(@"web.mytransform.config => c:\temp\web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsRelativePath_And_TargetIsFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying a transform from a relative directory to an absolute path target") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\transforms\web.mytransform.config") .When.UsingTransform(@"transforms\web.mytransform.config => c:\temp\web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsRelativePath_And_TargetIsWildcardFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying a transform from a relative directory to absolute path targets") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\transforms\web.mytransform.config") .When.UsingTransform(@"transforms\web.mytransform.config => c:\temp\*.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Then.SourceFile(@"c:\temp\app.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsFileNameOnly_And_TargetIsWildcardFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying a transform against an multiple targets with an absolute path") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\app.config") .And.FileExists(@"c:\temp\web.mytransform.config") .When.UsingTransform(@"web.mytransform.config => c:\temp\*.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Then.SourceFile(@"c:\temp\app.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsFullPath_And_TargetIsFullPath_ItFails() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Not supported: Applying a transform with an absolute path to a target with an absolute path") .Given.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\transforms\web.mytransform.config") .When.UsingTransform(@"c:\transforms\web.mytransform.config => c:\temp\web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsFullPath_And_TargetIsInTheExtractionDirectoryRoot_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform with an absolute path to a target in the extraction path root") .Given.ExtractionDirectoryIs(@"c:\temp") .And.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\subdir\web.config") .And.FileExists(@"c:\transforms\web.mytransform.config") .When.UsingTransform(@"c:\transforms\web.mytransform.config => .\web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.BeTransFormedBy(@"c:\transforms\web.mytransform.config") .And.SourceFile(@"c:\temp\subdir\web.config") .Should.FailToBeTransformed() .Verify(this); } [Test] public void When_TransformIsFullPath_And_TargetIsRelativeToExtractionDirectory_ItSucceeds() { ConfigurationTransformTestCaseBuilder .ForTheScenario("Applying a transform with an absolute path to a target relative to the extraction path") .Given.ExtractionDirectoryIs(@"c:\temp") .And.FileExists(@"c:\temp\web.config") .And.FileExists(@"c:\temp\subdir\web.config") .And.FileExists(@"c:\transforms\web.mytransform.config") .When.UsingTransform(@"c:\transforms\web.mytransform.config => .\subdir\web.config") .Then.SourceFile(@"c:\temp\web.config") .Should.FailToBeTransformed() .And.SourceFile(@"c:\temp\subdir\web.config") .Should.BeTransFormedBy(@"c:\transforms\web.mytransform.config") .Verify(this); } } } <file_sep>using System; using Microsoft.Win32; namespace Calamari.AzureServiceFabric.Util { static class ServiceFabricHelper { public static bool IsServiceFabricSdkKeyInRegistry() { var keyFound = false; using (var rootKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) using (var subKey = rootKey.OpenSubKey("SOFTWARE\\Microsoft\\Service Fabric SDK", false)) { if (subKey != null) keyFound = true; } return keyFound; } } enum AzureServiceFabricSecurityMode { Unsecure, SecureClientCertificate, SecureAzureAD, SecureAD, } } <file_sep>using System.IO; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.PowerShell { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public class PowerShellOnLinuxOrMacFixture : PowerShellFixtureBase { [SetUp] public void SetUp() { CommandLineRunner clr = new CommandLineRunner(ConsoleLog.Instance, new CalamariVariables()); var result = clr.Execute(new CommandLineInvocation("pwsh", "--version") { OutputToLog = false }); if (result.HasErrors) Assert.Inconclusive("PowerShell Core is not installed on this machine"); } [Test] public void ShouldRunBashInsteadOfPowerShell() { var variablesFile = Path.GetTempFileName(); var variables = new CalamariVariables(); variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.PowerShell), "Write-Host Hello PowerShell"); variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.CSharp), "Write-Host Hello CSharp"); variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.Bash), "echo Hello Bash"); variables.Save(variablesFile); using (new TemporaryFile(variablesFile)) { var output = Invoke(Calamari() .Action("run-script") .Argument("variables", variablesFile)); output.AssertSuccess(); output.AssertOutput("Hello Bash"); } } protected override PowerShellEdition PowerShellEdition => PowerShellEdition.Core; } }<file_sep>using System; using System.Diagnostics.CodeAnalysis; using Calamari.Common.Commands; namespace Calamari.Common.Plumbing { public static class Guard { public static void NotNullOrWhiteSpace([NotNull]string? value, string message) { if (string.IsNullOrWhiteSpace(value)) throw new CommandException(message); } public static void NotNull([NotNull]object? value, string message) { if (value == null) throw new ArgumentException(message); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Calamari.ConsolidateCalamariPackages { static class ConsolidatedPackageCreator { public static void Create(IEnumerable<SourceFile> sourceFiles, string destination) { using (var zip = ZipFile.Open(destination, ZipArchiveMode.Create)) { WriteUniqueFilesToZip(sourceFiles, zip); var indexEntry = zip.CreateEntry("index.json", CompressionLevel.Fastest); using (var destStream = indexEntry.Open()) WriteIndexTo(destStream, sourceFiles); } } private static void WriteUniqueFilesToZip(IEnumerable<SourceFile> sourceFiles, ZipArchive zip) { var uniqueFiles = sourceFiles .GroupBy(sourceFile => new {sourceFile.FullNameInDestinationArchive, sourceFile.Hash}) .Select(g => new { g.Key.FullNameInDestinationArchive, g.Key.Hash, g.First().FullNameInSourceArchive, g.First().ArchivePath }); foreach (var groupedBySourceArchive in uniqueFiles.GroupBy(f => f.ArchivePath)) { using (var sourceZip = ZipFile.OpenRead(groupedBySourceArchive.Key)) foreach (var uniqueFile in groupedBySourceArchive) { var entryName = Path.Combine(uniqueFile.Hash, uniqueFile.FullNameInDestinationArchive); var entry = zip.CreateEntry(entryName, CompressionLevel.Fastest); using (var destStream = entry.Open()) using (var sourceStream = sourceZip.Entries.First(e => e.FullName == uniqueFile.FullNameInSourceArchive).Open()) sourceStream.CopyTo(destStream); } } } private static void WriteIndexTo(Stream stream, IEnumerable<SourceFile> sourceFiles) { Dictionary<string, string[]> GroupByPlatform(IEnumerable<SourceFile> filesForPackage) => filesForPackage .GroupBy(f => f.Platform) .ToDictionary( g => g.Key, g => g.Select(f => f.Hash).OrderBy(h => h).ToArray() ); var index = new ConsolidatedPackageIndex( sourceFiles .GroupBy(i => new {i.PackageId, i.Version, i.IsNupkg }) .ToDictionary( g => g.Key.PackageId, g => new ConsolidatedPackageIndex.Package( g.Key.PackageId, g.Key.Version, g.Key.IsNupkg, GroupByPlatform(g) ) ) ); var bytes = Encoding.UTF8.GetBytes((string)JsonConvert.SerializeObject(index, Formatting.Indented)); stream.Write(bytes, 0, bytes.Length); } } }<file_sep>using System.Linq; using Calamari.Common.Plumbing.Extensions; using Calamari.Kubernetes.Integration; namespace Calamari.Kubernetes.ResourceStatus { public interface IKubectlGet { string Resource(string kind, string name, string @namespace, IKubectl kubectl); string AllResources(string kind, string @namespace, IKubectl kubectl); } public class KubectlGet : IKubectlGet { public string Resource(string kind, string name, string @namespace, IKubectl kubectl) { return kubectl.ExecuteCommandAndReturnOutput(new[] { "get", kind, name, "-o json", $"-n {@namespace}" }).Output.InfoLogs.Join(string.Empty); } public string AllResources(string kind, string @namespace, IKubectl kubectl) { return kubectl.ExecuteCommandAndReturnOutput(new[] { "get", kind, "-o json", $"-n {@namespace}" }).Output.InfoLogs.Join(string.Empty); } } }<file_sep>using System; using System.IO; using Calamari.Common.Plumbing.Logging; namespace Calamari.Integration.Packages.Download { /// <summary> /// Some common implementations used by package downloaders to find paths /// to store and search for artifacts. /// </summary> public class PackageDownloaderUtils : IPackageDownloaderUtils { public string RootDirectory => Path.Combine(TentacleHome, "Files"); public string TentacleHome { get { var tentacleHome = Environment.GetEnvironmentVariable("TentacleHome"); if (tentacleHome == null) { Log.Error("Environment variable 'TentacleHome' has not been set."); throw new InvalidOperationException("Environment variable 'TentacleHome' has not been set."); } return tentacleHome; } } public string GetPackageRoot(string prefix) { return string.IsNullOrWhiteSpace(prefix) ? RootDirectory : Path.Combine(RootDirectory, prefix); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; namespace Calamari.Common.Plumbing.Extensions { public static class LogExtensions { public static Operation BeginTimedOperation(this ILog log, string operationMessage) { return new Operation(log, operationMessage); } public static void LogMetric(this ILog log, string metricName, object metricValue, string? operationId = null) { var serviceMessageParameters = new Dictionary<string, string> { { ServiceMessageNames.CalamariDeploymentMetric.OperationIdAttribute, operationId }, { ServiceMessageNames.CalamariDeploymentMetric.MetricAttribute, metricName }, { ServiceMessageNames.CalamariDeploymentMetric.ValueAttribute, metricValue.ToString() }, }; log.WriteServiceMessage(new ServiceMessage(ServiceMessageNames.CalamariDeploymentMetric.Name, serviceMessageParameters)); } } } <file_sep>using System; using SharpCompress.Archives; namespace Calamari.Common.Features.Packages.Decorators.ArchiveLimits { /// <summary> /// This decorator prevents decompression of archives if they would extract to more than a limit configurable in Octopus Server, /// to prevent using too much disk space in scenarios where limited space is available. /// </summary> public class EnforceDecompressionLimitDecorator : PackageExtractorDecorator { readonly long maximumUncompressedSize; public EnforceDecompressionLimitDecorator(IPackageExtractor concreteExtractor, long maximumUncompressedSize) : base(concreteExtractor) { this.maximumUncompressedSize = maximumUncompressedSize; } public override int Extract(string packageFile, string directory) { if (!TryVerifyUncompressedSize(packageFile, out var exception)) throw exception!; return base.Extract(packageFile, directory); } bool TryVerifyUncompressedSize(string packageFile, out ArchiveLimitException? exception) { try { if (maximumUncompressedSize > 0) { using (var archive = ArchiveFactory.Open(packageFile)) { var totalUncompressedSize = archive.TotalUncompressSize; if (totalUncompressedSize > maximumUncompressedSize) { exception = ArchiveLimitException.FromUncompressedSizeBreach(totalUncompressedSize); return false; } } } } catch { // Never fail if something in the detection goes wrong. } exception = null; return true; } } } <file_sep>using System; using System.Linq; using System.Text; using System.Xml.Linq; using Calamari.Common.Plumbing.ServiceMessages; namespace Calamari.Testing.LogParser { public class ServiceMessageParser { readonly Action<ProcessOutputSource, string> output; readonly Action<ServiceMessage> serviceMessage; readonly StringBuilder buffer = new StringBuilder(); State state = State.Default; ProcessOutputSource lastSource; public ServiceMessageParser(Action<ProcessOutputSource, string> output, Action<ServiceMessage> serviceMessage) { this.output = output; this.serviceMessage = serviceMessage; } public void Append(ProcessOutputSource source, string line) { if (lastSource != source) Finish(); lastSource = source; for (var i = 0; i < line.Length; i++) { var c = line[i]; switch (state) { case State.Default: if (c == '\r') { } else if (c == '\n') { Flush(output); } else if (c == '#') { state = State.PossibleMessage; buffer.Append(c); } else { buffer.Append(c); } break; case State.PossibleMessage: buffer.Append(c); var progress = buffer.ToString(); if (ServiceMessage.ServiceMessageLabel == progress) { state = State.InMessage; buffer.Clear(); } else if (!ServiceMessage.ServiceMessageLabel.StartsWith(progress)) { state = State.Default; } break; case State.InMessage: if (c == ']') { Flush(ProcessMessage); state = State.Default; } else { buffer.Append(c); } break; default: throw new ArgumentOutOfRangeException(); } } } public void Finish() { if (buffer.Length > 0) { Flush(output); } } void ProcessMessage(ProcessOutputSource source, string message) { try { message = message.Trim().TrimStart('[').Replace("\r", "").Replace("\n", ""); var element = XElement.Parse("<" + message + "/>"); var name = element.Name.LocalName; var values = element.Attributes().ToDictionary(s => s.Name.LocalName, s => Encoding.UTF8.GetString(Convert.FromBase64String(s.Value)), StringComparer.OrdinalIgnoreCase); serviceMessage(new ServiceMessage(name, values)); } catch { serviceMessage(new ServiceMessage("stdout-warning", null)); output(source, $"Could not parse '{ServiceMessage.ServiceMessageLabel}[{message}]'"); serviceMessage(new ServiceMessage("stdout-default", null)); } } void Flush(Action<ProcessOutputSource, string> to) { var result = buffer.ToString(); buffer.Clear(); if (result.Length > 0) to(lastSource, result); } enum State { Default, PossibleMessage, InMessage } } }<file_sep>namespace Calamari.Common.Plumbing.Variables { static class ScriptFunctionsVariables { public const string Registration = "Octopus.Sashimi.ScriptFunctions.Registration"; public const string CopyScriptWrapper = "Octopus.Sashimi.ScriptFunctions.CopyScriptWrapper"; } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Azure; using Azure.ResourceManager.AppService; using Azure.ResourceManager.AppService.Models; using Azure.ResourceManager.Resources; using Azure.ResourceManager.Storage; using Azure.ResourceManager.Storage.Models; using Calamari.AzureAppService.Azure; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Testing; using Calamari.Testing.LogParser; using FluentAssertions; using NUnit.Framework; using FileShare = System.IO.FileShare; namespace Calamari.AzureAppService.Tests { public class AppServiceBehaviorFixture { [TestFixture] public class WhenUsingAWindowsDotNetAppService : AppServiceIntegrationTest { private AppServicePlanResource appServicePlanResource; protected override async Task ConfigureTestResources(ResourceGroupResource resourceGroup) { var (appServicePlan, webSite) = await CreateAppServicePlanAndWebApp(resourceGroup); appServicePlanResource = appServicePlan; WebSiteResource = webSite; } [Test] public async Task CanDeployWebAppZip() { var packageInfo = PrepareZipPackage(); await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageInfo.packagePath, packageInfo.packageName, packageInfo.packageVersion); AddVariables(context); }) .Execute(); await AssertContent(WebSiteResource.Data.DefaultHostName, $"Hello {greeting}"); } [Test] public async Task CanDeployWebAppZip_WithAzureCloudEnvironment() { var packageinfo = PrepareZipPackage(); await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); context.AddVariable(AccountVariables.Environment, "AzureCloud"); }) .Execute(); await AssertContent(WebSiteResource.Data.DefaultHostName, $"Hello {greeting}"); } [Test] public async Task CanDeployWebAppZip_ToDeploymentSlot() { const string slotName = "stage"; greeting = "stage"; (string packagePath, string packageName, string packageVersion) packageinfo; var slotTask = WebSiteResource.GetWebSiteSlots() .CreateOrUpdateAsync(WaitUntil.Completed, slotName, WebSiteResource.Data); var tempPath = TemporaryDirectory.Create(); new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage"); File.WriteAllText(Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"), "Hello #{Greeting}"); packageinfo.packagePath = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.zip"; packageinfo.packageVersion = "1.0.0"; packageinfo.packageName = "AzureZipDeployPackage"; ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath); var slotResponse = await slotTask; var slotResource = slotResponse.Value; await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); context.Variables.Add("Octopus.Action.Azure.DeploymentSlot", slotName); }) .Execute(); await AssertContent(slotResource.Data.DefaultHostName, $"Hello {greeting}"); } [Test] public async Task CanDeployNugetPackage() { (string packagePath, string packageName, string packageVersion) packageinfo; greeting = "nuget"; var tempPath = TemporaryDirectory.Create(); new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage"); var doc = new XDocument(new XElement("package", new XAttribute("xmlns", @"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd"), new XElement("metadata", new XElement("id", "AzureZipDeployPackage"), new XElement("version", "1.0.0"), new XElement("title", "AzureZipDeployPackage"), new XElement("authors", "<NAME>"), new XElement("description", "Test Package used to test nuget package deployments") ) )); await Task.Run(() => File.WriteAllText( Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"), "Hello #{Greeting}")); using (var writer = new XmlTextWriter( Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "AzureZipDeployPackage.nuspec"), Encoding.UTF8)) { doc.Save(writer); } packageinfo.packagePath = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.nupkg"; packageinfo.packageVersion = "1.0.0"; packageinfo.packageName = "AzureZipDeployPackage"; ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath); await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); }) .Execute(); //await new AzureAppServiceBehaviour(new InMemoryLog()).Execute(runningContext); await AssertContent(WebSiteResource.Data.DefaultHostName, $"Hello {greeting}"); } [Test] public async Task CanDeployWarPackage() { // Need to spin up a specific app service with Tomcat installed // Need java installed on the test runner (MJH 2022-05-06: is this actually true? I don't see why we'd need java on the test runner) var javaSite = await ResourceGroupResource.GetWebSites() .CreateOrUpdateAsync(WaitUntil.Completed, $"{ResourceGroupName}-java", new WebSiteData(ResourceGroupResource.Data.Location) { AppServicePlanId = appServicePlanResource.Data.Id, SiteConfig = new SiteConfigProperties { JavaVersion = "1.8", JavaContainer = "TOMCAT", JavaContainerVersion = "9.0" } }); (string packagePath, string packageName, string packageVersion) packageinfo; var assemblyFileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location); packageinfo.packagePath = Path.Combine(assemblyFileInfo.Directory.FullName, "sample.1.0.0.war"); packageinfo.packageVersion = "1.0.0"; packageinfo.packageName = "sample"; greeting = "java"; await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); context.Variables[SpecialVariables.Action.Azure.WebAppName] = javaSite.Value.Data.Name; context.Variables[PackageVariables.SubstituteInFilesTargets] = "test.jsp"; }) .Execute(); await AssertContent(javaSite.Value.Data.DefaultHostName, $"Hello! {greeting}", "test.jsp"); } [Test] public async Task DeployingWithInvalidEnvironment_ThrowsAnException() { var packageinfo = PrepareZipPackage(); var commandResult = await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion); AddVariables(context); context.AddVariable(AccountVariables.Environment, "NonSenseEnvironment"); }) .Execute(false); commandResult.Outcome.Should().Be(TestExecutionOutcome.Unsuccessful); } [Test] public async Task DeployToTwoTargetsInParallel_Succeeds() { // Arrange var packageInfo = PrepareFunctionAppZipPackage(); // Without larger changes to Calamari and the Test Framework, it's not possible to run two Calamari // processes in parallel in the same test method. Simulate the file locking behaviour by directly // opening the affected file instead var fileLock = File.Open(packageInfo.packagePath, FileMode.Open, FileAccess.Read, FileShare.Read); try { // Act var deployment = await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageInfo.packagePath, packageInfo.packageName, packageInfo.packageVersion); AddVariables(context); context.Variables[KnownVariables.Package.EnabledFeatures] = null; }) .Execute(); // Assert deployment.Outcome.Should().Be(TestExecutionOutcome.Successful); } finally { fileLock.Close(); } } private static (string packagePath, string packageName, string packageVersion) PrepareZipPackage() { (string packagePath, string packageName, string packageVersion) packageinfo; var tempPath = TemporaryDirectory.Create(); new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage"); File.WriteAllText(Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"), "Hello #{Greeting}"); packageinfo.packagePath = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.zip"; packageinfo.packageVersion = "1.0.0"; packageinfo.packageName = "AzureZipDeployPackage"; ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath); return packageinfo; } private static (string packagePath, string packageName, string packageVersion) PrepareFunctionAppZipPackage() { (string packagePath, string packageName, string packageVersion) packageInfo; var testAssemblyLocation = new FileInfo(Assembly.GetExecutingAssembly().Location); var sourceZip = Path.Combine(testAssemblyLocation.Directory.FullName, "functionapp.1.0.0.zip"); packageInfo.packagePath = sourceZip; packageInfo.packageVersion = "1.0.0"; packageInfo.packageName = "functionapp"; return packageInfo; } private void AddVariables(CommandTestBuilderContext context) { AddAzureVariables(context); context.Variables.Add("Greeting", greeting); context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.SubstituteInFiles); context.Variables.Add(PackageVariables.SubstituteInFilesTargets, "index.html"); context.Variables.Add(SpecialVariables.Action.Azure.DeploymentType, "ZipDeploy"); //set the feature toggle so we get the new code context.Variables.Add(KnownVariables.EnabledFeatureToggles, FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.ToString()); } } [TestFixture] public class WhenUsingALinuxAppService : AppServiceIntegrationTest { // For some reason we are having issues creating these linux resources on Standard in EastUS protected override string DefaultResourceGroupLocation => "westus2"; protected override async Task ConfigureTestResources(ResourceGroupResource resourceGroup) { var storageAccountName = ResourceGroupName.Replace("-", "").Substring(0, 20); var storageAccountResponse = await ResourceGroupResource .GetStorageAccounts() .CreateOrUpdateAsync(WaitUntil.Completed, storageAccountName, new StorageAccountCreateOrUpdateContent( new StorageSku(StorageSkuName.StandardLrs), StorageKind.Storage, ResourceGroupResource.Data.Location) ); var keys = await storageAccountResponse .Value .GetKeysAsync() .ToListAsync(); var linuxAppServicePlan = await resourceGroup.GetAppServicePlans() .CreateOrUpdateAsync(WaitUntil.Completed, $"{resourceGroup.Data.Name}-linux-asp", new AppServicePlanData(resourceGroup.Data.Location) { Sku = new AppServiceSkuDescription { Name = "S1", Tier = "Standard" }, Kind = "linux", IsReserved = true }); var linuxWebSiteResponse = await resourceGroup.GetWebSites() .CreateOrUpdateAsync(WaitUntil.Completed, $"{resourceGroup.Data.Name}-linux", new WebSiteData(resourceGroup.Data.Location) { AppServicePlanId = linuxAppServicePlan.Value.Id, Kind = "functionapp,linux", IsReserved = true, SiteConfig = new SiteConfigProperties { IsAlwaysOn = true, LinuxFxVersion = "DOTNET|6.0", Use32BitWorkerProcess = true, AppSettings = new List<AppServiceNameValuePair> { new AppServiceNameValuePair{Name = "FUNCTIONS_WORKER_RUNTIME", Value = "dotnet"}, new AppServiceNameValuePair{Name = "FUNCTIONS_EXTENSION_VERSION", Value = "~4"}, new AppServiceNameValuePair{Name = "AzureWebJobsStorage", Value = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={keys.First().Value};EndpointSuffix=core.windows.net"}, } } }); WebSiteResource = linuxWebSiteResponse.Value; } [Test] public async Task CanDeployZip_ToLinuxFunctionApp() { // Arrange var packageInfo = PrepareZipPackage(); // Act await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageInfo.packagePath, packageInfo.packageName, packageInfo.packageVersion); AddVariables(context); }) .Execute(); // Assert await DoWithRetries(10, async () => { await AssertContent(WebSiteResource.Data.DefaultHostName, rootPath: $"api/HttpExample?name={greeting}", actualText: $"Hello, {greeting}"); }, secondsBetweenRetries: 10); } [Test] public async Task CanDeployZip_ToLinuxFunctionApp_WithRunFromPackageFlag() { // Arrange AppServiceConfigurationDictionary settings = await WebSiteResource.GetApplicationSettingsAsync(); settings.Properties["WEBSITE_RUN_FROM_PACKAGE"] = "1"; await WebSiteResource.UpdateApplicationSettingsAsync(settings); var packageInfo = PrepareZipPackage(); // Act await CommandTestBuilder.CreateAsync<DeployAzureAppServiceCommand, Program>() .WithArrange(context => { context.WithPackage(packageInfo.packagePath, packageInfo.packageName, packageInfo.packageVersion); AddVariables(context); }) .Execute(); // Assert await DoWithRetries(10, async () => { await AssertContent(WebSiteResource.Data.DefaultHostName, rootPath: $"api/HttpExample?name={greeting}", actualText: $"Hello, {greeting}"); }, secondsBetweenRetries: 10); } private static (string packagePath, string packageName, string packageVersion) PrepareZipPackage() { // Looks like there's some file locking issues if multiple tests try to copy from the same file when running in parallel. // For each test that needs one, create a temporary copy. (string packagePath, string packageName, string packageVersion) packageInfo; var tempPath = TemporaryDirectory.Create(); new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage"); var testAssemblyLocation = new FileInfo(Assembly.GetExecutingAssembly().Location); var sourceZip = Path.Combine(testAssemblyLocation.Directory.FullName, "functionapp.1.0.0.zip"); var temporaryZipLocationForTest = $"{tempPath.DirectoryPath}/functionapp.1.0.0.zip"; File.Copy(sourceZip, temporaryZipLocationForTest); packageInfo.packagePath = temporaryZipLocationForTest; packageInfo.packageVersion = "1.0.0"; packageInfo.packageName = "functionapp"; return packageInfo; } private void AddVariables(CommandTestBuilderContext context) { AddAzureVariables(context); context.Variables.Add(SpecialVariables.Action.Azure.DeploymentType, "ZipDeploy"); //set the feature toggle so we get the new code context.Variables.Add(KnownVariables.EnabledFeatureToggles, FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.ToString()); } } } }<file_sep>using System; using Calamari.Common.Plumbing.Extensions; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using Calamari.Util; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Util { [TestFixture] public class StringExtensionsFixture { [TestCase("Hello World", "ello", true)] [TestCase("Hello World", "ELLO", true)] [TestCase("HELLO WORLD", "ello", true)] [TestCase("Hello, world", "lO, wOrL", true)] [TestCase("Hello, world", "abc", false)] [TestCase("Hello, world", "ABC", false)] [TestCase("Hello, world", "!@#", false)] [Test] public void ShouldContainString(string originalString, string value, bool expected) { Assert.AreEqual(expected, originalString.ContainsIgnoreCase(value)); } [Test] public void NullValueShouldThrowException() { Action action = () => "foo".ContainsIgnoreCase(null); action.Should().Throw<ArgumentNullException>(); } // This method has some weird legacy issues which we now rely on [TestCase(@"C:\Path\To\File1.txt", @"C:\Path\", @"To/File1.txt")] [TestCase(@"C:\Path\To\File2.txt", @"C:\Path", @"To/File2.txt")] [TestCase(@"C:\Path\To\File3 With Spaces.txt", @"C:\Path", @"To/File3 With Spaces.txt")] [TestCase(@"C:/Path/To/File4.txt", @"C:/Path", @"To/File4.txt")] [TestCase(@"C:/Path/To/File5 With Spaces.txt", @"C:/Path", @"To/File5 With Spaces.txt")] [Test] [Category(TestCategory.CompatibleOS.OnlyWindows)] public void AsRelativePathFrom(string source, string baseDirectory, string expected) { Assert.AreEqual(expected, source.AsRelativePathFrom(baseDirectory)); } } }<file_sep>using System.Threading.Tasks; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using Calamari.Tests.Fixtures; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] public class Helm2UpgradeFixture : HelmUpgradeFixture { [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public void Upgrade_Succeeds() { var result = DeployPackage(); result.AssertSuccess(); result.AssertOutputMatches($"NAMESPACE: {Namespace}"); result.AssertOutputMatches("STATUS: DEPLOYED"); result.AssertOutputMatches(ConfigMapName); result.AssertOutputMatches($"release \"{ReleaseName}\" deleted"); result.AssertOutput("Using custom helm executable at " + HelmExePath); Assert.AreEqual(ReleaseName.ToLower(), result.CapturedOutput.OutputVariables["ReleaseName"]); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMacAttribute] [Category(TestCategory.PlatformAgnostic)] public void TillerNamespace_CannotFindIfRandomNamespaceUsed() { // We're basically just testing here that setting the tiller namespace does put the param into the cmd Variables.Set(Kubernetes.SpecialVariables.Helm.TillerNamespace, "random-foobar"); var result = DeployPackage(); result.AssertFailure(); Log.StandardError.Should().ContainMatch("*Error: could not find tiller*"); } [Test] [RequiresNonFreeBSDPlatform] [RequiresNon32BitWindows] [RequiresNonMac] [Category(TestCategory.PlatformAgnostic)] public async Task CustomHelmExeInPackage_RelativePath() { await TestCustomHelmExeInPackage_RelativePath("2.9.0"); } protected override string ExplicitExeVersion => "2.9.1"; } } <file_sep>using System; using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Assent; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.StructuredVariables { [TestFixture] public class XmlVariableReplacerFixture : VariableReplacerFixture { public XmlVariableReplacerFixture() : base((fs, log) => new XmlFormatVariableReplacer(fs, log)) { } [Test] public void DoesNothingIfThereAreNoVariables() { var vars = new CalamariVariables(); RunTest(vars, "complex.xml"); } [Test] public void DoesNothingIfThereAreNoMatchingVariables() { Replace(new CalamariVariables { { "Non-matching", "variable" } }, "complex.xml"); Log.MessagesInfoFormatted.Should().Contain(StructuredConfigMessages.NoStructuresFound); Log.MessagesVerboseFormatted.Should().NotContain(m => Regex.IsMatch(m, StructuredConfigMessages.StructureFound(".*"))); } [Test] public void CanReplaceAComment() { var vars = new CalamariVariables { { "/document/comment()", "New Comment" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceAnAttribute() { var vars = new CalamariVariables { { "/document/setting[@id='id-1']/@id", "id-new" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceATextNode() { var vars = new CalamariVariables { { "/document/setting[@id='id-1']/text()", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceAnElementsText() { var vars = new CalamariVariables { { "/document/setting[@id='id-1']", "value<new" } }; RunTest(vars, "complex.xml"); Log.MessagesVerboseFormatted.Count(m => Regex.IsMatch(m, StructuredConfigMessages.StructureFound(".*"))).Should().Be(1); Log.MessagesVerboseFormatted.Should().Contain(StructuredConfigMessages.StructureFound("/document/setting[@id='id-1']")); Log.MessagesInfoFormatted.Should().NotContain(StructuredConfigMessages.NoStructuresFound); } [Test] public void CanInsertTextIntoAnEmptyElement() { var vars = new CalamariVariables { { "/document/empty", "value<new" } }; RunTest(vars, "elements.xml"); } [Test] public void CanInsertTextIntoASelfClosingElement() { var vars = new CalamariVariables { { "/document/selfclosing", "value<new" } }; RunTest(vars, "elements.xml"); } [Test] public void CanReplaceAnElementsChildrenWhenTheElementHasMixedContent() { var vars = new CalamariVariables { { "/document/mixed", "<newElement />" } }; RunTest(vars, "elements.xml"); } [Test] public void CanReplaceAnElementsChildren() { var vars = new CalamariVariables { { "//moreSettings", "<a /><b />" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceAnElementsChildrenWhenTheNewChildrenHaveNamespaces() { var vars = new CalamariVariables { { "//moreSettings", "<db:a />" } }; RunTest(vars, "complex.xml"); } [Test] public void DoesNotModifyDocumentWhenVariableCannotBeParsedAsMarkup() { var vars = new CalamariVariables { { "//moreSettings", "<<<<" } }; RunTest(vars, "complex.xml"); } [Test] public void DoesntTreatVariableAsMarkupWhenReplacingAnElementThatContainsNoElementChildren() { var vars = new CalamariVariables { { "/document/setting[@id='id-1']", "<a />" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceMultipleElements() { var vars = new CalamariVariables { { "/document/setting", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceMultipleElementsInDifferentPartsOfTheTree() { var vars = new CalamariVariables { { "//setting", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceCData() { var vars = new CalamariVariables { { "/document/setting[@id='id-3']/text()", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceCDataInAnElement() { var vars = new CalamariVariables { { "/document/setting[@id='id-3']", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void CanReplaceProcessingInstructions() { var vars = new CalamariVariables { { "/document/processing-instruction('xml-stylesheet')", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void CanInferNamespacePrefixesFromDocument() { var vars = new CalamariVariables { { "/document/unique:anotherSetting", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void CanUseXPath2Wildcards() { var vars = new CalamariVariables { { "//*:node", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void DoesNotThrowOnUnrecognisedNamespace() { var vars = new CalamariVariables { { "//env:something", "value-new" } }; RunTest(vars, "complex.xml"); } [Test] public void UsesTheFirstNamespaceWhenADuplicatePrefixIsFound() { var vars = new CalamariVariables { { "//parent/dupe:node", "value-new" } }; RunTest(vars, "duplicate-prefixes.xml"); } [Test] public void ShouldIgnoreOctopusPrefix() { var vars = new CalamariVariables { { "Octopus.Release.Id", "999" } }; RunTest(vars, "ignore-octopus.xml"); } [Test] public void HandlesVariablesThatReferenceOtherVariables() { var vars = new CalamariVariables { { "/document/selfclosing", "#{a}" }, { "a", "#{b}" }, { "b", "value-new" } }; RunTest(vars, "elements.xml"); } [Test] public void ShouldPreserveEncodingUtf8DosBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf8-dos-bom.xml"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingUtf8UnixNoBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf8-unix-nobom.xml"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingUtf16DosBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-utf16-dos-bom.xml"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingWindows1252DosNoBom() { this.Assent(ReplaceToHex(new CalamariVariables(), "enc-windows1252-dos-nobom.xml"), AssentConfiguration.Default); } [Test] public void ShouldUpgradeEncodingIfNecessaryToAccomodateVariables() { this.Assent(ReplaceToHex(new CalamariVariables{{"/doc/dagger", "\uFFE6"}}, "enc-windows1252-dos-nobom.xml"), AssentConfiguration.Default); } [Test] public void ShouldPreserveEncodingIso88592UnixNoBom() { this.Assent(ReplaceToHex(new CalamariVariables { { "//name[14]", "Miko\u0142aj" }, { "//name[.='Micha\u0142']", "Micha\u0142+"} }, "enc-iso88592-unix-nobom.xml"), AssentConfiguration.Default); } [Test] public void ShouldAdaptDeclaredEncodingWhenNecessary() { this.Assent(ReplaceToHex(new CalamariVariables { { "//name[14]", "\u5F20\u4F1F" } }, "enc-iso88592-unix-nobom.xml"), AssentConfiguration.Default); } void RunTest(CalamariVariables vars, string file, [CallerMemberName] string testName = null, [CallerFilePath] string filePath = null) { // ReSharper disable once ExplicitCallerInfoArgument this.Assent(Replace(vars, file), AssentConfiguration.Xml, testName, filePath); } } }<file_sep>using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Calamari.Common.Plumbing.Logging; using Stopwatch = System.Diagnostics.Stopwatch; namespace Calamari.Testing.Helpers { public class EventuallyStrategy { public enum Backoff { None, Linear, Exponential } static readonly TimeSpan TimeBetweenLoggingEachTransientFailure = TimeSpan.FromSeconds(15); readonly Timing timing; readonly ILog logger; readonly Stopwatch stopwatch = new(); TimeSpan elapsedTimeAtLastTransientFailure = TimeSpan.Zero; public EventuallyStrategy(ILog logger) : this(logger, Timing.Default) { } public EventuallyStrategy(ILog logger, Timing timing) { this.logger = logger; this.timing = timing; } public EventuallyStrategy WithTiming(Timing newTiming) => new(logger, newTiming); public async Task ShouldEventually(Func<CancellationToken, Task> action, CancellationToken cancellationToken) { stopwatch.Start(); // For logging only; not for retry/back-off logic. var delay = timing.MinDelay; Exception? exception = null; while (true) try { await action(cancellationToken); LogSuccess(); return; } catch (EventualAssertionPermanentlyFailedException ex) { LogPermanentFailure(ex); throw; } // If the exception thrown matches CancellationToken.None, this means the exception's CancellationToken has a null source // This means it is likely thrown via the calling code via throw new OperationCanceledException(), and not a result of the cancellationToken triggering // If that is the case, we want it to pass through to the transient handling in catch(Exception) catch (OperationCanceledException ex) when (ex.CancellationToken != CancellationToken.None && ex.CancellationToken == cancellationToken) { var exceptionToThrow = exception ?? ex; LogPermanentFailure(exceptionToThrow); ExceptionDispatchInfo.Capture(exceptionToThrow).Throw(); // Throw the previous assertion failure exception if there was one; otherwise it's just the OperationCanceledException. } catch (Exception ex) { if (cancellationToken.IsCancellationRequested) { LogPermanentFailure(ex); throw; } LogTransientFailure(ex); exception = ex; // Hold onto this exception so that if the next time around we just time out then we can rethrow the actual assertion-failure one. try { await Task.Delay(delay, cancellationToken); delay = timing.Backoff switch { Backoff.None => delay, Backoff.Linear => delay + timing.MinDelay, Backoff.Exponential => delay + delay, _ => throw new ArgumentException($"Unexpected backoff value of {timing.Backoff}") }; if (delay > timing.MaxDelay) delay = timing.MaxDelay; } catch (OperationCanceledException) { LogPermanentFailure(exception); ExceptionDispatchInfo.Capture(exception).Throw(); } } } void LogSuccess() { var elapsed = stopwatch.Elapsed; logger.Info($"Eventual assertion succeeded after {elapsed} {elapsed.TotalMilliseconds}"); } void LogTransientFailure(Exception exception) { var elapsed = stopwatch.Elapsed; if (elapsed - elapsedTimeAtLastTransientFailure > TimeBetweenLoggingEachTransientFailure) { elapsedTimeAtLastTransientFailure = elapsed; logger.Verbose( $"Eventual assertion failed after {elapsed} {elapsed.TotalMilliseconds} with message {exception.Message}. Will retry if there is time. Error: {exception.Message}"); } } void LogPermanentFailure(Exception exception) { var elapsed = stopwatch.Elapsed; logger.ErrorFormat( $"Eventual assertion failed after {elapsed} {elapsed.TotalMilliseconds} with message {exception.Message}. {exception}"); } public record struct Timing(TimeSpan MinDelay, TimeSpan MaxDelay, Backoff Backoff) { /// <summary> /// Default timing behaviour which is 1 second retry, with exponential backoff (double each time) up to 5 seconds /// </summary> public static Timing Default { get; } = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), Backoff.Exponential); /// <summary> /// Timing behaviour with no delay between retries /// </summary> public static Timing NoDelay { get; } = new(TimeSpan.Zero, TimeSpan.Zero, Backoff.None); public static Timing Fast { get; } = new(TimeSpan.FromSeconds(0.25), TimeSpan.FromSeconds(2), Backoff.Linear); } } } <file_sep>using System; using System.Text; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Calamari.Common.Features.StructuredVariables { public class JsonFormatVariableReplacer : IFileFormatVariableReplacer { readonly ICalamariFileSystem fileSystem; readonly ILog log; public JsonFormatVariableReplacer(ICalamariFileSystem fileSystem, ILog log) { this.log = log; this.fileSystem = fileSystem; } public string FileFormatName => StructuredConfigVariablesFileFormats.Json; public bool IsBestReplacerForFileName(string fileName) { return fileName.EndsWith(".json", StringComparison.InvariantCultureIgnoreCase); } public void ModifyFile(string filePath, IVariables variables) { try { var json = LoadJson(filePath); var map = new JsonUpdateMap(log); map.Load(json.root); map.Update(variables); fileSystem.OverwriteFile(filePath, textWriter => { textWriter.NewLine = json.lineEnding == StringExtensions.LineEnding.Unix ? "\n" : "\r\n"; var jsonWriter = new JsonTextWriter(textWriter); jsonWriter.Formatting = Formatting.Indented; json.root.WriteTo(jsonWriter); }, json.encoding); } catch (JsonReaderException e) { throw new StructuredConfigFileParseException(e.Message, e); } } (JToken root, StringExtensions.LineEnding? lineEnding, Encoding? encoding) LoadJson(string jsonFilePath) { if (!fileSystem.FileExists(jsonFilePath)) return (new JObject(), null, null); var fileText = fileSystem.ReadFile(jsonFilePath, out var encoding); if (fileText.Length == 0) return (new JObject(), null, null); return (JToken.Parse(fileText), fileText.GetMostCommonLineEnding(), encoding); } } }<file_sep>using System; using System.Linq; using Calamari.Common.Plumbing; namespace Calamari.Common.Features.Scripts { public static class ScriptSyntaxHelper { static readonly ScriptSyntax[] ScriptSyntaxPreferencesNonWindows = { ScriptSyntax.Bash, ScriptSyntax.Python, ScriptSyntax.CSharp, ScriptSyntax.FSharp, ScriptSyntax.PowerShell }; static readonly ScriptSyntax[] ScriptSyntaxPreferencesWindows = { ScriptSyntax.PowerShell, ScriptSyntax.Python, ScriptSyntax.CSharp, ScriptSyntax.FSharp, ScriptSyntax.Bash }; public static ScriptSyntax GetPreferredScriptSyntaxForEnvironment() { return CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac ? ScriptSyntaxPreferencesNonWindows.First() : ScriptSyntaxPreferencesWindows.First(); } public static ScriptSyntax[] GetPreferenceOrderedScriptSyntaxesForEnvironment() { return CalamariEnvironment.IsRunningOnNix || CalamariEnvironment.IsRunningOnMac ? ScriptSyntaxPreferencesNonWindows : ScriptSyntaxPreferencesWindows; } } }<file_sep>#!/usr/bin/env bash Green='\033[32m' Yellow='\033[1;33m' NoColour='\033[0m' # No Color StartMessage="${Green}\ ╬════════════════════════════════════════════════════════════════════════════════════════════════╬ ║ ║ ║ This is a helper script for running local Calamari builds, it's going to do the following: ║ ║ * Append a timestamp to the NuGet package versions to give you a unique version number ║ ║ without needing to commit your changes locally ║ ║ * Set the msbuild verbosity to minimal to reduce noise ║ ║ * Create NuGet packages for the various runtimes in parallel ║ ║ * Skip creating .Tests NuGet packages ║ ║ * Set the CalamariVersion property in Octopus.Server.csproj ║ ║ ║ ║ This script is intended to only be run locally and not in CI. ║ ║ ║ ║ If something unexpected is happening in your build or Calamari changes you may want to run ║ ║ the full build by running ./build.ps1 and check again as something in the optimizations here ║ ║ ║ ║ might have caused an issue. ║ ╬════════════════════════════════════════════════════════════════════════════════════════════════╬\ ${NoColour} " WarningMessage="${Yellow}\ ╬════════════════════════════════════════════════════════╬ ║ WARNING: ║ ║ Building Calamari on a non-windows machine will result ║ ║ in Calmari and Calamari.Cloud nuget packages being ║ ║ built against net6.0. This means that some ║ ║ steps may not work as expected because they require a ║ ║ .Net Framework compatible Calamari Nuget Package. ║ ╬════════════════════════════════════════════════════════╬\ ${NoColour}" FinishMessage="${Green}\ ╬══════════════════════════════════════════════════════════════════════════════════════╬ ║ ║ ║ Local build complete, restart your Octopus Server to test your Calamari changes :) ║ ║ ║ ╬══════════════════════════════════════════════════════════════════════════════════════╬\ ${NoColour}" echo -e "$StartMessage" echo -e "$WarningMessage" read -p "Are you sure you want to continue? (Y,n): " option if ! [[ -z "$option" ]] && ! [[ "$option" == 'Y' ]] && ! [[ "$option" == 'y' ]] then echo "Build Cancelled." exit 0; fi ./build.sh -BuildVerbosity Minimal -Verbosity Minimal -PackInParallel -AppendTimestamp -SetOctopusServerVersion echo -e "$FinishMessage" <file_sep>using System; using System.Collections.Generic; using Calamari.LaunchTools; using Calamari.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Calamari.Tests.Fixtures.Manifest { public class InstructionBuilder { readonly List<Instruction> instructions = new List<Instruction>(); InstructionBuilder() { } public static InstructionBuilder Create() { return new InstructionBuilder(); } public InstructionBuilder WithCalamariInstruction(string commandName, object inputs) { instructions.Add( new Instruction { Launcher = Calamari.LaunchTools.LaunchTools.Calamari, LauncherInstructions = JsonConvert.SerializeObject(new CalamariInstructions { Command = commandName, Inputs = JObject.FromObject(inputs) }, JsonSerialization.GetDefaultSerializerSettings()) }); return this; } public InstructionBuilder WithNodeInstruction() { instructions.Add(new Instruction { Launcher = Calamari.LaunchTools.LaunchTools.Node, LauncherInstructions = JsonConvert.SerializeObject(new NodeInstructions { BootstrapperPathVariable = nameof(NodeInstructions.BootstrapperPathVariable), NodePathVariable = nameof(NodeInstructions.NodePathVariable), TargetPathVariable = nameof(NodeInstructions.TargetPathVariable), InputsVariable = nameof(NodeInstructions.InputsVariable), DeploymentTargetInputsVariable = nameof(NodeInstructions.DeploymentTargetInputsVariable), BootstrapperInvocationCommand = "Execute" }, JsonSerialization.GetDefaultSerializerSettings()) }); return this; } public string AsString() { return JsonConvert.SerializeObject(instructions, JsonSerialization.GetDefaultSerializerSettings()); } } }<file_sep>using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Conventions { public class StageScriptPackagesConvention : IInstallConvention { private readonly string? packagePathContainingScript; private readonly ICalamariFileSystem fileSystem; private readonly IPackageExtractor extractor; private readonly bool forceExtract; public StageScriptPackagesConvention(string? packagePathContainingScript, ICalamariFileSystem fileSystem, IPackageExtractor extractor, bool forceExtract = false) { this.packagePathContainingScript = packagePathContainingScript; this.fileSystem = fileSystem; this.extractor = extractor; this.forceExtract = forceExtract; } public void Install(RunningDeployment deployment) { // If the script is contained in a package, then extract the containing package in the working directory if (!string.IsNullOrWhiteSpace(packagePathContainingScript)) { ExtractPackage(packagePathContainingScript, deployment.CurrentDirectory); deployment.Variables.Set(KnownVariables.OriginalPackageDirectoryPath, deployment.CurrentDirectory); } // Stage any referenced packages (i.e. packages that don't contain the script) // The may or may not be extracted. StagePackageReferences(deployment); } void StagePackageReferences(RunningDeployment deployment) { var variables = deployment.Variables; // No need to check for "default" package since it gets extracted in the current directory in previous step. var packageReferenceNames = variables.GetIndexes(PackageVariables.PackageCollection) .Where(i => !string.IsNullOrEmpty(i)); foreach (var packageReferenceName in packageReferenceNames) { Log.Verbose($"Considering '{packageReferenceName}' for extraction"); var sanitizedPackageReferenceName = fileSystem.RemoveInvalidFileNameChars(packageReferenceName); var packageOriginalPath = variables.Get(PackageVariables.IndexedOriginalPath(packageReferenceName)); if (string.IsNullOrWhiteSpace(packageOriginalPath)) { Log.Info($"Package '{packageReferenceName}' was not acquired or does not require staging"); continue; } packageOriginalPath = Path.GetFullPath(variables.Get(PackageVariables.IndexedOriginalPath(packageReferenceName))); // In the case of container images, the original path is not a file-path. We won't try and extract or move it. if (!fileSystem.FileExists(packageOriginalPath)) { Log.Verbose($"Package '{packageReferenceName}' was not found at '{packageOriginalPath}', skipping extraction"); continue; } var shouldExtract = variables.GetFlag(PackageVariables.IndexedExtract(packageReferenceName)); if (forceExtract || shouldExtract) { var extractionPath = Path.Combine(deployment.CurrentDirectory, sanitizedPackageReferenceName); ExtractPackage(packageOriginalPath, extractionPath); Log.SetOutputVariable(SpecialVariables.Packages.ExtractedPath(packageReferenceName), extractionPath, variables); } else { var localPackageFileName = sanitizedPackageReferenceName + Path.GetExtension(packageOriginalPath); var destinationPackagePath = Path.Combine(deployment.CurrentDirectory, localPackageFileName); Log.Info($"Copying package: '{packageOriginalPath}' -> '{destinationPackagePath}'"); fileSystem.CopyFile(packageOriginalPath, destinationPackagePath); Log.SetOutputVariable(SpecialVariables.Packages.PackageFilePath(packageReferenceName), destinationPackagePath, variables); Log.SetOutputVariable(SpecialVariables.Packages.PackageFileName(packageReferenceName), localPackageFileName, variables); } } } void ExtractPackage(string packageFile, string extractionDirectory) { Log.Info($"Extracting package '{packageFile}' to '{extractionDirectory}'"); if (!File.Exists(packageFile)) throw new CommandException("Could not find package file: " + packageFile); extractor.Extract(packageFile, extractionDirectory); } } }<file_sep>using System; namespace Calamari.Common.Plumbing.ServiceMessages { public class ServiceMessageNames { public static class SetVariable { public const string Name = "setVariable"; public const string NameAttribute = "name"; public const string ValueAttribute = "value"; } public static class CalamariFoundPackage { public const string Name = "calamari-found-package"; } public static class FoundPackage { public const string Name = "foundPackage"; public const string IdAttribute = "id"; public const string VersionAttribute = "version"; public const string VersionFormat = "versionFormat"; public const string HashAttribute = "hash"; public const string RemotePathAttribute = "remotePath"; public const string FileExtensionAttribute = "fileExtension"; } public static class PackageDeltaVerification { public const string Name = "deltaVerification"; public const string RemotePathAttribute = "remotePath"; public const string HashAttribute = "hash"; public const string SizeAttribute = "size"; public const string Error = "error"; } public static class CalamariTimedOperation { public const string Name = "calamari-timed-operation"; public const string NameAttribute = "name"; public const string OperationIdAttribute = "operationId"; public const string DurationMillisecondsAttribute = "durationMilliseconds"; public const string OutcomeAttribute = "outcome"; } public static class CalamariDeploymentMetric { public const string Name = "calamari-deployment-metric"; public const string OperationIdAttribute = "operationId"; public const string MetricAttribute = "metric"; public const string ValueAttribute = "value"; } } }<file_sep>#!/bin/bash set -e nginxTempDir=$(get_octopusvariable "OctopusNginxFeatureTempDirectory") if [ ! -d "$nginxTempDir" ]; then echo >&2 "Unable to find temporary folder '$nginxTempDir'." exit 1 fi nginxConfDir=$(get_octopusvariable "Octopus.Action.Nginx.ConfigurationsDirectory") # Always remove the temporary NGINX config folder trap 'echo "Removing temporary folder ${nginxTempDir}..." && sudo rm -rf $nginxTempDir' exit nginxConfRoot=${nginxConfDir:-/etc/nginx/conf.d} echo "Clearing the existing locations dir" for dir in $nginxTempDir/conf/* do fixedDir=${dir##*/} if [[ -d "$dir" && ! -L "$dir" && -d "$nginxConfRoot/$fixedDir" ]] then sudo rm -rf $nginxConfRoot/$fixedDir fi done echo "Copying $nginxTempDir/conf/* to $nginxConfRoot..." sudo cp -R $nginxTempDir/conf/* $nginxConfRoot -f if [ -d "$nginxTempDir/ssl" ]; then nginxSslDir=$(get_octopusvariable "Octopus.Action.Nginx.CertificatesDirectory") nginxSslDir=${nginxSslDir:-/etc/ssl} echo "Copying $nginxTempDir/ssl/* to $nginxSslDir..." sudo cp -R $nginxTempDir/ssl/* $nginxSslDir -f fi echo "Validating nginx configuration" echo "##octopus[stdout-verbose]" sudo nginx -t 2>&1 echo "##octopus[stdout-default]" echo "Reloading nginx configuration" echo "##octopus[stdout-verbose]" sudo nginx -s reload 2>&1 echo "##octopus[stdout-default]"<file_sep>using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureWebApp { [Command("deploy-azure-web", Description = "Extracts and installs a deployment package to an Azure Web Application")] public class DeployAzureWebCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<AzureWebAppBehaviour>(); yield return resolver.Create<LogAzureWebAppDetailsBehaviour>(); } } }<file_sep>using Calamari.Common.Features.Discovery; using FluentAssertions; using FluentAssertions.Execution; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Discovery { [TestFixture] public class TargetDiscoveryScopeFixture { private const string scopeSpace = "scope-space"; private const string scopeTenant = "scope-tenant"; private const string scopeProject = "scope-project"; private const string scopeEnvironment = "scope-environment"; private const string scopeRole1 = "scope-role-1"; private const string scopeRole2 = "scope-role-2"; private static readonly string[] scopeRoles = new string[] { scopeRole1, scopeRole2 }; private TargetDiscoveryScope sut = new TargetDiscoveryScope( scopeSpace, scopeEnvironment, scopeProject, scopeTenant, scopeRoles, "WorkerPool-1", null); [Test] public void Match_ShouldFail_IfEnvironmentTagIsMissing() { // Arrange var foundTags = new TargetTags( environment: null, role: scopeRole1, project: null, space: null, tenant: null); // Act var result = sut.Match(foundTags); // Assert using (new AssertionScope()) { result.IsSuccess.Should().BeFalse(); result.FailureReasons.Should().ContainSingle().Which.Should().Be( "Missing environment tag. Match requires 'octopus-environment' tag with value 'scope-environment'."); } } [Test] public void Match_ShouldFail_IfEnvironmentTagIsMismatched() { // Arrange var foundTags = new TargetTags( environment: "wrong-environment", role: scopeRole1, project: null, space: null, tenant: null); // Act var result = sut.Match(foundTags); // Assert using (new AssertionScope()) { result.IsSuccess.Should().BeFalse(); result.FailureReasons.Should().ContainSingle().Which.Should().Be( "Mismatched environment tag. Match requires 'octopus-environment' tag with value 'scope-environment', but found 'wrong-environment'."); } } [Test] public void Match_ShouldFail_IfRoleTagIsMissing() { // Arrange var foundTags = new TargetTags( environment: scopeEnvironment, role: null, project: null, space: null, tenant: null); // Act var result = sut.Match(foundTags); // Assert using (new AssertionScope()) { result.IsSuccess.Should().BeFalse(); result.FailureReasons.Should().ContainSingle().Which.Should().Be( "Missing role tag. Match requires 'octopus-role' tag with value from ['scope-role-1', 'scope-role-2']."); } } [Test] public void Match_ShouldFail_IfRoleTagIsMismatched() { // Arrange var foundTags = new TargetTags( environment: scopeEnvironment, role: "wrong-role", project: null, space: null, tenant: null); // Act var result = sut.Match(foundTags); // Assert using (new AssertionScope()) { result.IsSuccess.Should().BeFalse(); result.FailureReasons.Should().ContainSingle().Which.Should().Be( "Mismatched role tag. Match requires 'octopus-role' tag with value from ['scope-role-1', 'scope-role-2'], but found 'wrong-role'."); } } [Test] public void Match_ShouldSucceed_IfRoleAndEnvironmentTagsMatchAndNoOptionalTagsArePresent() { // Arrange var foundTags = new TargetTags( environment: scopeEnvironment, role: scopeRole1, project: null, space: null, tenant: null); // Act var result = sut.Match(foundTags); // Assert result.IsSuccess.Should().BeTrue(); } [Test] public void Match_ShouldCaptureMatchingRole_WhenMatchSucceeds() { // Arrange var foundTags = new TargetTags( environment: scopeEnvironment, role: scopeRole2, project: null, space: null, tenant: null); // Act var result = sut.Match(foundTags); // Assert result.Role.Should().Be(scopeRole2); } [Test] public void Match_ShouldFail_IfMismatchedProjectTagIsPresent() { // Arrange var foundTags = new TargetTags( environment: scopeEnvironment, role: scopeRole1, project: "wrong-project", space: null, tenant: null); // Act var result = sut.Match(foundTags); // Assert using (new AssertionScope()) { result.IsSuccess.Should().BeFalse(); result.FailureReasons.Should().ContainSingle().Which.Should().Be( "Mismatched project tag. Optional 'octopus-project' tag must match 'scope-project' if present, but is 'wrong-project'."); } } [Test] public void Match_ShouldFail_IfMismatchedSpaceTagIsPresent() { // Arrange var foundTags = new TargetTags( environment: scopeEnvironment, role: scopeRole1, project: null, space: "wrong-space", tenant: null); // Act var result = sut.Match(foundTags); // Assert using (new AssertionScope()) { result.IsSuccess.Should().BeFalse(); result.FailureReasons.Should().ContainSingle().Which.Should().Be( "Mismatched space tag. Optional 'octopus-space' tag must match 'scope-space' if present, but is 'wrong-space'."); } } [Test] public void Match_ShouldFail_IfMismatchedTenantTagIsPresent() { // Arrange var foundTags = new TargetTags( environment: scopeEnvironment, role: scopeRole1, project: null, space: null, tenant: "wrong-tenant"); // Act var result = sut.Match(foundTags); // Assert using (new AssertionScope()) { result.IsSuccess.Should().BeFalse(); result.FailureReasons.Should().ContainSingle().Which.Should().Be( "Mismatched tenant tag. Optional 'octopus-tenant' tag must match 'scope-tenant' if present, but is 'wrong-tenant'."); } } [Test] public void Match_ShouldSucceed_IfOptionalTagsAllMatchScope() { // Arrange var foundTags = new TargetTags( environment: scopeEnvironment, role: scopeRole1, project: scopeProject, space: scopeSpace, tenant: scopeTenant); // Act var result = sut.Match(foundTags); // Assert result.IsSuccess.Should().BeTrue(); } [Test] public void Match_ShouldMakeOrdinalCaseInsenitiveComparisons() { // Arrange var foundTags = new TargetTags( environment: "sCoPe-eNvIrOnMeNt", role: "sCoPe-rOlE-1", project: "sCoPe-pRoJeCt", space: "sCoPe-sPaCe", tenant: "sCoPe-tEnAnT"); // Act var result = sut.Match(foundTags); // Assert result.IsSuccess.Should().BeTrue(); } [Test] public void Match_ShouldUseRoleCasingFromScope_WhenSucessful() { // Arrange var foundTags = new TargetTags( environment: "sCoPe-eNvIrOnMeNt", role: "sCoPe-rOlE-1", project: null, space: null, tenant: null); // Act var result = sut.Match(foundTags); // Assert result.Role.Should().Be("scope-role-1"); } [Test] public void Match_ShouldIncludeAllFailureReasons_IfMultipleReasonsExist() { // Arrange var foundTags = new TargetTags( environment: "wrong-environment", role: "wrong-role", project: "wrong-project", space: "wrong-space", tenant: "wrong-tenant"); // Act var result = sut.Match(foundTags); // Assert using (new AssertionScope()) { result.IsSuccess.Should().BeFalse(); result.FailureReasons.Should().Contain("Mismatched environment tag. Match requires 'octopus-environment' tag with value 'scope-environment', but found 'wrong-environment'."); result.FailureReasons.Should().Contain("Mismatched role tag. Match requires 'octopus-role' tag with value from ['scope-role-1', 'scope-role-2'], but found 'wrong-role'."); result.FailureReasons.Should().Contain("Mismatched project tag. Optional 'octopus-project' tag must match 'scope-project' if present, but is 'wrong-project'."); result.FailureReasons.Should().Contain("Mismatched space tag. Optional 'octopus-space' tag must match 'scope-space' if present, but is 'wrong-space'."); result.FailureReasons.Should().Contain("Mismatched tenant tag. Optional 'octopus-tenant' tag must match 'scope-tenant' if present, but is 'wrong-tenant'."); } } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.ConfigurationTransforms; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Octopus.CoreUtilities.Extensions; namespace Calamari.Common.Features.Behaviours { public class ConfigurationTransformsBehaviour : IBehaviour { readonly ICalamariFileSystem fileSystem; readonly IVariables variables; readonly IConfigurationTransformer configurationTransformer; readonly ITransformFileLocator transformFileLocator; readonly ILog log; private readonly string subdirectory; public ConfigurationTransformsBehaviour( ICalamariFileSystem fileSystem, IVariables variables, IConfigurationTransformer configurationTransformer, ITransformFileLocator transformFileLocator, ILog log, string subdirectory = "") { this.fileSystem = fileSystem; this.variables = variables; this.configurationTransformer = configurationTransformer; this.transformFileLocator = transformFileLocator; this.log = log; this.subdirectory = subdirectory; } public bool IsEnabled(RunningDeployment deployment) { return deployment.Variables.IsFeatureEnabled(KnownVariables.Features.ConfigurationTransforms); } public Task Execute(RunningDeployment deployment) { DoTransforms(Path.Combine(deployment.CurrentDirectory, subdirectory)); return this.CompletedTask(); } public void DoTransforms(string currentDirectory) { var explicitTransforms = GetExplicitTransforms(); var automaticTransforms = GetAutomaticTransforms(); var sourceExtensions = GetSourceExtensions(explicitTransforms); var allTransforms = explicitTransforms.Concat(automaticTransforms).ToList(); var transformDefinitionsApplied = new List<XmlConfigTransformDefinition>(); var duplicateTransformDefinitions = new List<XmlConfigTransformDefinition>(); var transformFilesApplied = new HashSet<Tuple<string, string>>(); var diagnosticLoggingEnabled = variables.GetFlag(KnownVariables.Package.EnableDiagnosticsConfigTransformationLogging); if (diagnosticLoggingEnabled) log.Verbose($"Recursively searching for transformation files that match {string.Join(" or ", sourceExtensions)} in folder '{currentDirectory}'"); foreach (var configFile in MatchingFiles(currentDirectory, sourceExtensions)) { if (diagnosticLoggingEnabled) log.Verbose($"Found config file '{configFile}'"); ApplyTransformations(configFile, allTransforms, transformFilesApplied, transformDefinitionsApplied, duplicateTransformDefinitions, diagnosticLoggingEnabled, currentDirectory); } LogFailedTransforms(explicitTransforms, automaticTransforms, transformDefinitionsApplied, duplicateTransformDefinitions, diagnosticLoggingEnabled); variables.SetStrings(KnownVariables.AppliedXmlConfigTransforms, transformFilesApplied.Select(t => t.Item1), "|"); } List<XmlConfigTransformDefinition> GetAutomaticTransforms() { var result = new List<XmlConfigTransformDefinition>(); if (variables.GetFlag(KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles)) { result.Add(new XmlConfigTransformDefinition("Release")); var environment = variables.Get( DeploymentEnvironment.Name); if (!string.IsNullOrWhiteSpace(environment)) { result.Add(new XmlConfigTransformDefinition(environment)); } var tenant = variables.Get(DeploymentVariables.Tenant.Name); if (!string.IsNullOrWhiteSpace(tenant)) { result.Add(new XmlConfigTransformDefinition(tenant)); } } return result; } List<XmlConfigTransformDefinition> GetExplicitTransforms() { var transforms = variables.Get(KnownVariables.Package.AdditionalXmlConfigurationTransforms); if (string.IsNullOrWhiteSpace(transforms)) return new List<XmlConfigTransformDefinition>(); return transforms .Split(',', '\r', '\n') .Select(s => s.Trim()) .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => new XmlConfigTransformDefinition(s)) .ToList(); } void ApplyTransformations(string sourceFile, IEnumerable<XmlConfigTransformDefinition> transformations, ISet<Tuple<string, string>> transformFilesApplied, IList<XmlConfigTransformDefinition> transformDefinitionsApplied, IList<XmlConfigTransformDefinition> duplicateTransformDefinitions, bool diagnosticLoggingEnabled, string currentDirectory) { foreach (var transformation in transformations) { if (diagnosticLoggingEnabled) log.Verbose($" - checking against transform '{transformation}'"); if (transformation.IsTransformWildcard && !sourceFile.EndsWith(GetFileName(transformation.SourcePattern!), StringComparison.OrdinalIgnoreCase)) { if (diagnosticLoggingEnabled) log.Verbose($" - skipping transform as its a wildcard transform and source file \'{sourceFile}\' does not end with \'{GetFileName(transformation.SourcePattern!)}\'"); continue; } try { ApplyTransformations(sourceFile, transformation, transformFilesApplied, transformDefinitionsApplied, duplicateTransformDefinitions, diagnosticLoggingEnabled, currentDirectory); } catch (Exception) { log.ErrorFormat("Could not transform the file '{0}' using the {1}pattern '{2}'.", sourceFile, transformation.IsTransformWildcard ? "wildcard " : "", transformation.TransformPattern); throw; } } } void ApplyTransformations(string sourceFile, XmlConfigTransformDefinition transformation, ISet<Tuple<string, string>> transformFilesApplied, ICollection<XmlConfigTransformDefinition> transformDefinitionsApplied, ICollection<XmlConfigTransformDefinition> duplicateTransformDefinitions, bool diagnosticLoggingEnabled, string currentDirectory) { if (transformation == null) return; var transformFileNames = transformFileLocator.DetermineTransformFileNames(sourceFile, transformation, diagnosticLoggingEnabled, currentDirectory) .Distinct() .ToArray(); foreach (var transformFile in transformFileNames) { var transformFiles = new Tuple<string, string>(transformFile, sourceFile); if (transformFilesApplied.Contains(transformFiles)) { if (diagnosticLoggingEnabled) log.Verbose($" - Skipping as target \'{sourceFile}\' has already been transformed by transform \'{transformFile}\'"); duplicateTransformDefinitions.Add(transformation); continue; } log.Info($"Transforming '{sourceFile}' using '{transformFile}'."); configurationTransformer.PerformTransform(sourceFile, transformFile, sourceFile); transformFilesApplied.Add(transformFiles); transformDefinitionsApplied.Add(transformation); } } string[] GetSourceExtensions(List<XmlConfigTransformDefinition> transformDefinitions) { var extensions = new HashSet<string>(); if (variables.GetFlag(KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles)) { extensions.Add("*.config"); } foreach (var definition in transformDefinitions .Where(transform => transform.Advanced) .Select(transform => "*" + Path.GetExtension(transform.SourcePattern)) .Distinct()) { extensions.Add(definition); } return extensions.ToArray(); } void LogFailedTransforms(IEnumerable<XmlConfigTransformDefinition> configTransform, List<XmlConfigTransformDefinition> automaticTransforms, List<XmlConfigTransformDefinition> transformDefinitionsApplied, List<XmlConfigTransformDefinition> duplicateTransformDefinitions, bool diagnosticLoggingEnabled) { foreach (var transform in configTransform.Except(transformDefinitionsApplied).Except(duplicateTransformDefinitions).Select(trans => trans.ToString()).Distinct()) { log.Verbose($"The transform pattern \"{transform}\" was not performed as no matching files could be found."); if (!diagnosticLoggingEnabled) log.Verbose("For detailed diagnostic logging, please set a variable 'Octopus.Action.Package.EnableDiagnosticsConfigTransformationLogging' with a value of 'True'."); } foreach (var transform in duplicateTransformDefinitions.Except(automaticTransforms).Select(trans => trans.ToString()).Distinct()) { log.VerboseFormat("The transform pattern \"{0}\" was not performed as it overlapped with another transform.", transform); } } [return: NotNullIfNotNull("path")] static string? GetFileName(string? path) { return Path.GetFileName(path); } List<string> MatchingFiles(string currentDirectory, string[] sourceExtensions) { var files = fileSystem.EnumerateFilesRecursively(currentDirectory, sourceExtensions).ToList(); foreach (var path in variables.GetStrings(ActionVariables.AdditionalPaths).Where(s => !string.IsNullOrWhiteSpace(s))) { var pathFiles = fileSystem.EnumerateFilesRecursively(path, sourceExtensions); files.AddRange(pathFiles); } return files; } } }<file_sep>using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment.Journal; using Calamari.Common.Features.Processes.Semaphores; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Retention; using Calamari.Integration.Time; namespace Calamari.Commands { [Command("clean", Description = "Removes packages and files according to the configured retention policy")] public class CleanCommand : Command { readonly IVariables variables; readonly ICalamariFileSystem fileSystem; string retentionPolicySet; int days; int releases; public CleanCommand(IVariables variables, ICalamariFileSystem fileSystem) { this.variables = variables; this.fileSystem = fileSystem; Options.Add("retentionPolicySet=", "The release-policy-set ID", x => retentionPolicySet = x); Options.Add("days=", "Number of days to keep artifacts", x => int.TryParse(x, out days)); //TODO: rename 'releases' to 'deployments' here Options.Add("releases=", "Number of releases to keep artifacts for", x => int.TryParse(x, out releases)); } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); Guard.NotNullOrWhiteSpace(retentionPolicySet, "No retention-policy-set was specified. Please pass --retentionPolicySet \"Environments-2/projects-161/Step-Package B/machines-65/<default>\""); if (days <=0 && releases <= 0) throw new CommandException("A value must be provided for either --days or --releases"); var deploymentJournal = new DeploymentJournal(fileSystem, SemaphoreFactory.Get(), variables); var clock = new SystemClock(); var retentionPolicy = new RetentionPolicy(fileSystem, deploymentJournal, clock); retentionPolicy.ApplyRetentionPolicy(retentionPolicySet, days, releases); return 0; } } }<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Conventions; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class ConditionalConventionFixture { public class TestInstallConvention : IInstallConvention { private readonly Action<RunningDeployment> callback; public TestInstallConvention(Action<RunningDeployment> callback) { this.callback = callback; } public void Install(RunningDeployment deployment) { callback(deployment); } } RunningDeployment deployment; [SetUp] public void SetUp() { deployment = new RunningDeployment("c:\\packages", new CalamariVariables()); } [Test] public void ShouldInstallIfPredicatePasses() { bool didExecute = false; var convention = new TestInstallConvention((_) => didExecute = true).When(_ => true); convention.Install(deployment); didExecute.Should().BeTrue(); } [Test] public void ShouldNotInstallIfPredicateFails() { bool didExecute = false; var convention = new TestInstallConvention((_) => didExecute = true).When(_ => false); convention.Install(deployment); didExecute.Should().BeFalse(); } } } <file_sep>using System; using System.IO; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; using Octopus.CoreUtilities.Extensions; namespace Calamari.Common.Features.Behaviours { public class StructuredConfigurationVariablesBehaviour : IBehaviour { readonly IStructuredConfigVariablesService structuredConfigVariablesService; private readonly string subdirectory; public StructuredConfigurationVariablesBehaviour(IStructuredConfigVariablesService structuredConfigVariablesService, string subdirectory = "") { this.structuredConfigVariablesService = structuredConfigVariablesService; this.subdirectory = subdirectory; } public bool IsEnabled(RunningDeployment context) { return context.Variables.IsFeatureEnabled(KnownVariables.Features.StructuredConfigurationVariables); } public Task Execute(RunningDeployment context) { structuredConfigVariablesService.ReplaceVariables(Path.Combine(context.CurrentDirectory, subdirectory)); return this.CompletedTask(); } } }<file_sep>#if !NET40 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus.Resources; using Newtonsoft.Json.Linq; using Octopus.CoreUtilities.Extensions; namespace Calamari.Kubernetes.Commands.Executors { public interface IGatherAndApplyRawYamlExecutor { Task<bool> Execute(RunningDeployment deployment, Func<ResourceIdentifier[], Task> appliedResourcesCallback = null); } public class GatherAndApplyRawYamlExecutor : IGatherAndApplyRawYamlExecutor { private const string GroupedDirectoryName = "grouped"; private readonly ILog log; private readonly ICalamariFileSystem fileSystem; private readonly Kubectl kubectl; public GatherAndApplyRawYamlExecutor( ILog log, ICalamariFileSystem fileSystem, Kubectl kubectl) { this.log = log; this.fileSystem = fileSystem; this.kubectl = kubectl; } public async Task<bool> Execute(RunningDeployment deployment, Func<ResourceIdentifier[], Task> appliedResourcesCallback) { try { var variables = deployment.Variables; var globs = variables.GetPaths(SpecialVariables.CustomResourceYamlFileName); if (globs.IsNullOrEmpty()) return true; var directories = GroupFilesIntoDirectories(deployment, globs, variables); var resources = new HashSet<Resource>(); foreach (var directory in directories) { var res = ApplyBatchAndReturnResources(directory).ToList(); if (appliedResourcesCallback != null) { await appliedResourcesCallback(res.Select(r => r.ToResourceIdentifier()).ToArray()); } resources.UnionWith(res); } WriteResourcesToOutputVariables(resources); return true; } catch (GatherAndApplyRawYamlException) { return false; } catch (Exception e) { log.Error($"Deployment Failed due to exception: {e.Message}"); return false; } } private void WriteResourcesToOutputVariables(IEnumerable<Resource> resources) { foreach (var resource in resources) { try { var result = kubectl.ExecuteCommandAndReturnOutput("get", resource.Kind, resource.Metadata.Name, "-o", "json"); log.WriteServiceMessage(new ServiceMessage(ServiceMessageNames.SetVariable.Name, new Dictionary<string, string> { {ServiceMessageNames.SetVariable.NameAttribute, $"CustomResources({resource.Metadata.Name})"}, {ServiceMessageNames.SetVariable.ValueAttribute, result.Output.InfoLogs.Join("\n")} })); } catch { log.Warn( $"Could not save json for resource to output variable for '{resource.Kind}/{resource.Metadata.Name}'"); } } } private IEnumerable<GlobDirectory> GroupFilesIntoDirectories(RunningDeployment deployment, List<string> globs, IVariables variables) { var stagingDirectory = deployment.CurrentDirectory; var packageDirectory = Path.Combine(stagingDirectory, KubernetesDeploymentCommandBase.PackageDirectoryName) + Path.DirectorySeparatorChar; var directories = new List<GlobDirectory>(); for (var i = 1; i <= globs.Count; i ++) { var glob = globs[i-1]; var directoryPath = Path.Combine(stagingDirectory, GroupedDirectoryName, i.ToString()); var directory = new GlobDirectory(i, glob, directoryPath); fileSystem.CreateDirectory(directoryPath); var globMode = GlobModeRetriever.GetFromVariables(variables); var results = fileSystem.EnumerateFilesWithGlob(packageDirectory, globMode, glob); foreach (var file in results) { var relativeFilePath = fileSystem.GetRelativePath(packageDirectory, file); var targetPath = Path.Combine(directoryPath, relativeFilePath); var targetDirectory = Path.GetDirectoryName(targetPath); if (targetDirectory != null) { fileSystem.CreateDirectory(targetDirectory); } fileSystem.CopyFile(file, targetPath); } directories.Add(directory); } variables.Set(SpecialVariables.GroupedYamlDirectories, string.Join(";", directories.Select(d => d.Directory))); return directories; } private IEnumerable<Resource> ApplyBatchAndReturnResources(GlobDirectory globDirectory) { var index = globDirectory.Index; var directoryWithTrailingSlash = globDirectory.Directory + Path.DirectorySeparatorChar; log.Info($"Applying Batch #{index} for YAML matching '{globDirectory.Glob}'"); var files = fileSystem.EnumerateFilesRecursively(globDirectory.Directory).ToArray(); if (!files.Any()) { log.Warn($"No files found matching '{globDirectory.Glob}'"); return Enumerable.Empty<Resource>(); } foreach (var file in files) { log.Verbose($"Matched file: {fileSystem.GetRelativePath(directoryWithTrailingSlash, file)}"); } var result = kubectl.ExecuteCommandAndReturnOutput("apply", "-f", $@"""{globDirectory.Directory}""", "--recursive", "-o", "json"); foreach (var message in result.Output.Messages) { switch (message.Level) { case Level.Info: //No need to log as it's the output json from above. break; case Level.Error: //Files in the error are shown with the full path in their batch directory, //so we'll remove that for the user. log.Error(message.Text.Replace($"{directoryWithTrailingSlash}", "")); break; default: throw new ArgumentOutOfRangeException(); } } if (result.Result.ExitCode != 0) { LogParsingError(null, index); } // If it did not error, the output should be valid json. var outputJson = result.Output.InfoLogs.Join(Environment.NewLine); try { var token = JToken.Parse(outputJson); List<Resource> lastResources; if (token["kind"]?.ToString() != "List" || (lastResources = token["items"]?.ToObject<List<Resource>>()) == null) { lastResources = new List<Resource> { token.ToObject<Resource>() }; } var resources = lastResources.Select(r => r.ToResourceIdentifier()).ToList(); if (resources.Any()) { log.Verbose("Created Resources:"); log.LogResources(resources); } return lastResources; } catch { LogParsingError(outputJson, index); } return Enumerable.Empty<Resource>(); } private void LogParsingError(string outputJson, int index) { log.Error($"\"kubectl apply -o json\" returned invalid JSON for Batch #{index}:"); log.Error("---------------------------"); log.Error(outputJson); log.Error("---------------------------"); log.Error("This can happen with older versions of kubectl. Please update to a recent version of kubectl."); log.Error("See https://github.com/kubernetes/kubernetes/issues/58834 for more details."); log.Error("Custom resources will not be saved as output variables."); throw new GatherAndApplyRawYamlException(); } private class ResourceMetadata { public string Namespace { get; set; } public string Name { get; set; } } private class Resource { public string Kind { get; set; } public ResourceMetadata Metadata { get; set; } public ResourceIdentifier ToResourceIdentifier() { return new ResourceIdentifier(Kind, Metadata.Name, Metadata.Namespace); } } private class GatherAndApplyRawYamlException : Exception { } private class GlobDirectory { public GlobDirectory(int index, string glob, string directory) { Index = index; Glob = glob; Directory = directory; } public int Index { get; } public string Glob { get; } public string Directory { get; } } } } #endif<file_sep>using System; using System.Net; using System.Net.Sockets; using Calamari.Common.Plumbing.Logging; using Octopus.CoreUtilities; namespace Calamari.Common.Plumbing.Proxies { public static class SystemWebProxyRetriever { public static Maybe<IWebProxy> GetSystemWebProxy() { try { var TestUri = new Uri("http://test9c7b575efb72442c85f706ef1d64afa6.com"); var systemWebProxy = WebRequest.GetSystemWebProxy(); var proxyUri = systemWebProxy.GetProxy(TestUri); if (proxyUri == null) return Maybe<IWebProxy>.None; return proxyUri.Host != TestUri.Host ? systemWebProxy.AsSome() : Maybe<IWebProxy>.None; } catch (SocketException) { /* Ignore this exception. It is probably just an inability to get the IE proxy settings. e.g. Unhandled Exception: System.Net.Sockets.SocketException: The requested service provider could not be loaded or initialized at System.Net.SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, Boolean autoReset, Boolean signaled) at System.Net.NetworkAddressChangePolled..ctor() at System.Net.AutoWebProxyScriptEngine.AutoDetector.Initialize() at System.Net.AutoWebProxyScriptEngine.AutoDetector.get_CurrentAutoDetector() at System.Net.AutoWebProxyScriptEngine..ctor(WebProxy proxy, Boolean useRegistry) at System.Net.WebProxy.UnsafeUpdateFromRegistry() at System.Net.WebRequest.InternalGetSystemWebProxy() at System.Net.WebRequest.GetSystemWebProxy() at Calamari.Integration.Proxies.ProxyInitializer.InitializeDefaultProxy() at Calamari.Program.Execute(String[] args) at Calamari.Program.Main(String[] args) */ Log.Error("Failed to get the system proxy settings. Calamari will not use any proxy settings."); return Maybe<IWebProxy>.None; } } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Pipeline; using Calamari.Terraform.Behaviours; namespace Calamari.Terraform.Commands { public abstract class TerraformCommand : PipelineCommand { protected override bool IncludeConfiguredScriptBehaviour => false; protected override bool IncludePackagedScriptBehaviour => false; protected override IEnumerable<IPreDeployBehaviour> PreDeploy(PreDeployResolver resolver) { yield return resolver.Create<TerraformSubstituteBehaviour>(); } } }<file_sep>using System; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Newtonsoft.Json; namespace Calamari.Deployment.PackageRetention.Model { public class UsageDetails : IUsageDetails { public CacheAge CacheAgeAtUsage { get; } public DateTime DateTime { get; } public ServerTaskId DeploymentTaskId { get; } /// <summary> Defaults DateTime to DateTime.Now </summary> public UsageDetails(ServerTaskId deploymentTaskId, CacheAge cacheAge) : this(deploymentTaskId, cacheAge, DateTime.Now) { } [JsonConstructor] public UsageDetails(ServerTaskId deploymentTaskId, CacheAge cacheAgeAtUsage, DateTime dateTime) { CacheAgeAtUsage = cacheAgeAtUsage; DateTime = dateTime; DeploymentTaskId = deploymentTaskId; } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT #nullable disable using System; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles; namespace Calamari.Integration.Certificates.WindowsNative { internal static class WindowsX509Native { [DllImport("Crypt32.dll", SetLastError = true)] public static extern SafeCertStoreHandle CertOpenStore(CertStoreProviders lpszStoreProvider, IntPtr notUsed, IntPtr notUsed2, CertificateSystemStoreLocation location, [MarshalAs(UnmanagedType.LPWStr)] string storeName); [DllImport("Crypt32.dll", SetLastError = true)] public static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags); [DllImport("Crypt32.dll", SetLastError = true)] public static extern SafeCertStoreHandle PFXImportCertStore(ref CryptoData pPfx, [MarshalAs(UnmanagedType.LPWStr)] string szPassword, PfxImportFlags dwFlags); [DllImport("Crypt32.dll", SetLastError = true)] public static extern bool CertAddCertificateContextToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, AddCertificateDisposition dwAddDisposition, ref IntPtr ppStoreContext); [DllImport("Crypt32.dll", SetLastError = true)] public static extern SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertificateEncodingType dwCertEncodingType, IntPtr notUsed, CertificateFindType dwFindType, ref CryptoData pvFindPara, IntPtr pPrevCertContext); [DllImport("Crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeCertContextHandle CertDuplicateCertificateContext(IntPtr pCertContext); [DllImport("Crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")] public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStringType pvPara, [Out] StringBuilder pszNameString, int cchNameString); [DllImport("Crypt32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CertCompareCertificateName(CertificateEncodingType dwCertEncodingType, ref CryptoData pCertName1, ref CryptoData pCertName2); [DllImport("Crypt32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CertGetCertificateContextProperty(IntPtr pCertContext, CertificateProperty dwPropId, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pvData, [In, Out] ref int pcbData); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CryptAcquireContextW")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CryptAcquireContext(out IntPtr psafeProvHandle, [MarshalAs(UnmanagedType.LPWStr)] string pszContainer, [MarshalAs(UnmanagedType.LPWStr)] string pszProvider, int dwProvType, CryptAcquireContextFlags dwFlags); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CryptGetProvParam(SafeCspHandle hProv, CspProperties dwParam, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData, ref int pdwDataLen, SecurityDesciptorParts dwFlags); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CryptSetProvParam(SafeCspHandle hProv, CspProperties dwParam, [In] byte[] pbData, SecurityDesciptorParts dwFlags); [DllImport("Crypt32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert, AcquireCertificateKeyOptions dwFlags, IntPtr pvReserved, // void * [Out] out SafeCspHandle phCryptProvOrNCryptKey, [Out] out int dwKeySpec, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfCallerFreeProvOrNCryptKey); [DllImport("Crypt32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert, AcquireCertificateKeyOptions dwFlags, IntPtr pvReserved, // void * [Out] out SafeNCryptKeyHandle phCryptProvOrNCryptKey, [Out] out int dwKeySpec, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfCallerFreeProvOrNCryptKey); [DllImport("Crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CertEnumSystemStore(CertificateSystemStoreLocation dwFlags, IntPtr notUsed1, IntPtr notUsed2, CertEnumSystemStoreCallBackProto fn); /// <summary> /// signature of call back function used by CertEnumSystemStore /// </summary> internal delegate bool CertEnumSystemStoreCallBackProto( [MarshalAs(UnmanagedType.LPWStr)] string storeName, uint dwFlagsNotUsed, IntPtr notUsed1, IntPtr notUsed2, IntPtr notUsed3); [DllImport("Ncrypt.dll", SetLastError = true, ExactSpelling = true)] internal static extern int NCryptGetProperty(SafeNCryptHandle hObject, [MarshalAs(UnmanagedType.LPWStr)] string szProperty, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbOutput, int cbOutput, ref int pcbResult, int flags); [DllImport("Ncrypt.dll", SetLastError = true, ExactSpelling = true)] internal static extern int NCryptSetProperty(SafeNCryptHandle hObject, [MarshalAs(UnmanagedType.LPWStr)] string szProperty, IntPtr pbInputByteArray, int cbInput, int flags); [DllImport("Ncrypt.dll")] internal static extern int NCryptDeleteKey(SafeNCryptKeyHandle hKey, int flags); [Flags] internal enum CertStoreProviders { CERT_STORE_PROV_SYSTEM = 10 } internal enum AddCertificateDisposition { CERT_STORE_ADD_NEW = 1, CERT_STORE_ADD_REPLACE_EXISTING = 3 } internal enum CertificateSystemStoreLocation { CurrentUser = 1 << 16, // CERT_SYSTEM_STORE_CURRENT_USER LocalMachine = 2 << 16, // CERT_SYSTEM_STORE_LOCAL_MACHINE CurrentService = 4 << 16, // CERT_SYSTEM_STORE_CURRENT_SERVICE Services = 5 << 16, // CERT_SYSTEM_STORE_SERVICES Users = 6 << 16, // CERT_SYSTEM_STORE_USERS UserGroupPolicy = 7 << 16, // CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY MachineGroupPolicy = 8 << 16, // CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY LocalMachineEnterprise = 9 << 16, // CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE } internal enum CertificateFindType { Sha1Hash = 1 << 16 // CERT_FIND_SHA1_HASH } [Flags] internal enum CertificateEncodingType { X509AsnEncoding = 0x00000001, // X509_ASN_ENCODING Pkcs7AsnEncoding = 0x00010000, // PKCS_7_ASN_ENCODING Pkcs7OrX509AsnEncoding = X509AsnEncoding | Pkcs7AsnEncoding } internal enum CertNameType { CERT_NAME_EMAIL_TYPE = 1, CERT_NAME_RDN_TYPE = 2, CERT_NAME_ATTR_TYPE = 3, CERT_NAME_SIMPLE_DISPLAY_TYPE = 4, CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5, CERT_NAME_DNS_TYPE = 6, CERT_NAME_URL_TYPE = 7, CERT_NAME_UPN_TYPE = 8, } [Flags] internal enum CertNameFlags { None = 0x00000000, CERT_NAME_ISSUER_FLAG = 0x00000001, } [Flags] internal enum CertNameStringType { CERT_X500_NAME_STR = 3, CERT_NAME_STR_REVERSE_FLAG = 0x02000000, } // CRYPTOAPI_BLOB [StructLayout(LayoutKind.Sequential)] public struct CryptoData { public int cbData; public IntPtr pbData; } [StructLayout(LayoutKind.Sequential)] internal struct KeyProviderInfo { [MarshalAs(UnmanagedType.LPWStr)] internal string pwszContainerName; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszProvName; internal int dwProvType; internal int dwFlags; internal int cProvParam; internal IntPtr rgProvParam; // PCRYPT_KEY_PROV_PARAM internal int dwKeySpec; } [Flags] public enum PfxImportFlags { CRYPT_EXPORTABLE = 0x00000001, CRYPT_MACHINE_KEYSET = 0x00000020, CRYPT_USER_KEYSET = 0x00001000, PKCS12_PREFER_CNG_KSP = 0x00000100, PKCS12_ALWAYS_CNG_KSP = 0x00000200 } /// <summary> /// Well known certificate property IDs /// </summary> public enum CertificateProperty { KeyProviderInfo = 2, // CERT_KEY_PROV_INFO_PROP_ID KeyContext = 5, // CERT_KEY_CONTEXT_PROP_ID } /// <summary> /// Flags for the CryptAcquireCertificatePrivateKey API /// </summary> [Flags] internal enum AcquireCertificateKeyOptions { None = 0x00000000, AcquireSilent = 0x00000040, AcquireAllowNCryptKeys = 0x00010000, // CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG AcquireOnlyNCryptKeys = 0x00040000, // CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG } [Flags] internal enum CryptAcquireContextFlags { None = 0x00000000, Delete = 0x00000010, // CRYPT_DELETEKEYSET MachineKeySet = 0x00000020, // CRYPT_MACHINE_KEYSET Silent = 0x40 // CRYPT_SILENT } public enum CspProperties { SecurityDescriptor = 0x8 // PP_KEYSET_SEC_DESCR } public static class NCryptProperties { public const string SecurityDescriptor = "Security Descr"; // NCRYPT_SECURITY_DESCR_PROPERTY } [Flags] public enum NCryptFlags { Silent = 0x00000040, } public enum SecurityDesciptorParts { DACL_SECURITY_INFORMATION = 0x00000004 } public enum NCryptErrorCode { Success = 0x00000000, // ERROR_SUCCESS BufferTooSmall = unchecked((int) 0x80090028), // NTE_BUFFER_TOO_SMALL } [StructLayout(LayoutKind.Sequential)] internal struct CERT_CONTEXT { public CertificateEncodingType dwCertEncodingType; public IntPtr pbCertEncoded; public int cbCertEncoded; public IntPtr pCertInfo; public IntPtr hCertStore; } public enum CapiErrorCode { CRYPT_E_EXISTS = unchecked((int) 0x80092005) } [StructLayout(LayoutKind.Sequential)] internal struct CERT_INFO { public int dwVersion; public CryptoData SerialNumber; public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; public CryptoData Issuer; public FILETIME NotBefore; public FILETIME NotAfter; public CryptoData Subject; public CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; public CRYPT_BIT_BLOB IssuerUniqueId; public CRYPT_BIT_BLOB SubjectUniqueId; public int cExtension; public IntPtr rgExtension; } [StructLayout(LayoutKind.Sequential)] internal struct FILETIME { private uint ftTimeLow; private uint ftTimeHigh; public DateTime ToDateTime() { long fileTime = (((long) ftTimeHigh) << 32) + ftTimeLow; return DateTime.FromFileTime(fileTime); } public static FILETIME FromDateTime(DateTime dt) { long fileTime = dt.ToFileTime(); return new FILETIME() { ftTimeLow = (uint) fileTime, ftTimeHigh = (uint) (fileTime >> 32), }; } } [StructLayout(LayoutKind.Sequential)] internal struct CERT_PUBLIC_KEY_INFO { public CRYPT_ALGORITHM_IDENTIFIER Algorithm; public CRYPT_BIT_BLOB PublicKey; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_ALGORITHM_IDENTIFIER { public IntPtr pszObjId; public CryptoData Parameters; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_BIT_BLOB { public int cbData; public IntPtr pbData; public int cUnusedBits; } } } #endif<file_sep>using System; using System.IO; using System.Security.Cryptography; using System.Text; using Calamari.Aws.Deployment.Conventions; using Calamari.Aws.Integration.S3; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.AWS.S3 { [TestFixture] public class BucketKeyProviderFixture { IBucketKeyProvider sut; [SetUp] public void Setup() { sut = new BucketKeyProvider(); } [Test] public void PackageFilenameBehaviorUsesDefaultWithPrefix() { var result = sut.GetBucketKey("default", new S3PackageOptions { BucketKeyPrefix = "test/", BucketKey = "something", BucketKeyBehaviour = BucketKeyBehaviourType.Filename }); result.Should().Be("test/default"); } [Test] public void PackageCustomBehaviorUsesProvidedBucketKey() { var result = sut.GetBucketKey("default", new S3PackageOptions { BucketKeyPrefix = "test/", BucketKey = "something", BucketKeyBehaviour = BucketKeyBehaviourType.Custom }); result.Should().Be("something"); } [Test] public void SingleSelectionFilenameBehaviorUsesDefaultWithPrefix() { var result = sut.GetBucketKey("default", new S3SingleFileSelectionProperties { BucketKeyBehaviour = BucketKeyBehaviourType.Filename, BucketKeyPrefix = "test/", BucketKey = "something" }); result.Should().Be("test/default"); } [Test] public void SingleFileSelectionCustomBehaviorUsesProvidedBucketKey() { var result = sut.GetBucketKey("default", new S3SingleFileSelectionProperties { BucketKeyBehaviour = BucketKeyBehaviourType.Custom, BucketKeyPrefix = "test/", BucketKey = "something" }); result.Should().Be("something"); } [Test] public void EncodeBucketKeyForUrl_ShouldEncodeFileName() { var bucketKey = "dir/subdir/filename@ABC.extension"; var result = sut.EncodeBucketKeyForUrl(bucketKey); result.Should().Be("dir/subdir/filename%40ABC.extension"); } [Test] public void EncodeBucketKeyForUrl_ShouldReturnInputStringIfNoEncodingRequired() { var bucketKey = "dir/subdir/filename.extension"; var result = sut.EncodeBucketKeyForUrl(bucketKey); result.Should().Be("dir/subdir/filename.extension"); } [Test] public void EncodeBucketKeyForUrl_ShouldEncodedFileNameIfThereNoPrefixes() { var bucketKey = "filename@ABC.extension"; var result = sut.EncodeBucketKeyForUrl(bucketKey); result.Should().Be("filename%40ABC.extension"); } [Test] public void GetBucketKey_PackageOptions_ShouldAppendContentHash() { var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", "TestZipPackage.1.0.0.zip"); var packageContentHash = CalculateContentHash(packageFilePath); var fileName = "defaultKey"; var result = sut.GetBucketKey($"{fileName}.zip", new S3PackageOptions { BucketKeyPrefix = "test/", BucketKey = "something", BucketKeyBehaviour = BucketKeyBehaviourType.FilenameWithContentHash }, packageFilePath ); result.Should().Be($"test/{fileName}@{packageContentHash}.zip"); } [Test] public void GetBucketKey_PackageOptions_ShouldNotAppendContentHash_WhenPackageFilePathNotFound() { var fileName = "defaultKey"; var result = sut.GetBucketKey($"{fileName}.zip", new S3PackageOptions { BucketKeyPrefix = "test/", BucketKey = "something", BucketKeyBehaviour = BucketKeyBehaviourType.FilenameWithContentHash }, String.Empty ); result.Should().Be($"test/{fileName}.zip"); } [Test] public void GetBucketKey_PackageOptions_ShouldAppendContentHash_WhenExtensionHasMultipleParts() { var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", "TestZipPackage.1.0.0.zip"); var packageContentHash = CalculateContentHash(packageFilePath); var fileName = "defaultKey"; var result = sut.GetBucketKey($"{fileName}.tar.gz", new S3PackageOptions { BucketKeyPrefix = "test/", BucketKey = "something", BucketKeyBehaviour = BucketKeyBehaviourType.FilenameWithContentHash }, packageFilePath ); result.Should().Be($"test/{fileName}@{packageContentHash}.tar.gz"); } [Test] public void GetBucketKey_PackageOptions_ShouldAppendContentHash_WhenFileNameHasVersionNumbers() { var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", "TestZipPackage.1.0.0.zip"); var packageContentHash = CalculateContentHash(packageFilePath); var fileName = "defaultKey.1.0.0"; var result = sut.GetBucketKey($"{fileName}.tar.gz", new S3PackageOptions { BucketKeyPrefix = "test/", BucketKey = "something", BucketKeyBehaviour = BucketKeyBehaviourType.FilenameWithContentHash }, packageFilePath ); result.Should().Be($"test/{fileName}@{packageContentHash}.tar.gz"); } [Test] public void GetBucketKey_PackageOptions_ShouldAppendContentHash_WhenFileNameHasVersionNumbersAndReleaseTag() { var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", "TestZipPackage.1.0.0.zip"); var packageContentHash = CalculateContentHash(packageFilePath); var fileName = "defaultKey.1.0.0-beta"; var result = sut.GetBucketKey($"{fileName}.tar.gz", new S3PackageOptions { BucketKeyPrefix = "test/", BucketKey = "something", BucketKeyBehaviour = BucketKeyBehaviourType.FilenameWithContentHash }, packageFilePath ); result.Should().Be($"test/{fileName}@{packageContentHash}.tar.gz"); } [Test] public void GetBucketKey_PackageOptions_ShouldSubstituteContentHashVariable() { var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", "TestZipPackage.1.0.0.zip"); var packageContentHash = CalculateContentHash(packageFilePath); var fileName = "defaultKey"; var result = sut.GetBucketKey($"{fileName}.zip", new S3PackageOptions { BucketKeyPrefix = "test", BucketKey = "something/#{Octopus.Action.Package.PackageContentHash}/customFileName.zip", BucketKeyBehaviour = BucketKeyBehaviourType.Custom }, packageFilePath ); result.Should().Be($"something/{packageContentHash}/customFileName.zip"); } static string CalculateContentHash(string packageFilePath) { var packageContent = File.ReadAllBytes(packageFilePath); using (SHA256 sha256Hash = SHA256.Create()) { var computedHashByte = sha256Hash.ComputeHash(packageContent); var computedHash = new StringBuilder(); foreach (var c in computedHashByte) { computedHash.Append(c.ToString("X2")); } return computedHash.ToString(); } } } }<file_sep>#if NETCORE using System; using System.Collections.Generic; using Calamari.Aws.Kubernetes.Discovery; using Calamari.Kubernetes; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures { /// <remarks> /// This is a special test fixture, that gets remotely executed on the cluster created by the test /// Calamari.Tests.KubernetesFixtures.KubernetesContextScriptWrapperLiveFixture.UsingEc2Instance /// (see Terraform/EC2/ec2.kubernetes.tf and Terraform/EC2/test.sh) /// /// It's allowed to access environment variables directly because of this specialness. /// It's ignored from direct runs locally or on CI using the [Explicit] attribute. /// </remarks> [TestFixture] [Explicit] public class KubernetesContextScriptWrapperLiveFixtureForEc2Instance : KubernetesContextScriptWrapperLiveFixtureBase { string eksIamRolArn; string region; string eksClusterArn; string eksClusterName; string eksClusterEndpoint; [OneTimeSetUp] public void OneTimeSetup() { region = Environment.GetEnvironmentVariable("AWS_REGION"); eksIamRolArn = Environment.GetEnvironmentVariable("AWS_IAM_ROLE_ARN"); eksClusterArn = Environment.GetEnvironmentVariable("AWS_CLUSTER_ARN"); eksClusterName = Environment.GetEnvironmentVariable("AWS_CLUSTER_NAME"); eksClusterEndpoint = Environment.GetEnvironmentVariable("AWS_CLUSTER_URL"); } [Test] [TestCase(true)] [TestCase(false)] public void AuthoriseWithAmazonEC2Role(bool runAsScript) { variables.Set(Deployment.SpecialVariables.Account.AccountType, "AmazonWebServicesAccount"); variables.Set(SpecialVariables.ClusterUrl, eksClusterEndpoint); variables.Set(SpecialVariables.EksClusterName, eksClusterName); variables.Set(SpecialVariables.SkipTlsVerification, Boolean.TrueString); variables.Set("Octopus.Action.Aws.AssumeRole", Boolean.FalseString); variables.Set("Octopus.Action.Aws.Region", region); if (runAsScript) { DeployWithKubectlTestScriptAndVerifyResult(); } else { ExecuteCommandAndVerifyResult(TestableKubernetesDeploymentCommand.Name); } } [Test] public void DiscoverKubernetesClusterWithEc2InstanceCredentialsAndIamRole() { var authenticationDetails = new AwsAuthenticationDetails { Type = "Aws", Credentials = new AwsCredentials { Type = "worker" }, Role = new AwsAssumedRole { Type = "assumeRole", Arn = eksIamRolArn }, Regions = new[] { region } }; var serviceMessageProperties = new Dictionary<string, string> { { "name", eksClusterArn }, { "clusterName", eksClusterName }, { "clusterUrl", eksClusterEndpoint }, { "skipTlsVerification", bool.TrueString }, { "octopusDefaultWorkerPoolIdOrName", "WorkerPools-1" }, { "octopusRoles", "discovery-role" }, { "updateIfExisting", bool.TrueString }, { "isDynamic", bool.TrueString }, { "awsUseWorkerCredentials", bool.TrueString }, { "awsAssumeRole", bool.TrueString }, { "awsAssumeRoleArn", eksIamRolArn }, }; DoDiscoveryAndAssertReceivedServiceMessageWithMatchingProperties(authenticationDetails, serviceMessageProperties); } [Test] public void DiscoverKubernetesClusterWithEc2InstanceCredentialsAndNoIamRole() { var authenticationDetails = new AwsAuthenticationDetails { Type = "Aws", Credentials = new AwsCredentials { Type = "worker" }, Role = new AwsAssumedRole { Type = "noAssumedRole" }, Regions = new []{region} }; var serviceMessageProperties = new Dictionary<string, string> { { "name", eksClusterArn }, { "clusterName", eksClusterName }, { "clusterUrl", eksClusterEndpoint }, { "skipTlsVerification", bool.TrueString }, { "octopusDefaultWorkerPoolIdOrName", "WorkerPools-1" }, { "octopusRoles", "discovery-role" }, { "updateIfExisting", bool.TrueString }, { "isDynamic", bool.TrueString }, { "awsUseWorkerCredentials", bool.TrueString }, { "awsAssumeRole", bool.FalseString } }; DoDiscoveryAndAssertReceivedServiceMessageWithMatchingProperties(authenticationDetails, serviceMessageProperties); } } } #endif<file_sep>using System; using System.Collections.Generic; using System.Linq; namespace Calamari.Common.Features.Discovery { public class TargetDiscoveryScope { public TargetDiscoveryScope( string spaceName, string environmentName, string projectName, string? tenantName, string[] roles, string? workerPoolId, FeedImage? healthCheckContainer) { SpaceName = spaceName; EnvironmentName = environmentName; ProjectName = projectName; TenantName = tenantName; Roles = roles; WorkerPoolId = workerPoolId; HealthCheckContainer = healthCheckContainer; } public string SpaceName { get; private set; } public string EnvironmentName { get; private set; } public string ProjectName { get; private set; } public string? TenantName { get; private set; } public string[] Roles { get; private set; } public string? WorkerPoolId { get; private set; } public FeedImage? HealthCheckContainer { get; private set; } public TargetMatchResult Match(TargetTags tags) { var failureReasons = new List<string>(); if (tags.Role == null) { failureReasons.Add( $"Missing role tag. Match requires '{TargetTags.RoleTagName}' tag with value from ['{string.Join("', '", Roles)}']."); } else if (!Roles.Any(r => r.Equals(tags.Role, StringComparison.OrdinalIgnoreCase))) { failureReasons.Add( $"Mismatched role tag. Match requires '{TargetTags.RoleTagName}' tag with value from ['{string.Join("', '", Roles)}'], but found '{tags.Role}'."); } if (tags.Environment == null) { failureReasons.Add( $"Missing environment tag. Match requires '{TargetTags.EnvironmentTagName}' tag with value '{EnvironmentName}'."); } else if (!tags.Environment.Equals(EnvironmentName, StringComparison.OrdinalIgnoreCase)) { failureReasons.Add( $"Mismatched environment tag. Match requires '{TargetTags.EnvironmentTagName}' tag with value '{EnvironmentName}', but found '{tags.Environment}'."); } if (tags.Project != null && !tags.Project.Equals(this.ProjectName, StringComparison.OrdinalIgnoreCase)) { failureReasons.Add( $"Mismatched project tag. Optional '{TargetTags.ProjectTagName}' tag must match '{ProjectName}' if present, but is '{tags.Project}'."); } if (tags.Space != null && !tags.Space.Equals(this.SpaceName, StringComparison.OrdinalIgnoreCase)) { failureReasons.Add( $"Mismatched space tag. Optional '{TargetTags.SpaceTagName}' tag must match '{SpaceName}' if present, but is '{tags.Space}'."); } if (tags.Tenant != null && !tags.Tenant.Equals(this.TenantName, StringComparison.OrdinalIgnoreCase)) { failureReasons.Add( $"Mismatched tenant tag. Optional '{TargetTags.TenantTagName}' tag must match '{TenantName}' if present, but is '{tags.Tenant}'."); } return failureReasons.Any() ? TargetMatchResult.Failure(failureReasons) : TargetMatchResult.Success(this.Roles.First(r => r.Equals(tags.Role, StringComparison.OrdinalIgnoreCase))); } } public class FeedImage{ public FeedImage(string imageNameAndTag, string feedIdOrName) { ImageNameAndTag = imageNameAndTag; FeedIdOrName = feedIdOrName; } public string ImageNameAndTag { get; private set; } public string FeedIdOrName { get; private set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Calamari.Deployment.PackageRetention.Model; namespace Calamari.Deployment.PackageRetention.Caching { public class LeastFrequentlyUsedWithAgingSort : ISortJournalEntries { readonly decimal ageFactor; readonly decimal hitFactor; readonly decimal newerVersionFactor; public LeastFrequentlyUsedWithAgingSort(decimal ageFactor = 0.5m, decimal hitFactor = 1m, decimal newerVersionFactor = 1m) { this.ageFactor = ageFactor; this.hitFactor = hitFactor; this.newerVersionFactor = newerVersionFactor; } public IEnumerable<JournalEntry> Sort(IEnumerable<JournalEntry> journalEntries) { var entries = journalEntries.Where(e => !e.HasLock()).ToList(); //We don't need the actual age of cache entries, just the relative age. var currentCacheAge = entries.Max(je => je.GetUsageDetails().Max(u => u.CacheAgeAtUsage)); return OrderByValue(entries.ToList(), currentCacheAge).Select(v => v.Entry); } IEnumerable<LeastFrequentlyUsedJournalEntry> OrderByValue(IList<JournalEntry> journalEntries, CacheAge currentCacheAge) { if (!journalEntries.Any()) return new LeastFrequentlyUsedJournalEntry[0]; var details = CreateLeastFrequentlyUsedJournalEntries(journalEntries).ToList(); var hitCountRange = GetHitCountRange(details); var cacheAgeRange = GetCacheAgeRange(details, currentCacheAge); var newVersionCountRange = GetVersionCountRange(details); decimal CalculateValue(LeastFrequentlyUsedJournalEntry pi) => Normalise(pi.HitCount, hitCountRange) * hitFactor - Normalise(currentCacheAge.Value - pi.Age.Value, cacheAgeRange) * ageFactor - Normalise(pi.NewerVersionCount, newVersionCountRange) * newerVersionFactor; return details.OrderBy(CalculateValue); } static (int Min, int Max) GetHitCountRange(List<LeastFrequentlyUsedJournalEntry> details) => (details.Min(d => d.HitCount), details.Max(d => d.HitCount)); static (int Min, int Max) GetCacheAgeRange(List<LeastFrequentlyUsedJournalEntry> details, CacheAge currentCacheAge) => (currentCacheAge.Value - details.Max(d => d.Age.Value), currentCacheAge.Value - details.Min(d => d.Age.Value)); static (int Min, int Max) GetVersionCountRange(List<LeastFrequentlyUsedJournalEntry> details) => (details.Min(d => d.NewerVersionCount), details.Max(d => d.NewerVersionCount)); static IEnumerable<LeastFrequentlyUsedJournalEntry> CreateLeastFrequentlyUsedJournalEntries(IList<JournalEntry> journalEntries) { var packageIdVersions = journalEntries .GroupBy(entry => entry.Package.PackageId); foreach (var grouping in packageIdVersions) { var current = -1; foreach (var entry in grouping.OrderByDescending(e => e.Package.Version)) { current++; var age = entry.GetUsageDetails().Min(ud => ud.CacheAgeAtUsage); var hitCount = entry.GetUsageDetails().Count; yield return new LeastFrequentlyUsedJournalEntry(entry, age, hitCount, current); } } } static decimal Normalise(int value, (int Min, int Max) range) { var divisor = range.Max - range.Min; divisor = divisor == 0 ? 1 : divisor; var scale = 1M / divisor; //Scales from 0..1 return (value - range.Min) * scale; } } }<file_sep>using Calamari.Util; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures { [TestFixture] public class GoDurationParserFixture { [TestCase("100")] [TestCase(" 100 ")] [TestCase("100s")] [TestCase("100us")] [TestCase("100µs")] [TestCase("100m10s")] [TestCase("300ms")] [TestCase("-1.5h")] [TestCase("2h45m")] public void ValidateTimeouts(string timeout) { GoDurationParser.ValidateTimeout(timeout).Should().BeTrue(); } [TestCase("")] [TestCase(" ")] [TestCase("100blah")] public void InvalidateTimeouts(string timeout) { GoDurationParser.ValidateTimeout(timeout).Should().BeFalse(); } } }<file_sep>using System; using System.IO; using Calamari.Common.Features.Scripting.WindowsPowerShell; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Testing.Requirements; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Scripting { [TestFixture] public class PowerShellScriptEngineFixture : ScriptEngineFixtureBase { [Test] [RequiresNonFreeBSDPlatform] public void PowerShellDecryptsVariables() { using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1"))) { File.WriteAllText(scriptFile.FilePath, "Write-Host $mysecrect"); var result = ExecuteScript(new PowerShellScriptExecutor(), scriptFile.FilePath, GetVariables()); result.AssertOutput("KingKong"); } } [Test] [TestCase("true")] [TestCase("True")] [TestCase("1")] [TestCase("2")] [RequiresNonFreeBSDPlatform] [RequiresPowerShell5OrAbove] public void PowerShellCanSetTraceMode(string variableValue) { using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1"))) { File.WriteAllText(scriptFile.FilePath, "Write-Host $mysecrect"); var calamariVariableDictionary = GetVariables(); calamariVariableDictionary.Set("Octopus.Action.PowerShell.PSDebug.Trace", variableValue); var result = ExecuteScript(new PowerShellScriptExecutor(), scriptFile.FilePath, calamariVariableDictionary); result.AssertOutput("KingKong"); result.AssertOutput("DEBUG: 1+ >>>> Write-Host $mysecrect"); result.AssertNoOutput("PowerShell tracing is only supported with PowerShell versions 5 and above"); if (variableValue != "1") { //see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-psdebug?view=powershell-6#description //When the Trace parameter has a value of 1, each line of script is traced as it runs. //When the parameter has a value of 2, variable assignments, function calls, and script calls are also traced //we translate "true" to "2" result.AssertOutput("! CALL function 'Import-CalamariModules'"); } } } [Test] [TestCase("true")] [TestCase("True")] [TestCase("1")] [TestCase("2")] [RequiresNonFreeBSDPlatform] [RequiresPowerShell4] public void PowerShell4DoesntSupport(string variableValue) { //this may cause an `Inconclusive: Outcome value 0 is not understood` error in Rider //known bug - https://youtrack.jetbrains.com/issue/RSRP-465549 if (ScriptingEnvironment.SafelyGetPowerShellVersion().Major != 4) Assert.Inconclusive("This test requires PowerShell 4"); using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1"))) { File.WriteAllText(scriptFile.FilePath, "Write-Host $mysecrect"); var calamariVariableDictionary = GetVariables(); calamariVariableDictionary.Set("Octopus.Action.PowerShell.PSDebug.Trace", variableValue); var result = ExecuteScript(new PowerShellScriptExecutor(), scriptFile.FilePath, calamariVariableDictionary); result.AssertOutput("KingKong"); result.AssertOutput("Octopus.Action.PowerShell.PSDebug.Trace is enabled, but PowerShell tracing is only supported with PowerShell versions 5 and above. This server is currently running PowerShell version 4.0."); } } [Test] [TestCase("0")] [TestCase("False")] [TestCase("false")] [TestCase("")] [RequiresNonFreeBSDPlatform] public void PowerShellDoesntForceTraceMode(string variableValue) { using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1"))) { File.WriteAllText(scriptFile.FilePath, "Write-Host $mysecrect"); var calamariVariableDictionary = GetVariables(); if (!string.IsNullOrEmpty(variableValue)) calamariVariableDictionary.Set("Octopus.Action.PowerShell.PSDebug.Trace", variableValue); var result = ExecuteScript(new PowerShellScriptExecutor(), scriptFile.FilePath, calamariVariableDictionary); result.AssertOutput("KingKong"); result.AssertNoOutput("DEBUG: 1+ >>>> Write-Host $mysecrect"); } } [Test] [RequiresNonFreeBSDPlatform] public void PowerShellWorksWithStrictMode() { using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1"))) { File.WriteAllText(scriptFile.FilePath, "$newVar = $nonExistentVar" + Environment.NewLine + "write-host \"newVar = '$newVar'\""); var calamariVariableDictionary = GetVariables(); calamariVariableDictionary.Set("Octopus.Action.PowerShell.PSDebug.Strict", "true"); var result = ExecuteScript(new PowerShellScriptExecutor(), scriptFile.FilePath, calamariVariableDictionary); result.AssertErrorOutput(" cannot be retrieved because it has not been set."); result.AssertFailure(); } } [Test] [TestCase("false")] [TestCase("")] [RequiresNonFreeBSDPlatform] public void PowerShellDoesntForceStrictMode(string variableValue) { using (var scriptFile = new TemporaryFile(Path.ChangeExtension(Path.GetTempFileName(), "ps1"))) { File.WriteAllText(scriptFile.FilePath, "$newVar = $nonExistentVar" + Environment.NewLine + "write-host \"newVar = '$newVar'\""); var calamariVariableDictionary = GetVariables(); if (!string.IsNullOrEmpty(variableValue)) calamariVariableDictionary.Set("Octopus.Action.PowerShell.PSDebug.Strict", variableValue); var result = ExecuteScript(new PowerShellScriptExecutor(), scriptFile.FilePath, calamariVariableDictionary); result.AssertOutput("newVar = ''"); result.AssertNoOutput(" cannot be retrieved because it has not been set."); } } } } <file_sep>#if AWS using System; using System.Threading.Tasks; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.AWS.CloudFormation { [TestFixture] [Category(TestCategory.RunOnceOnWindowsAndLinux)] public class CloudFormationVariableReplacementFixture { string StackName; string ReplacedName; public CloudFormationVariableReplacementFixture() { var unique = Guid.NewGuid().ToString("N").ToLowerInvariant(); StackName = $"calamariteststack{unique}"; ReplacedName = $"calamaritestreplaced{unique}"; } [Test] public async Task CreateCloudFormationWithStructuredVariableReplacement() { var cloudFormationFixtureHelpers = new CloudFormationFixtureHelpers(); var templateFilePath = cloudFormationFixtureHelpers.WriteTemplateFile(CloudFormationFixtureHelpers.GetBasicS3Template(StackName)); var variables = new CalamariVariables(); variables.Set(KnownVariables.Package.EnabledFeatures, "Octopus.Features.JsonConfigurationVariables"); variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, templateFilePath); variables.Set($"Resources:{StackName}:Properties:BucketName", ReplacedName); try { cloudFormationFixtureHelpers.DeployTemplate(StackName, templateFilePath, variables); await cloudFormationFixtureHelpers.ValidateS3BucketExists(ReplacedName); } finally { cloudFormationFixtureHelpers.CleanupStack(StackName); } } } } #endif<file_sep>using System; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.Variables; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment.Conventions { [TestFixture] public class RunningDeploymentFixture { [Test] public void ShouldReturnCorrectDirectories() { var deployment = new RunningDeployment("C:\\Package.nupkg", new CalamariVariables()); // When no custom installation directory is chosen, custom points to staging deployment.Variables.Set(KnownVariables.OriginalPackageDirectoryPath, "C:\\Apps\\MyPackage\\1.0.0_1"); Assert.That(deployment.StagingDirectory, Is.EqualTo("C:\\Apps\\MyPackage\\1.0.0_1")); Assert.That(deployment.CustomDirectory, Is.EqualTo("C:\\Apps\\MyPackage\\1.0.0_1")); Assert.That(deployment.CurrentDirectory, Is.EqualTo("C:\\Apps\\MyPackage\\1.0.0_1")); // Custom installation directory is always available, but the staging directory points to current deployment.Variables.Set(PackageVariables.CustomInstallationDirectory, "C:\\MyWebsite"); Assert.That(deployment.StagingDirectory, Is.EqualTo("C:\\Apps\\MyPackage\\1.0.0_1")); Assert.That(deployment.CustomDirectory, Is.EqualTo("C:\\MyWebsite")); Assert.That(deployment.CurrentDirectory, Is.EqualTo("C:\\Apps\\MyPackage\\1.0.0_1")); // After the package contents is copied to the custom installation directory, the current directory changes deployment.CurrentDirectoryProvider = DeploymentWorkingDirectory.CustomDirectory; Assert.That(deployment.StagingDirectory, Is.EqualTo("C:\\Apps\\MyPackage\\1.0.0_1")); Assert.That(deployment.CustomDirectory, Is.EqualTo("C:\\MyWebsite")); Assert.That(deployment.CurrentDirectory, Is.EqualTo("C:\\MyWebsite")); } } } <file_sep>using System; namespace Calamari.Build { public static class Frameworks { public const string Net40 = "net40"; public const string Net452 = "net452"; public const string Net461 = "net461"; public const string Net60 = "net6.0"; } }<file_sep>using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Integration.Proxies; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Bash { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyNixOrMac)] public class BashProxyFixture : ScriptProxyFixtureBase { protected override CalamariResult RunScript() { return RunScript("proxy.sh").result; } } }<file_sep>using Calamari.AzureAppService.Behaviors; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Variables; using Calamari.Testing.Helpers; using FluentAssertions; using NUnit.Framework; using System.Threading.Tasks; namespace Calamari.AzureAppService.Tests { [TestFixture] public class TargetDiscoveryBehaviourUnitTestFixture { [Test] public async Task Execute_LogsError_WhenContextIsMissing() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Act await sut.Execute(context); // Assert log.StandardOut.Should().Contain(line => line.Contains("Could not find target discovery context in variable")); log.StandardOut.Should().Contain(line => line.Contains("Aborting target discovery.")); } [Test] public async Task Exectute_LogsError_WhenContextIsInIncorrectFormat() { // Arrange var variables = new CalamariVariables(); var context = new RunningDeployment(variables); context.Variables.Add("Octopus.TargetDiscovery.Context", "bogus json"); var log = new InMemoryLog(); var sut = new TargetDiscoveryBehaviour(log); // Act await sut.Execute(context); // Assert log.StandardOut.Should().Contain(line => line.Contains("Target discovery context from variable Octopus.TargetDiscovery.Context is in wrong format")); log.StandardOut.Should().Contain(line => line.Contains("Aborting target discovery.")); } private void CreateVariables(RunningDeployment context, string targetDiscoveryContextJson) { context.Variables.Add("Octopus.TargetDiscovery.Context", targetDiscoveryContextJson); } } }<file_sep>using Calamari.Deployment.PackageRetention.Repositories; namespace Calamari.Tests.Fixtures.PackageRetention.Repository { public class StaticJsonJournalPathProvider : IJsonJournalPathProvider { readonly string path; public StaticJsonJournalPathProvider(string path) { this.path = path; } public string GetJournalPath() => path; } }<file_sep>using Calamari.Common.Plumbing.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calamari.Common.Plumbing.ServiceMessages { public class ServiceMessage { public const string ServiceMessageLabel = "##octopus"; readonly Dictionary<string, string> properties; public ServiceMessage(string name, Dictionary<string, string>? properties = null) { this.Name = name; this.properties = properties ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } private ServiceMessage(string name, params (string, string)[] parameters) { this.Name = name; this.properties = parameters.ToDictionary(kvp => kvp.Item1, kvp => kvp.Item2); } public string Name { get; } public IDictionary<string, string> Properties => properties; public static ServiceMessage Create(string name, params (string, string)[] parameters) => new ServiceMessage(name, parameters); public string? GetValue(string key) { string s; return properties.TryGetValue(key, out s) ? s : null; } public override string ToString() { var parameters = properties .Where(kvp => kvp.Value != null) .Select(kvp => $"{kvp.Key}=\"{AbstractLog.ConvertServiceMessageValue(kvp.Value)}\""); return $"{ServiceMessageLabel}[{Name} {string.Join(" ", parameters)}]"; } } }<file_sep>using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.FileSystem.GlobExpressions; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.FileSystem { public class SubstituteInFiles : ISubstituteInFiles { readonly ILog log; readonly ICalamariFileSystem fileSystem; readonly IFileSubstituter substituter; readonly IVariables variables; public SubstituteInFiles(ILog log, ICalamariFileSystem fileSystem, IFileSubstituter substituter, IVariables variables) { this.log = log; this.fileSystem = fileSystem; this.substituter = substituter; this.variables = variables; } public void SubstituteBasedSettingsInSuppliedVariables(string currentDirectory) { var filesToTarget = variables.GetPaths(PackageVariables.SubstituteInFilesTargets); Substitute(currentDirectory, filesToTarget); } public void Substitute(string currentDirectory, IList<string> filesToTarget, bool warnIfFileNotFound = true) { foreach (var target in filesToTarget) { var matchingFiles = MatchingFiles(currentDirectory, target); if (!matchingFiles.Any()) { if (warnIfFileNotFound && variables.GetFlag(PackageVariables.EnableNoMatchWarning, true)) log.WarnFormat("No files were found in {0} that match the substitution target pattern '{1}'", currentDirectory, target); continue; } foreach (var file in matchingFiles) substituter.PerformSubstitution(file, variables); } } List<string> MatchingFiles(string currentDirectory, string target) { var globMode = GlobModeRetriever.GetFromVariables(variables); var files = fileSystem.EnumerateFilesWithGlob(currentDirectory, globMode, target).Select(Path.GetFullPath).ToList(); foreach (var path in variables.GetStrings(ActionVariables.AdditionalPaths) .Where(s => !string.IsNullOrWhiteSpace(s))) { var pathFiles = fileSystem.EnumerateFilesWithGlob(path, globMode, target).Select(Path.GetFullPath); files.AddRange(pathFiles); } return files; } } }<file_sep>using System; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Tests.Fixtures.Deployment.Packages; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { public abstract class DeployWindowsServiceAbstractFixture : DeployPackageFixture { [SetUp] public override void SetUp() { DeleteExistingService(); base.SetUp(); } [TearDown] public override void CleanUp() { DeleteExistingService(); base.CleanUp(); } protected virtual string PackageName => "Acme.Service"; protected abstract string ServiceName { get; } private void DeleteExistingService() { var service = GetInstalledService(); if (service != null) { var system32 = Environment.GetFolderPath(Environment.SpecialFolder.System); var sc = Path.Combine(system32, "sc.exe"); Process.Start(new ProcessStartInfo(sc, $"stop {ServiceName}") { CreateNoWindow = true, UseShellExecute = false })?.WaitForExit(); Process.Start(new ProcessStartInfo(sc, $"delete {ServiceName}") { CreateNoWindow = true, UseShellExecute = false })?.WaitForExit(); } } protected void RunDeployment(Action extraAsserts = null) { if (string.IsNullOrEmpty(Variables[KnownVariables.Package.EnabledFeatures])) Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.WindowsService"; Variables["Octopus.Action.WindowsService.CreateOrUpdateService"] = "True"; Variables["Octopus.Action.WindowsService.ServiceAccount"] = "_CUSTOM"; Variables["Octopus.Action.WindowsService.StartMode"] = "auto"; Variables["Octopus.Action.WindowsService.ServiceName"] = ServiceName; if (Variables["Octopus.Action.WindowsService.DisplayName"] == null) { Variables["Octopus.Action.WindowsService.DisplayName"] = ServiceName; } Variables["Octopus.Action.WindowsService.ExecutablePath"] = $"{PackageName}.exe"; using (var file = new TemporaryFile(PackageBuilder.BuildSamplePackage(PackageName, "1.0.0"))) { var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutput("Extracting package to: " + Path.Combine(StagingDirectory, PackageName, "1.0.0")); result.AssertOutput("Extracted 1 files"); using (var installedService = GetInstalledService()) { Assert.NotNull(installedService, "Service is installed"); Assert.AreEqual(ServiceControllerStatus.Running, installedService.Status); } extraAsserts?.Invoke(); } } private ServiceController GetInstalledService() { return ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == ServiceName); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calamari.Integration.Nginx { public class NginxMissingRootLocationException : Exception { public NginxMissingRootLocationException() : base("") { } public NginxMissingRootLocationException(string message) : base(message) { } } } <file_sep>using Calamari.Common.Plumbing.Extensions; using Calamari.Util; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Util { [TestFixture] class ScriptVariableEncryptorFixture { [Test] public void EncryptionIsSymmetrical() { var passphrase = "<PASSWORD>"; var text = "Put It In H!"; var encryptor = new AesEncryption(passphrase); Assert.AreEqual(text, encryptor.Decrypt(encryptor.Encrypt(text))); } } } <file_sep>using System; namespace Calamari.Common.Features.Processes { public class SilentProcessRunnerResult { public SilentProcessRunnerResult(int exitCode, string errorOutput) { ExitCode = exitCode; ErrorOutput = errorOutput; } public int ExitCode { get; } public string ErrorOutput { get; } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Variables; using Calamari.Scripting; using NUnit.Framework; using Calamari.Testing; using Calamari.Testing.Requirements; using Calamari.Testing.Tools; namespace Calamari.AzureScripting.Tests { [TestFixture] class AzurePowerShellCommandFixture { string? clientId; string? clientSecret; string? tenantId; string? subscriptionId; static IDeploymentTool AzureCLI = new InPathDeploymentTool("Octopus.Dependencies.AzureCLI", "AzureCLI\\wbin"); static IDeploymentTool AzureCmdlets = new BoostrapperModuleDeploymentTool("Octopus.Dependencies.AzureCmdlets", new[] { "Powershell\\Azure.Storage\\4.6.1", "Powershell\\Azure\\5.3.0", "Powershell", }); [OneTimeSetUp] public void Setup() { clientId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId); clientSecret = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword); tenantId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId); subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId); } [Test] [WindowsTest] [RequiresPowerShell5OrAbove] public async Task ExecuteAnInlineWindowsPowerShellScript() { var psScript = @" $ErrorActionPreference = 'Continue' az --version Get-AzureEnvironment az group list"; await CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { AddDefaults(context); context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); context.Variables.Add(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); context.Variables.Add(ScriptVariables.ScriptBody, psScript); }) .Execute(); } [Test] [RequiresPowerShell5OrAbove] public async Task ExecuteAnInlinePowerShellCoreScript() { var psScript = @" $ErrorActionPreference = 'Continue' az --version Get-AzureEnvironment az group list"; await CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { AddDefaults(context); context.Variables.Add(PowerShellVariables.Edition, ScriptVariables.ScriptSourceOptions.Core); context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); context.Variables.Add(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); context.Variables.Add(ScriptVariables.ScriptBody, psScript); }) .Execute(); } [Test] [RequiresPowerShell5OrAbove] public async Task ExecuteAnInlinePowerShellCoreScriptAgainstAnInvalidAzureEnvironment() { var psScript = @" $ErrorActionPreference = 'Continue' az --version Get-AzureEnvironment az group list"; await CommandTestBuilder.CreateAsync<RunScriptCommand, Program>() .WithArrange(context => { AddDefaults(context); context.Variables.Add(SpecialVariables.Action.Azure.Environment, "NotARealAzureEnvironment"); context.Variables.Add(PowerShellVariables.Edition, ScriptVariables.ScriptSourceOptions.Core); context.Variables.Add(ScriptVariables.ScriptSource, ScriptVariables.ScriptSourceOptions.Inline); context.Variables.Add(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString()); context.Variables.Add(ScriptVariables.ScriptBody, psScript); }) .Execute(false); // Should fail due to invalid azure environment } void AddDefaults(CommandTestBuilderContext context) { context.Variables.Add(SpecialVariables.Account.AccountType, "AzureServicePrincipal"); context.Variables.Add(SpecialVariables.Action.Azure.SubscriptionId, subscriptionId); context.Variables.Add(SpecialVariables.Action.Azure.TenantId, tenantId); context.Variables.Add(SpecialVariables.Action.Azure.ClientId, clientId); context.Variables.Add(SpecialVariables.Action.Azure.Password, clientSecret); context.WithTool(AzureCLI); context.WithTool(AzureCmdlets); } } }<file_sep>using System; namespace Calamari.Common.Features.Packages.Java { public class JarPackageExtractor : IPackageExtractor { public static readonly string[] SupportedExtensions = { ".jar", ".war", ".ear", ".rar", ".zip" }; readonly JarTool jarTool; public JarPackageExtractor(JarTool jarTool) { this.jarTool = jarTool; } public string[] Extensions => SupportedExtensions; public int Extract(string packageFile, string directory) { return jarTool.ExtractJar(packageFile, directory); } } }<file_sep>using System; using Calamari.Aws.Deployment.Conventions; using Calamari.Commands.Support; using Calamari.Deployment; using Calamari.Deployment.Conventions; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Calamari.Aws.Deployment; using Calamari.Aws.Integration.CloudFormation; using Calamari.Aws.Integration.CloudFormation.Templates; using Calamari.Aws.Util; using Calamari.CloudAccounts; using Calamari.Commands; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Features.Packages; using Calamari.Common.Features.StructuredVariables; using Calamari.Common.Plumbing.Deployment; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Common.Util; using Newtonsoft.Json; using Octopus.CoreUtilities; namespace Calamari.Aws.Commands { [Command("deploy-aws-cloudformation", Description = "Creates a new AWS CloudFormation deployment")] public class DeployCloudFormationCommand : Command { readonly ILog log; readonly IVariables variables; readonly ICalamariFileSystem fileSystem; readonly IExtractPackage extractPackage; readonly IStructuredConfigVariablesService structuredConfigVariablesService; PathToPackage pathToPackage; string templateFile; string templateParameterFile; string templateS3Url; string templateParameterS3Url; bool waitForComplete; string stackName; bool disableRollback; public DeployCloudFormationCommand(ILog log, IVariables variables, ICalamariFileSystem fileSystem, IExtractPackage extractPackage, IStructuredConfigVariablesService structuredConfigVariablesService) { this.log = log; this.variables = variables; this.fileSystem = fileSystem; this.extractPackage = extractPackage; this.structuredConfigVariablesService = structuredConfigVariablesService; Options.Add("package=", "Path to the NuGet package to install.", v => pathToPackage = new PathToPackage(Path.GetFullPath(v))); Options.Add("template=", "Path to the JSON template file.", v => templateFile = v); Options.Add("templateParameters=", "Path to the JSON template parameters file.", v => templateParameterFile = v); Options.Add("templateS3=", "S3 URL to the JSON template file.", v => templateS3Url = v); Options.Add("templateS3Parameters=", "S3 URL to the JSON template parameters file.", v => templateParameterS3Url = v); Options.Add("waitForCompletion=", "True if the deployment process should wait for the stack to complete, and False otherwise.", v => waitForComplete = !bool.FalseString.Equals(v, StringComparison.OrdinalIgnoreCase)); //True by default Options.Add("stackName=", "The name of the CloudFormation stack.", v => stackName = v); Options.Add("disableRollback=", "True to disable the CloudFormation stack rollback on failure, and False otherwise.", v => disableRollback = bool.TrueString.Equals(v, StringComparison.OrdinalIgnoreCase)); //False by default } public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); var filesInPackage = !string.IsNullOrWhiteSpace(pathToPackage); var environment = AwsEnvironmentGeneration.Create(log, variables).GetAwaiter().GetResult(); var templateResolver = new TemplateResolver(fileSystem); IAmazonCloudFormation ClientFactory() => ClientHelpers.CreateCloudFormationClient(environment); StackArn StackProvider(RunningDeployment x) => new StackArn(stackName); ChangeSetArn ChangesetProvider(RunningDeployment x) => new ChangeSetArn(x.Variables[AwsSpecialVariables.CloudFormation.Changesets.Arn]); string RoleArnProvider(RunningDeployment x) => x.Variables[AwsSpecialVariables.CloudFormation.RoleArn]; var iamCapabilities = JsonConvert.DeserializeObject<List<string>>(variables.Get(AwsSpecialVariables.IamCapabilities, "[]")); var tags = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(variables.Get(AwsSpecialVariables.CloudFormation.Tags, "[]")); var deployment = new RunningDeployment(pathToPackage, variables); ICloudFormationRequestBuilder TemplateFactory() => string.IsNullOrWhiteSpace(templateS3Url) ? CloudFormationTemplate.Create(templateResolver, templateFile, templateParameterFile, filesInPackage, fileSystem, variables, stackName, iamCapabilities, disableRollback, RoleArnProvider(deployment), tags, StackProvider(deployment), ClientFactory) : CloudFormationS3Template.Create(templateS3Url, templateParameterS3Url, fileSystem, variables, log, stackName, iamCapabilities, disableRollback, RoleArnProvider(deployment), tags, StackProvider(deployment), ClientFactory); var stackEventLogger = new StackEventLogger(log); var conventions = new List<IConvention> { new LogAwsUserInfoConvention(environment), new DelegateInstallConvention(d => extractPackage.ExtractToStagingDirectory(pathToPackage)), new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(structuredConfigVariablesService)), //Create or Update the stack using changesets new AggregateInstallationConvention( new GenerateCloudFormationChangesetNameConvention(log), new CreateCloudFormationChangeSetConvention(ClientFactory, stackEventLogger, StackProvider, TemplateFactory), new DescribeCloudFormationChangeSetConvention(ClientFactory, stackEventLogger, StackProvider, ChangesetProvider), new ExecuteCloudFormationChangeSetConvention(ClientFactory, stackEventLogger, StackProvider, ChangesetProvider, waitForComplete) .When(ImmediateChangesetExecution), new CloudFormationOutputsAsVariablesConvention(ClientFactory, stackEventLogger, StackProvider) .When(ImmediateChangesetExecution) ).When(ChangesetsEnabled), //Create or update stack using a template (no changesets) new AggregateInstallationConvention( new DeployAwsCloudFormationConvention( ClientFactory, TemplateFactory, stackEventLogger, StackProvider, RoleArnProvider, waitForComplete, stackName, environment), new CloudFormationOutputsAsVariablesConvention(ClientFactory, stackEventLogger, StackProvider) ) .When(ChangesetsDisabled) }; var conventionRunner = new ConventionProcessor(deployment, conventions, log); conventionRunner.RunConventions(); return 0; } bool ChangesetsDeferred(RunningDeployment deployment) { return string.Compare(deployment.Variables[AwsSpecialVariables.CloudFormation.Changesets.Defer], bool.TrueString, StringComparison.OrdinalIgnoreCase) == 0; } bool ImmediateChangesetExecution(RunningDeployment deployment) { return !ChangesetsDeferred(deployment); } bool ChangesetsEnabled(RunningDeployment deployment) { return deployment.Variables.Get(KnownVariables.Package.EnabledFeatures) ?.Contains(AwsSpecialVariables.CloudFormation.Changesets.Feature) ?? false; } bool ChangesetsDisabled(RunningDeployment deployment) { return !ChangesetsEnabled(deployment); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Deployment.PackageRetention; using Newtonsoft.Json; namespace Calamari.Deployment.PackageRetention.Model { public class JournalEntry { public PackageIdentity Package { get; } [JsonProperty] readonly PackageUsages usages; [JsonProperty] readonly PackageLocks locks; public ulong FileSizeBytes { get; } [JsonConstructor] public JournalEntry(PackageIdentity package, ulong fileSizeBytes, PackageLocks packageLocks = null, PackageUsages packageUsages = null) { Package = package ?? throw new ArgumentNullException(nameof(package)); FileSizeBytes = fileSizeBytes; locks = packageLocks ?? new PackageLocks(); usages = packageUsages ?? new PackageUsages(); } public void AddUsage(ServerTaskId deploymentTaskId, CacheAge cacheAge) { usages.Add(new UsageDetails(deploymentTaskId, cacheAge)); } public void AddLock(ServerTaskId deploymentTaskId, CacheAge cacheAge) { locks.Add(new UsageDetails(deploymentTaskId, cacheAge)); } public void RemoveLock(ServerTaskId deploymentTaskId) { locks.RemoveAll(l => l.DeploymentTaskId == deploymentTaskId); } public bool HasLock() => locks.Count > 0; public PackageUsages GetUsageDetails() => usages; public IEnumerable<UsageDetails> GetLockDetails() => locks; } }<file_sep> using System; using System.IO; System.IO.Directory.CreateDirectory("Temp"); System.IO.File.WriteAllBytes(Path.Combine("Temp","myFile.txt"), new byte[100]); Octopus.CreateArtifact(Path.Combine("Temp","myFile.txt")); <file_sep>using System.Collections.Generic; using System.Linq; using Calamari.Deployment.PackageRetention.Model; namespace Calamari.Deployment.PackageRetention.Caching { public class FirstInFirstOutJournalEntrySort : ISortJournalEntries { public IEnumerable<JournalEntry> Sort(IEnumerable<JournalEntry> journalEntries) { return journalEntries.OrderBy(entry => entry, new FirstInFirstOutJournalEntryComparer()); } } }<file_sep>#!/bin/bash echo kubectl version to test connectivity kubectl version --short || exit 1 canQueryNodes=`kubectl auth can-i get nodes --all-namespaces` if [[ $canQueryNodes == 'yes' ]]; then nodes="" for line in $(kubectl get nodes -o=custom-columns=NAME:.metadata.name --all-namespaces); do line=$(echo $line | awk '{$1=$1};1') if [[ $line != 'NAME' ]]; then nodes="$nodes \"$line\"," fi done nodes=${nodes:: $((${#nodes} - 1))} read -r -d '' METADATA <<EOT { "type": "kubernetes", "thumbprint": "%THUMBPRINT%", "metadata": { "nodes":[$nodes] } } EOT parameters="" parameters="$parameters deploymentTargetId='$(encode_servicemessagevalue "%DEPLOYMENTTARGETID%")'" parameters="$parameters metadata='$(encode_servicemessagevalue "$METADATA")'" echo "##octopus[set-deploymenttargetmetadata ${parameters}]" else read -r -d '' METADATA <<EOT { "type": "kubernetes", "thumbprint": "%THUMBPRINT%", "metadata": { "INSUFFICIENTPRIVILEGES": "Insufficient privileges to retrieve deployment target metadata" } } EOT parameters="" parameters="$parameters deploymentTargetId='$(encode_servicemessagevalue "%DEPLOYMENTTARGETID%")'" parameters="$parameters metadata='$(encode_servicemessagevalue "$METADATA")'" echo "##octopus[set-deploymenttargetmetadata ${parameters}]" fi <file_sep>using System; using Calamari.Kubernetes.ResourceStatus; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus { [TestFixture] public class TimerTests { [Test] public void ZeroDurationTimer_ShouldNotCompleteBeforeItIsStarted() { var timer = new Timer(TimeSpan.FromSeconds(1), TimeSpan.Zero); timer.HasCompleted().Should().BeFalse(); } } } <file_sep>using System; using System.IO; using NUnit.Framework; using YamlDotNet.Core; using YamlDotNet.Serialization; namespace Calamari.Tests.Fixtures.StructuredVariables { [TestFixture] [Explicit] public class YamlTransformApproachComparisonDemoFixture { [Test] public void YamlTransformApproachComparisonDemo() { var input = @"Numbers: !!omap [ one: 1, two: 2, three: 3, octy: 010, norway: no ]"; Demo(nameof(YamlDotNetSerializerIdentityTransform), () => YamlDotNetSerializerIdentityTransform(input)); Demo(nameof(YamlDotNetParserEmitterIdentityTransform), () => YamlDotNetParserEmitterIdentityTransform(input)); //Demo(nameof(SharpYamlSerializerIdentityTransform), () => SharpYamlSerializerIdentityTransform(input)); //Demo(nameof(SharpYamlParserEmitterIdentityTransform), () => SharpYamlParserEmitterIdentityTransform(input)); } public void Demo(string name, Func<string> transform) { var output = ""; try { output = transform(); } catch (Exception ex) { Console.WriteLine($"** {name} failed: {ex}"); } Console.WriteLine($"{name}:"); Console.WriteLine("[["); Console.WriteLine(output); Console.WriteLine("]]"); } string YamlDotNetSerializerIdentityTransform(string input) { using (var textReader = new StringReader(input)) using (var textWriter = new StringWriter()) { var deserializer = new DeserializerBuilder().Build(); var data = deserializer.Deserialize(textReader); new Serializer().Serialize(textWriter, data ?? ""); textWriter.Close(); return textWriter.ToString(); } } string YamlDotNetParserEmitterIdentityTransform(string input) { using (var textReader = new StringReader(input)) using (var textWriter = new StringWriter()) { var parser = new Parser(textReader); var emitter = new Emitter(textWriter); while (parser.MoveNext()) if (parser.Current != null) emitter.Emit(parser.Current); textWriter.Close(); return textWriter.ToString(); } } /*string SharpYamlSerializerIdentityTransform(string input) { using (var textReader = new StringReader(input)) using (var textWriter = new StringWriter()) { var serializer = new SharpYaml.Serialization.Serializer(new SharpYaml.Serialization.SerializerSettings { EmitShortTypeName = true }); var data = serializer.Deserialize(textReader); serializer.Serialize(textWriter, data); textWriter.Close(); return textWriter.ToString(); } }*/ /*string SharpYamlParserEmitterIdentityTransform(string input) { using (var textReader = new StringReader(input)) using (var textWriter = new StringWriter()) { var parser = new SharpYaml.Parser(textReader); var emitter = new SharpYaml.Emitter(textWriter); while (parser.MoveNext()) { emitter.Emit(parser.Current); } textWriter.Close(); return textWriter.ToString(); } }*/ } }<file_sep>using System; using System.IO; using System.Linq; using System.Net; using System.Net.Cache; using System.Threading; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Octopus.Versioning; using SharpCompress.Common; using SharpCompress.Readers; using SharpCompress.Writers; using SharpCompress.Writers.Zip; namespace Calamari.Integration.Packages.Download { public class GitHubPackageDownloader : IPackageDownloader { const string Extension = ".zip"; const char OwnerRepoSeperator = '/'; static readonly IPackageDownloaderUtils PackageDownloaderUtils = new PackageDownloaderUtils(); public static readonly string DownloadingExtension = ".downloading"; readonly ICalamariFileSystem fileSystem; readonly ILog log; public GitHubPackageDownloader(ILog log, ICalamariFileSystem fileSystem) { this.log = log; this.fileSystem = fileSystem; } public PackagePhysicalFileMetadata DownloadPackage(string packageId, IVersion version, string feedId, Uri feedUri, string? feedUsername, string? feedPassword, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { var cacheDirectory = PackageDownloaderUtils.GetPackageRoot(feedId); fileSystem.EnsureDirectoryExists(cacheDirectory); if (!forcePackageDownload) { var downloaded = SourceFromCache(packageId, version, cacheDirectory); if (downloaded != null) { Log.VerboseFormat("Package was found in cache. No need to download. Using file: '{0}'", downloaded.FullFilePath); return downloaded; } } return DownloadPackage(packageId, version, feedUri, feedPassword, cacheDirectory, maxDownloadAttempts, downloadAttemptBackoff); } void SplitPackageId(string packageId, out string? owner, out string repo) { var parts = packageId.Split(OwnerRepoSeperator); if (parts.Length > 1) { owner = parts[0]; repo = parts[1]; } else { owner = null; repo = packageId; } } PackagePhysicalFileMetadata? SourceFromCache(string packageId, IVersion version, string cacheDirectory) { Log.VerboseFormat("Checking package cache for package {0} v{1}", packageId, version.ToString()); var files = fileSystem.EnumerateFilesRecursively(cacheDirectory, PackageName.ToSearchPatterns(packageId, version, new[] { Extension })); foreach (var file in files) { var package = PackageName.FromFile(file); if (package == null) continue; if (string.Equals(package.PackageId, packageId, StringComparison.OrdinalIgnoreCase) && package.Version.Equals(version)) { var packagePhysicalFileMetadata = PackagePhysicalFileMetadata.Build(file, package); return packagePhysicalFileMetadata ?? throw new CommandException($"Unable to retrieve metadata for package {packageId}, version {version}"); } } return null; } PackagePhysicalFileMetadata DownloadPackage( string packageId, IVersion version, Uri feedUri, string? authorizationToken, string cacheDirectory, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { Log.Info("Downloading GitHub package {0} v{1} from feed: '{2}'", packageId, version, feedUri); Log.VerboseFormat("Downloaded package will be stored in: '{0}'", cacheDirectory); fileSystem.EnsureDirectoryExists(cacheDirectory); SplitPackageId(packageId, out var owner, out var repository); if (string.IsNullOrWhiteSpace(owner) || string.IsNullOrWhiteSpace(repository)) throw new InvalidOperationException( "Invalid PackageId for GitHub feed. Expecting format `<owner>/<repo>`"); var page = 0; JArray? req = null; while (req == null || req.Count != 0 && req.Count < 1000) { var uri = feedUri.AbsoluteUri + $"repos/{Uri.EscapeUriString(owner)}/{Uri.EscapeUriString(repository)}/tags?page={++page}&per_page=1000"; req = PerformRequest(authorizationToken, uri) as JArray; if (req == null) break; foreach (var tag in req) { var v = TryParseVersion((string)tag["name"]); if (v == null || !version.Equals(v)) continue; var zipball = (string)tag["zipball_url"]; return DownloadFile(zipball, cacheDirectory, packageId, version, authorizationToken, maxDownloadAttempts, downloadAttemptBackoff); } } throw new Exception("Unable to find package {0} v{1} from feed: '{2}'"); } static IVersion? TryParseVersion(string input) { if (input == null) return null; if (input[0].Equals('v') || input[0].Equals('V')) input = input.Substring(1); return VersionFactory.TryCreateVersion(input, VersionFormat.Semver); } PackagePhysicalFileMetadata DownloadFile(string uri, string cacheDirectory, string packageId, IVersion version, string? authorizationToken, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff) { var localDownloadName = Path.Combine(cacheDirectory, PackageName.ToCachedFileName(packageId, version, Extension)); var tempPath = Path.GetTempFileName(); if (File.Exists(tempPath)) File.Delete(tempPath); for (var retry = 0; retry < maxDownloadAttempts; ++retry) try { if (retry != 0) Log.Verbose($"Download Attempt #{retry + 1}"); using (var client = new WebClient()) { client.CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable); client.Headers.Set(HttpRequestHeader.UserAgent, GetUserAgent()); AddAuthorization(client, authorizationToken); client.DownloadFileWithProgress(uri, tempPath, (progress, total) => log.Progress(progress, $"Downloading {packageId} v{version}")); DeNestContents(tempPath, localDownloadName); var packagePhysicalFileMetadata = PackagePhysicalFileMetadata.Build(localDownloadName); return packagePhysicalFileMetadata ?? throw new CommandException($"Unable to retrieve metadata for package {packageId}, version {version}"); } } catch (WebException) { Thread.Sleep(downloadAttemptBackoff); } throw new Exception("Failed to download the package."); } JToken PerformRequest(string? authorizationToken, string uri) { try { using (var client = new WebClient()) { client.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); client.Headers.Set(HttpRequestHeader.UserAgent, GetUserAgent()); client.Headers.Set("Accept", "application/vnd.github.v3+json"); AddAuthorization(client, authorizationToken); using (var readStream = client.OpenRead(uri)) { var reader = new JsonTextReader(new StreamReader(readStream ?? throw new InvalidOperationException())); return JToken.Load(reader); } } } catch (WebException ex) when (ex.Response is HttpWebResponse response) { if (response.StatusCode == HttpStatusCode.Forbidden) VerifyRateLimit(response); else if (response.StatusCode == HttpStatusCode.Unauthorized) throw new Exception("Failed to authenticate GitHub request"); else if ((int)response.StatusCode == 422) //Unprocessable Entity throw new Exception("Error performing request"); throw; } } void AddAuthorization(WebClient client, string? authorizationToken) { if (!String.IsNullOrWhiteSpace(authorizationToken)) { client.Headers.Set(HttpRequestHeader.Authorization, String.Concat("token ", authorizationToken)); } } void VerifyRateLimit(HttpWebResponse response) { var remainingRequests = response.Headers.GetValues("X-RateLimit-Remaining").FirstOrDefault(); if (remainingRequests == "0") { var secondsToWait = -1; if (int.TryParse(response.Headers.GetValues("X-RateLimit-Reset").FirstOrDefault(), out var reset)) { var t = DateTime.UtcNow - new DateTime(1970, 1, 1); secondsToWait = reset - (int)t.TotalSeconds; } throw new Exception($"GitHub request rate limit has been hit. Try operation again in {secondsToWait} seconds. " + "Unauthenticated users can perform 10 search requests and 60 non search HTTP requests to GitHub per minute per IP address." + "It is reccomended that you provide credentials to increase this limit."); } } string GetUserAgent() { return $"OctopusDeploy-Calamari/{GetType().Assembly.GetInformationalVersion()}"; } /// <summary> /// Takes files from the root inner directory, and moves down to root. /// Currently only relevent for Git archives. /// e.g. /Dir/MyFile => /MyFile /// This was created indpependantly from the version above since Calamari needs to support .net 4.0 here which does not have `System.IO.Compression` library. /// The reason this library is preferred over `SharpCompress` is that it can update zips in-place and it preserves empty directories. /// https://github.com/adamhathcock/sharpcompress/issues/62 /// https://github.com/adamhathcock/sharpcompress/issues/34 /// https://github.com/adamhathcock/sharpcompress/issues/242 /// Unfortunately the server needs the same logic so that we can ensure that the Hash comparisons match. /// </summary> /// <param name="fileName"></param> static void DeNestContents(string src, string dest) { var rootPathSeperator = -1; using (var readerStram = File.Open(src, FileMode.Open, FileAccess.ReadWrite)) using (var reader = ReaderFactory.Open(readerStram)) { using (var writerStream = File.Open(dest, FileMode.CreateNew, FileAccess.ReadWrite)) using (var writer = WriterFactory.Open(writerStream, ArchiveType.Zip, new ZipWriterOptions(CompressionType.Deflate))) { while (reader.MoveToNextEntry()) { var entry = reader.Entry; if (!reader.Entry.IsDirectory) { if (rootPathSeperator == -1) rootPathSeperator = entry.Key.IndexOf('/') + 1; try { var newFilePath = entry.Key.Substring(rootPathSeperator); if (newFilePath != string.Empty) writer.Write(newFilePath, reader.OpenEntryStream()); } catch (Exception) { } } } } } } } }<file_sep>using System; namespace Calamari.Common.Features.StructuredVariables { public static class StructuredConfigMessages { public static readonly string NoStructuresFound = "No structures have been found that match variable names, so no structured variable replacements have been applied."; public static string StructureFound(string name) { return $"Structure found matching the variable '{name}'. Replacing its content with the variable value."; } } }<file_sep>using System; using System.Threading.Tasks; using Calamari.AzureAppService.Azure; using Calamari.Common.Commands; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureAppService.Behaviors { public class LegacyAppDeployBehaviour : IDeployBehaviour { readonly LegacyAzureAppServiceDeployContainerBehavior containerBehaviour; readonly LegacyAzureAppServiceBehaviour appServiceBehaviour; ILog Log { get; } public LegacyAppDeployBehaviour(ILog log) { Log = log; containerBehaviour = new LegacyAzureAppServiceDeployContainerBehavior(log); appServiceBehaviour = new LegacyAzureAppServiceBehaviour(log); } public bool IsEnabled(RunningDeployment context) => !FeatureToggle.ModernAzureAppServiceSdkFeatureToggle.IsEnabled(context.Variables); public Task Execute(RunningDeployment context) { var deploymentType = context.Variables.Get(SpecialVariables.Action.Azure.DeploymentType); Log.Verbose($"Deployment type: {deploymentType}"); return deploymentType switch { "Container" => containerBehaviour.Execute(context), _ => appServiceBehaviour.Execute(context) }; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Commands; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Proxies; using Calamari.Common.Plumbing.Variables; using Calamari.Util; namespace Calamari.LaunchTools { [LaunchTool(LaunchTools.Node)] public class NodeExecutor : LaunchTool<NodeInstructions> { readonly CommonOptions options; readonly IVariables variables; readonly ICommandLineRunner commandLineRunner; readonly ILog log; const string DebugVariableName = "Octopus.StepPackage.Bootstrap.Debug"; public NodeExecutor(CommonOptions options, IVariables variables, ICommandLineRunner commandLineRunner, ILog log) { this.options = options; this.variables = variables; this.commandLineRunner = commandLineRunner; this.log = log; } protected override int ExecuteInternal(NodeInstructions instructions) { using (var variableFile = new TemporaryFile(Path.GetTempFileName())) { var jsonInputs = variables.GetRaw(instructions.InputsVariable) ?? string.Empty; variables.Set(instructions.InputsVariable, InputSubstitution.SubstituteAndEscapeAllVariablesInJson(jsonInputs, variables, log)); var variablesAsJson = variables.CloneAndEvaluate().SaveAsString(); File.WriteAllBytes(variableFile.FilePath, new AesEncryption(options.InputVariables.SensitiveVariablesPassword).Encrypt(variablesAsJson)); var pathToNode = variables.Get(instructions.NodePathVariable); var nodeExecutablePath = BuildNodePath(pathToNode); var parameters = BuildParams(instructions, variableFile.FilePath); var runningDeployment = new RunningDeployment(variables); var commandLineInvocation = new CommandLineInvocation(nodeExecutablePath, parameters) { WorkingDirectory = runningDeployment.CurrentDirectory, OutputToLog = true, EnvironmentVars = ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables().ToDictionary(e => e.Key, e => e.Value) }; var commandResult = commandLineRunner.Execute(commandLineInvocation); return commandResult.ExitCode; } } static string BuildNodePath(string pathToNode) => CalamariEnvironment.IsRunningOnWindows ? Path.Combine(pathToNode, "node.exe") : Path.Combine(pathToNode, "bin", "node"); string BuildParams(NodeInstructions instructions, string sensitiveVariablesFilePath) { var parameters = new List<string>(); var debugMode = variables.GetFlag(DebugVariableName, false); if (debugMode) { parameters.Add("--inspect-brk"); } var pathToBootstrapperFolder = variables.Get(instructions.BootstrapperPathVariable); var pathToBootstrapper = Path.Combine(pathToBootstrapperFolder, "bootstrapper.js"); parameters.Add(pathToBootstrapper); parameters.Add(instructions.BootstrapperInvocationCommand); var pathToStepPackage = variables.Get(instructions.TargetPathVariable); parameters.Add(pathToStepPackage); parameters.Add(sensitiveVariablesFilePath); parameters.Add(options.InputVariables.SensitiveVariablesPassword); parameters.Add(AesEncryption.SaltRaw); if (string.Equals(instructions.BootstrapperInvocationCommand, "Execute", StringComparison.OrdinalIgnoreCase)) { parameters.Add(instructions.InputsVariable); parameters.Add(instructions.DeploymentTargetInputsVariable); } else if (string.Equals(instructions.BootstrapperInvocationCommand, "Discover", StringComparison.OrdinalIgnoreCase)) { parameters.Add(instructions.TargetDiscoveryContextVariable); } else { throw new CommandException($"Unknown bootstrapper invocation command: '{instructions.BootstrapperInvocationCommand}'"); } return string.Join(" ", parameters.Select(p => $"\"{p}\"")); } } public class NodeInstructions { public string NodePathVariable { get; set; } public string TargetPathVariable { get; set; } public string BootstrapperPathVariable { get; set; } public string BootstrapperInvocationCommand { get; set; } public string InputsVariable { get; set; } public string DeploymentTargetInputsVariable { get; set; } public string TargetDiscoveryContextVariable { get; set; } } }<file_sep>namespace Calamari.Aws.Integration.S3 { public enum S3TargetMode { Unknown = 0, EntirePackage = 1, FileSelections = 2 } }<file_sep>using System; using System.Security.Cryptography; namespace Calamari.Tests.Fixtures.Util { /// <summary> /// This class largely implements the original method at https://referencesource.microsoft.com/#System.Web/Security/Membership.cs,302 /// which is currently not available in netstandard. /// Feel free to remove this if\when it becomes available again in a standard library /// </summary> public static class PasswordGenerator { static readonly char[] Punctuations = "!@#$%^&*()_-+=[{]};:>|./?".ToCharArray(); static readonly char[] StartingChars = {'<', '&'}; public static string Generate(int length, int numberOfNonAlphanumericCharacters) { if (length < 1 || length > 128) { throw new ArgumentException(nameof(length)); } if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0) { throw new ArgumentException(nameof(numberOfNonAlphanumericCharacters)); } using (var rng = RandomNumberGenerator.Create()) { string password; do { var byteBuffer = new byte[length]; rng.GetBytes(byteBuffer); var count = 0; var characterBuffer = new char[length]; for (var iter = 0; iter < length; iter++) { var i = byteBuffer[iter] % 87; if (i < 10) { characterBuffer[iter] = (char) ('0' + i); } else if (i < 36) { characterBuffer[iter] = (char) ('A' + i - 10); } else if (i < 62) { characterBuffer[iter] = (char) ('a' + i - 36); } else { characterBuffer[iter] = Punctuations[i - 62]; count++; } } if (count < numberOfNonAlphanumericCharacters) { int j; var rand = new Random(); for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++) { int k; do { k = rand.Next(0, length); } while (!char.IsLetterOrDigit(characterBuffer[k])); characterBuffer[k] = Punctuations[rand.Next(0, Punctuations.Length)]; } } password = new string(characterBuffer); } while (IsDangerousString(password, out _)); return password; } } static bool IsAtoZ(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } internal static bool IsDangerousString(string s, out int matchIndex) { //bool inComment = false; matchIndex = 0; for (int i = 0;;) { // Look for the start of one of our patterns int n = s.IndexOfAny(StartingChars, i); // If not found, the string is safe if (n < 0) return false; // If it's the last char, it's safe if (n == s.Length - 1) return false; matchIndex = n; switch (s[n]) { case '<': // If the < is followed by a letter or '!', it's unsafe (looks like a tag or HTML comment) if (IsAtoZ(s[n + 1]) || s[n + 1] == '!' || s[n + 1] == '/' || s[n + 1] == '?') return true; break; case '&': // If the & is followed by a #, it's unsafe (e.g. &#83;) if (s[n + 1] == '#') return true; break; } // Continue searching i = n + 1; } } } }<file_sep>using System; using System.Runtime.Serialization; namespace Calamari.Aws.Deployment { public class AmazonFileUploadException : Exception { public AmazonFileUploadException(){} public AmazonFileUploadException(string message) : base(message){} public AmazonFileUploadException(string message, Exception innerException) : base(message, innerException){} protected AmazonFileUploadException(SerializationInfo info, StreamingContext context) : base(info, context){} } }<file_sep>using System; using System.Net; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.Proxies; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Proxies { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class ProxyInitializerFixture { const string BadproxyUrl = "http://proxy-initializer-fixture-bad-proxy:1234"; const string WebRequestUrl = "http://octopus.com"; const string ProxyUserName = "someuser"; const string ProxyPassword = "<PASSWORD>"; string proxyHost; int proxyPort; string proxyUrl; IWebProxy defaultWebProxy; [SetUp] public void Setup() { if (CalamariEnvironment.IsRunningOnWindows) defaultWebProxy = WebRequest.DefaultWebProxy; proxyHost = "proxy-initializer-fixture-good-proxy"; proxyPort = 8888; proxyUrl = $"http://{proxyHost}:{proxyPort}"; } [TearDown] public void TearDown() { ResetProxyEnvironmentVariables(); if (CalamariEnvironment.IsRunningOnWindows) WebRequest.DefaultWebProxy = defaultWebProxy; ResetSystemProxy(); } static void ResetSystemProxy() { if (CalamariEnvironment.IsRunningOnWindows) ProxyRoutines.SetProxy(false).Should().BeTrue(); } [Test] [RequiresDotNetFramework] public void Initialize_HasSystemProxy_NoProxy() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); RunWith(false, "", 80, "", ""); AssertProxyNotUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_HasSystemProxy_UseSystemProxy() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); RunWith(true, "", 80, "", ""); AssertUnauthenticatedSystemProxyUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_HasSystemProxy_UseSystemProxyWithCredentials() { ProxyRoutines.SetProxy(proxyUrl).Should().BeTrue(); RunWith(true, "", 80, ProxyUserName, ProxyPassword); AssertAuthenticatedProxyUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_HasSystemProxy_CustomProxy() { ProxyRoutines.SetProxy(BadproxyUrl).Should().BeTrue(); RunWith(false, proxyHost, proxyPort, "", ""); AssertUnauthenticatedProxyUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_HasSystemProxy_CustomProxyWithCredentials() { ProxyRoutines.SetProxy(BadproxyUrl).Should().BeTrue(); RunWith(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword); AssertAuthenticatedProxyUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_NoSystemProxy_NoProxy() { RunWith(false, "", 80, "", ""); AssertProxyNotUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_NoSystemProxy_UseSystemProxy() { RunWith(true, "", 80, "", ""); AssertProxyNotUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_NoSystemProxy_UseSystemProxyWithCredentials() { RunWith(true, "", 80, ProxyUserName, ProxyPassword); AssertProxyNotUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_NoSystemProxy_CustomProxy() { RunWith(false, proxyHost, proxyPort, "", ""); AssertUnauthenticatedProxyUsed(); } [Test] [RequiresDotNetFramework] public void Initialize_NoSystemProxy_CustomProxyWithCredentials() { RunWith(false, proxyHost, proxyPort, ProxyUserName, ProxyPassword); AssertAuthenticatedProxyUsed(); } void RunWith( bool useDefaultProxy, string proxyhost, int proxyPort, string proxyUsername, string proxyPassword) { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy, useDefaultProxy.ToString()); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, proxyhost); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, proxyPort.ToString()); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername, proxyUsername); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword, <PASSWORD>Password); ProxyInitializer.InitializeDefaultProxy(); } void ResetProxyEnvironmentVariables() { Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleUseDefaultProxy, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyHost, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyUsername, string.Empty); Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPassword, string.Empty); } void AssertAuthenticatedProxyUsed() { AssertProxyUsed(); var credentials = WebRequest.DefaultWebProxy.Credentials.Should().BeOfType<NetworkCredential>().Subject; credentials.UserName.Should().Be(ProxyUserName); credentials.Password.Should().Be(ProxyPassword); } void AssertUnauthenticatedProxyUsed() { AssertProxyUsed(); var credentials = WebRequest.DefaultWebProxy.Credentials.Should().BeOfType<NetworkCredential>().Subject; credentials.UserName.Should().Be(""); credentials.Password.Should().Be(""); } void AssertUnauthenticatedSystemProxyUsed() { AssertProxyUsed(); var credentials = WebRequest.DefaultWebProxy.Credentials.Should().BeAssignableTo<NetworkCredential>() .Subject; credentials.GetType().Name.Should() .Be("SystemNetworkCredential"); //It's internal so we can't access the type credentials.UserName.Should().Be(""); credentials.Password.Should().Be(""); } void AssertProxyUsed() { var uri = new Uri(WebRequestUrl); WebRequest.DefaultWebProxy.GetProxy(uri).Should().Be(new Uri(proxyUrl), "should use the proxy"); } static void AssertProxyNotUsed() { var uri = new Uri(WebRequestUrl); WebRequest.DefaultWebProxy.GetProxy(uri).Should().Be(uri, "shouldn't use the proxy"); } } } <file_sep>using System; using System.Diagnostics; using System.Net; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Packages.NuGet; using Calamari.Testing.Requirements; using FluentAssertions; using NSubstitute; using NUnit.Framework; using Octopus.Versioning; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class NuGetPackageDownloaderFixture { [Test] public void AttemptsOnlyOnceIfSuccessful() { var packageId = "FakePackageId"; var version = VersionFactory.CreateSemanticVersion(1, 2, 3); var feedUri = new Uri("http://www.myget.org"); var feedCredentials = new CredentialCache(); var targetFilePath = "FakeTargetFilePath"; var filesystem = Substitute.For<ICalamariFileSystem>(); var variables = new CalamariVariables(); var calledCount = 0; var downloader = new InternalNuGetPackageDownloader(filesystem, variables); downloader.DownloadPackage(packageId, version, feedUri, feedCredentials, targetFilePath, maxDownloadAttempts: 5, downloadAttemptBackoff: TimeSpan.Zero, action: (arg1, arg2, arg3, arg4, arg5) => { calledCount++; }); Assert.That(calledCount, Is.EqualTo(1)); } [Test] [TestCase(1, ExpectedResult = 1)] [TestCase(5, ExpectedResult = 5)] [TestCase(7, ExpectedResult = 7)] public int AttemptsTheRightNumberOfTimesOnError(int maxDownloadAttempts) { var packageId = "FakePackageId"; var version = VersionFactory.CreateSemanticVersion(1, 2, 3); var feedUri = new Uri("http://www.myget.org"); var feedCredentials = new CredentialCache(); var targetFilePath = "FakeTargetFilePath"; var filesystem = Substitute.For<ICalamariFileSystem>(); var variables = new CalamariVariables(); var calledCount = 0; Assert.Throws<Exception>(() => { var downloader = new InternalNuGetPackageDownloader(filesystem, variables); downloader.DownloadPackage(packageId, version, feedUri, feedCredentials, targetFilePath, maxDownloadAttempts: maxDownloadAttempts, downloadAttemptBackoff: TimeSpan.Zero, action: (arg1, arg2, arg3, arg4, arg5) => { calledCount++; throw new Exception("Expected exception from test: simulate download failing"); }); }); return calledCount; } #if USE_NUGET_V2_LIBS const string SkipFreeBsdBecause = "performance on Mono+FreeBSD fluctuates significantly"; // We only support the specification of HTTP timeouts on V3 nuget endpoints in // .NET framework. V2 nuget endpoints and .net core runtimes execute entirely // different codepaths that don't give us an easy way to allow users to specify // timeouts. [Test] [NonParallelizable] [RequiresNonFreeBSDPlatform(SkipFreeBsdBecause)] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void TimesOutIfAValidTimeoutIsDefinedInVariables() { RunNugetV3TimeoutTest("00:00:01", TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1)); } [Test] [NonParallelizable] [RequiresNonFreeBSDPlatform(SkipFreeBsdBecause)] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void IgnoresTheTimeoutIfAnInvalidTimeoutIsDefinedInVariables() { RunNugetV3TimeoutTest("this is not a valid timespan", TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2)); } [Test] [NonParallelizable] [RequiresNonFreeBSDPlatform(SkipFreeBsdBecause)] [RequiresMinimumMonoVersion(5, 12, 0, Description = "HttpClient 4.3.2 broken on Mono - https://xamarin.github.io/bugzilla-archives/60/60315/bug.html#c7")] public void DoesNotTimeOutIfTheServerRespondsBeforeTheTimeout() { RunNugetV3TimeoutTest("00:01:00", TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); } void RunNugetV3TimeoutTest(string timeoutInVariables, TimeSpan serverResponseTime, TimeSpan estimatedTimeout) { using (var server = new TestHttpServer(9001, serverResponseTime)) { var packageId = "FakePackageId"; var version = VersionFactory.CreateSemanticVersion(1, 2, 3); var feedCredentials = new CredentialCache(); var targetFilePath = "FakeTargetFilePath"; var filesystem = Substitute.For<ICalamariFileSystem>(); var v3NugetUri = new Uri(server.BaseUrl + "/index.json"); var variables = new CalamariVariables(); if (timeoutInVariables != null) { variables[KnownVariables.NugetHttpTimeout] = timeoutInVariables; } var downloader = new InternalNuGetPackageDownloader(filesystem, variables); var stopwatch = new Stopwatch(); Action invocation = () => { stopwatch.Start(); try { downloader.DownloadPackage( packageId, version, v3NugetUri, feedCredentials, targetFilePath, maxDownloadAttempts: 1, downloadAttemptBackoff: TimeSpan.Zero ); } finally { stopwatch.Stop(); } }; invocation.Should() .ThrowExactly<Exception>(); stopwatch.Elapsed .Should() .BeCloseTo(estimatedTimeout, TimeSpan.FromSeconds(0.5)); } } #endif } } <file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.Commands; namespace Calamari.Common.Features.Processes { public class SplitCommandInvocationOutputSink : ICommandInvocationOutputSink { readonly List<ICommandInvocationOutputSink> outputs; public SplitCommandInvocationOutputSink(params ICommandInvocationOutputSink[] outputs) : this(new List<ICommandInvocationOutputSink>(outputs)) { } public SplitCommandInvocationOutputSink(List<ICommandInvocationOutputSink> outputs) { this.outputs = outputs; } public void WriteInfo(string line) { foreach (var output in outputs) output.WriteInfo(line); } public void WriteError(string line) { foreach (var output in outputs) output.WriteError(line); } } }<file_sep>using System; namespace Calamari.Aws.Deployment { public static class CloudFormationDefaults { public static readonly TimeSpan StatusWaitPeriod; public static readonly int RetryCount = 3; static CloudFormationDefaults() { StatusWaitPeriod = TimeSpan.FromSeconds(5); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.Deployment; using Calamari.Testing.Helpers; using Calamari.Testing.Requirements; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.DotnetScript { [TestFixture] [Category(TestCategory.ScriptingSupport.DotnetScript)] public class DotnetScriptFixture : CalamariFixture { [Test, RequiresDotNetCore] public void ShouldPrintEncodedVariable() { var (output, _) = RunScript("PrintEncodedVariable.csx"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='RG9ua2V5' value='S29uZw==']"); } [Test, RequiresDotNetCore] public void ShouldPrintSensitiveVariable() { var (output, _) = RunScript("PrintSensitiveVariable.csx"); output.AssertSuccess(); output.AssertOutput("##octopus[setVariable name='UGFzc3dvcmQ=' value='Y29ycmVjdCBob3JzZSBiYXR0ZXJ5IHN0YXBsZQ==' sensitive='VHJ1ZQ==']"); } [Test, RequiresDotNetCore] public void ShouldCreateArtifact() { var (output, _) = RunScript("CreateArtifact.csx"); output.AssertSuccess(); output.AssertOutput("##octopus[createArtifact"); output.AssertOutput("name='bXlGaWxlLnR4dA==' length='MTAw']"); } [Test, RequiresDotNetCore] public void ShouldUpdateProgress() { var (output, _) = RunScript("UpdateProgress.csx"); output.AssertSuccess(); output.AssertOutput("##octopus[progress percentage='NTA=' message='SGFsZiBXYXk=']"); } [Test, RequiresDotNetCore] public void ShouldCallHello() { var (output, _) = RunScript("Hello.csx", new Dictionary<string, string>() { ["Name"] = "Paul", ["Variable2"] = "DEF", ["Variable3"] = "GHI", ["Foo_bar"] = "Hello", ["Host"] = "Never", }); output.AssertSuccess(); output.AssertOutput("Hello Paul"); //output.AssertProcessNameAndId("dotnet-script"); } [Test, RequiresDotNetCore] public void ShouldCallHelloWithSensitiveVariable() { var (output, _) = RunScript("Hello.csx", new Dictionary<string, string>() { ["Name"] = "NameToEncrypt" }, sensitiveVariablesPassword: "<PASSWORD>=="); output.AssertSuccess(); output.AssertOutput("Hello NameToEncrypt"); } [Test, RequiresDotNetCore] public void ShouldConsumeParametersWithQuotes() { var (output, _) = RunScript("Parameters.csx", new Dictionary<string, string>() { [SpecialVariables.Action.Script.ScriptParameters] = "-- \"Para meter0\" Parameter1" }); output.AssertSuccess(); output.AssertOutput("Parameters Para meter0Parameter1"); } [Test, RequiresDotNetCore] public void ShouldConsumeParametersWithoutParametersPrefix() { var (output, _) = RunScript("Parameters.csx", new Dictionary<string, string>() { [SpecialVariables.Action.Script.ScriptParameters] = "Parameter0 Parameter1" }); output.AssertSuccess(); output.AssertOutput("Parameters Parameter0Parameter1"); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes; using Calamari.Kubernetes.Integration; using Calamari.Kubernetes.ResourceStatus; using Calamari.Kubernetes.ResourceStatus.Resources; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Integration.FileSystem; using Calamari.Tests.Helpers; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.KubernetesFixtures.ResourceStatus { [TestFixture] public class ResourceStatusReportWrapperTests { private const ScriptSyntax Syntax = ScriptSyntax.Bash; [Test] public void Enabled_WhenDeployingToAKubernetesClusterWithStatusCheckEnabled() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => new MockResourceStatusChecker(rs)); AddKubernetesStatusCheckVariables(variables); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.IsEnabled(Syntax).Should().BeTrue(); } [Test] public void NotEnabled_WhenDeployingToAKubernetesClusterWithStatusCheckDisabled() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => new MockResourceStatusChecker(rs)); variables.Set(KnownVariables.EnabledFeatureToggles, "KubernetesDeploymentStatusFeatureToggle"); variables.Set(SpecialVariables.ClusterUrl, "https://localhost"); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.IsEnabled(Syntax).Should().BeFalse(); } [Test] public void NotEnabled_WhenDoingABlueGreenDeployment() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => new MockResourceStatusChecker(rs)); AddKubernetesStatusCheckVariables(variables); variables.Set(SpecialVariables.DeploymentStyle, "bluegreen"); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.IsEnabled(Syntax).Should().BeFalse(); } [Test] public void NotEnabled_WhenWaitForDeploymentIsSelected() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => new MockResourceStatusChecker(rs)); AddKubernetesStatusCheckVariables(variables); variables.Set(SpecialVariables.DeploymentWait, "wait"); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.IsEnabled(Syntax).Should().BeFalse(); } [Test] public void FindsCorrectManifestFiles() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); MockResourceStatusChecker statusChecker = null; var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => statusChecker = new MockResourceStatusChecker(rs)); AddKubernetesStatusCheckVariables(variables); variables.Set(SpecialVariables.CustomResourceYamlFileName, "custom.yml"); var testDirectory = TestEnvironment.GetTestPath("KubernetesFixtures", "ResourceStatus", "assets", "manifests"); fileSystem.SetFileBasePath(testDirectory); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.NextWrapper = new StubScriptWrapper().Enable(); wrapper.ExecuteScript( new Script("stub"), Syntax, new CommandLineRunner(log, variables), new Dictionary<string, string>()); statusChecker.Should().NotBeNull(); statusChecker.CheckedResources.Should().BeEquivalentTo( new ResourceIdentifier("Deployment", "deployment", "default"), new ResourceIdentifier("Ingress", "ingress", "default"), new ResourceIdentifier("Secret", "secret", "default"), new ResourceIdentifier("Service", "service", "default"), new ResourceIdentifier("CustomResource", "custom-resource", "default")); } [Test] public void FindsConfigMapsDeployedInADeployContainerStepWhenConfigMapDataIsNotEmpty() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); MockResourceStatusChecker statusChecker = null; var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => statusChecker = new MockResourceStatusChecker(rs)); const string configMapName = "ConfigMap-Deployment-01"; AddKubernetesStatusCheckVariables(variables); variables.Set("Octopus.Action.KubernetesContainers.KubernetesConfigMapEnabled", "True"); variables.Set("Octopus.Action.KubernetesContainers.ComputedConfigMapName", configMapName); variables.Set("Octopus.Action.KubernetesContainers.ConfigMapData[1].FileName", "1"); var tempDirectory = fileSystem.CreateTemporaryDirectory(); try { fileSystem.SetFileBasePath(tempDirectory); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.NextWrapper = new StubScriptWrapper().Enable(); wrapper.ExecuteScript( new Script("stub"), Syntax, new CommandLineRunner(log, variables), new Dictionary<string, string>()); statusChecker.Should().NotBeNull(); statusChecker.CheckedResources.Should().BeEquivalentTo(new ResourceIdentifier("ConfigMap", configMapName, "default")); } finally { fileSystem.DeleteDirectory(tempDirectory); } } [Test] public void SkipsConfigMapsInADeployContainerStepWhenConfigMapDataIsNotSet() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); MockResourceStatusChecker statusChecker = null; var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => statusChecker = new MockResourceStatusChecker(rs)); const string configMapName = "ConfigMap-Deployment-01"; AddKubernetesStatusCheckVariables(variables); variables.Set("Octopus.Action.KubernetesContainers.KubernetesConfigMapEnabled", "True"); variables.Set("Octopus.Action.KubernetesContainers.ComputedConfigMapName", configMapName); var tempDirectory = fileSystem.CreateTemporaryDirectory(); try { fileSystem.SetFileBasePath(tempDirectory); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.NextWrapper = new StubScriptWrapper().Enable(); wrapper.ExecuteScript( new Script("stub"), Syntax, new CommandLineRunner(log, variables), new Dictionary<string, string>()); statusChecker.Should().NotBeNull(); statusChecker.CheckedResources.Should().BeEmpty(); } finally { fileSystem.DeleteDirectory(tempDirectory); } } [Test] public void FindsSecretsDeployedInADeployContainerStepWhenSecretDataIsSet() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); MockResourceStatusChecker statusChecker = null; var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => statusChecker = new MockResourceStatusChecker(rs)); const string secret = "Secret-Deployment-01"; AddKubernetesStatusCheckVariables(variables); variables.Set("Octopus.Action.KubernetesContainers.KubernetesSecretEnabled", "True"); variables.Set("Octopus.Action.KubernetesContainers.ComputedSecretName", secret); variables.Set("Octopus.Action.KubernetesContainers.SecretData[1].FileName", "1"); var tempDirectory = fileSystem.CreateTemporaryDirectory(); try { fileSystem.SetFileBasePath(tempDirectory); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.NextWrapper = new StubScriptWrapper().Enable(); wrapper.ExecuteScript( new Script("stub"), Syntax, new CommandLineRunner(log, variables), new Dictionary<string, string>()); statusChecker.Should().NotBeNull(); statusChecker.CheckedResources.Should().BeEquivalentTo(new[] { new ResourceIdentifier("Secret", secret, "default") }); } finally { fileSystem.DeleteDirectory(tempDirectory); } } [Test] public void SkipsSecretsInADeployContainerStepWhenSecretDataIsNotSet() { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); MockResourceStatusChecker statusChecker = null; var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => statusChecker = new MockResourceStatusChecker(rs)); const string secret = "Secret-Deployment-01"; AddKubernetesStatusCheckVariables(variables); variables.Set("Octopus.Action.KubernetesContainers.KubernetesSecretEnabled", "True"); variables.Set("Octopus.Action.KubernetesContainers.ComputedSecretName", secret); var tempDirectory = fileSystem.CreateTemporaryDirectory(); try { fileSystem.SetFileBasePath(tempDirectory); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.NextWrapper = new StubScriptWrapper().Enable(); wrapper.ExecuteScript( new Script("stub"), Syntax, new CommandLineRunner(log, variables), new Dictionary<string, string>()); statusChecker.Should().NotBeNull(); statusChecker.CheckedResources.Should().BeEmpty(); } finally { fileSystem.DeleteDirectory(tempDirectory); } } [TestCase(null)] [TestCase("")] public void SetNamespaceToDefaultWhenTheDefaultNamespaceIsNullOrAnEmptyString(string @namespace) { var variables = new CalamariVariables(); var log = new SilentLog(); var fileSystem = new TestCalamariPhysicalFileSystem(); var kubectl = new Kubectl(variables, log, new CommandLineRunner(log, variables)); MockResourceStatusChecker statusChecker = null; var reportExecutor = new ResourceStatusReportExecutor(variables, (_, __, rs) => statusChecker = new MockResourceStatusChecker(rs)); AddKubernetesStatusCheckVariables(variables); variables.Set(SpecialVariables.Namespace, @namespace); var testDirectory = TestEnvironment.GetTestPath("KubernetesFixtures", "ResourceStatus", "assets", "no-namespace"); fileSystem.SetFileBasePath(testDirectory); var wrapper = new ResourceStatusReportWrapper(kubectl, variables, fileSystem, reportExecutor); wrapper.NextWrapper = new StubScriptWrapper().Enable(); wrapper.ExecuteScript( new Script("stub"), Syntax, new CommandLineRunner(log, variables), new Dictionary<string, string>()); statusChecker.Should().NotBeNull(); statusChecker.CheckedResources.Should().BeEquivalentTo(new ResourceIdentifier("Deployment", "deployment", "default")); } private static void AddKubernetesStatusCheckVariables(IVariables variables) { variables.Set(SpecialVariables.ClusterUrl, "https://localhost"); variables.Set(SpecialVariables.ResourceStatusCheck, "True"); } } internal class MockResourceStatusChecker : IRunningResourceStatusCheck { public HashSet<ResourceIdentifier> CheckedResources { get; } = new HashSet<ResourceIdentifier>(); public MockResourceStatusChecker(IEnumerable<ResourceIdentifier> initialResources) { CheckedResources.UnionWith(initialResources); } public async Task<bool> WaitForCompletionOrTimeout() { return await Task.FromResult(true); } public async Task AddResources(ResourceIdentifier[] newResources) { await Task.CompletedTask; CheckedResources.UnionWith(newResources); } } internal class StubScriptWrapper : IScriptWrapper { private bool isEnabled = false; public int Priority { get; } = 1; public IScriptWrapper NextWrapper { get; set; } public bool IsEnabled(ScriptSyntax syntax) => isEnabled; // We manually enable this wrapper when needed, // to avoid this wrapper being auto-registered and called from real programs public StubScriptWrapper Enable() { isEnabled = true; return this; } public CommandResult ExecuteScript( Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string> environmentVars) { return new CommandResult("stub", 0); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Calamari.Common.Features.Processes.Semaphores; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Integration.Process.Semaphores { [TestFixture] public class ProcessFinderFixture { [Test] public void ProcessIsRunningReturnsTrueForCurrentProcess() { var processFinder = new ProcessFinder(); var currentProcess = System.Diagnostics.Process.GetCurrentProcess(); var result = processFinder.ProcessIsRunning(currentProcess.Id, currentProcess.ProcessName); Assert.That(result, Is.True); } [Test] public void ProcessIsRunningReturnsFalseForNonExistantProcess() { var processFinder = new ProcessFinder(); var result = processFinder.ProcessIsRunning(-1, Guid.NewGuid().ToString()); Assert.That(result, Is.EqualTo(GetExpectedResult())); } private bool GetExpectedResult() { try { var processes = System.Diagnostics.Process.GetProcesses(); return false; } catch (NotSupportedException) { //not supported on FreeBSD. Probably a nicer way to do this. return true; } } } } <file_sep>#if NETCORE using System; using System.Collections.Generic; using System.IO; using Calamari.Aws.Kubernetes.Discovery; using Calamari.Commands; using Calamari.Common.Features.Discovery; using Calamari.Common.Features.Scripts; using Calamari.Common.FeatureToggles; using Calamari.Common.Plumbing; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Common.Plumbing.Variables; using Calamari.Kubernetes.Commands; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; using KubernetesSpecialVariables = Calamari.Kubernetes.SpecialVariables; using SpecialVariables = Calamari.Deployment.SpecialVariables; namespace Calamari.Tests.KubernetesFixtures { public abstract class KubernetesContextScriptWrapperLiveFixtureBase : CalamariFixture { protected const string TestNamespace = "calamari-testing"; protected IVariables variables; protected string testFolder; [OneTimeSetUp] public void SetupTests() { testFolder = Path.GetDirectoryName(GetType().Assembly.FullLocalPath()); } [SetUp] public void Setup() { variables = new CalamariVariables(); variables.Set(KnownVariables.EnabledFeatureToggles, FeatureToggle.KubernetesAksKubeloginFeatureToggle.ToString()); Log = new DoNotDoubleLog(); SetTestClusterVariables(); } protected void DeployWithDeploymentScriptAndVerifyResult(Func<string, string> addFilesOrPackageFunc = null, bool shouldSucceed = true) { var scriptPath = Path.Combine(testFolder, "KubernetesFixtures/Scripts"); var bashScript = File.ReadAllText(Path.Combine(scriptPath, "KubernetesDeployment.sh")); var powershellScript = File.ReadAllText(Path.Combine(scriptPath, "KubernetesDeployment.ps1")); SetInlineScriptVariables(bashScript, powershellScript); ExecuteCommandAndVerifyResult(RunScriptCommand.Name, addFilesOrPackageFunc, shouldSucceed); } protected void DeployWithKubectlTestScriptAndVerifyResult() { SetInlineScriptVariables("#{Octopus.Action.Kubernetes.CustomKubectlExecutable} cluster-info"); ExecuteCommandAndVerifyResult(RunScriptCommand.Name); } protected void DeployWithNonKubectlTestScriptAndVerifyResult() { SetInlineScriptVariables("echo running target script..."); ExecuteCommandAndVerifyResult(RunScriptCommand.Name); } protected void ExecuteCommandAndVerifyResult(string commandName, Func<string, string> addFilesOrPackageFunc = null, bool shouldSucceed = true) { using (var dir = TemporaryDirectory.Create()) { var directoryPath = dir.DirectoryPath; // Note: the "Test Folder" has a space in it to test that working directories // with spaces are handled correctly by Kubernetes Steps. var folderPath = Path.Combine(directoryPath, "Test Folder"); Directory.CreateDirectory(folderPath); var packagePath = addFilesOrPackageFunc?.Invoke(folderPath); var output = ExecuteCommand(commandName, folderPath, packagePath); WriteLogMessagesToTestOutput(); if (shouldSucceed) { output.AssertSuccess(); } else { output.AssertFailure(); } } } protected virtual Dictionary<string, string> GetEnvironments() { return new Dictionary<string, string>(); } protected void DoDiscovery(AwsAuthenticationDetails authenticationDetails) { var scope = new TargetDiscoveryScope("TestSpace", "Staging", "testProject", null, new[] { "discovery-role" }, "WorkerPools-1", null); var targetDiscoveryContext = new TargetDiscoveryContext<AwsAuthenticationDetails>(scope, authenticationDetails); ExecuteDiscoveryCommandAndVerifyResult(targetDiscoveryContext); } protected void DoDiscoveryAndAssertReceivedServiceMessageWithMatchingProperties( AwsAuthenticationDetails authenticationDetails, Dictionary<string,string> properties) { DoDiscovery(authenticationDetails); var expectedServiceMessage = new ServiceMessage( KubernetesDiscoveryCommand.CreateKubernetesTargetServiceMessageName, properties); Log.ServiceMessages.Should() .ContainSingle(s => s.Name == KubernetesDiscoveryCommand.CreateKubernetesTargetServiceMessageName && s.Properties["name"] == properties["name"]) .Which.Should() .BeEquivalentTo(expectedServiceMessage); } protected void ExecuteDiscoveryCommandAndVerifyResult<TAuthenticationDetails>( TargetDiscoveryContext<TAuthenticationDetails> discoveryContext) where TAuthenticationDetails : class, ITargetDiscoveryAuthenticationDetails { variables.Add(KubernetesDiscoveryCommand.ContextVariableName, JsonConvert.SerializeObject(discoveryContext)); ExecuteCommandAndVerifyResult(KubernetesDiscoveryCommand.Name); } private void SetTestClusterVariables() { variables.Set(KubernetesSpecialVariables.Namespace, TestNamespace); variables.Set(ScriptVariables.Syntax, CalamariEnvironment.IsRunningOnWindows ? ScriptSyntax.PowerShell.ToString() : ScriptSyntax.Bash.ToString()); } private void SetInlineScriptVariables(string script) { SetInlineScriptVariables(script, script); } private void SetInlineScriptVariables(string bashScript, string powershellScript) { variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.Bash), bashScript); variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.PowerShell), powershellScript); } private CalamariResult ExecuteCommand(string command, string workingDirectory, string packagePath) { using (var variablesFile = new TemporaryFile(Path.GetTempFileName())) { variables.Save(variablesFile.FilePath); var calamariCommand = Calamari().Action(command) .Argument("variables", variablesFile.FilePath) .WithEnvironmentVariables(GetEnvironments()) .WithWorkingDirectory(workingDirectory) .OutputToLog(true); if (packagePath != null) { calamariCommand.Argument("package", packagePath); } return Invoke(calamariCommand, variables, Log); } } private void WriteLogMessagesToTestOutput() { foreach (var message in Log.Messages) { Console.WriteLine($"[{message.Level}] {message.FormattedMessage}"); } } } } #endif<file_sep>using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Calamari.Common; using Calamari.Common.Plumbing.Logging; using Calamari.Scripting; namespace Calamari.AzureScripting { public class Program : CalamariFlavourProgramAsync { public Program(ILog log) : base(log) { } public static Task<int> Main(string[] args) { return new Program(ConsoleLog.Instance).Run(args); } protected override IEnumerable<Assembly> GetProgramAssembliesToRegister() { yield return typeof(RunScriptCommand).Assembly; yield return typeof(Program).Assembly; } } }<file_sep>#if WINDOWS_CERTIFICATE_STORE_SUPPORT using System; using Microsoft.Win32.SafeHandles; namespace Calamari.Integration.Certificates.WindowsNative { internal class SafeCertStoreHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeCertStoreHandle() : base(true) { } private SafeCertStoreHandle(IntPtr handle) : this(handle, true) { } public SafeCertStoreHandle(IntPtr handle, bool ownsHandle) : base(ownsHandle) { SetHandle(handle); } protected override bool ReleaseHandle() { return WindowsX509Native.CertCloseStore(base.handle, 0); } public static SafeCertStoreHandle InvalidHandle => new SafeCertStoreHandle(IntPtr.Zero); } } #endif <file_sep>using System; using System.IO; namespace Calamari.Common.Plumbing.FileSystem { public class NixCalamariPhysicalFileSystem : CalamariPhysicalFileSystem { public override bool GetDiskFreeSpace(string directoryPath, out ulong totalNumberOfFreeBytes) { // This method will not work for UNC paths on windows // (hence WindowsPhysicalFileSystem) but should be sufficient for Linux mounts var pathRoot = Path.GetPathRoot(directoryPath); foreach (var drive in DriveInfo.GetDrives()) { if (!drive.Name.Equals(pathRoot)) continue; totalNumberOfFreeBytes = (ulong)drive.TotalFreeSpace; return true; } totalNumberOfFreeBytes = 0; return false; } public override bool GetDiskTotalSpace(string directoryPath, out ulong totalNumberOfBytes) { var pathRoot = Path.GetPathRoot(directoryPath); foreach (var drive in DriveInfo.GetDrives()) { if (!drive.Name.Equals(pathRoot)) continue; totalNumberOfBytes = (ulong)drive.TotalSize; return true; } totalNumberOfBytes = 0; return false; } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Calamari.Common.Features.Processes { public class CommandLine { readonly string? executable; readonly Func<string[], int>? func; readonly List<Arg> args = new List<Arg>(); string? action; bool useDotnet; private Dictionary<string,string>? environmentVariables = null; private bool outputToLog = true; private string workingDirectory; public CommandLine(Func<string[], int> func) { this.func = func; } public CommandLine(string executable) { this.executable = executable ?? throw new ArgumentNullException(nameof(executable)); } public CommandLine Action(string actionName) { if (action != null) throw new InvalidOperationException("Action is already set"); action = actionName ?? throw new ArgumentNullException(nameof(actionName)); args.Insert(0, Arg.MakeRaw(actionName)); return this; } public CommandLine Argument(string argument) { args.Add(Arg.MakePositional(argument)); return this; } public CommandLine Flag(string flagName) { args.Add(Arg.MakeFlag(flagName)); return this; } public CommandLine UseDotnet() { useDotnet = true; return this; } public CommandLine PositionalArgument(object argValue) { args.Add(Arg.MakePositional(argValue)); return this; } public CommandLine Argument(string argName, object argValue) { args.Add(Arg.MakeArg(argName, argValue)); return this; } public CommandLine WithEnvironmentVariables(Dictionary<string, string> environmentVariables) { this.environmentVariables = environmentVariables; return this; } public CommandLine WithWorkingDirectory(string workingDirectory) { this.workingDirectory = workingDirectory; return this; } public CommandLine OutputToLog(bool outputToLog) { this.outputToLog = outputToLog; return this; } public CommandLineInvocation Build() { var argLine = new List<Arg>(); var actualExe = executable; if (actualExe == null) throw new InvalidOperationException("Executable was not specified"); if (useDotnet) { argLine.Add(Arg.MakePositional(executable)); actualExe = "dotnet"; } argLine.AddRange(args); return new CommandLineInvocation(actualExe, argLine.Select(b => b.Build(true)).ToArray()) { EnvironmentVars = environmentVariables, OutputToLog = outputToLog, WorkingDirectory = workingDirectory }; } public LibraryCallInvocation BuildLibraryCall() { if (func == null) throw new InvalidOperationException("Library call function was not specified"); return new LibraryCallInvocation(func, args.Select(b => b.Build(false)).ToArray()); } public string[] GetRawArgs() { return args.SelectMany(b => b.Raw()).ToArray(); } class Arg { string? Name { get; set; } object? Value { get; set; } bool Flag { get; set; } bool IsRaw { get; set; } public static Arg MakeArg(string name, object value) { return new Arg { Name = name, Value = value }; } public static Arg MakePositional(object? value) { return new Arg { Value = value, Flag = false }; } public static Arg MakeFlag(string flag) { return new Arg { Name = flag, Flag = true }; } public static Arg MakeRaw(string value) { return new Arg { Name = value, IsRaw = true }; } public string[] Raw() { if (Flag || IsRaw || string.IsNullOrWhiteSpace(Name)) return new[] { Build(false) }; return new[] { $"-{Normalize(Name)}", GetValue(false) }; } public string Build(bool escapeArg) { if (Flag) return $"-{Normalize(Name)}"; if (IsRaw) return Normalize(Name); var sval = GetValue(escapeArg); return string.IsNullOrWhiteSpace(Name) ? sval : $"-{Normalize(Name)} {sval}"; } static string Normalize(string? text) { if (text == null) throw new ArgumentNullException(nameof(text)); return text.Trim(); } string GetValue(bool escapeArg) { var sval = ""; if (Value is IFormattable f) sval = f.ToString(null, CultureInfo.InvariantCulture); else if (Value != null) sval = Value.ToString(); sval = Escape(sval, escapeArg); return sval; } string Escape(string argValue, bool escapeArg) { if (argValue == null) throw new ArgumentNullException("argValue"); if (!escapeArg) return argValue; // Though it isn't aesthetically pleasing, we always return a double-quoted // value. var last = argValue.Length - 1; var preq = true; while (last >= 0) { // Escape backslashes only when they're butted up against the // end of the value, or an embedded double quote var cur = argValue[last]; if (cur == '\\' && preq) argValue = argValue.Insert(last, "\\"); else if (cur == '"') preq = true; else preq = false; last -= 1; } #if WORKAROUND_FOR_EMPTY_STRING_BUG // linux under bash on netcore empty "" gets eaten, hand "\0" // which gets through as a null string if(argValue == "") argValue = "\0"; #endif // Double-quotes are always escaped. return "\"" + argValue.Replace("\"", "\\\"") + "\""; } } } }<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Calamari.Common.Commands; using Calamari.Common.Features.Substitutions; using Calamari.Common.Plumbing.Pipeline; using Calamari.Common.Plumbing.Variables; namespace Calamari.Terraform.Behaviours { class TerraformSubstituteBehaviour : IPreDeployBehaviour { readonly ISubstituteInFiles substituteInFiles; public TerraformSubstituteBehaviour(ISubstituteInFiles substituteInFiles) { this.substituteInFiles = substituteInFiles; } public bool IsEnabled(RunningDeployment context) { return true; } public Task Execute(RunningDeployment context) { var filesToSubstitute = GetFilesToSubstitute(context.Variables); substituteInFiles.Substitute(context.CurrentDirectory, filesToSubstitute); return this.CompletedTask(); } string[] GetFilesToSubstitute(IVariables variables) { var isEnableNoMatchWarningSet = variables.IsSet(PackageVariables.EnableNoMatchWarning); var additionalFileSubstitutions = GetAdditionalFileSubstitutions(variables); if (!isEnableNoMatchWarningSet) { var hasAdditionalSubstitutions = !string.IsNullOrEmpty(additionalFileSubstitutions); variables.AddFlag(PackageVariables.EnableNoMatchWarning, hasAdditionalSubstitutions); } var result = new List<string>(); var runAutomaticFileSubstitution = variables.GetFlag(TerraformSpecialVariables.Action.Terraform.RunAutomaticFileSubstitution, true); if (runAutomaticFileSubstitution) result.AddRange(new[] { "**/*.tf", "**/*.tf.json", "**/*.tfvars", "**/*.tfvars.json" }); var additionalFileSubstitution = additionalFileSubstitutions; if (!string.IsNullOrWhiteSpace(additionalFileSubstitution)) result.AddRange(additionalFileSubstitution.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)); return result.ToArray(); } string GetAdditionalFileSubstitutions(IVariables variables) { return variables.Get(TerraformSpecialVariables.Action.Terraform.FileSubstitution); } } }<file_sep>using System; using System.Collections.Generic; using Calamari.AzureAppService.Behaviors; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; namespace Calamari.AzureAppService { [Command("deploy-azure-app-service", Description = "Extracts and installs a deployment package to an Azure Web Application as a zip file")] public class DeployAzureAppServiceCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { //Legacy behaviours yield return resolver.Create<LegacyAppDeployBehaviour>(); yield return resolver.Create<LegacyAzureAppServiceSettingsBehaviour>(); yield return resolver.Create<LegacyRestartAzureWebAppBehaviour>(); //Modern behaviours yield return resolver.Create<AppDeployBehaviour>(); yield return resolver.Create<AzureAppServiceSettingsBehaviour>(); yield return resolver.Create<RestartAzureWebAppBehaviour>(); } } [Command("deploy-azure-app-settings", Description = "Creates or updates existing app settings")] public class DeployAzureAppSettingsCommand : PipelineCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { //Legacy behaviour yield return resolver.Create<LegacyAzureAppServiceBehaviour>(); //Modern behaviour yield return resolver.Create<AzureAppServiceBehaviour>(); } } } <file_sep>#if USE_NUGET_V2_LIBS using System; using System.IO; using System.Net; using Calamari.Common.Plumbing.Logging; using Calamari.Integration.Packages.Download; using NuGet; using SemanticVersion = NuGet.SemanticVersion; namespace Calamari.Integration.Packages.NuGet { public class NuGetV2Downloader { public static void DownloadPackage(string packageId, string packageVersion, Uri feedUri, ICredentials feedCredentials, string targetFilePath) { SetFeedCredentials(feedUri, feedCredentials); var package = FindPackage(packageId, packageVersion, feedUri, out var downloader); DownloadPackage(package, targetFilePath, downloader); } private static IPackage FindPackage(string packageId, string packageVersion, Uri feed, out PackageDownloader downloader) { var remoteRepository = PackageRepositoryFactory.Default.CreateRepository(feed.AbsoluteUri); downloader = remoteRepository is DataServicePackageRepository dspr ? dspr.PackageDownloader : null; var requiredVersion = new SemanticVersion(packageVersion); var package = remoteRepository.FindPackage(packageId, requiredVersion, true, true); if (package == null) throw new Exception($"Could not find package {packageId} {packageVersion} in feed: '{feed}'"); if (!requiredVersion.Equals(package.Version)) { throw new Exception($"The package version '{package.Version}' returned from the package repository doesn't match the requested package version '{requiredVersion}'."); } return package; } private static void DownloadPackage(IPackage package, string fullPathToDownloadTo, PackageDownloader directDownloader) { Log.VerboseFormat("Found package {0} v{1}", package.Id, package.Version); Log.Verbose("Downloading to: " + fullPathToDownloadTo); if (package is DataServicePackage dsp && directDownloader != null) { Log.Verbose("A direct download is possible; bypassing the NuGet machine cache"); using (var targetFile = new FileStream(fullPathToDownloadTo, FileMode.CreateNew)) directDownloader.DownloadPackage(dsp.DownloadUrl, dsp, targetFile); return; } var physical = new PhysicalFileSystem(Path.GetDirectoryName(fullPathToDownloadTo)); var local = new LocalPackageRepository(new FixedFilePathResolver(package.Id, fullPathToDownloadTo), physical); local.AddPackage(package); } static void SetFeedCredentials(Uri feedUri, ICredentials feedCredentials) { FeedCredentialsProvider.Instance.SetCredentials(feedUri, feedCredentials); HttpClient.DefaultCredentialProvider = FeedCredentialsProvider.Instance; } } } #endif<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Plumbing.ServiceMessages; using Calamari.Testing.LogParser; namespace Calamari.Testing { public class TestCalamariCommandResult { public TestCalamariCommandResult(int exitCode, IReadOnlyDictionary<string, TestOutputVariable> outputVariables, IReadOnlyList<TestScriptOutputAction> outputActions, IReadOnlyList<ServiceMessage> serviceMessages, string? resultMessage, IReadOnlyList<CollectedArtifact> artifacts, string fullLog, string workingPath) { ExitCode = exitCode; OutputVariables = outputVariables; OutputActions = outputActions; ServiceMessages = serviceMessages; ResultMessage = resultMessage; FullLog = fullLog; WorkingPath = workingPath; Artifacts = artifacts; } public string FullLog { get; } public string WorkingPath { get; } public IReadOnlyList<CollectedArtifact> Artifacts { get; } public IReadOnlyDictionary<string, TestOutputVariable> OutputVariables { get; } public IReadOnlyList<TestScriptOutputAction> OutputActions { get; } public IReadOnlyList<ServiceMessage> ServiceMessages { get; } public TestExecutionOutcome Outcome => WasSuccessful ? TestExecutionOutcome.Successful : TestExecutionOutcome.Unsuccessful; public bool WasSuccessful => ExitCode == 0; public string? ResultMessage { get; } public int ExitCode { get; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Features.Scripts; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.AzureScripting { public class AzureContextScriptWrapper : IScriptWrapper { const string CertificateFileName = "azure_certificate.pfx"; const int PasswordSizeBytes = 20; const string DefaultAzureEnvironment = "AzureCloud"; readonly ICalamariFileSystem fileSystem; readonly ICalamariEmbeddedResources embeddedResources; readonly ILog log; readonly IVariables variables; readonly ScriptSyntax[] supportedScriptSyntax = {ScriptSyntax.PowerShell, ScriptSyntax.Bash}; public AzureContextScriptWrapper(IVariables variables, ICalamariFileSystem fileSystem, ICalamariEmbeddedResources embeddedResources, ILog log) { this.variables = variables; this.fileSystem = fileSystem; this.embeddedResources = embeddedResources; this.log = log; } public int Priority => ScriptWrapperPriorities.CloudAuthenticationPriority; public bool IsEnabled(ScriptSyntax syntax) => supportedScriptSyntax.Contains(syntax); public IScriptWrapper? NextWrapper { get; set; } public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary<string, string>? environmentVars) { var workingDirectory = Path.GetDirectoryName(script.File)!; variables.Set("OctopusAzureTargetScript", script.File); variables.Set("OctopusAzureTargetScriptParameters", script.Parameters); SetOutputVariable("OctopusAzureSubscriptionId", variables.Get(SpecialVariables.Action.Azure.SubscriptionId)!); SetOutputVariable("OctopusAzureStorageAccountName", variables.Get(SpecialVariables.Action.Azure.StorageAccountName)!); var azureEnvironment = variables.Get(SpecialVariables.Action.Azure.Environment, DefaultAzureEnvironment)!; if (azureEnvironment != DefaultAzureEnvironment) { log.InfoFormat("Using Azure Environment override - {0}", azureEnvironment); } SetOutputVariable("OctopusAzureEnvironment", azureEnvironment); SetOutputVariable("OctopusAzureExtensionsDirectory", variables.Get(SpecialVariables.Action.Azure.ExtensionsDirectory)!); using (new TemporaryFile(Path.Combine(workingDirectory, "AzureProfile.json"))) using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory, scriptSyntax))) { if (variables.Get(SpecialVariables.Account.AccountType) == "AzureServicePrincipal") { SetOutputVariable("OctopusUseServicePrincipal", bool.TrueString); SetOutputVariable("OctopusAzureADTenantId", variables.Get(SpecialVariables.Action.Azure.TenantId)!); SetOutputVariable("OctopusAzureADClientId", variables.Get(SpecialVariables.Action.Azure.ClientId)!); variables.Set("OctopusAzureADPassword", variables.Get(SpecialVariables.Action.Azure.Password)); return NextWrapper!.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars); } //otherwise use management certificate SetOutputVariable("OctopusUseServicePrincipal", false.ToString()); using (new TemporaryFile(CreateAzureCertificate(workingDirectory))) { return NextWrapper!.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars); } } } string CreateContextScriptFile(string workingDirectory, ScriptSyntax syntax) { string contextFile; switch (syntax) { case ScriptSyntax.Bash: contextFile = "AzureContext.sh"; break; case ScriptSyntax.PowerShell: contextFile = "AzureContext.ps1"; break; default: throw new InvalidOperationException($"No Azure context wrapper exists for {syntax}"); } var azureContextScriptFile = Path.Combine(workingDirectory, $"Octopus.{contextFile}"); var contextScript = embeddedResources.GetEmbeddedResourceText(GetType().Assembly, $"{GetType().Namespace}.Scripts.{contextFile}"); fileSystem.OverwriteFile(azureContextScriptFile, contextScript); return azureContextScriptFile; } string CreateAzureCertificate(string workingDirectory) { var certificateFilePath = Path.Combine(workingDirectory, CertificateFileName); var certificatePassword = GenerateCertificatePassword(); var azureCertificate = CalamariCertificateStore.GetOrAdd(variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint)!, Convert.FromBase64String(variables.Get(SpecialVariables.Action.Azure.CertificateBytes)!), StoreName.My); variables.Set("OctopusAzureCertificateFileName", certificateFilePath); variables.Set("OctopusAzureCertificatePassword", certificatePassword); fileSystem.WriteAllBytes(certificateFilePath, azureCertificate.Export(X509ContentType.Pfx, certificatePassword)); return certificateFilePath; } void SetOutputVariable(string name, string value) { if (variables.Get(name) != value) { log.SetOutputVariable(name, value, variables); } } static string GenerateCertificatePassword() { var random = RandomNumberGenerator.Create(); var bytes = new byte[PasswordSizeBytes]; random.GetBytes(bytes); return Convert.ToBase64String(bytes); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.FSharp { public class FSharpExecutor : ScriptExecutor { protected override IEnumerable<ScriptExecution> PrepareExecution(Script script, IVariables variables, Dictionary<string, string>? environmentVars = null) { var workingDirectory = Path.GetDirectoryName(script.File); var executable = FSharpBootstrapper.FindExecutable(); var configurationFile = FSharpBootstrapper.PrepareConfigurationFile(workingDirectory, variables); var (bootstrapFile, otherTemporaryFiles) = FSharpBootstrapper.PrepareBootstrapFile(script.File, configurationFile, workingDirectory, variables); var arguments = FSharpBootstrapper.FormatCommandArguments(bootstrapFile, script.Parameters); yield return new ScriptExecution( new CommandLineInvocation(executable, arguments) { WorkingDirectory = workingDirectory, EnvironmentVars = environmentVars }, otherTemporaryFiles.Concat(new[] { bootstrapFile, configurationFile }) ); } } }<file_sep>using System; using Calamari.Commands.Support; using Calamari.Common.Commands; namespace Calamari.Aws.Exceptions { /// <summary> /// Represents a failed deployment that resulted in a rollback state /// </summary> public class RollbackException : CommandException { public RollbackException(string message) : base(message) { } public RollbackException(string message, Exception inner) : base(message, inner) { } } } <file_sep>using Calamari.CloudAccounts; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace Calamari.Tests.AWS { [TestFixture] public class AwsEnvironmentGenerationFixture { [Test] [TestCase("arn:aws:iam::0123456789AB:role/test-role", "My session name", "900", 900)] [TestCase("arn:aws:iam::0123456789AB:role/test-role", "My session name", null, 0)] [TestCase("arn:aws:iam::0123456789AB:role/test-role", "My session name", "", 0)] public void CreatesAssumeRoleRequestWithExpectedParams(string arn, string sessionName, string duration, int? expectedDuration) { IVariables variables = new CalamariVariables(); variables.Add("Octopus.Action.Aws.AssumeRole", "True"); variables.Add("Octopus.Action.Aws.AssumedRoleArn", arn); variables.Add("Octopus.Action.Aws.AssumedRoleSession", sessionName); variables.Add("Octopus.Action.Aws.AssumeRoleSessionDurationSeconds", duration); var awsEnvironmentGenerator = new AwsEnvironmentGeneration(Substitute.For<ILog>(), variables); var request = awsEnvironmentGenerator.GetAssumeRoleRequest(); request.RoleArn.Should().Be(arn); request.RoleSessionName.Should().Be(sessionName); request.DurationSeconds.Should().Be(expectedDuration); } } } <file_sep>#if !HAS_NULLABLE_REF_TYPES using System; /// <summary> /// These attributes replicate the ones from System.Diagnostics.CodeAnalysis, and are here so we can still compile against the older frameworks. /// </summary> namespace Calamari.Common { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] public sealed class NotNullIfNotNullAttribute : Attribute { public NotNullIfNotNullAttribute(string parameterName) { this.ParameterName = parameterName; } public string ParameterName { get; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] public sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] public sealed class NotNullAttribute : Attribute { } /// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary> [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class NotNullWhenAttribute : Attribute { /// <summary>Initializes the attribute with the specified return value condition.</summary> /// <param name="returnValue"> /// The return value condition. If the method returns this value, the associated parameter will not be null. /// </param> public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; /// <summary>Gets the return value condition.</summary> public bool ReturnValue { get; } } } #endif<file_sep>using System; using System.Collections.Generic; using Amazon.CloudFormation.Model; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Common.Util; using Calamari.Integration.FileSystem; using Calamari.Integration.Processes; using Calamari.Util; using Newtonsoft.Json; using Octopus.CoreUtilities; namespace Calamari.Aws.Integration.CloudFormation.Templates { public class CloudFormationParametersFile : ITemplate, ITemplateInputs<Parameter> { private readonly Func<Maybe<string>> content; private readonly Func<string, List<Parameter>> parse; public static CloudFormationParametersFile Create(Maybe<ResolvedTemplatePath> path, ICalamariFileSystem fileSystem, IVariables variables) { return new CloudFormationParametersFile(() => path.Select(x => variables.Evaluate(fileSystem.ReadFile(x.Value))), JsonConvert.DeserializeObject<List<Parameter>>); } public CloudFormationParametersFile(Func<Maybe<string>> content, Func<string, List<Parameter>> parse) { this.content = content; this.parse = parse; } public string Content => content().SomeOrDefault(); public IEnumerable<Parameter> Inputs => content().Select(parse).SelectValueOr(x => x, new List<Parameter>()); } }<file_sep>using Calamari.Common.Plumbing.Commands; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.ServiceMessages; namespace Calamari.Testing.Helpers; public class CalamariInvocationToLogOutputSink : ICommandInvocationOutputSink { readonly ILog log; private readonly ServiceMessageParser serviceMessageParser; private LogLevel logLevel = LogLevel.Info; public CalamariInvocationToLogOutputSink(ILog log) { this.log = log; serviceMessageParser = new ServiceMessageParser(ProcessServiceMessage); } private void ProcessServiceMessage(ServiceMessage serviceMessage) { logLevel = serviceMessage.Name switch { "stdout-verbose" => LogLevel.Verbose, "stdout-default" => LogLevel.Info, "stdout-warning" => LogLevel.Warn, _ => logLevel }; log.WriteServiceMessage(serviceMessage); } public void WriteInfo(string line) { if (serviceMessageParser.Parse(line)) return; switch (logLevel) { case LogLevel.Verbose: log.Verbose(line); break; case LogLevel.Warn: log.Warn(line); break; case LogLevel.Info: default: log.Info(line); break; } } public void WriteError(string line) { log.Error(line); } private enum LogLevel { Verbose, Info, Warn } }<file_sep>using System; using System.ComponentModel; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.PackageRetention; using Newtonsoft.Json; namespace Calamari.Common.Plumbing.Deployment.PackageRetention { public class ServerTaskId : CaseInsensitiveTinyType { [JsonConstructor] public ServerTaskId(string value) : base(value) { } public static ServerTaskId FromVariables(IVariables variables) { var taskId = variables.Get(KnownVariables.ServerTask.Id); if (taskId == null) throw new Exception("ServerTask.Id not set."); return new ServerTaskId(taskId); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Calamari.Common.Commands; using Calamari.Common.Features.EmbeddedResources; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment.Features; namespace Calamari.Deployment.Conventions { public class FeatureConvention : FeatureConventionBase, IInstallConvention { public FeatureConvention(string deploymentStage, IEnumerable<IFeature> featureClasses, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner, ICalamariEmbeddedResources embeddedResources) : base(deploymentStage, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources) { } public void Install(RunningDeployment deployment) { Run(deployment); } } public class FeatureRollbackConvention : FeatureConventionBase, IRollbackConvention { public FeatureRollbackConvention(string deploymentStage, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner, ICalamariEmbeddedResources embeddedResources) : base(deploymentStage, null, fileSystem, scriptEngine, commandLineRunner, embeddedResources) { } public void Rollback(RunningDeployment deployment) { Run(deployment); } public void Cleanup(RunningDeployment deployment) { } } public abstract class FeatureConventionBase { readonly string deploymentStage; readonly ICalamariFileSystem fileSystem; readonly ICalamariEmbeddedResources embeddedResources; readonly IScriptEngine scriptEngine; readonly ICommandLineRunner commandLineRunner; const string scriptResourcePrefix = "Calamari.Scripts."; readonly ICollection<IFeature> featureClasses; static readonly Assembly Assembly = typeof(FeatureConventionBase).Assembly; protected FeatureConventionBase(string deploymentStage, IEnumerable<IFeature> featureClasses, ICalamariFileSystem fileSystem, IScriptEngine scriptEngine, ICommandLineRunner commandLineRunner, ICalamariEmbeddedResources embeddedResources) { this.deploymentStage = deploymentStage; this.fileSystem = fileSystem; this.embeddedResources = embeddedResources; this.scriptEngine = scriptEngine; this.commandLineRunner = commandLineRunner; this.featureClasses = featureClasses?.ToList(); } protected void Run(RunningDeployment deployment) { var features = deployment.Variables.GetStrings(KnownVariables.Package.EnabledFeatures).Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); if (!features.Any()) return; var embeddedResourceNames = new HashSet<string>(embeddedResources.GetEmbeddedResourceNames(Assembly)); foreach (var feature in features) { // Features can be implemented as either classes or scripts (or both) ExecuteFeatureClasses(deployment, feature); ExecuteFeatureScripts(deployment, feature, embeddedResourceNames); } } void ExecuteFeatureClasses(RunningDeployment deployment, string feature) { var compiledFeature = featureClasses?.FirstOrDefault(f => f.Name.Equals(feature, StringComparison.OrdinalIgnoreCase) && f.DeploymentStage.Equals(deploymentStage, StringComparison.OrdinalIgnoreCase)); if (compiledFeature == null) return; Log.Verbose($"Executing feature-class '{compiledFeature.GetType()}'"); compiledFeature.Execute(deployment); } void ExecuteFeatureScripts(RunningDeployment deployment, string feature, HashSet<string> embeddedResourceNames) { foreach (var featureScript in GetScriptNames(feature)) { // Determine the embedded-resource name var scriptEmbeddedResource = GetEmbeddedResourceName(featureScript); // If there is a matching embedded resource if (!embeddedResourceNames.Contains(scriptEmbeddedResource)) continue; var scriptFile = Path.Combine(deployment.CurrentDirectory, featureScript); // To execute the script, we need a physical file on disk. // If one already exists, we don't recreate it, as this provides a handy // way to override behaviour. if (!fileSystem.FileExists(scriptFile)) { Log.VerboseFormat("Creating '{0}' from embedded resource", scriptFile); fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText(Assembly, scriptEmbeddedResource)); } else { Log.WarnFormat("Did not overwrite '{0}', it was already on disk", scriptFile); } // Execute the script Log.VerboseFormat("Executing '{0}'", scriptFile); var result = scriptEngine.Execute(new Script(scriptFile), deployment.Variables, commandLineRunner); // And then delete it Log.VerboseFormat("Deleting '{0}'", scriptFile); fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure); if (result.ExitCode != 0) { throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile, result.ExitCode)); } } } public static string GetEmbeddedResourceName(string featureScriptName) { return scriptResourcePrefix + featureScriptName; } public static string GetScriptName(string feature, string suffix, string extension) { return feature + "_" + suffix + "." + extension; } /// <summary> /// Generates possible script names using the supplied suffix, and all supported extensions /// </summary> private IEnumerable<string> GetScriptNames(string feature) { return scriptEngine.GetSupportedTypes() .Select(type => GetScriptName(feature, deploymentStage, type.FileExtension())); } } } <file_sep>using System.Collections.Generic; using System.IO; using Calamari.Common.Features.Processes; using Calamari.Common.Features.Scripting.WindowsPowerShell; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Integration.FileSystem; using Calamari.Integration.Processes; using Calamari.Testing.Helpers; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.PowerShell { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class PowerShellCoreOnWindowsFixture : PowerShellFixtureBase { protected override PowerShellEdition PowerShellEdition => PowerShellEdition.Core; [SetUp] public void SetUp() { var path = new WindowsPowerShellCoreBootstrapper(new WindowsPhysicalFileSystem()).PathToPowerShellExecutable(new CalamariVariables()); if (!File.Exists(path)) { CommandLineRunner clr = new CommandLineRunner(ConsoleLog.Instance, new CalamariVariables()); var result = clr.Execute(new CommandLineInvocation("pwsh.exe", "--version") { OutputToLog = false }); if (result.HasErrors) Assert.Inconclusive("PowerShell Core is not installed on this machine"); } } [Test] public void IncorrectPowerShellEditionShouldThrowException() { var nonExistentEdition = "PowerShellCore"; var output = RunScript("Hello.ps1", new Dictionary<string, string>() {{PowerShellVariables.Edition, nonExistentEdition}}); output.result.AssertFailure(); output.result.AssertErrorOutput("Attempted to use 'PowerShellCore' edition of PowerShell, but this edition could not be found. Possible editions: Core, Desktop"); } } }<file_sep>using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace Calamari.Kubernetes.ResourceStatus.Resources { public class DaemonSet: Resource { public override string ChildKind => "Pod"; public int Desired { get; } public int Current { get; } public int Ready { get; } public int UpToDate { get; } public int Available { get; } public string NodeSelector { get; } public DaemonSet(JObject json, Options options) : base(json, options) { Desired = FieldOrDefault("$.status.desiredNumberScheduled", 0); Current = FieldOrDefault("$.status.currentNumberScheduled", 0); Ready = FieldOrDefault("$.status.numberReady", 0); UpToDate = FieldOrDefault("$.status.updatedNumberScheduled", 0); Available = FieldOrDefault("$.status.numberAvailable", 0); var selectors = data.SelectToken("$.spec.template.spec.nodeSelector") ?.ToObject<Dictionary<string, string>>() ?? new Dictionary<string, string>(); NodeSelector = FormatNodeSelectors(selectors); ResourceStatus = Available == Desired && UpToDate == Desired && Ready == Desired ? ResourceStatus.Successful : ResourceStatus.InProgress; } public override bool HasUpdate(Resource lastStatus) { var last = CastOrThrow<DaemonSet>(lastStatus); return last.Desired != Desired || last.Current != Current || last.Ready != Ready || last.UpToDate != UpToDate || last.Available != Available || last.NodeSelector != NodeSelector; } private static string FormatNodeSelectors(Dictionary<string, string> nodeSelectors) { var selectors = nodeSelectors .ToList() .OrderBy(_ => _.Key) .ThenBy(_ => _.Value) .Select(_ => $"{_.Key}={_.Value}"); return string.Join(",", selectors); } } } <file_sep>using Calamari.Aws.Deployment.Conventions; namespace Calamari.Aws.Integration.CloudFormation { public class RunningChangeSet { public StackArn Stack { get; } public ChangeSetArn ChangeSet { get; } public RunningChangeSet(StackArn stack, ChangeSetArn changeSet) { Stack = stack; ChangeSet = changeSet; } } }<file_sep>using System; using System.IO; using Calamari.Deployment; using Calamari.Tests.Helpers; using NUnit.Framework; using Assent; using Assent.Reporters; using Assent.Reporters.DiffPrograms; using Calamari.Testing.Helpers; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class DeployWindowsServiceArgumentsFixture : DeployWindowsServiceAbstractFixture { protected override string ServiceName => "DumpArgs"; protected override string PackageName => "DumpArgs"; [Test] public void ShouldDeployAndInstallWhenThereAreArguments() { Variables[SpecialVariables.Action.WindowsService.Arguments] = "--SomeArg -Foo \"path somewhere\""; RunDeployment(() => { var argsFilePath = Path.Combine(StagingDirectory, PackageName, "1.0.0", "Args.txt"); Assert.IsTrue(File.Exists(argsFilePath)); this.Assent(File.ReadAllText(argsFilePath), AssentConfiguration.Default); }); } [Test] public void ShouldDeployAndInstallWhenThereAreSpacesInArguments() { Variables[SpecialVariables.Action.WindowsService.Arguments] = "\"Argument with Space\" ArgumentWithoutSpace"; RunDeployment(() => { var argsFilePath = Path.Combine(StagingDirectory, PackageName, "1.0.0", "Args.txt"); Assert.IsTrue(File.Exists(argsFilePath)); this.Assent(File.ReadAllText(argsFilePath), AssentConfiguration.Default); }); } } }<file_sep>using Autofac; using Calamari.Common.Plumbing.Extensions; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Util { [TestFixture] public class PrioritisedRegistrationFixture { ContainerBuilder builder; [SetUp] public void SetUp() { builder = new ContainerBuilder(); builder.RegisterPrioritisedList<ITestService>(); } [Test] public void WithNoServices_ReturnsEmptyList() { var services = ResolvePrioritisedList(); services.Should().BeEmpty(); } [Test] public void WithUnprioritisedServices_ReturnsListInAnyOrder() { builder.RegisterType<TestServiceA>().As<ITestService>(); builder.RegisterType<TestServiceB>().As<ITestService>(); var services = ResolvePrioritisedList(); services.Should().Contain(its => its.Identifier == "ServiceA"); services.Should().Contain(its => its.Identifier == "ServiceB"); } [Test] public void WithPrioritisedServices_ReturnsListInPriorityOrder() { builder.RegisterType<TestServiceB>().As<ITestService>().WithPriority(1); builder.RegisterType<TestServiceA>().As<ITestService>().WithPriority(2); var services = ResolvePrioritisedList(); services[0].Identifier.Should().Be("ServiceB"); services[1].Identifier.Should().Be("ServiceA"); } [Test] public void WithPrioritisedServices_ReturnsListInPriorityOrder_RegardlessOfRegistrationOrder() { builder.RegisterType<TestServiceA>().As<ITestService>().WithPriority(2); builder.RegisterType<TestServiceB>().As<ITestService>().WithPriority(1); var services = ResolvePrioritisedList(); services[0].Identifier.Should().Be("ServiceB"); services[1].Identifier.Should().Be("ServiceA"); } [Test] public void WithMixedPrioritisedAndUnprioritisedServices_ReturnsPrioritisedFirst_FollowedByUnprioritised() { builder.RegisterType<TestServiceA>().As<ITestService>().WithPriority(2); builder.RegisterType<TestServiceB>().As<ITestService>(); builder.RegisterType<TestServiceC>().As<ITestService>().WithPriority(1); var services = ResolvePrioritisedList(); services[0].Identifier.Should().Be("ServiceC"); services[1].Identifier.Should().Be("ServiceA"); services[2].Identifier.Should().Be("ServiceB"); } [Test] public void WithDuplicatePrioritisations_DoesntBlowUp() { builder.RegisterType<TestServiceA>().As<ITestService>().WithPriority(1); builder.RegisterType<TestServiceB>().As<ITestService>().WithPriority(1); builder.RegisterType<TestServiceC>().As<ITestService>().WithPriority(1); var services = ResolvePrioritisedList(); services.Count.Should().Be(3); } PrioritisedList<ITestService> ResolvePrioritisedList() { var container = builder.Build(); using (var scope = container.BeginLifetimeScope()) { return scope.Resolve<PrioritisedList<ITestService>>(); } } public class TestServiceA : ITestService { public string Identifier => "ServiceA"; } public class TestServiceB : ITestService { public string Identifier => "ServiceB"; } public class TestServiceC : ITestService { public string Identifier => "ServiceC"; } public interface ITestService { string Identifier { get; } } } } <file_sep>using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Features.Deployment; using Calamari.Common.Plumbing.Logging; using Calamari.Common.Plumbing.Variables; namespace Calamari.Deployment.Features.Java { public class WildflyFeature : IFeature { readonly JavaRunner javaRunner; public WildflyFeature(JavaRunner javaRunner) { this.javaRunner = javaRunner; } public string Name => SpecialVariables.Action.Java.WildFly.Feature; public string DeploymentStage => DeploymentStages.BeforeDeploy; public void Execute(RunningDeployment deployment) { var variables = deployment.Variables; // Octopus.Features.WildflyDeployCLI was set to True previously, // but now we rely on the feature being enabled if (!(variables.GetFlag(SpecialVariables.Action.Java.WildFly.Feature) || (variables.Get(KnownVariables.Package.EnabledFeatures) ?? "").Contains(SpecialVariables.Action.Java.WildFly.Feature))) return; // Environment variables are used to pass parameters to the Java library Log.Verbose("Invoking java to perform WildFly integration"); javaRunner.Run("com.octopus.calamari.wildfly.WildflyDeploy", new Dictionary<string, string>() { {"OctopusEnvironment_Octopus_Tentacle_CurrentDeployment_PackageFilePath", deployment.Variables.Get(PackageVariables.Output.InstallationPackagePath, deployment.PackageFilePath)}, {"OctopusEnvironment_WildFly_Deploy_Name", variables.Get(SpecialVariables.Action.Java.WildFly.DeployName)}, {"OctopusEnvironment_WildFly_Deploy_User", variables.Get(SpecialVariables.Action.Java.WildFly.User)}, {"OctopusEnvironment_WildFly_Deploy_Password", variables.Get(SpecialVariables.Action.Java.WildFly.Password)}, {"OctopusEnvironment_WildFly_Deploy_Enabled", variables.Get(SpecialVariables.Action.Java.WildFly.Enabled)}, {"OctopusEnvironment_WildFly_Deploy_Port", variables.Get(SpecialVariables.Action.Java.WildFly.Port)}, {"OctopusEnvironment_WildFly_Deploy_Protocol", variables.Get(SpecialVariables.Action.Java.WildFly.Protocol)}, {"OctopusEnvironment_WildFly_Deploy_EnabledServerGroup", variables.Get(SpecialVariables.Action.Java.WildFly.EnabledServerGroup)}, {"OctopusEnvironment_WildFly_Deploy_DisabledServerGroup", variables.Get(SpecialVariables.Action.Java.WildFly.DisabledServerGroup)}, {"OctopusEnvironment_WildFly_Deploy_ServerType", variables.Get(SpecialVariables.Action.Java.WildFly.ServerType)}, {"OctopusEnvironment_WildFly_Deploy_Controller", variables.Get(SpecialVariables.Action.Java.WildFly.Controller)} }); } } }<file_sep>using System; namespace Calamari.Testing.LogParser { public enum ProcessOutputSource { StdOut, StdErr, Debug, } }<file_sep>using System; using System.Collections.Generic; using Calamari.Common.Commands; using Calamari.Common.Plumbing.Pipeline; using Calamari.Terraform.Behaviours; namespace Calamari.Terraform.Commands { [Command("destroyplan-terraform", Description = "Plans the destruction of Terraform resources")] public class DestroyPlanCommand : TerraformCommand { protected override IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver) { yield return resolver.Create<DestroyPlanBehaviour>(); } } }<file_sep>#if !NET40 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Autofac; using Calamari.Common.Commands; using Calamari.Common.Features.Behaviours; using Calamari.Common.Plumbing.Extensions; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Plumbing.Pipeline { public abstract class PipelineCommand { protected virtual IEnumerable<IBeforePackageExtractionBehaviour> BeforePackageExtraction(BeforePackageExtractionResolver resolver) { return Enumerable.Empty<IBeforePackageExtractionBehaviour>(); } protected virtual IEnumerable<IPackageExtractionBehaviour> PackageExtraction(PackageExtractionResolver resolver) { yield return resolver.Create<ExtractBehaviour>(); } protected virtual IEnumerable<IAfterPackageExtractionBehaviour> AfterPackageExtraction(AfterPackageExtractionResolver resolver) { return Enumerable.Empty<IAfterPackageExtractionBehaviour>(); } protected virtual IEnumerable<IPreDeployBehaviour> PreDeploy(PreDeployResolver resolver) { return Enumerable.Empty<IPreDeployBehaviour>(); } protected abstract IEnumerable<IDeployBehaviour> Deploy(DeployResolver resolver); protected virtual IEnumerable<IPostDeployBehaviour> PostDeploy(PostDeployResolver resolver) { return Enumerable.Empty<IPostDeployBehaviour>(); } protected virtual IEnumerable<IOnFinishBehaviour> OnFinish(OnFinishResolver resolver) { return Enumerable.Empty<IOnFinishBehaviour>(); } protected virtual bool IncludePackagedScriptBehaviour { get; } = true; protected virtual bool IncludeConfiguredScriptBehaviour { get; } = true; public async Task Execute(ILifetimeScope lifetimeScope, IVariables variables) { var pathToPrimaryPackage = variables.GetPathToPrimaryPackage(lifetimeScope.Resolve<ICalamariFileSystem>(), false); var deployment = new RunningDeployment(pathToPrimaryPackage, variables); try { foreach (var behaviour in GetBehaviours(lifetimeScope, deployment)) { await behaviour; if (deployment.Variables.GetFlag(KnownVariables.Action.SkipRemainingConventions)) { break; } } } catch (Exception installException) { Console.Error.WriteLine("Running rollback behaviours..."); deployment.Error(installException); try { // Rollback behaviours include tasks like DeployFailed.ps1 await ExecuteBehaviour(deployment, lifetimeScope.Resolve<RollbackScriptBehaviour>()); } catch (Exception rollbackException) { Console.Error.WriteLine(rollbackException); } throw; } } IEnumerable<Task> GetBehaviours(ILifetimeScope lifetimeScope, RunningDeployment deployment) { foreach (var behaviour in BeforePackageExtraction(new BeforePackageExtractionResolver(lifetimeScope))) { yield return ExecuteBehaviour(deployment, behaviour); } foreach (var behaviour in PackageExtraction(new PackageExtractionResolver(lifetimeScope))) { yield return ExecuteBehaviour(deployment, behaviour); } foreach (var behaviour in AfterPackageExtraction(new AfterPackageExtractionResolver(lifetimeScope))) { yield return ExecuteBehaviour(deployment, behaviour); } foreach (var scriptBehaviour in MaybeIncludeScriptBehaviours<PreDeployPackagedScriptBehaviour, PreDeployConfiguredScriptBehaviour>(lifetimeScope)) { yield return ExecuteBehaviour(deployment, scriptBehaviour); } foreach (var behaviour in PreDeploy(new PreDeployResolver(lifetimeScope))) { yield return ExecuteBehaviour(deployment, behaviour); } yield return ExecuteBehaviour(deployment, lifetimeScope.Resolve<SubstituteInFilesBehaviour>()); yield return ExecuteBehaviour(deployment, lifetimeScope.Resolve<ConfigurationTransformsBehaviour>()); yield return ExecuteBehaviour(deployment, lifetimeScope.Resolve<ConfigurationVariablesBehaviour>()); yield return ExecuteBehaviour(deployment, lifetimeScope.Resolve<StructuredConfigurationVariablesBehaviour>()); foreach (var scriptBehaviour in MaybeIncludeScriptBehaviours<DeployPackagedScriptBehaviour, DeployConfiguredScriptBehaviour>(lifetimeScope)) { yield return ExecuteBehaviour(deployment, scriptBehaviour); } foreach (var behaviour in Deploy(new DeployResolver(lifetimeScope))) { yield return ExecuteBehaviour(deployment, behaviour); } foreach (var behaviour in PostDeploy(new PostDeployResolver(lifetimeScope))) { yield return ExecuteBehaviour(deployment, behaviour); } foreach (var scriptBehaviour in MaybeIncludeScriptBehaviours<PostDeployPackagedScriptBehaviour, PostDeployConfiguredScriptBehaviour>(lifetimeScope)) { yield return ExecuteBehaviour(deployment, scriptBehaviour); } foreach (var behaviour in OnFinish(new OnFinishResolver(lifetimeScope))) { yield return ExecuteBehaviour(deployment, behaviour); } } IEnumerable<IBehaviour> MaybeIncludeScriptBehaviours<TPackagedScriptBehaviour, TConfiguredScriptBehaviour>(ILifetimeScope lifetimeScope) where TPackagedScriptBehaviour : PackagedScriptBehaviour where TConfiguredScriptBehaviour : ConfiguredScriptBehaviour { if (IncludePackagedScriptBehaviour) { yield return lifetimeScope.Resolve<TPackagedScriptBehaviour>(); } if (IncludeConfiguredScriptBehaviour) { yield return lifetimeScope.Resolve<TConfiguredScriptBehaviour>(); } } static async Task ExecuteBehaviour(RunningDeployment context, IBehaviour behaviour) { if (behaviour.IsEnabled(context)) { await behaviour.Execute(context); } } } } #endif <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using Calamari.Common.Features.Processes; using Calamari.Common.Plumbing.Variables; namespace Calamari.Common.Features.Scripting.Bash { public class BashScriptExecutor : ScriptExecutor { protected override IEnumerable<ScriptExecution> PrepareExecution(Script script, IVariables variables, Dictionary<string, string>? environmentVars = null) { var workingDirectory = Path.GetDirectoryName(script.File); var configurationFile = BashScriptBootstrapper.PrepareConfigurationFile(workingDirectory, variables); var (bootstrapFile, otherTemporaryFiles) = BashScriptBootstrapper.PrepareBootstrapFile(script, configurationFile, workingDirectory, variables); var invocation = new CommandLineInvocation( BashScriptBootstrapper.FindBashExecutable(), BashScriptBootstrapper.FormatCommandArguments(Path.GetFileName(bootstrapFile)) ) { WorkingDirectory = workingDirectory, EnvironmentVars = environmentVars }; yield return new ScriptExecution( invocation, otherTemporaryFiles.Concat(new[] { bootstrapFile, configurationFile }) ); } } }
b51b6a572433f534634fd0c1bf48610778a47185
[ "Markdown", "C#", "Python", "Java Properties", "Shell" ]
1,025
C#
OctopusDeploy/Calamari
6bc2bd56eb30c6c27aef6a13c53d1c5fb51231f7
0f338fa24f394036921cecbac487786b8ccfca0c
refs/heads/master
<file_sep>package com.frozen.tankbrigade.map.paths; import com.frozen.tankbrigade.map.model.GameBoard; import com.frozen.tankbrigade.map.model.GameUnit; import com.frozen.tankbrigade.map.model.TerrainType; /** * Created by sam on 09/03/14. */ public class AStarBoardAdapter implements AStarMap { private GameBoard board; private GameUnit unit; private int w; private int h; private boolean ignoreMovesLeft=false; private boolean ignoreEnemyUnits=false; public AStarBoardAdapter(GameBoard board, GameUnit unit) { this.board = board; this.unit = unit; w=board.width(); h=board.height(); } //for CostAnalyzer AI, we want to assume unit has all it's moves left //so this would be set to true public void setIgnoreMovesLeft(boolean b) { ignoreMovesLeft=b; } //for MapAnalyzer AI, in order to find direction towards enemy, //it is necessary to ignore other units on the board public void setIgnoreEnemyUnits(boolean b) {ignoreEnemyUnits=b;} @Override public boolean canMoveHere(int x, int y) { if (!board.isInBounds(x,y)) return false; TerrainType terrain=board.getTerrain(x,y); GameUnit mapUnit=board.getUnitAt(x,y); if (mapUnit!=null&&mapUnit.ownerId!=unit.ownerId&&!ignoreEnemyUnits) { return false; } if (!isTraversable(terrain, unit)) { return false; } return true; } @Override public int getCost(int x, int y) { if (unit.type.isAir()) return 1; else { TerrainType terrain=board.getTerrain(x,y); return (int)Math.floor(terrain.movement); } } @Override public int getMaxCost() { if (ignoreMovesLeft) return unit.type.movement; else return unit.movesLeft; } private boolean isTraversable(TerrainType terrain, GameUnit unit) { if (unit.type.isLand()&&!terrain.isLand()) return false; if (unit.type.isWater()&&!terrain.isWater()) return false; if (unit.type.isTank()&&terrain.symbol==TerrainType.MOUNTAIN) return false; return true; } } <file_sep>include ':TankBrigade' <file_sep>package com.frozen.tankbrigade.util; import android.graphics.Matrix; import android.graphics.RectF; /** * Created by sam on 17/03/14. */ public class TileRect extends RectF { private float mapLeft; private float mapTop; public void setMatrix(Matrix tileToScreen) { set(0, 0, 1, 1); tileToScreen.mapRect(this); mapLeft=left; mapTop=top; } public void setTilePos(int x, int y) { offsetTo(mapLeft+x*width(),mapTop+y*height()); } public void setTilePos(float x, float y) { offsetTo(mapLeft+x*width(),mapTop+y*height()); } } <file_sep>package com.frozen.tankbrigade.ai; import com.frozen.tankbrigade.map.model.GameBoard; import com.frozen.tankbrigade.map.model.GameUnit; import com.frozen.tankbrigade.map.paths.AStar; import com.frozen.tankbrigade.map.paths.AStarBoardAdapter; import com.frozen.tankbrigade.map.paths.AStarNode; import com.frozen.tankbrigade.util.SparseMap; /** * Created by sam on 09/03/14. */ public class BorderMapAnalyzer implements MapAnalyzer { private float[][] ownerShip; //create a series of weights to see if each square is more in player 1's territory or player 2's territory public void analyzeMap(GameBoard board, int curPlayer) { float[][][] weights=new float[2][board.width()][board.height()]; ownerShip=new float[board.width()][board.height()]; int playerId; AStar astar=new AStar(); AStarAnalyzerMap astarMap; SparseMap<AStarNode> moves; for (GameUnit unit:board.getUnits()) { playerId=(unit.ownerId==curPlayer)?0:1; astarMap=new AStarAnalyzerMap(board,unit); astarMap.setIgnoreEnemyUnits(true); moves=astar.findMoves(astarMap,unit.x,unit.y); for (AStarNode move:moves.getAllNodes()) { int unitMoves=unit.type.movement; //heuristic for unit weight score set to 1/x where x is number of turns to get to that place //i.e. x=num moves/unit moves per turn weights[playerId][move.x][move.y]+=unitMoves/(float)(move.totalCost+unitMoves); } } float totalWeight; for (int i=0;i<board.width();i++) { for (int j=0;j<board.height();j++) { totalWeight=weights[0][i][j]+weights[1][i][j]; if (totalWeight==0) ownerShip[i][j]=-1; else ownerShip[i][j]=weights[0][i][j]/totalWeight; } } } public float getMoveBonus(int x, int y) { return 1-ownerShip[x][y]; } private static class AStarAnalyzerMap extends AStarBoardAdapter { public AStarAnalyzerMap(GameBoard board, GameUnit unit) { super(board,unit); } @Override public int getMaxCost() { return 50; } } } <file_sep>package com.frozen.tankbrigade.debug; import android.util.Log; import com.frozen.tankbrigade.ai.ClosesUnitMapAnalyzer; import com.frozen.tankbrigade.ai.CostAnalyzer; import com.frozen.tankbrigade.ai.MapAnalyzer; import com.frozen.tankbrigade.map.moves.DamageInfo; import com.frozen.tankbrigade.map.moves.UnitMove; import com.frozen.tankbrigade.map.model.GameBoard; import com.frozen.tankbrigade.map.model.GameUnit; import com.frozen.tankbrigade.map.paths.PathFinder; import com.frozen.tankbrigade.util.SparseMap; /** * Created by sam on 04/12/14. */ public class DebugTools { public static MapAnalyzer testMapAnalyzer=new ClosesUnitMapAnalyzer(); private CostAnalyzer costAnalyzer; private PathFinder pathFinder=new PathFinder(); private static final String debugTag="AI_DEBUG"; public DebugTools() { } //debugging moves: public UnitMove debugUnitMoves(GameBoard board,GameUnit unit,boolean doLog) { costAnalyzer=new CostAnalyzer(pathFinder, board,unit.ownerId); SparseMap<UnitMove> moveMap=pathFinder.findLegalMoves(board,unit); if (doLog) Log.i(debugTag, "Debugging unit " + unit.toString()); float highestScore=0; UnitMove bestMove=null; for (UnitMove move:moveMap.getAllNodes()) { if (doLog) Log.d(debugTag,logMove(move)); float score=costAnalyzer.getScore(move); if (score>highestScore||bestMove==null) { bestMove=move; highestScore=score; } } if (doLog) Log.i(debugTag,"------------------------------------------"); return bestMove; } public void debugMove(GameBoard board, UnitMove move) { costAnalyzer=new CostAnalyzer(pathFinder, board,move.unit.ownerId); Log.d(debugTag,logMove(move)); } private String logMove(UnitMove move) { costAnalyzer.DEBUG=true; DamageInfo damageDone=costAnalyzer.getDamageDone(move); DamageInfo damageTaken=costAnalyzer.getDamageTaken(move); float buildingCaptureScore=costAnalyzer.getBuildingCaptureScore(move,damageDone.isKill,damageTaken.isKill); float moveBonus=costAnalyzer.getMoveTowardsEnemyBonus(move); costAnalyzer.DEBUG=false; return String.format("score=%.2f attack=%s defense=%s building=%.1f movebonus=%.1f move=%s",costAnalyzer.getScore(move), damageDone,damageTaken,buildingCaptureScore,moveBonus,move.toString()); } } <file_sep>package com.frozen.tankbrigade.loaders; import android.util.Log; import android.util.SparseArray; import com.frozen.tankbrigade.map.model.Building; import com.frozen.tankbrigade.map.model.GameBoard; import com.frozen.tankbrigade.map.model.GameConfig; import com.frozen.tankbrigade.map.model.GameUnit; import com.frozen.tankbrigade.map.model.GameUnitType; import com.frozen.tankbrigade.map.model.Player; import com.frozen.tankbrigade.map.model.TerrainMap; import com.frozen.tankbrigade.map.model.TerrainType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by sam on 26/12/14. */ public class GameBoardParser { private GameBoard board; private static class StringIterator { private String[] strings; private int pos; private StringIterator(String[] strings) { this.strings = strings; pos=0; } public boolean hasNext() { return pos+1<strings.length; } public boolean hasCurrent() { return pos<strings.length; } public String next() { pos++; return strings[pos]; } public String get() { return strings[pos]; } } public GameBoard parseMapFile(String fileContents,GameConfig config) { return parseMapFile(fileContents.split("\n"),config); } public GameBoard parseMapFile(String[] fileContents,GameConfig config) { StringIterator lines=new StringIterator(fileContents); String line; board=new GameBoard(); while (lines.hasNext()) { line=lines.get().trim(); if (line.contains("Map(")) { parseTerrainMap(lines,config.terrainTypes); continue; } if (line.contains("Units(")) { parseUnits(lines,config); continue; } if (line.contains("Buildings(")) { parseBuildings(lines); continue; } lines.next(); continue; } board.addPlayer(Player.USER_ID, 0); board.addPlayer(Player.AI_ID, 0); return board; } private void parseTerrainMap(StringIterator lines,List<TerrainType> terrainTypes) { String line=lines.get(); String[] args=line.substring(line.indexOf("(")+1,line.indexOf(")")).split(","); int w=Integer.parseInt(args[0]); int h=Integer.parseInt(args[1]); TerrainMap terrainMap=new TerrainMap(w,h); SparseArray<TerrainType> typeMap=new SparseArray<TerrainType>(terrainTypes.size()); for (TerrainType terrain:terrainTypes) { typeMap.put(terrain.symbol, terrain); } int y=0; while (lines.hasNext()&&y<h) { line=lines.next().trim(); if (line.startsWith(":")) break; if (line.length()<w) continue; for (int x=0;x<w;x++) { terrainMap.setTerrain(x, y, typeMap.get(line.charAt(x))); } y++; } board.setTerrainMap(terrainMap); } private void parseUnits(StringIterator lines,GameConfig config) { String line=lines.get(); String arg=line.substring(line.indexOf("(") + 1, line.indexOf(")")); int owner=Integer.parseInt(arg); while (lines.hasNext()) { line=lines.next().trim(); if (line.startsWith(":")) break; if (line.length()==0) continue; int commapos=line.indexOf(','); int dashpos=line.indexOf('-'); if (commapos<0||dashpos<0) continue; int x=Integer.parseInt(line.substring(0,commapos).trim()); int y=Integer.parseInt(line.substring(commapos+1,dashpos).trim()); String unitName=line.substring(dashpos+1).trim().toLowerCase(); GameUnit unit=new GameUnit(config.getUnitTypeByName(unitName),x,y,owner); Log.d("parse", unit.x + "," + unit.y + " " + unitName + " " + unit.type.name + " " + unit.ownerId); board.addUnit(unit); } } private void parseBuildings(StringIterator lines) { String line=lines.get(); String arg=line.substring(line.indexOf("(") + 1, line.indexOf(")")); int owner=Integer.parseInt(arg); while (lines.hasNext()) { line=lines.next().trim(); if (line.startsWith(":")) break; if (line.length()==0) continue; int commapos=line.indexOf(','); int dashpos=line.indexOf('-'); if (commapos<0||dashpos<0) continue; int x=Integer.parseInt(line.substring(0,commapos).trim()); int y=Integer.parseInt(line.substring(commapos+1,dashpos).trim()); String buildingName; buildingName=line.substring(dashpos+1).trim().toLowerCase(); Building building=new Building(buildingName,x,y,owner); board.addBuilding(building); } } //----------------------------------- SERIALIZE -------------------------------------- public JSONObject serialize(GameBoard board) throws JSONException { JSONObject data=new JSONObject(); JSONArray playersJson=new JSONArray(); for (int i=0;i<board.getPlayers().size();i++) { Player player=board.getPlayers().valueAt(i); playersJson.put(serializePlayer(player)); } data.put("players",playersJson); JSONArray unitsJson=new JSONArray(); for (GameUnit unit:board.getUnits()) unitsJson.put(serializeUnit(unit)); data.put("units",unitsJson); JSONArray buildingsJson=new JSONArray(); for (Building building:board.getBuildings()) buildingsJson.put(serializeBuilding(building)); data.put("buildings",buildingsJson); data.put("map",board.mapId); return data; } private JSONObject serializePlayer(Player player) throws JSONException { JSONObject playerJson=new JSONObject(); playerJson.put("id",player.id); playerJson.put("money",player.money); return playerJson; } private JSONObject serializeUnit(GameUnit unit) throws JSONException { JSONObject unitJson=new JSONObject(); unitJson.put("x",unit.x); unitJson.put("y",unit.y); unitJson.put("owner",unit.ownerId); unitJson.put("health",unit.health); unitJson.put("movesLeft",unit.movesLeft); unitJson.put("type",Character.toString(unit.type.symbol)); return unitJson; } private JSONObject serializeBuilding(Building building) throws JSONException { JSONObject buildingJson=new JSONObject(); buildingJson.put("x",building.x); buildingJson.put("y",building.y); boolean isCapturing=building.getIsCapturing(); buildingJson.put("isCapturing",isCapturing); buildingJson.put("owner",building.getOldOwnerId()); if (isCapturing) { buildingJson.put("occupier",building.getOccupyingOwnerId()); buildingJson.put("turns",building.getCaptureTurns()); } buildingJson.put("type",building.name); return buildingJson; } //----------------------------------- DESERIALIZE -------------------------------------- public GameBoard deserialize(JSONObject data, GameConfig config) throws JSONException { GameBoard board=new GameBoard(); JSONArray arr; arr=data.getJSONArray("players"); for (int i=0;i<arr.length();i++) { board.addPlayer(deserializePlayer((JSONObject)arr.get(i))); } arr=data.getJSONArray("units"); for (int i=0;i<arr.length();i++) { board.addUnit(deserializeUnit((JSONObject) arr.get(i),config)); } arr=data.getJSONArray("buildings"); for (int i=0;i<arr.length();i++) { board.addBuilding(deserializeBuilding((JSONObject) arr.get(i))); } board.mapId=data.getString("map"); return board; } private Player deserializePlayer(JSONObject obj) throws JSONException { int id=obj.getInt("id"); int money=obj.getInt("money"); Player player=new Player(id,money); return player; } private GameUnit deserializeUnit(JSONObject obj, GameConfig config) throws JSONException { int owner=obj.getInt("owner"); int x=obj.getInt("x"); int y=obj.getInt("y"); char typeSymbol=obj.getString("type").charAt(0); GameUnitType type=config.getUnitTypeBySymbol(typeSymbol); GameUnit unit=new GameUnit(type,x,y,owner); unit.health=obj.getInt("health"); unit.movesLeft=obj.getInt("movesLeft"); return unit; } private Building deserializeBuilding(JSONObject obj) throws JSONException { int x=obj.getInt("x"); int y=obj.getInt("y"); String type=obj.getString("type"); int owner=obj.getInt("owner"); boolean isCapturing=obj.getBoolean("isCapturing"); if (isCapturing) { int occupier=obj.getInt("occupier"); int numTurns=obj.getInt("turns"); return new Building(type,x,y,owner,occupier,numTurns); } else { return new Building(type,x,y,owner); } } } <file_sep>package com.frozen.tankbrigade.ui; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathEffect; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.util.Log; import android.util.SparseArray; import com.frozen.tankbrigade.R; import com.frozen.tankbrigade.debug.DebugTools; import com.frozen.tankbrigade.map.anim.MapAnimation; import com.frozen.tankbrigade.map.anim.SpriteAnimation; import com.frozen.tankbrigade.map.model.Building; import com.frozen.tankbrigade.map.model.GameBoard; import com.frozen.tankbrigade.map.model.GameConfig; import com.frozen.tankbrigade.map.model.GameUnit; import com.frozen.tankbrigade.map.model.GameUnitType; import com.frozen.tankbrigade.map.model.Player; import com.frozen.tankbrigade.map.model.TerrainMap; import com.frozen.tankbrigade.map.model.TerrainType; import com.frozen.tankbrigade.util.ColorGradient; import com.frozen.tankbrigade.util.GeomUtils; import com.frozen.tankbrigade.util.Iterator2D; import com.frozen.tankbrigade.util.TileRect; import java.util.ArrayList; import java.util.List; /** * Created by sam on 12/01/14. */ public class GraphicMapDrawer implements MapDrawer { private static final String TAG="BasicMapDrawer"; private Matrix tileToScreen=new Matrix(); private Matrix screenToTile=new Matrix(); private RectF screenRect=new RectF(); private RectF mapBoundsRect=new RectF(); private TileRect drawRect=new TileRect(); private RectF subrect=new RectF(); private Paint paint=new Paint(); private ColorFilters filters=new ColorFilters(); private BitmapCache terrainTiles; private int moveOverlayColor=0x44FFFFFF; private int attackOverlayColor=0x88DD4422; private int invalidOverlayColor=0x80000000; private int selectedOverlayColor=0x88FFFF88; private final static int tileW=100; private final static int tileH=80; private static class BitmapCache { private SparseArray<Bitmap> bitmapCache; private Resources res; private BitmapCache(Resources res) { this.res = res; bitmapCache=new SparseArray<Bitmap>(); } public Bitmap get(int id) { Bitmap bitmap=bitmapCache.get(id); if (bitmap==null) { Log.d(TAG,"loading bitmap first time - "+id); bitmap = BitmapFactory.decodeResource(res, id); bitmapCache.put(id,bitmap); } return bitmap; } } public GraphicMapDrawer(Context context, GameConfig config) { terrainTiles=new BitmapCache(context.getResources()); } public void drawMap(Canvas canvas, GameBoard map, Matrix screenTransform) { drawMap(canvas, map, screenTransform,null); } private int count=0; public void drawMap(Canvas canvas, GameBoard map, Matrix screenTransform,MapDrawParameters params) { count++; int w=canvas.getWidth(); int h=canvas.getHeight(); //Log.i(TAG, "drawSurface - map=" + map + " view dims=" + w + "," + h); if (map==null) return; if (w==0||h==0) return; screenRect.set(0, 0, w, h); tileToScreen.set(screenTransform); tileToScreen.preScale(tileW,tileH); tileToScreen.invert(screenToTile); screenToTile.mapRect(mapBoundsRect,screenRect); drawRect.setMatrix(tileToScreen); Rect mapBounds=new Rect(); mapBounds.left=Math.max((int)Math.floor(mapBoundsRect.left),0); mapBounds.right=Math.min((int) Math.ceil(mapBoundsRect.right), map.width()); mapBounds.top=Math.max((int)Math.floor(mapBoundsRect.top),0); mapBounds.bottom=Math.min((int) Math.ceil(mapBoundsRect.bottom), map.height()); //Log.d(TAG,"screenRect="+screenRect); //Log.d(TAG,"drawRect="+drawRect); //Log.d(TAG,"range = "+minX+","+minY+"-"+maxX+","+maxY); //reset canvas canvas.drawColor(Color.BLACK); if (params.testMode>0) drawTestMap(canvas,map,params,mapBounds); else drawMapAux(canvas, map, params, mapBounds); } private void drawMapAux(Canvas canvas, GameBoard map, MapDrawParameters params, Rect mapBounds) { int minY=mapBounds.top; int maxY=mapBounds.bottom; int minX=mapBounds.left; int maxX=mapBounds.right; synchronized (map.getUnits()) { for (GameUnit unitToUpdate:map.getUnits()) { unitToUpdate.updateAnimationPos(); //rfresh animation position } } Iterator2D<Building> buildingIter=new Iterator2D<Building>(map.getBuildings()); Iterator2D<GameUnit> unitIter=new Iterator2D<GameUnit>(map.getUnits()); Building building; GameUnit unit; //boolean showMoves=false; int shadingType; ColorMatrix shading=null; for (int tileY=minY;tileY<maxY;tileY++) { //first draw terrrains for row for (int tileX=minX;tileX<maxX;tileX++) { if (params!=null) shadingType=params.getOverlay(tileX,tileY); else shadingType=MapDrawParameters.SHADE_NONE; if (shadingType==MapDrawParameters.SHADE_INVALID) { shading=ColorFilters.darkenColorMatrix; } else if (shadingType==MapDrawParameters.SHADE_ATTACK) { shading=ColorFilters.redColorMatrix; } else if (shadingType==MapDrawParameters.SHADE_SELECTED_UNIT) { shading=ColorFilters.highlightColorMatrix; } else shading=null; drawRect.setTilePos(tileX,tileY); drawTerrain(canvas, drawRect,map.getTerrainMap(),tileX,tileY,shading); if (shadingType==MapDrawParameters.SHADE_INVALID) { shading=ColorFilters.darkenColorMatrix; } else shading=null; building=buildingIter.seek(tileX,tileY); if (building!=null) drawBuilding(canvas, building, drawRect,shading); } //then draw units for (int tileX=minX;tileX<maxX;tileX++) { unit=unitIter.seek(tileX,tileY); while (unit!=null) { boolean moveSelected=false; if (params!=null) { shadingType=params.getOverlay(tileX,tileY); moveSelected=params.hasSelectedMove(); } else shadingType=MapDrawParameters.SHADE_NONE; if (unit.movesLeft==0&&unit.ownerId==Player.USER_ID&&!unit.isAnimating()) { shading=ColorFilters.darkenColorMatrix; } else if (shadingType==MapDrawParameters.SHADE_INVALID) { shading=ColorFilters.darkenColorMatrix; } else if (moveSelected&&shadingType==MapDrawParameters.SHADE_ATTACK) { shading=ColorFilters.highlightColorMatrix; } else shading=null; PointF unitPos=unit.getAnimationPos().point; float unitPosY=unitPos.y; //move unit up or down based on terrain level unitPosY-=interpolateLevel(map.getTerrainMap(),unitPos.x,unitPos.y)*0.4f; drawRect.setTilePos(unitPos.x,unitPosY); drawUnit(canvas,unit,drawRect,shading); if (unit.health<unit.type.health) { float healthPercent=unit.health/(float)unit.type.health; drawUnitHealthBar(canvas,healthPercent,drawRect); } unit=unitIter.seek(tileX,tileY); } } } if (params==null) return; paint.reset(); paint.setStyle(Paint.Style.FILL); if (params.showPath()) drawPath(canvas, drawRect, params.getSelectedPath()); for (MapAnimation animation:params.getAnimations()) { if (animation instanceof SpriteAnimation) { drawAnimation(canvas, drawRect, (SpriteAnimation) animation); } } } private Rect srcRect=new Rect(); private RectF destRect=new RectF(); //yOffset is percentage of the tile width private void drawWithOverflow(Canvas canvas, Bitmap bitmap, RectF rect, int level) { drawWithOverflow(canvas, bitmap, rect, level,null); } private void drawWithOverflow(Canvas canvas, Bitmap bitmap, RectF rect, int level,Paint paint) { srcRect.set(0,0,bitmap.getWidth()-1,bitmap.getHeight()); float w=rect.width(); float yOffset=w*(0.5f+0.4f*level); destRect.set(0,0,w,w*srcRect.height()/srcRect.width()); destRect.offsetTo(rect.left,rect.top-yOffset); canvas.drawBitmap(bitmap,srcRect,destRect,paint); } private void drawTerrain(Canvas canvas, RectF rect, TerrainMap map, int x, int y, ColorMatrix colorMatrix) { TerrainType terrain=map.getTerrain(x,y); int resId=DrawableMapping.getTerrainDrawable(map, x, y); if (resId==0) return; Bitmap bitmap=terrainTiles.get(resId); int ypos=terrain.getLevel(); drawWithOverflow(canvas, bitmap, rect, ypos,filters.getPaint(colorMatrix)); if (terrain.getLevel()==0) { if (map.getTerrainLevel(x-1,y+1)==0&&map.getTerrainLevel(x,y+1)==-1) { bitmap=terrainTiles.get(R.drawable.shadow_side_w); drawWithOverflow(canvas, bitmap, rect, ypos); } } else if (terrain.getLevel()==-1) { if (map.getTerrainLevel(x,y+1)==0) { bitmap=terrainTiles.get(R.drawable.shadow_s); drawWithOverflow(canvas, bitmap, rect, ypos); } if (map.getTerrainLevel(x,y-1)==0) { bitmap=terrainTiles.get(R.drawable.shadow_n); drawWithOverflow(canvas, bitmap, rect, ypos); } if (map.getTerrainLevel(x+1,y)==0) { bitmap=terrainTiles.get(R.drawable.shadow_e); drawWithOverflow(canvas, bitmap, rect, ypos); } if (map.getTerrainLevel(x-1,y)==0) { bitmap=terrainTiles.get(R.drawable.shadow_w); drawWithOverflow(canvas, bitmap, rect, ypos); } if (map.getTerrainLevel(x+1,y+1)==0&&map.getTerrainLevel(x+1,y)<0) { bitmap=terrainTiles.get(R.drawable.shadow_se); drawWithOverflow(canvas, bitmap, rect, ypos); } if (map.getTerrainLevel(x-1,y+1)==0&&map.getTerrainLevel(x-1,y)<1) { bitmap=terrainTiles.get(R.drawable.shadow_sw); drawWithOverflow(canvas, bitmap, rect, ypos); } if (map.getTerrainLevel(x+1,y-1)==0&& map.getTerrainLevel(x+1,y)<1&& map.getTerrainLevel(x,y-1)<1) { bitmap=terrainTiles.get(R.drawable.shadow_ne); drawWithOverflow(canvas, bitmap, rect, ypos); } if (map.getTerrainLevel(x-1,y-1)==0&& map.getTerrainLevel(x-1,y)<1&& map.getTerrainLevel(x,y-1)<1) { bitmap=terrainTiles.get(R.drawable.shadow_nw); drawWithOverflow(canvas, bitmap, rect, ypos); } } if (terrain.symbol==TerrainType.BRIDGE) { bitmap=terrainTiles.get(DrawableMapping.getBridgeDrawable(map, x, y)); drawWithOverflow(canvas, bitmap, rect, 0,filters.getPaint()); } } private void drawPath(Canvas canvas, TileRect drawRect, Point[] pts) { paint.setStyle(Paint.Style.STROKE); paint.setColor(0xFF555555); paint.setStrokeWidth(drawRect.width()/6); //Log.d(TAG,"drawPath "+pts); if (pts.length<2) return; Path path=new Path(); drawRect.setTilePos(pts[0].x,pts[0].y); float x=drawRect.centerX(); float y=drawRect.centerY(); path.moveTo(x,y); for (int i=1;i<pts.length;i++) { drawRect.setTilePos(pts[i].x,pts[i].y); x=drawRect.centerX(); y=drawRect.centerY(); path.lineTo(x,y); } canvas.drawPath(path,paint); } private void drawAnimation(Canvas canvas, TileRect drawRect,SpriteAnimation animation) { Bitmap bitmap=animation.getBitmap(); if (bitmap==null) return; drawRect.setTilePos(animation.position.x,animation.position.y); int w=bitmap.getWidth(); int h=bitmap.getHeight(); srcRect.set(0,0,w,h); destRect.set(drawRect); GeomUtils.setRectAspect(destRect,w,h); canvas.drawBitmap(bitmap,srcRect,destRect,null); } private void drawUnit(Canvas canvas, GameUnit unit, RectF rect,ColorMatrix colorMatrix) { filters.setMatrix(colorMatrix); if (unit.ownerId== Player.USER_ID) filters.addMatrix(ColorFilters.redColorMatrix); else filters.addMatrix(ColorFilters.blueColorMatrix); Bitmap bitmap=terrainTiles.get(DrawableMapping.getUnitDrawable(unit.type)); drawUnitBitmap(canvas,bitmap,rect,unit.getAnimationPos().angle==0,filters.getPaint()); } private Matrix unitDrawMatrix=new Matrix(); private void drawUnitBitmap(Canvas canvas, Bitmap bitmap, RectF rect, boolean flipped, Paint unitPaint) { int w=bitmap.getWidth(); int h=bitmap.getHeight(); //Log.d(TAG,"drawUnitBitmap "+w+","+h+" rect="+rect); unitDrawMatrix.reset(); unitDrawMatrix.postTranslate(0,-w*0.45f); if (flipped) unitDrawMatrix.postScale(-1,1,w/2,0); float scale=rect.width()/w; unitDrawMatrix.postScale(scale, scale); unitDrawMatrix.postTranslate(rect.left, rect.top); canvas.drawBitmap(bitmap,unitDrawMatrix,unitPaint); } private RectF subrect2=new RectF(); private void drawUnitHealthBar(Canvas canvas, float percent, RectF rect) { subrect.set(0.7f,0.05f,0.95f,0.55f); GeomUtils.transformRect(rect, subrect); subrect2.set(0, 1 - percent, 1, 1); GeomUtils.transformRect(subrect,subrect2); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setStrokeWidth(drawRect.width()*0.025f); paint.setColor(0xFF000000); canvas.drawRect(subrect,paint); paint.setStyle(Paint.Style.FILL); paint.setColor(0xFF000000+GeomUtils.interpolateColor(0xFF0000,0x00AA00,percent)); canvas.drawRect(subrect2, paint); } private int getBuildingDrawable(Building building) { if (building.isFactory()) { if (building.isOwnedBy(Player.USER_ID)) return R.drawable.factory_red; else if (building.isOwnedBy(Player.AI_ID)) return R.drawable.factory_blue; else return R.drawable.factory; } else return R.drawable.gem; } private void drawBuilding(Canvas canvas, Building building, RectF rect,ColorMatrix colorMatrix) { Bitmap bitmap=terrainTiles.get(getBuildingDrawable(building)); int w=bitmap.getWidth(); int h=bitmap.getHeight(); unitDrawMatrix.reset(); unitDrawMatrix.postTranslate(0,-w*0.45f); float scale=rect.width()/w; unitDrawMatrix.postScale(scale, scale); unitDrawMatrix.postTranslate(rect.left, rect.top); filters.setMatrix(colorMatrix); ColorMatrix matrix; if (building.isOil()&&building.isOwnedBy(Player.USER_ID)) { filters.addMatrix(ColorFilters.redColorMatrix); } else if (building.isOil()&&building.isOwnedBy(Player.AI_ID)) { filters.addMatrix(ColorFilters.blueColorMatrix); } canvas.drawBitmap(bitmap,unitDrawMatrix, filters.getPaint()); } private float interpolateLevel(TerrainMap map, float x, float y) { int xInt=(int)Math.floor(x); int yInt=(int)Math.floor(y); float xFrac=x-xInt; float yFrac=y-yInt; int lev1=map.getTerrainLevel2(xInt,yInt); int lev2=map.getTerrainLevel2(xInt+1,yInt); int lev3=map.getTerrainLevel2(xInt,yInt+1); int lev4=map.getTerrainLevel2(xInt+1,yInt+1); return GeomUtils.interpolate( GeomUtils.interpolate(lev1,lev2,xFrac), GeomUtils.interpolate(lev3,lev4,xFrac), yFrac ); } @Override public Point getMapPosFromScreen(float screenX, float screenY, Matrix screenTransform, GameBoard map) { tileToScreen.set(screenTransform); tileToScreen.preScale(tileW,tileH); tileToScreen.invert(screenToTile); float[] xy={screenX,screenY}; screenToTile.mapPoints(xy); int tileX=(int)Math.floor(xy[0]); int tileY=(int)Math.floor(xy[1]); //Log.d(TAG,"getMapPosFromScreen - "+screenX+","+screenY+" = "+tileX+","+tileY); if (tileX<0||tileY<0||tileX>=map.width()||tileY>=map.height()) return null; return new Point(tileX,tileY); } @Override public RectF getScreenBounds(Rect mapBounds) { RectF bounds=new RectF( mapBounds.left*tileW, mapBounds.top*tileH, mapBounds.right*tileW, mapBounds.bottom*tileH ); return bounds; } private ColorGradient gradient; private void drawTestMap(Canvas canvas, GameBoard map, MapDrawParameters params, Rect mapBounds) { if (gradient==null) { gradient=new ColorGradient(0xFF0000,0x00CC00); } paint.setStyle(Paint.Style.FILL); for (int tileY=mapBounds.top;tileY<mapBounds.bottom;tileY++) { for (int tileX=mapBounds.left;tileX<mapBounds.right;tileX++) { drawRect.setTilePos(tileX, tileY); //float val=0.5f; float val= DebugTools.testMapAnalyzer.getMoveBonus(tileX,tileY); if (val>=0){ paint.setColor(gradient.getColor(val)); paint.setAlpha(50); canvas.drawRect(drawRect,paint); } } } } }<file_sep>package com.frozen.tankbrigade.ui; import android.content.Context; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.Rect; import android.graphics.RectF; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.frozen.tankbrigade.map.anim.MapAnimation; import com.frozen.tankbrigade.map.anim.SpriteAnimation; import com.frozen.tankbrigade.map.anim.UnitAnimation; import com.frozen.tankbrigade.map.anim.UnitAttackAnimation; import com.frozen.tankbrigade.map.model.GameConfig; import com.frozen.tankbrigade.map.model.GameUnit; import com.frozen.tankbrigade.map.model.GameBoard; import com.frozen.tankbrigade.map.moves.UnitMove; import com.frozen.tankbrigade.util.SparseMap; import org.metalev.multitouch.controller.MultiTouchController; import org.metalev.multitouch.controller.MultiTouchController.PointInfo; import org.metalev.multitouch.controller.MultiTouchController.PositionAndScale; import java.util.Iterator; /** * Created by sam on 04/01/14. */ //public class GameView extends View { public class GameView extends BaseSurfaceView implements View.OnTouchListener, MultiTouchController.MultiTouchObjectCanvas<Object> { public GameView(Context context) { this(context, null, 0); } public GameView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public GameView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setOnTouchListener(this); } public static interface GameViewListener { public void onTileSelected(Point pos); public void onAnimationComplete(MapAnimation animation, boolean allComplete); } public static final String TAG="GameView"; private GameBoard map; private Matrix transformMtx; private RectF unitRect =new RectF(); private MapDrawer renderer; private GameViewListener listener; private MapDrawParameters drawParams =new MapDrawParameters(); private static final float MIN_SCALE=0.2f; private static final float MAX_SCALE=1.5f; private boolean uiEnabled=true; private MultiTouchController<Object> multitouch=new MultiTouchController<Object>(this); public void setMap(GameBoard map,GameConfig config) { //renderer=new BasicMapDrawer(getContext(),config); renderer=new GraphicMapDrawer(getContext(),config); this.map=map; transformMtx =new Matrix(); invalidate(); } public void setListener(GameViewListener listener) { this.listener=listener; } @Override protected void drawSurface(Canvas canvas) { synchronized (drawParams) { if (drawParams!=null&&drawParams.isAnimating()) { //Log.d(TAG,"animation complete"); Iterator<MapAnimation> animationIterator=drawParams.getAnimations().iterator(); int animCount=drawParams.getAnimations().size(); while (animationIterator.hasNext()) { final MapAnimation animation=animationIterator.next(); if (animation.isAnimationComplete()) { animationIterator.remove(); animCount--; final boolean animationsComplete=(animCount==0); if (listener!=null) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { listener.onAnimationComplete(animation,animationsComplete); } }); } } } if (!drawParams.isAnimating()) uiEnabled=true; } } if (map==null) return; MapDrawParameters drawParameters=this.drawParams.clone(); //to avoid concurrency issues renderer.drawMap(canvas,map, transformMtx, drawParameters); } //handle touch events private long pressTime; private Point pressedTilePos; @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (!uiEnabled) return false; if (transformMtx ==null) return true; if (motionEvent.getActionMasked()==MotionEvent.ACTION_DOWN&&motionEvent.getActionIndex()==0) { pressTime=System.currentTimeMillis(); pressedTilePos=renderer.getMapPosFromScreen(motionEvent.getX(),motionEvent.getY(), transformMtx,map); } if (motionEvent.getActionMasked()==MotionEvent.ACTION_UP&&motionEvent.getActionIndex()==0) { long timeElapsed=System.currentTimeMillis()-pressTime; if (timeElapsed<250&&pressedTilePos!=null&&listener!=null) { listener.onTileSelected(pressedTilePos); pressedTilePos=null; } } //check uienabled again in case animation was started if (uiEnabled) multitouch.onTouchEvent(motionEvent); return true; } @Override public Object getDraggableObjectAtPoint(PointInfo touchPoint) { return new Object(); } @Override public void getPositionAndScale(Object obj, PositionAndScale objPosAndScaleOut) { unitRect.set(0, 0, 1, 1); transformMtx.mapRect(unitRect); Log.d(TAG,"getPositionAndScale"); objPosAndScaleOut.set(unitRect.left, unitRect.top,true, unitRect.width(),false,0,0,false,0); } private Rect mapTranslateBounds; private Matrix workingMatrix=new Matrix(); @Override public boolean setPositionAndScale(Object obj, PositionAndScale newObjPosAndScale, PointInfo touchPoint) { float scale=newObjPosAndScale.getScale(); //float maxScale=getWidth()/4; if (scale<MIN_SCALE||scale>MAX_SCALE) return false; if (screenRect==null) return false; workingMatrix.reset(); workingMatrix.setScale(scale, scale); workingMatrix.postTranslate(newObjPosAndScale.getXOff(), newObjPosAndScale.getYOff()); //check if it board is not off-screen if (mapTranslateBounds==null) mapTranslateBounds=new Rect(-1,-1,map.width()+1,map.height()+1); RectF bounds=renderer.getScreenBounds(mapTranslateBounds); RectF areaShown=getAreaShown(workingMatrix); if (areaShown.width()>bounds.width()&&areaShown.height()>bounds.height()) { return false; } float adjustX=-panAdjustment(areaShown.left,areaShown.right,bounds.left,bounds.right)*scale; float adjustY=-panAdjustment(areaShown.top,areaShown.bottom,bounds.top,bounds.bottom)*scale; if (adjustX!=0||adjustY!=0) { workingMatrix.postTranslate(adjustX,adjustY); } transformMtx.set(workingMatrix); return true; } private float panAdjustment(float start, float end, float boundsStart, float boundsEnd) { float w=end-start; float bw=boundsEnd-boundsStart; if (w>bw) { float targetStart=boundsStart-(w-bw)*0.5f; return targetStart-start; } else if (start<boundsStart) return boundsStart-start; else if (end>boundsEnd) return boundsEnd-end; else return 0; } @Override public void selectObject(Object obj, PointInfo touchPoint) { //Log.d(TAG,"selectObject"); } private RectF screenRect; @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { if (w==0||h==0) screenRect=null; else screenRect=new RectF(0,0,w,h); super.onSizeChanged(w, h, oldw, oldh); } private Matrix inverseTransform=new Matrix(); private RectF areaShown=new RectF(); public RectF getAreaShown() { return getAreaShown(transformMtx); } protected RectF getAreaShown(Matrix mtx) { if (screenRect==null) return null; mtx.invert(inverseTransform); inverseTransform.mapRect(areaShown,screenRect); return areaShown; } public void setFocusRect(Rect rect,boolean union) { if (screenRect==null) return; RectF focusRect=renderer.getScreenBounds(rect); if (union) { focusRect.union(getAreaShown()); } transformMtx.setRectToRect(focusRect, screenRect, Matrix.ScaleToFit.CENTER); } // ----------- UI ---------------- public void startAnimation() { Log.d(TAG,"startAnimation"); uiEnabled=false; } public void clearPath() { drawParams.selectedPath=null; drawParams.selectedAttack=null; } public void setOverlay(GameUnit selectedUnit, SparseMap<UnitMove> moveMap) { drawParams.setMoveOverlay(new Point(selectedUnit.x,selectedUnit.y),moveMap); } public void removeOverlay() { drawParams.setMoveOverlay(null,null); } public void setTestMode(int testMode) { drawParams.testMode=testMode; } public int getTestMode() { return drawParams.testMode; } public void highlightPath(Point[] path,Point attack) { drawParams.selectedPath=path; drawParams.selectedAttack=attack; } public void animateMove(UnitMove move) { UnitAnimation unitAnim=new UnitAnimation(move); move.unit.setAnimation(unitAnim); addAnimation(unitAnim); } public void animateAttack(UnitMove move) { animateAttack(move,move.unit,move.getAttackPoint()); } public void animateCounterattack(UnitMove move) { animateAttack(move,move.attackTarget,move.unit.getPos()); } protected void animateAttack(UnitMove move, GameUnit unit, Point target) { UnitAttackAnimation unitAnim=new UnitAttackAnimation(move,unit); unit.setAnimation(unitAnim); addAnimation(unitAnim); SpriteAnimation explosion=new SpriteAnimation(getContext(), SpriteAnimation.EXPLOSION_RES,300,target); explosion.setStartTime(200); addAnimation(explosion); } protected void addAnimation(MapAnimation animation) { uiEnabled=false; synchronized (drawParams) { drawParams.addAnimation(animation); } } public void focusOnMove(UnitMove move) { Rect moveRect=new Rect(0,0,1,1); moveRect.offsetTo(move.unit.x, move.unit.y); Rect endRect=new Rect(0,0,1,1); Point endpoint=move.getEndPoint(); if (endpoint!=null) { endRect.offsetTo(endpoint.x,endpoint.y); moveRect.union(endRect); } endpoint=move.getAttackPoint(); if (endpoint!=null) { endRect.offsetTo(endpoint.x,endpoint.y); moveRect.union(endRect); } setFocusRect(moveRect,true); multitouch.anchorAtThisPositionAndScale(); } } <file_sep>package com.frozen.tankbrigade.map.model; import android.util.SparseArray; import com.frozen.easyjson.JsonProperty; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by sam on 08/02/14. */ public class GameConfig { @JsonProperty public List<TerrainType> terrainTypes; @JsonProperty public List<GameUnitType> unitTypes; private Map<String,GameUnitType> unitNameMap; private SparseArray<GameUnitType> unitSymbolMap; public GameUnitType getUnitTypeBySymbol(char typeSymbol) { if (unitSymbolMap==null) { unitSymbolMap=new SparseArray<GameUnitType>(unitTypes.size()); for (GameUnitType unitType:unitTypes) { unitSymbolMap.put(unitType.symbol,unitType); } } return unitSymbolMap.get(typeSymbol); } public GameUnitType getUnitTypeByName(String name) { if (unitNameMap==null) { unitNameMap=new HashMap<String, GameUnitType>(unitTypes.size()); for (GameUnitType unitType:unitTypes) { unitNameMap.put(unitType.name,unitType); } } return unitNameMap.get(name); } } <file_sep>package com.frozen.tankbrigade.ui; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * Created by sam on 04/01/14. */ public abstract class BaseSurfaceView extends SurfaceView implements Runnable,SurfaceHolder.Callback { public static final String TAG="BaseSurfaceView"; private Thread thread; private SurfaceHolder holder; private volatile boolean running=false; public BaseSurfaceView(Context context) { super(context); init(); } public BaseSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BaseSurfaceView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { holder=getHolder(); holder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { Log.i(TAG,"surfaceCreated"); thread=new Thread(this); running=true; thread.start(); } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) { Log.i(TAG,"surfaceChanged"); } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { Log.i(TAG,"surfaceDestroyed"); boolean retry = true; running = false; while(retry){ try { thread.join(); retry = false; } catch (InterruptedException e) { e.printStackTrace(); } } } @Override public void run() { Log.i(TAG,"run"); while (running) { if(holder.getSurface().isValid()){ try { Canvas canvas = holder.lockCanvas(); if (canvas!=null) drawSurface(canvas); holder.unlockCanvasAndPost(canvas); } catch (Exception e) { Log.w(TAG,"Could not draw surface - "+e.toString()); e.printStackTrace(); running=false; } } } } protected abstract void drawSurface(Canvas canvas); } <file_sep>package com.frozen.tankbrigade.map.moves; import android.graphics.Point; import com.frozen.tankbrigade.map.paths.AStarNode; import com.frozen.tankbrigade.map.model.GameUnit; /** * Created by sam on 02/02/14. */ public class UnitMove { public static final int NONE=0; //no action public static final int MOVE=1; //can move here public static final int ATTACK=2; //attack move private AStarNode node; private Point[] path; public GameUnit unit; public GameUnit attackTarget; public int movementCost; public int x; public int y; public UnitMove(GameUnit unit, AStarNode moveNode, GameUnit attackTarget) { if (path!=null&&path.length==0) path=null; this.node = moveNode; this.movementCost=moveNode.totalCost; this.unit = unit; this.attackTarget = attackTarget; if (attackTarget!=null) { x=attackTarget.x; y=attackTarget.y; } else if (node!=null) { x=node.x; y=node.y; } else { x=unit.x; y=unit.y; } } public UnitMove(GameUnit unit, Point[] path, int movementCost, GameUnit attackTarget) { if (path!=null&&path.length==0) path=null; this.path = path; this.movementCost=movementCost; this.unit = unit; this.attackTarget = attackTarget; if (attackTarget!=null) { x=attackTarget.x; y=attackTarget.y; } else if (getEndPoint()!=null) { Point end=getEndPoint(); x=end.x; y=end.y; } else { x=unit.x; y=unit.y; } } public Point getEndPoint() { if (path!=null&&path.length>0) return path[path.length-1]; else if (node!=null) return new Point(node.x,node.y); else return new Point(unit.x,unit.y); } public Point getEndPointIfExists() { if (path!=null&&path.length>0) return path[path.length-1]; else if (node!=null) return new Point(node.x,node.y); else return null; } public Point getAttackPoint() { if (attackTarget==null) return null; else return attackTarget.getPos(); } public int getActionType() { if (attackTarget!=null) return ATTACK; else if (x==unit.x&&y==unit.y) return NONE; else return MOVE; } public boolean isAttack() { return attackTarget!=null; } public boolean hasMove() { return (path!=null&&path.length>0)||node!=null; } public Point[] getPath() { if (path==null&&node!=null) { //lazy evaluation of node path, then you can throw node away path=node.getPath(); node=null; } return path; } public String toString() { return "[UnitMove unit="+unit.toString()+" moveTo="+getEndPoint()+" attackTarget="+attackTarget+"]"; } public UnitMove createAttackFromMove(GameUnit attackTarget) { UnitMove move; if (node!=null) move=new UnitMove(unit,node,attackTarget); else move=new UnitMove(unit,path,movementCost,attackTarget); return move; } } <file_sep>package com.frozen.tankbrigade.map.model; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; /** * Created by sam on 27/11/14. */ public class Building implements Ordered2D { public String name; public int x; public int y; private BuildingType type; private int ownerId; private boolean isCapturing; private int capturingPlayerId; private int captureTurns=0; public enum BuildingType {FACTORY,OIL,GOLD}; public Building(String name, int x, int y, int ownerId) { this.name = name; this.x = x; this.y = y; this.ownerId = ownerId; type=BuildingType.valueOf(name.toUpperCase()); } public Building(String name, int x, int y, int ownerId, int occupyingId, int numTurns) { this.name = name; this.x = x; this.y = y; this.ownerId = ownerId; this.capturingPlayerId=occupyingId; this.captureTurns=numTurns; isCapturing=true; type=BuildingType.valueOf(name.toUpperCase()); } public boolean isFactory() { return type==BuildingType.FACTORY; } public boolean isOwnedBy(int playerId) { return playerId==ownerId&&!isCapturing; } public int getOwnerId() { if (isCapturing) return Player.NONE; else return ownerId; } public void capture(int playerId) { if (playerId==ownerId) return; if (!(isCapturing&&playerId==capturingPlayerId)) { startCapture(playerId); } captureTurns++; if (captureTurns==2) { ownerId=capturingPlayerId; endCapture(); } } private void startCapture(int playerId) { isCapturing=true; capturingPlayerId=playerId; captureTurns=0; } public void endCapture() { isCapturing=false; capturingPlayerId=0; captureTurns=0; } public int moneyGenerated() { if (type==BuildingType.GOLD) return 200; else if (type==BuildingType.OIL) return 80; else return 0; } public boolean isOil() { //HACK: this is for graphic drawing - for now, use the same graphic for gold and oil return type==BuildingType.GOLD||type==BuildingType.OIL; } //------ AI stuff -- //assign a value to the building for AI purposes public int getAIValue() { if (type==BuildingType.GOLD) return 400; else if (type==BuildingType.OIL) return 160; else return 400; } private static final float CAPTURE_PER_TURN=0.5f; public float getOwnershipAmt(int playerId) { int owner; float amt=1; if (isCapturing) { owner=capturingPlayerId; amt=captureTurns*CAPTURE_PER_TURN; } else { owner=ownerId; amt=1; } return Player.compare(playerId,owner)*amt; } public float getOwnershipAmtIfOccupied(int playerId, int occupyingId) { int owner; float amt=1; if (occupyingId==ownerId||occupyingId==Player.NONE) { //Log.d("I_DEBUG","getOwnership - no change - owner="+ownerId); owner=ownerId; amt=1; } else { owner=occupyingId; //Log.d("I_DEBUG","getOwnership - changing - owner="+ownerId+" isCapturing="+isCapturing+" capturer="+capturingPlayerId+" turns="+captureTurns); if (isCapturing&&capturingPlayerId==occupyingId) { amt=(captureTurns+1)*CAPTURE_PER_TURN; } else amt=CAPTURE_PER_TURN; } //Log.i("I_DEBUG","getOwnership - player="+playerId+" owner="+owner+" amt="+amt+" compare="+Player.compare(playerId,owner)); return Player.compare(playerId,owner)*amt; } //------------- public boolean getIsCapturing() { return isCapturing; } public int getOldOwnerId() {return ownerId; } public int getOccupyingOwnerId() {return capturingPlayerId; } public int getCaptureTurns() {return captureTurns; } //------------- @Override public int getOrderX() { return x; } @Override public int getOrderY() { return y; } public Building clone() { return new Building(name,x,y,ownerId); } @Override public String toString() { return String.format("[Building %s %d,%d]",name,x,y); } } <file_sep>package com.frozen.easyjson; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** sammyer Use this as a replacement for com.fasterxml.jackson.annotation.JsonProperty */ @Retention(RetentionPolicy.RUNTIME) public @interface JsonProperty { }<file_sep>package com.frozen.tankbrigade.map.model; import com.frozen.easyjson.JsonProperty; /** * Created by sam on 12/01/14. */ public class GameUnitType { public static final char COMMANDO='C'; public static final char BAZOOKA='B'; public static final char FLAK='F'; public static final char TANK='T'; public static final char ROCKET='R'; public static final char AIRPLANE='A'; public static final char BOMBER='O'; public static final char GOLIATH='G'; public static final char MORTAR='M'; private enum MoveMode {foot,tracked,air,water}; private static final int LIGHT=1; private static final int MEDIUM=2; private static final int HEAVY=3; @JsonProperty public char symbol; @JsonProperty public String name; @JsonProperty public int damage; @JsonProperty public int health; @JsonProperty public int movement; @JsonProperty public int attackType=MEDIUM; @JsonProperty public int defenseType=MEDIUM; @JsonProperty private int[] range; @JsonProperty private String moveType; @JsonProperty public boolean canAttackAir=false; @JsonProperty public int price; public GameUnitType() { } public boolean canAttack(GameUnitType defender) { //TODO: fill this in if (defender.isAir()&&!canAttackAir) return false; return true; } public boolean canAttack(GameUnitType defender, int attackX, int attackY, int defendX, int defendY) { if (!canAttack(defender)) return false; //manhattan distance int range=Math.abs(attackX-defendX)+Math.abs(attackY-defendY); if (isRanged()) { if (range<getMinRange()||range>getMaxRange()) return false; } else { if (range!=1) return false; } return true; } public float getDamageMultiplier(GameUnitType defender) { if (attackType==MEDIUM||defender.defenseType==MEDIUM) return 1; if (attackType==defender.defenseType) return 2; else return 0.5f; } public boolean isTank() { return moveType.equals("tracked"); } public boolean isLand() { return moveType.equals("tracked")|| moveType.equals("foot"); } public boolean isWater() { return moveType.equals("water"); } public boolean isAir() { return moveType.equals("air"); } public boolean canCaptureBuildings() { return !isAir(); } public boolean isRanged() { return range!=null; } public int getMinRange() { if (range==null||range.length==0) return 1; else return range[0]; } public int getMaxRange() { if (range==null||range.length==0) return 1; else if (range.length==1) return range[0]; else return range[1]; } } <file_sep>package com.frozen.tankbrigade.map.model; /** * Created by sam on 08/02/14. */ public class Player { public static int USER_ID=1; public static int AI_ID=2; public static int NONE =0; public int id; public int money; public Player(int id, int startingMoney) { this.id=id; this.money=startingMoney; } //returns 1 if is same player, -1 if different players, or 0 if comparing to neutral public static int compare(int playerId1, int playerId2) { if (playerId1==Player.NONE||playerId2==Player.NONE) return 0; else if (playerId1==playerId2) return 1; else return -1; } public Player clone() { return new Player(id,money); } } <file_sep>package com.frozen.tankbrigade; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; /** * Created by sam on 02/12/14. */ public class WinLoseActivity extends Activity { public static final String EXTRA_OUTCOME = "EXTRA_OUTCOME"; private boolean outcome; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_winlose); TextView titleView=(TextView)findViewById(R.id.titleText); TextView messageView=(TextView)findViewById(R.id.messageText); findViewById(R.id.continueBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goToNextScreen(); } }); if (savedInstanceState==null) outcome=getIntent().getBooleanExtra(EXTRA_OUTCOME,true); else outcome=savedInstanceState.getBoolean(EXTRA_OUTCOME,true); titleView.setText(outcome?"WIN!":"FAIL."); messageView.setText(outcome?"You have won. Solid.":"You have lost. Bummer."); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(EXTRA_OUTCOME,outcome); super.onSaveInstanceState(outState); } private void goToNextScreen() { Intent intent=new Intent(this,MenuActivity.class); startActivity(intent); } } <file_sep>package com.frozen.tankbrigade.map.paths; import com.frozen.tankbrigade.util.SparseMap; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by sam on 09/03/14. */ public class AStar { private List<AStarNode> nodeSearchQueue=new ArrayList<AStarNode>(); private SparseMap<AStarNode> nodeMap; private Comparator<AStarNode> costComparator=new Comparator<AStarNode>() { @Override public int compare(AStarNode node, AStarNode node2) { return node.totalCost-node2.totalCost; } }; public SparseMap<AStarNode> findMoves(AStarMap map, int startX, int startY) { nodeMap=new SparseMap<AStarNode>(1000,1000); nodeSearchQueue.clear(); AStarNode node=new AStarNode(startX,startY,null,0); nodeMap.set(startX,startY,node); nodeSearchQueue.add(node); while (nodeSearchQueue.size()>0) { node=nodeSearchQueue.remove(0); checkNode(map, node.x + 1, node.y, node); checkNode(map,node.x-1,node.y,node); checkNode(map,node.x,node.y+1,node); checkNode(map,node.x,node.y-1,node); } return nodeMap; } private void checkNode(AStarMap map, int x, int y, AStarNode prev) { if (!map.canMoveHere(x,y)) return; int cost=map.getCost(x,y); int totalCost=prev.totalCost+cost; if (totalCost>map.getMaxCost()) return; AStarNode node=nodeMap.get(x,y); if (node!=null&&node.totalCost<=totalCost) return; node=new AStarNode(x,y,prev,cost); nodeMap.set(x,y,node); //dont bother adding to queue if cost==movement or if this is an enemy square if (totalCost!=map.getMaxCost()) { int queuePos= Collections.binarySearch(nodeSearchQueue, node, costComparator); if (queuePos<0) queuePos=-queuePos-1; //see doc for binarysearch nodeSearchQueue.add(queuePos,node); } } } <file_sep>package com.frozen.tankbrigade.util; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; /** * Created by sam on 26/01/14. */ public class GeomUtils { public static final int UP=90; public static final int LEFT=180; public static final int RIGHT=0; public static final int DOWN=270; public static PointF interpolatePoint(Point start, Point end, float d) { float x=start.x*(1-d)+end.x*d; float y=start.y*(1-d)+end.y*d; return new PointF(x,y); } //same as Matrix.setRecttoRect(unit,xform).mapRect(rect) public static void transformRect(RectF xform, RectF rect) { rect.set( rect.left*xform.width()+xform.left, rect.top*xform.height()+xform.top, rect.right*xform.width()+xform.left, rect.bottom*xform.height()+xform.top ); } public static int getSquareAngle(Point start, Point end) { if (Math.abs(start.x-end.x)>Math.abs(start.y-end.y)) { if (start.x>end.x) return LEFT; else return RIGHT; } else { if (start.y>end.y) return UP; else return DOWN; } } public static boolean isArraySize(Object[][] arr, int w, int h) { if (arr==null) return false; if (arr.length==0) return false; if (arr.length!=w) return false; if (arr[0]==null) return false; if (arr[0].length!=h) return false; return true; } public static boolean isInBounds(Object[][] arr, int x, int y) { if (x<0||y<0) return false; if (arr==null||arr.length==0||arr[0].length==0) return false; if (x>=arr.length) return false; if (y>=arr[0].length) return false; return true; } public static float interpolate(float a, float b, float proportion) { return a + ((b - a) * proportion); } public static int interpolateColor(int a, int b, float proportion) { float[] hsva = new float[3]; float[] hsvb = new float[3]; Color.colorToHSV(a, hsva); Color.colorToHSV(b, hsvb); for (int i = 0; i < 3; i++) { hsvb[i] = interpolate(hsva[i], hsvb[i], proportion); } return Color.HSVToColor(hsvb); } private static RectF r=new RectF(0,0,1,1); public static String matrixToString(Matrix m) { r.set(0,0,1,1); m.mapRect(r); return "[Matrix trans="+r.left+","+r.top+" scale="+r.width()+","+r.height()+"]"; } public static void setRectAspect(RectF rect, float w, float h) { float targetRatio=w/h; float ratio=rect.width()/rect.height(); if (ratio==targetRatio) return; else if (ratio>targetRatio) { float w2=rect.height()*targetRatio; float centerX=rect.centerX(); rect.left=centerX-w2/2; rect.right=centerX+w2/2; } else { float h2=rect.width()/targetRatio; float centerY=rect.centerY(); rect.top=centerY-h2/2; rect.bottom=centerY+h2/2; } } } <file_sep>package com.frozen.tankbrigade.ai; import com.frozen.tankbrigade.map.model.GameBoard; import com.frozen.tankbrigade.map.model.GameUnit; import com.frozen.tankbrigade.map.paths.AStar; import com.frozen.tankbrigade.map.paths.AStarBoardAdapter; import com.frozen.tankbrigade.map.paths.AStarNode; import com.frozen.tankbrigade.util.SparseMap; /** * Created by sam on 26/12/14. */ public class ClosesUnitMapAnalyzer implements MapAnalyzer { private float[][] ownership; private int numUnits; public void analyzeMap(GameBoard board, int curPlayer) { ownership=new float[board.width()][board.height()]; AStar astar=new AStar(); AStarAnalyzerMap astarMap; SparseMap<AStarNode> moves; numUnits=0; for (GameUnit unit:board.getUnits()) { if (unit.ownerId==curPlayer) continue; astarMap=new AStarAnalyzerMap(board,unit); astarMap.setIgnoreEnemyUnits(true); moves=astar.findMoves(astarMap,unit.x,unit.y); for (AStarNode move:moves.getAllNodes()) { int unitMoves=unit.type.movement; //heuristic for unit weight score set to 1/x where x is number of turns to get to that place //i.e. x=num moves/unit moves per turn ownership[move.x][move.y]+=unitMoves/(float)(move.totalCost+unitMoves); } numUnits++; } } public float getMoveBonus(int x, int y) { return ownership[x][y]/numUnits; } private static class AStarAnalyzerMap extends AStarBoardAdapter { public AStarAnalyzerMap(GameBoard board, GameUnit unit) { super(board,unit); } @Override public int getMaxCost() { return 50; } } } <file_sep>package com.frozen.tankbrigade.map.anim; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import com.frozen.tankbrigade.R; /** * Created by sam on 02/02/14. */ public class SpriteAnimation implements MapAnimation { public long animateStartTime; private int duration; public Point position; private Bitmap[] bitmaps; public static final int[] EXPLOSION_RES = { R.drawable.explosion1, R.drawable.explosion2, R.drawable.explosion3, R.drawable.explosion4, R.drawable.explosion5 }; public SpriteAnimation(Context context, int[] resourceIds, int durationMillis, Point position) { this(load(context,resourceIds),durationMillis,position); } public SpriteAnimation(Bitmap[] bitmaps, int durationMillis, Point position) { this.bitmaps=bitmaps; animateStartTime=System.currentTimeMillis(); this.duration=durationMillis; this.position=position; } public void setStartTime(int offsetMillis) { animateStartTime=System.currentTimeMillis()+offsetMillis; } @Override public boolean isAnimationComplete() { long timediff=System.currentTimeMillis()-animateStartTime; return timediff>duration; } protected int getIdx() { int n=bitmaps.length; long timediff=System.currentTimeMillis()-animateStartTime; int idx=(int)timediff*n/duration; if (idx<0) return -1; if (idx>=n) return -1; return idx; } public static Bitmap[] load(Context context,int[] resourceIds) { int n=resourceIds.length; Bitmap[] bitmaps=new Bitmap[n]; for (int i=0;i<n;i++) { bitmaps[i]= BitmapFactory.decodeResource(context.getResources(), resourceIds[i]); } return bitmaps; } public Bitmap getBitmap() { int idx=getIdx(); if (idx<0) return null; else return bitmaps[idx]; } } <file_sep>/** sammyer This is to replace the Jackson library. It should work about the same. */ package com.frozen.easyjson; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { private static final boolean DEBUG = false; private static final String TAG = "JSONParser"; public static <T> T parse(JSONObject obj, Class<T> clazz) { return parseClass(obj, clazz); } private static <T> T parseClass(JSONObject json, Class<T> clazz) { if (DEBUG) Log.i(TAG, "parseClass "+clazz.getName()); T obj; try { obj = clazz.newInstance(); } catch (Exception e) { logException(e); return null; } for (Field field:clazz.getDeclaredFields()) { if (field.isAnnotationPresent(JsonProperty.class)) { parseField(json,obj,field); } } return obj; } private static void parseField(JSONObject json, Object obj, Field field) { FieldStruct fieldData=new FieldStruct(field); if (fieldData.clazz==null) return; try { if (fieldData.type==FieldType.PRIMITIVE) parsePrimitiveField(json, obj, fieldData); else if (fieldData.type==FieldType.CLASS) parseClassField(json, obj, fieldData); else if (fieldData.type==FieldType.LIST) parseListField(json, obj, fieldData); else if (fieldData.type==FieldType.ARRAY) parseArrayField(json, obj, fieldData); else if (fieldData.type==FieldType.JSON) parseJsonField(json, obj, fieldData); } catch (JSONException e) { logException(e); } catch (Exception e) { logException(e); } } private static void logException(Exception e) { if (DEBUG) Log.e(TAG,"jpt errx - "+e.toString()); e.printStackTrace(); } private static void parsePrimitiveField(JSONObject json, Object obj, FieldStruct field) throws IllegalArgumentException, IllegalAccessException, JSONException { if (DEBUG) Log.i(TAG, "parsePrimitiveField "+field.name); field.field.setAccessible(true); if (field.clazz.equals(int.class)) { field.field.set(obj, json.getInt(field.name)); } else if (field.clazz.equals(long.class)) { field.field.set(obj, json.getLong(field.name)); } else if (field.clazz.equals(float.class)) { field.field.set(obj, (float)json.getDouble(field.name)); } else if (field.clazz.equals(double.class)) { field.field.set(obj, json.getDouble(field.name)); } else if (field.clazz.equals(boolean.class)) { field.field.set(obj, json.getBoolean(field.name)); } else if (field.clazz.equals(short.class)) { field.field.set(obj, (short)json.getInt(field.name)); } else if (field.clazz.equals(char.class)) { String s=json.getString(field.name); if (s!=null&s.length()>0) field.field.set(obj, s.charAt(0)); } else if (field.clazz.equals(byte.class)) { field.field.set(obj, (byte)json.getInt(field.name)); } else if (field.clazz.equals(String.class)) { field.field.set(obj, json.getString(field.name)); } else { field.field.set(obj, parseBoxedPrimitive(json, field.name, field.clazz)); } } private static void parseClassField(JSONObject json, Object obj, FieldStruct field) throws JSONException, IllegalArgumentException, IllegalAccessException { if (DEBUG) Log.i(TAG, "parseClassField "+field.name); JSONObject childJson; childJson=json.getJSONObject(field.name); field.field.setAccessible(true); field.field.set(obj, parseClass(childJson,field.clazz)); } private static void parseJsonField(JSONObject json, Object obj, FieldStruct field) throws JSONException, IllegalArgumentException, IllegalAccessException { if (DEBUG) Log.i(TAG, "parseClassField "+field.name); JSONObject childJson; childJson=json.getJSONObject(field.name); field.field.setAccessible(true); field.field.set(obj, childJson); } @SuppressWarnings({ "rawtypes", "unchecked" }) private static void parseListField(JSONObject json, Object obj, FieldStruct field) throws IllegalArgumentException, IllegalAccessException, JSONException { if (DEBUG) Log.i(TAG, "parseListField "+field.name); JSONArray jsonarr; jsonarr=json.getJSONArray(field.name); int arrlen=jsonarr.length(); ArrayList list=new ArrayList(); boolean isBoxedPrimitive=FieldStruct.isPrimitive(field.clazz); for (int i=0;i<arrlen;i++) { if (isBoxedPrimitive) { list.add(parseBoxedPrimitive(jsonarr, i, field.clazz)); } else { JSONObject jsonobj; jsonobj = (JSONObject)jsonarr.get(i); if (jsonobj==null) continue; list.add(parseClass(jsonobj,field.clazz)); } } field.field.setAccessible(true); field.field.set(obj, list); } private static Object parseBoxedPrimitive(JSONArray jsonarr, int i, Class<?> clazz) throws JSONException { if (clazz.equals(String.class)) { return jsonarr.getString(i); } if (clazz.equals(Integer.class)) { return Integer.valueOf(jsonarr.getInt(i)); } else if (clazz.equals(Float.class)) { return Float.valueOf((float)jsonarr.getDouble(i)); } else if (clazz.equals(Double.class)) { return Double.valueOf(jsonarr.getDouble(i)); } else if (clazz.equals(Long.class)) { return Long.valueOf(jsonarr.getLong(i)); } else if (clazz.equals(Short.class)) { return Short.valueOf((short)jsonarr.getInt(i)); } else if (clazz.equals(Byte.class)) { return Byte.valueOf((byte)jsonarr.getInt(i)); } else if (clazz.equals(Character.class)) { String s=jsonarr.getString(i); if (s!=null&s.length()>0) { return Character.valueOf(s.charAt(0)); } } else if (clazz.equals(Boolean.class)) { return Boolean.valueOf(jsonarr.getBoolean(i)); } throw new JSONException("parseBoxedPrimitive :: type not handled"); } private static Object parseBoxedPrimitive(JSONObject json, String fieldName, Class<?> clazz) throws JSONException { if (clazz.equals(String.class)) { return json.get(fieldName); } else if (clazz.equals(Integer.class)) { return Integer.valueOf(json.getInt(fieldName)); } else if (clazz.equals(Long.class)) { return Long.valueOf(json.getLong(fieldName)); } else if (clazz.equals(Float.class)) { return Float.valueOf((float)json.getDouble(fieldName)); } else if (clazz.equals(Double.class)) { return Double.valueOf(json.getDouble(fieldName)); } else if (clazz.equals(Boolean.class)) { return Boolean.valueOf(json.getBoolean(fieldName)); } else if (clazz.equals(Short.class)) { return Short.valueOf((short)json.getInt(fieldName)); } else if (clazz.equals(Character.class)) { String s=json.getString(fieldName); if (s!=null&s.length()>0) return Character.valueOf(s.charAt(0)); } else if (clazz.equals(Byte.class)) { return Byte.valueOf((byte)json.getInt(fieldName)); } throw new JSONException("parseBoxedPrimitive :: type not handled"); } private static void parseArrayField(JSONObject json, Object obj, FieldStruct field) throws IllegalArgumentException, IllegalAccessException, JSONException { if (DEBUG) Log.i(TAG, "parseArrayField "+field.name+" cl="+field.clazz); JSONArray jsonarr; jsonarr=json.getJSONArray(field.name); field.field.setAccessible(true); int arrlen=jsonarr.length(); Object arr=Array.newInstance(field.clazz, arrlen); for (int i=0;i<arrlen;i++) { parseArrayFieldAux(arr, jsonarr, i, field.clazz); } field.field.set(obj, arr); } private static void parseArrayFieldAux(Object arr, JSONArray jsonarr, int i, Class<?> clazz) throws ArrayIndexOutOfBoundsException, IllegalArgumentException, JSONException { if (clazz.equals(int.class)) { Array.setInt(arr, i, jsonarr.getInt(i)); } else if (clazz.equals(float.class)) { Array.setFloat(arr, i, (float)jsonarr.getDouble(i)); } else if (clazz.equals(double.class)) { Array.setDouble(arr, i, jsonarr.getDouble(i)); } else if (clazz.equals(long.class)) { Array.setLong(arr, i, jsonarr.getLong(i)); } else if (clazz.equals(short.class)) { Array.setShort(arr, i, (short)jsonarr.getInt(i)); } else if (clazz.equals(byte.class)) { Array.setByte(arr, i, (byte)jsonarr.getInt(i)); } else if (clazz.equals(char.class)) { String s=jsonarr.getString(i); if (s!=null&s.length()>0) Array.setChar(arr, i, s.charAt(0)); } else if (clazz.equals(boolean.class)) { Array.setBoolean(arr, i, jsonarr.getBoolean(i)); } else if (clazz.equals(String.class)) { Array.set(arr, i, jsonarr.getString(i)); } else if (clazz.isArray()) { //multidimensional arrays JSONArray subJsonArr=jsonarr.getJSONArray(i); Class<?> subclazz=clazz.getComponentType(); Object subarr=Array.newInstance(subclazz, subJsonArr.length()); for (int j=0;j<subJsonArr.length();j++) { parseArrayFieldAux(subarr, subJsonArr, j, subclazz); } Array.set(arr, i, subarr); } else if (FieldStruct.isPrimitive(clazz)) { Array.set(arr, i, parseBoxedPrimitive(jsonarr, i, clazz)); } else { JSONObject obj=(JSONObject)jsonarr.get(i); if (obj!=null) Array.set(arr, i, parseClass(obj,clazz)); } } private enum FieldType { PRIMITIVE,LIST,ARRAY,CLASS,JSON } private static class FieldStruct { public Field field; public String name; public FieldType type; public Class<?> clazz; private static final Class<?>[] primitiveClasses={ Boolean.class,Byte.class,Short.class,Integer.class,Long.class, Float.class,Double.class,Character.class,String.class}; public FieldStruct(Field field) { this.field=field; name=field.getName(); clazz=field.getType(); if (isPrimitive(clazz)) { type=FieldType.PRIMITIVE; } else if (clazz.isArray()) { type=FieldType.ARRAY; clazz=clazz.getComponentType(); } else if (clazz.isAssignableFrom(ArrayList.class)) { type=FieldType.LIST; try { ParameterizedType ptype=(ParameterizedType)field.getGenericType(); clazz=(Class<?>) ptype.getActualTypeArguments()[0]; } catch (Exception e) { clazz=null; } } else if (clazz.isAssignableFrom(JSONObject.class)) { type=FieldType.JSON; } else type=FieldType.CLASS; } private static boolean isPrimitive(Class<?> clazz) { if (clazz.isPrimitive()) return true; for (Class<?> pclazz:primitiveClasses) { if (clazz==pclazz) return true; } return false; } } }<file_sep>package com.frozen.tankbrigade.util; import com.frozen.tankbrigade.map.model.Ordered2D; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * Created by sam on 30/11/14. */ public class Iterator2D<T extends Ordered2D> implements Iterator<T> { private Iterator<T> iterator; private Comparator2D comparator; private T curItem; private class Comparator2D implements Comparator<T> { private boolean horizontal; private boolean reverseX; private boolean reverseY; private Comparator2D(boolean horizontal, boolean reverseX, boolean reverseY) { this.horizontal = horizontal; this.reverseX = reverseX; this.reverseY = reverseY; } @Override public int compare(T item1, T item2) { return compare(item1.getOrderX(),item1.getOrderY(),item2.getOrderX(),item2.getOrderY()); } public int compare(int x1, int y1, int x2, int y2) { int diffX=x1-x2; if (reverseX) diffX=-diffX; int diffY=y1-y2; if (reverseY) diffY=-diffY; if (horizontal) return compare2D(diffY,diffX); else return compare2D(diffX,diffY); } private int compare2D(int primary, int secondary) { if (primary==0) return secondary; else return primary; } } public Iterator2D(Collection<T> items) { this(items,true,false,false); } public Iterator2D(Collection<T> items, boolean horizontal, boolean reverseX, boolean reverseY) { List<T> sortedItems=new ArrayList<T>(items); comparator=new Comparator2D(horizontal,reverseX,reverseY); Collections.sort(sortedItems,comparator); iterator=sortedItems.iterator(); next(); } //iterates through items until we get to position x,y public T seek(int x, int y) { int order; int itemX; int itemY; while (curItem!=null) { itemX=curItem.getOrderX(); itemY=curItem.getOrderY(); order=comparator.compare(x,y,itemX,itemY); if (order==0) return next(); //x,y, is current item else if (order>0) next(); //x,y, is after itemX,itemY else return null; //x,y, is before itemX,itemY } return null; } @Override public boolean hasNext() { return curItem!=null; } public T next() { T item=curItem; if (iterator.hasNext()) curItem=iterator.next(); else curItem=null; return item; } @Override public void remove() { throw new UnsupportedOperationException(); } }
41b6dba60e1081331451a1f594046bc07c90bb5c
[ "Java", "Gradle" ]
22
Java
sammyer/tankbrigade
0904105fda0fa5e6c46ac3898eb683e238d0371d
7a83f2d2741f44710e1b32da54bfaff09cad3e04
refs/heads/master
<repo_name>wammamms/ProjectTB<file_sep>/app/src/main/java/com/seventyseven/projecttb/utils/DatabindingHelper.kt package com.seventyseven.projecttb.utils import android.app.Activity import android.content.Intent import android.graphics.Color import android.graphics.Paint import android.view.View import android.widget.GridView import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.widget.Toolbar import androidx.constraintlayout.widget.ConstraintLayout import androidx.databinding.BindingAdapter import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.bumptech.glide.Glide import com.seventyseven.projecttb.R import com.seventyseven.projecttb.adapter.ActionAdapter import com.seventyseven.projecttb.adapter.GridViewAdapter import com.seventyseven.projecttb.adapter.RecommendAdapter import com.seventyseven.projecttb.model.bean.Product import com.seventyseven.projecttb.ui.LoginActivity import com.seventyseven.projecttb.ui.home.HomeViewModel import com.seventyseven.projecttb.viewmodel.SplashViewModel import com.nostra13.universalimageloader.core.ImageLoader class DatabindingHelper { companion object { @BindingAdapter("imageUrl") @JvmStatic fun loadImage(iv: ImageView, url: String?) { ImageLoader.getInstance().displayImage(url, iv) } @BindingAdapter("resId") @JvmStatic fun loadImageResource(iv: ImageView, resId: Int) { iv.setImageResource(resId) } @BindingAdapter("toolbar") @JvmStatic fun toolbarMenu(toolbar: Toolbar, menu: Int) { toolbar.inflateMenu(menu) toolbar.setOnMenuItemClickListener { when(it.itemId){ R.id.logout ->{ val intent= Intent(toolbar.context,LoginActivity::class.java) (toolbar.context as Activity).startActivity(intent) return@setOnMenuItemClickListener true } else ->{return@setOnMenuItemClickListener false} } } } @BindingAdapter(value = ["picList", "nameList"], requireAll = true) @JvmStatic fun loadGridView( gridView: GridView, picList: MutableList<Int>?, nameList: MutableList<String>? ) { if (picList.isNullOrEmpty() || nameList.isNullOrEmpty()) return gridView.adapter = GridViewAdapter(picList, nameList) } @BindingAdapter("loadActivityBackground") @JvmStatic fun loadBActivityBackground( view: LinearLayout, i:Int ) { when (i) { 0 -> {//促销 view.setBackgroundResource(R.drawable.bg_nomal_bitmap) } 1 -> {//中秋 view.setBackgroundResource(R.drawable.bg_midautum_bitmap) } 2 -> {//圣诞 view.setBackgroundResource(R.drawable.bg_chrismas_bitmap) } } } @BindingAdapter("loadActivityIcon") @JvmStatic fun loadCActivityBackground( view: ImageView, i:Int ) { when (i) { 0 -> {//促销 view.setBackgroundResource(R.drawable.bg_nomal_bitmap) } 1 -> {//中秋 view.setBackgroundResource(R.drawable.midautumicon) } 2 -> {//圣诞 view.setBackgroundResource(R.drawable.chrismasoldmanicon) } } } @BindingAdapter("productList") @JvmStatic fun loadRecyclerView( recyclerView: RecyclerView, productList: MutableList<Product>? ) { if (productList.isNullOrEmpty()) return val layoutManager = LinearLayoutManager(recyclerView.context) layoutManager.orientation = LinearLayoutManager.HORIZONTAL recyclerView.layoutManager = layoutManager recyclerView.adapter = ActionAdapter(productList as ArrayList<Product>) } @BindingAdapter("recommendList") @JvmStatic fun loadRecommendView( recyclerView: RecyclerView, productList: MutableList<Product>? ) { if (productList.isNullOrEmpty()) return val layoutManager = StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL) recyclerView.layoutManager = layoutManager recyclerView.adapter = RecommendAdapter(productList as ArrayList<Product>) } @BindingAdapter("refreshData") @JvmStatic fun refresh( view: SwipeRefreshLayout, refreshData : HomeViewModel ) { view.setOnRefreshListener { view.isRefreshing = false refreshData.loadDatas() } } @BindingAdapter("isVisiable") @JvmStatic fun setVisiable( view: View, productList: MutableList<Product>? ) { if(productList.isNullOrEmpty()) view.visibility = View.GONE else view.visibility = View.VISIBLE } @BindingAdapter("RecommendBg") @JvmStatic fun setRecommendBg( view : ConstraintLayout, actionType: Int ){ when(actionType) { 0 -> { view.setBackgroundResource(R.drawable.bg_common) } 1 -> { view.setBackgroundResource(R.drawable.midautumn_recommend) } 2 -> { view.setBackgroundResource(R.drawable.chrismas_recommend) } } } @BindingAdapter("RecommendTextColor") @JvmStatic fun setRecommendTextColor( tv : TextView, actionType : Int ){ when(actionType) { 0->{ tv.setTextColor(Color.parseColor("#000000")) } 2 ->{ tv.setTextColor(Color.parseColor("#FFFFFF")) } 1 -> { tv.setTextColor(Color.parseColor("#DA941F")) } } } @BindingAdapter("ActionTextBg") @JvmStatic fun setActionTextBg( tv : TextView, actionType : Int ){ when(actionType) { 1 -> { tv.setBackgroundResource(R.drawable.bg_text_moon) } 2->{ tv.setBackgroundResource(R.drawable.bg_text_christmas) } } } @BindingAdapter("ActionTextColor") @JvmStatic fun setActionTextColor( tv : TextView, actionType : Int ){ when(actionType) { 1 -> { tv.setTextColor(Color.parseColor("#B61F1D")) } 2->{ tv.setTextColor(Color.parseColor("#154C22")) } } } @BindingAdapter("priceType") @JvmStatic fun setTextType( view: TextView, flag : Boolean ) { if (flag) { view.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG view.paint.isAntiAlias = true //抗锯齿 } } @BindingAdapter("activityBanner") @JvmStatic fun setActivityBanner( view: ImageView, actionType : Int ) { when (actionType) { 0 -> { view.visibility = View.GONE } 1 -> { view.visibility = View.VISIBLE Glide.with(view.context).load(R.drawable.bg_moon_banner).into(view) } 2 -> { view.visibility = View.VISIBLE Glide.with(view.context).load(R.drawable.bg_christmas).into(view) } } } @BindingAdapter("activityBg") @JvmStatic fun setActivityBg( view: ImageView, actionType : Int ) { when (actionType) { 0->{ Glide.with(view.context).load(R.drawable.bg_nomal).into(view) } 1 -> { Glide.with(view.context).load(R.drawable.bg_moon).into(view) } 2 -> { Glide.with(view.context).load(R.drawable.bg_christmas).into(view) } } } } }<file_sep>/app/src/main/java/com/seventyseven/projecttb/model/adapter/ActionAdapter.java package com.seventyseven.projecttb.model.adapter; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.seventyseven.projecttb.MyApplication; import com.seventyseven.projecttb.R; import com.seventyseven.projecttb.model.bean.Product; import java.util.ArrayList; public class ActionAdapter extends RecyclerView.Adapter<ActionAdapter.Holder> { private ArrayList<Product> list; public ActionAdapter(ArrayList<Product> list){ this.list = list; } @Override public ActionAdapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(parent.getContext(), R.layout.item_action, null); Holder holder = new Holder(view); return holder; } @Override public void onBindViewHolder(ActionAdapter.Holder holder, int position) { Glide.with(MyApplication.getContext()).load(list.get(position).getPicture()).into(holder.image); holder.name.setText(list.get(position).getName()); holder.introduce.setText(list.get(position).getIntroduce()); holder.price.setText("¥"+list.get(position).getPrice()); holder.add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Product p = list.get(position); p.setCount(p.getCount()+1); boolean t = p.save(); if (t){ Toast.makeText(MyApplication.getContext(),"已添加进购物车!!",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MyApplication.getContext(),"添加失败,请重试!!",Toast.LENGTH_SHORT).show(); } } }); } @Override public int getItemCount() { return list.size(); } public class Holder extends RecyclerView.ViewHolder{ private final TextView name; private final TextView introduce; private final TextView price; private final ImageView image; private final ImageView add; public Holder(View itemView) { super(itemView); name = itemView.findViewById(R.id.tv_product_name); introduce = itemView.findViewById(R.id.tv_product_introduce); price = itemView.findViewById(R.id.tv_product_price); image = itemView.findViewById(R.id.item_action_iv); add = itemView.findViewById(R.id.iv_buy); } } } <file_sep>/app/src/main/java/com/seventyseven/projecttb/model/bean/ProductDetailResponse.kt package com.seventyseven.projecttb.model.bean
c00023212b517090b6d9bbb819e9ad168f743e88
[ "Java", "Kotlin" ]
3
Kotlin
wammamms/ProjectTB
a0eea9322ec9a1e86b931a9a691f7fdd66f4edbb
252bf6624c0db31a97c59fb2b3acff0ae6d08f2f
refs/heads/master
<repo_name>Bob-Paulson/ShotInTheMouthPHP<file_sep>/frame.php <?php function __topFrame__ ($num_stars) { for ($i = 0; $i < ($num_stars * 2) + 2; $i++){ echo "*"; } echo "<br>"; }
b6d46d15ec7c414346a2a76afc66b1d4b794b888
[ "PHP" ]
1
PHP
Bob-Paulson/ShotInTheMouthPHP
72f33b7b6631a948ffa9ab02729a245caebed02f
174257d6ae622621540f9e04d128f94bc5d0afda
refs/heads/master
<file_sep>-- 工具 -- yueqiumao (<EMAIL>) -- 获取开机到现在经过的毫秒数 function millis() return rtos.tick() / (16384 / 1000) end <file_sep>## 大球车 这里是大球的小破车,大球的小破车将来可是要上天的 QQ群:227819081<file_sep>-- 负责与服务器交互 -- yueqiumao (<EMAIL>) Network = class("Network", Component) local TAG = "Network" function Network:get_setup_priority() return SETUP_PRIORITY_AFTER_GPRS end function Network:set_setup_priority() end function Network:begin() logger:info(TAG, "网络组件启动") end function Network:loop() end function Network:shutdown() end function Network:destroy() end
71ca9b994b2725d0571c6ca4f810b62dd03dcb34
[ "Markdown", "Lua" ]
3
Lua
bpiq/bbc
28c6eccb027776c909afc5ba0cbee5a5bbfde319
60b385edcd52a13361f94d7a254d68f97b09a1b3
refs/heads/master
<repo_name>lzhice/visualization<file_sep>/src/exceptions/configloadexception.cpp #include "configloadexception.h" QString ConfigLoadException::context; <file_sep>/includes/wysiwyg/editsignal.h #ifndef EDITSIGNAL_H #define EDITSIGNAL_H #include <QPointer> #include <QWidget> #include <QLayout> #include <QPushButton> #include <QTableWidget> #include <QHeaderView> #include "visumisc.h" #include "visuconfigloader.h" #include "visusignal.h" #include "visupropertymeta.h" #include <QTableWidget> #include <QMap> #include <QSharedPointer> class EditSignal : public QWidget { Q_OBJECT public: EditSignal(QWidget* parent, QPointer<VisuSignal> visuSignal = nullptr) : QWidget(parent) { setWindowFlags(Qt::Dialog); setup(visuSignal); } signals: void signalAdded(QPointer<VisuSignal>,bool); public slots: void addSignal(); void cellUpdated(int row, int col); void propertyChange(); private: QPointer<QTableWidget> mTable; bool mNewSignal; QPointer<VisuSignal> mSignal; static const int mWidth = 400; void setup(QPointer<VisuSignal> visuSignal); }; #endif // EDITSIGNAL_H <file_sep>/includes/visuinstrument.h #ifndef INSTRUMENT_H #define INSTRUMENT_H #include <QtGlobal> #include <QWidget> #include <QColor> #include <QPixmap> #include <QMap> #include <QPainter> #include <QPointer> #include "visupropertyloader.h" #include "visusignal.h" #include "visuwidget.h" class VisuSignal; // forward declare Signal class class VisuInstrument : public VisuWidget { Q_OBJECT protected: quint16 cSignalId; // associated signal id QColor cColorBackground; // instrument background color QColor cColorStatic; // color for nonchanging parts (scales, marks, etc) QColor cColorForeground; // color for changing parts (pointers, indicators, etc) quint8 cFontSize; // Size of font used on labels QString cFontType; // pixmaps QPixmap mPixmap; // holds instrument rendered with last received signal value QPixmap mPixmapStatic; // holds prerendered pixmap generated by renderStatic() bool mFirstRun; const VisuSignal *mSignal; // Pointer to last signal that was updated void paintEvent(QPaintEvent* event); virtual void renderStatic(QPainter*) = 0; // Renders static parts of instrument virtual void renderDynamic(QPainter*) = 0; // Renders signal value dependent parts void setFont(QPainter* painter); void setPen(QPainter* painter, QColor color, int thickness = 1); void setBrush(QPainter* painter, QColor color); void clear(QPainter* painter); void setup(); QVector<QPointer<VisuSignal>> connectedSignals; public slots: void signalUpdated(const VisuSignal* const mSignal); void initialUpdate(const VisuSignal* const signal); public: virtual bool refresh(const QString& key); public: explicit VisuInstrument(QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuWidget(parent, properties, metaProperties) {} virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); void connectSignals(); void disconnectSignals(); void initializeInstrument(); // Getters quint16 getSignalId(); quint16 getId(); void render(); }; #endif // INSTRUMENT_H <file_sep>/src/instruments/instlinear.cpp #include "instlinear.h" const QString InstLinear::TAG_NAME = "LINEAR"; const QString InstLinear::KEY_HORIZONTAL = "horizontal"; bool InstLinear::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; InstLinear::loadProperties(); return InstLinear::refresh(key); } void InstLinear::loadProperties() { VisuInstrument::loadProperties(); GET_PROPERTY(cLineThickness, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorLen, mProperties, mPropertiesMeta); GET_PROPERTY(cMinorLen, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorCnt, mProperties, mPropertiesMeta); GET_PROPERTY(cMinorCnt, mProperties, mPropertiesMeta); GET_PROPERTY(cBarThickness, mProperties, mPropertiesMeta); GET_PROPERTY(cHorizontal, mProperties, mPropertiesMeta); mTagName = InstLinear::TAG_NAME; } void InstLinear::renderLabel(QPainter* painter, int sigCur, quint16 ofs) { QString label = QString("%1").arg((int)sigCur); QFontMetrics fontMetrics = painter->fontMetrics(); double labelWidth = fontMetrics.width(label); double labelHeight = fontMetrics.height(); if (cHorizontal) { painter->drawText(ofs - labelWidth / 2, cBarThickness + cMajorLen + 2 * SPACING + labelHeight, label); } else { painter->drawText(cBarThickness + cMajorLen + 3 * SPACING, ofs + labelHeight / 2, label); } } void InstLinear::renderDivisions(QPainter* painter) { quint16 total = cMajorCnt * cMinorCnt; int directionDimension = cHorizontal ? cWidth : cHeight; double delta = (double)(directionDimension - 2 * mMargin) / total; double ofs = mMargin; quint16 tmpMargin; double sigMax = mSignal->getMax(); double sigMin = mSignal->getMin(); double sigStep = (sigMax - sigMin) / (cMajorCnt); double sigCur = sigMin; if (!cHorizontal) { sigStep = -sigStep; sigCur = sigMax; } for (int i=0; i<=total; ++i) { if (i % cMinorCnt == 0) { renderLabel(painter, sigCur, ofs); sigCur += sigStep; tmpMargin = cMajorLen; } else { tmpMargin = cMinorLen; } if (cHorizontal) { painter->drawLine(ofs, cBarThickness + 2 * SPACING, ofs, cBarThickness + 2 * SPACING + tmpMargin); } else { painter->drawLine(cBarThickness + 2 * SPACING, ofs, cBarThickness + 2 * SPACING + tmpMargin, ofs); } ofs += delta; } mBarLength = ofs - delta - mMargin; } void InstLinear::setupMargin(QPainter* painter) { QFontMetrics fontMetrics = painter->fontMetrics(); if (cHorizontal) { int minValueWidth = fontMetrics.width(QString("%1").arg(mSignal->getMin())); int maxValueWidth = fontMetrics.width(QString("%1").arg(mSignal->getMax())); mMargin = std::max(minValueWidth, maxValueWidth) / 2; } else { mMargin = fontMetrics.height() / 2; } } void InstLinear::renderStatic(QPainter *painter) { clear(painter); setPen(painter, cColorStatic, cLineThickness); setFont(painter); setupMargin(painter); renderDivisions(painter); if (cHorizontal) { painter->drawLine(mMargin, cBarThickness + 2 * SPACING, mBarLength + mMargin, cBarThickness + 2 * SPACING); } else { painter->drawLine(cBarThickness + 2 * SPACING, mMargin, cBarThickness + 2 * SPACING, mMargin + mBarLength); } } void InstLinear::renderDynamic(QPainter *painter) { setPen(painter, cColorStatic); setBrush(painter, cColorForeground); double ofs = mSignal->getNormalizedValue() * mBarLength; if (cHorizontal) { painter->drawRect(mMargin, SPACING, ofs, cBarThickness); } else { painter->drawRect(SPACING, cHeight - mMargin, cBarThickness, -ofs); } } bool InstLinear::refresh(const QString& key) { bool changed = false; if (key == KEY_HORIZONTAL) { // update dimensions as well std::swap(cWidth, cHeight); std::swap(mProperties[KEY_WIDTH], mProperties[KEY_HEIGHT]); setup(); changed = true; } VisuInstrument::refresh(key); return changed; } <file_sep>/src/instruments/instxyplot.cpp #include "instxyplot.h" const QString InstXYPlot::TAG_NAME = "XY_PLOT"; bool InstXYPlot::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; InstXYPlot::loadProperties(); return VisuInstrument::refresh(key); } void InstXYPlot::loadProperties() { VisuInstrument::loadProperties(); GET_PROPERTY(cSignalIdY, mProperties, mPropertiesMeta); GET_PROPERTY(cBallSize, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorCntX, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorCntY, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorLenX, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorLenY, mProperties, mPropertiesMeta); GET_PROPERTY(cPadding, mProperties, mPropertiesMeta); GET_PROPERTY(cDecimals, mProperties, mPropertiesMeta); GET_PROPERTY(cReverseX, mProperties, mPropertiesMeta); GET_PROPERTY(cReverseY, mProperties, mPropertiesMeta); mTagName = InstXYPlot::TAG_NAME; } void InstXYPlot::renderSingleAxis(QPainter* painter, int sigInd, int divisions, int length) { VisuSignal* sig = connectedSignals[sigInd]; double pos = cPadding; double posDelta = (double)(length - 2*cPadding) / divisions; double lbl = sig->getMin(); double lblDelta = (sig->getMax() - sig->getMin()) / divisions; QFontMetrics fm = painter->fontMetrics(); if (cReverseX && sigInd == SIGNAL_FIRST) { pos = cWidth - cPadding; posDelta = -posDelta; } else if (cReverseY && sigInd == SIGNAL_SECOND) { pos = cHeight - cPadding; posDelta = -posDelta; } for (int i=0; i<divisions + 1; ++i) { QString lblStr = QString::number(lbl, 'f', cDecimals); if (sigInd == SIGNAL_FIRST) { int lblHalfWidth = fm.width(lblStr) / 2; painter->drawLine(pos, mCenterY-cMajorLenY, pos, mCenterY+cMajorLenY); painter->drawText(pos - lblHalfWidth, mCenterY-cMajorLenY-MARGIN, lblStr); } else { int lblHalfHeight = fm.height()/3; painter->drawLine(mCenterX-cMajorLenX, pos, mCenterX+cMajorLenX, pos); painter->drawText(mCenterX+cMajorLenX+MARGIN, pos + lblHalfHeight, lblStr); } pos += posDelta; lbl += lblDelta; } } void InstXYPlot::renderAxis(QPainter* painter) { renderSingleAxis(painter, SIGNAL_FIRST, cMajorCntX, cWidth); renderSingleAxis(painter, SIGNAL_SECOND, cMajorCntY, cHeight); } void InstXYPlot::renderBall(QPainter* painter) { setPen(painter, cColorStatic); setBrush(painter, cColorForeground); int x = mLastValX * (cWidth - 2 * cPadding) + cPadding - cBallSize / 2; int y = mLastValY * (cHeight - 2 * cPadding) + cPadding - cBallSize / 2; if (cReverseX) { x = cWidth - cBallSize - x; } if (cReverseY) { y = cHeight - cBallSize - y; } QRect rect(x, y, cBallSize, cBallSize); painter->drawEllipse(rect); } void InstXYPlot::renderStatic(QPainter *painter) { setFont(painter); setPen(painter, cColorStatic); clear(painter); mCenterX = cWidth / 2; mCenterY = cHeight / 2; painter->drawLine(cPadding, mCenterY, cWidth - cPadding, mCenterY); painter->drawLine(mCenterX, cPadding, mCenterX, cHeight - cPadding); renderAxis(painter); } void InstXYPlot::renderDynamic(QPainter *painter) { if (mSignal->getId() == cSignalId) { mLastValX = mSignal->getNormalizedValue(); // primary signal shown on X axis mSignalX = mSignal; } else { mLastValY = mSignal->getNormalizedValue(); // additional signal shown on Y axis mSignalY = mSignal; } renderBall(painter); } <file_sep>/src/instruments/instled.cpp #include "instled.h" #include "visuconfiguration.h" const QString InstLED::TAG_NAME = "LED"; bool InstLED::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; InstLED::loadProperties(); return VisuInstrument::refresh(key); } void InstLED::loadProperties() { VisuInstrument::loadProperties(); GET_PROPERTY(cRadius, mProperties, mPropertiesMeta); GET_PROPERTY(cVal1, mProperties, mPropertiesMeta); GET_PROPERTY(cVal2, mProperties, mPropertiesMeta); GET_PROPERTY(cCondition, mProperties, mPropertiesMeta); GET_PROPERTY(cColorOn, mProperties, mPropertiesMeta); GET_PROPERTY(cColorOff, mProperties, mPropertiesMeta); GET_PROPERTY(cImageOn, mProperties, mPropertiesMeta); GET_PROPERTY(cImageOff, mProperties, mPropertiesMeta); GET_PROPERTY(cShowSignalName, mProperties, mPropertiesMeta); mTagName = InstLED::TAG_NAME; } void InstLED::renderStatic(QPainter *painter) { clear(painter); cCenterH = (cHeight - cRadius) / 2; if (cShowSignalName) { setPen(painter, cColorStatic); setFont(painter); painter->drawText(cRadius+5, cCenterH + cFontSize, mSignal->getName()); } } void InstLED::renderDynamic(QPainter *painter) { setPen(painter, cColorStatic); double value = mSignal->getRealValue(); bool conditionOn = false; switch(cCondition) { case LedCondition::BETWEEN: conditionOn = (value > cVal1) && (value < cVal2); break; case LedCondition::LESS_THAN: conditionOn = value < cVal1; break; case LedCondition::LESS_EQUAL: conditionOn = value <= cVal1; break; case LedCondition::MORE_EQUAL: conditionOn = value >= cVal1; break; case LedCondition::MORE_THAN: conditionOn = value > cVal1; break; } int imageId = conditionOn ? cImageOn : cImageOff; if (imageId >= 0) { VisuWidget* imageWidget = VisuConfiguration::get()->getWidget(imageId); StaticImage* image; if ( (image = qobject_cast<StaticImage*>(imageWidget)) != nullptr) { painter->drawImage(0, 0, image->getImage()); } } else { setBrush(painter, conditionOn ? cColorOn : cColorOff); QRect rect(2, cCenterH, cRadius, cRadius); painter->drawEllipse(rect); } } <file_sep>/src/visuconfigloader.cpp #include "visuconfigloader.h" #include <QFile> #include "exceptions/configloadexception.h" #include <QXmlStreamAttribute> #include "visuappinfo.h" const QString VisuConfigLoader::PATH = "system/"; QByteArray VisuConfigLoader::loadXMLFromFile(QString path) { QFile xml_file(path); xml_file.open(QFile::ReadOnly); QByteArray contents = xml_file.readAll(); xml_file.close(); if (contents.isEmpty()) { throw ConfigLoadException("Error loading config from file %1", path); } return contents; } QMap<QString, VisuPropertyMeta> VisuConfigLoader::parseMetaToMap(QXmlStreamReader& xmlReader, QString element) { QMap<QString, VisuPropertyMeta> map; QString name; VisuPropertyMeta meta; int order = 0; while (xmlReader.tokenType() != QXmlStreamReader::EndElement || xmlReader.name() != element) { if (xmlReader.tokenType() == QXmlStreamReader::Invalid) { QString errorMsg = xmlReader.errorString() + " Near node: \"%1\""; throw ConfigLoadException(errorMsg, xmlReader.name().toString()); } else if (xmlReader.tokenType() == QXmlStreamReader::StartElement) { name = xmlReader.name().toString(); meta = VisuPropertyMeta(); for (const QXmlStreamAttribute& attr : xmlReader.attributes()) { QString metaKey = attr.name().toString(); if (metaKey == VisuPropertyMeta::KEY_MIN) { meta.min = attr.value().toDouble(); } else if (metaKey == VisuPropertyMeta::KEY_MAX) { meta.max = attr.value().toDouble(); } else if (metaKey == VisuPropertyMeta::KEY_TYPE) { meta.type = VisuPropertyMeta::typeFromString(attr.value().toString()); } else if (metaKey == VisuPropertyMeta::KEY_EXTRA) { meta.extra = attr.value().toString(); } else if (metaKey == VisuPropertyMeta::KEY_LABEL) { meta.label = attr.value().toString(); } else if (metaKey == VisuPropertyMeta::KEY_DEPENDS) { meta.depends = attr.value().toString(); } else if (metaKey == VisuPropertyMeta::KEY_DEPSCRIPTION) { meta.description = attr.value().toString(); } } } else if (xmlReader.tokenType() == QXmlStreamReader::Characters && !xmlReader.isWhitespace()) { meta.defaultVal = xmlReader.text().toString(); if (meta.type != VisuPropertyMeta::HIDDEN) { meta.order = order++; } map[name] = meta; } xmlReader.readNext(); } return map; } QMap<QString, QString> VisuConfigLoader::parseToMap(QXmlStreamReader& xmlReader, QString element) { QMap<QString, QString> map; QString name; QString value; while ( xmlReader.tokenType() != QXmlStreamReader::EndElement || xmlReader.name() != element) { if (xmlReader.tokenType() == QXmlStreamReader::Invalid) { QString errorMsg = xmlReader.errorString() + " Near node: \"%1\""; throw ConfigLoadException(errorMsg, xmlReader.name().toString()); } else if (xmlReader.tokenType() == QXmlStreamReader::StartElement) { name = xmlReader.name().toString(); } else if (xmlReader.tokenType() == QXmlStreamReader::Characters && !xmlReader.isWhitespace()) { value = xmlReader.text().toString(); map[name] = value; } xmlReader.readNext(); } return map; } QMap<QString, QString> VisuConfigLoader::getMapFromFile(QString type, QString tag) { QString path = PATH + type + ".xml"; QString xmlString = VisuConfigLoader::loadXMLFromFile(path); QXmlStreamReader xmlReader(xmlString); return VisuConfigLoader::parseToMap(xmlReader, tag); } QMap<QString, VisuPropertyMeta> VisuConfigLoader::getMetaMapFromFile(QString type, QString tag) { QString path = PATH + type + ".xml"; QString xmlString = VisuConfigLoader::loadXMLFromFile(path); QXmlStreamReader xmlReader(xmlString); return VisuConfigLoader::parseMetaToMap(xmlReader, tag); } <file_sep>/includes/visumisc.h #ifndef VISUMISC_H #define VISUMISC_H #include <QWidget> #include <QColor> #include <QTableWidget> #include <QMap> #include <QFile> #include <QPen> #include <visuconfiguration.h> #include "visupropertymeta.h" class VisuMisc { public: static void setBackgroundColor(QWidget* widget, QColor color); static QString getXMLDeclaration(); static QString addElement(QString tag, QMap<QString, QString> properties, int tabs = 0); static QString openTag(QString tag, int tabs = 0); static QString closeTag(QString tag, int tabs = 0); static QString mapToString(QMap<QString, QString> properties, int tabs = 0); static QString saveToFile(QFile &file, QString contents); static QPen getDashedPen(QColor color, int thickness); static QColor strToColor(const QString& str); static QString colorToStr(const QColor& color); static QImage strToImage(const QString& str, const QString &format); }; #endif // VISUMISC_H <file_sep>/includes/visuwidget.h #ifndef VISUWIDGET_H #define VISUWIDGET_H #include <QObject> #include <QWidget> #include <QMap> #include "visupropertyloader.h" #include "visupropertymeta.h" class VisuWidget : public QWidget { Q_OBJECT public: explicit VisuWidget( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : QWidget(parent), mProperties(properties), mPropertiesMeta(metaProperties) { setObjectName(VisuWidget::OBJECT_NAME); mActive = false; } virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); static const QString TAG_NAME; static const QString KEY_ID; static const QString KEY_WIDTH; static const QString KEY_HEIGHT; static const QString KEY_X; static const QString KEY_Y; static const QString KEY_NAME; static const QString KEY_TYPE; QMap<QString, QString>& getProperties(); void setPropertiesMeta(QMap<QString, VisuPropertyMeta> meta); QMap<QString, VisuPropertyMeta> getPropertiesMeta(); QString getName(); void setName(QString name); void setPosition(QPoint position); const QSize sizeHint(); QString getType(); void setActive(bool active); quint16 getId() const; void setId(quint16 id); // Drag&drop related QPoint mDragStartPosition; QPoint mDragStartRelativePosition; void mousePressEvent(QMouseEvent * event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent* event); void mouseDoubleClickEvent(QMouseEvent* event); void paintEvent(QPaintEvent* event); QPoint getRelativeOffset(); void drawActiveBox(QPainter* painter); virtual bool refresh(const QString& key); static const QString OBJECT_NAME; signals: void widgetActivated(VisuWidget*); void widgetContextMenu(VisuWidget*); protected: // properties map QMap<QString, QString> mProperties; QMap<QString, VisuPropertyMeta> mPropertiesMeta; quint16 cId; QString cName; quint16 cX; // x position in pixels quint16 cY; // y position in pixels quint16 cWidth; // width in pixels quint16 cHeight; // height in pixels QSize mSize; QString mTagName; bool mActive; // true when widget is active in wysiwyg editor void setup(); }; #endif // VISUWIDGET_H <file_sep>/src/wysiwyg/stage.cpp #include "wysiwyg/stage.h" #include <QMimeData> #include "instruments/instanalog.h" #include "visuconfigloader.h" #include "wysiwyg/visuwidgetfactory.h" #include "ctrlbutton.h" void Stage::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/plain")) event->acceptProposedAction(); } void Stage::dropEvent(QDropEvent *event) { VisuWidget* widget; VisuWidget* sourceWidget = static_cast<VisuWidget*>(event->source()); if (mMainWindow->dragOriginIsToolbar(sourceWidget)) { // This is new widget widget = cloneWidget(sourceWidget); connect(widget, SIGNAL(widgetActivated(VisuWidget*)), this, SLOT(activateWidget(VisuWidget*))); mMainWindow->updateMenuWidgetsList(); } else { widget = sourceWidget; } QPoint position = getNewWidgetPosition(event->pos(), sourceWidget->getRelativeOffset(), sourceWidget->size()); widget->setPosition(position); mMainWindow->setActiveWidget(widget); mMainWindow->setChanged(); event->acceptProposedAction(); } VisuWidget* Stage::cloneWidget(VisuWidget *sourceWidget) { VisuWidget* widget = VisuWidgetFactory::createWidget(this, sourceWidget->getProperties()); mMainWindow->getConfiguration()->addWidget(widget); widget->show(); widget->refresh(VisuWidget::KEY_ID); return widget; } QPoint Stage::getNewWidgetPosition(QPoint eventPos, QPoint grabOffset, QSize instSize) { QPoint position = eventPos - grabOffset; // corect if horizontal position outside of container if (position.x() < 0) { position.setX(0); } else if (position.x() + instSize.width() > width()) { position.setX(width() - instSize.width()); } // corect if vertical position outside of container if (position.y() < 0) { position.setY(0); } else if (position.y() + instSize.height() > height()) { position.setY(height() - instSize.height()); } return position; } void Stage::activateWidget(VisuWidget* widget) { mMainWindow->setActiveWidget(widget); } void Stage::paintEvent(QPaintEvent *event) { // Allow stylesheets (void)event; QStyleOption o; o.initFrom(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &o, &p, this); } QSize Stage::sizeHint() const { VisuConfiguration* config = mMainWindow->getConfiguration(); return (config != nullptr) ? config->getSize() : QSize(); } <file_sep>/includes/visuappinfo.h #ifndef VISUAPPINFO_H #define VISUAPPINFO_H #include <QString> #include <QStringList> class VisuServer; class VisuAppInfo { public: enum class CLI_Args { PROGRAM_NAME, CONFIG_PATH, SERIAL_PORT_NAME, BAUD_RATE }; static bool isInEditorMode(); static void setInEditorMode(bool mode); static bool isConfigWrong(); static void setConfigWrong(bool wrong); static void setConfigWrong(const QString& issue); static const QStringList& getConfigIssues(); static const QString& getCLIArg(CLI_Args arg); static void setCLIArgs(int argc, char* argv[]); static int argsSize(); static void setServer(VisuServer* srv); static VisuServer* getServer(); private: static VisuAppInfo* getInstance(); static VisuAppInfo* instance; bool inEditorMode; bool configWrong; QStringList configIssues; QStringList cliArgs; VisuServer* server; }; #endif // VISUAPPINFO_H <file_sep>/src/visupropertyloader.cpp #include "visupropertyloader.h" #include "exceptions/configloadexception.h" #include "statics/staticimage.h" #include "visuappinfo.h" #include <QByteArray> #include "visumisc.h" namespace VisuPropertyLoader { QString transformKey(const QString &key) { return key.mid(1, 1).toLower() + key.mid(2); } void handleMissingKey(const QString &key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties) { if (!properties.contains(key)) { ConfigLoadException exception(QObject::tr("Missing property: %1 (%2)").arg(metaProperties[key].label).arg(key)); VisuAppInfo::setConfigWrong(exception.getMessage()); if (VisuAppInfo::isInEditorMode()) { properties[key] = metaProperties[key].defaultVal; } else { throw exception; } } } void set(double& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties) { handleMissingKey(key, properties, metaProperties); property = properties[key].toDouble(); } void set(QString& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties) { handleMissingKey(key, properties, metaProperties); property = properties[key]; } void set( QColor& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties) { handleMissingKey(key, properties, metaProperties); QColor color = VisuMisc::strToColor(properties[key]); if (!color.isValid()) { throw ConfigLoadException("Wrong color format (%1)", properties[key]); } property = color; } void set(QImage& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties) { handleMissingKey(key, properties, metaProperties); property = VisuMisc::strToImage(properties[key], properties[StaticImage::KEY_FORMAT]); } void set(bool& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties) { handleMissingKey(key, properties, metaProperties); property = (properties[key].toInt() != 0); } } <file_sep>/src/instruments/insttimeplot.cpp #include "insttimeplot.h" #include "visumisc.h" const QString InstTimePlot::TAG_NAME = "TIME_PLOT"; bool InstTimePlot::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; InstTimePlot::loadProperties(); return VisuInstrument::refresh(key); } void InstTimePlot::loadProperties() { VisuInstrument::loadProperties(); GET_PROPERTY(cLineThickness, mProperties, mPropertiesMeta); GET_PROPERTY(cStaticThickness, mProperties, mPropertiesMeta); GET_PROPERTY(cMarkerThickness, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorCnt, mProperties, mPropertiesMeta); GET_PROPERTY(cMinorCnt, mProperties, mPropertiesMeta); GET_PROPERTY(cTicksInSecond, mProperties, mPropertiesMeta); GET_PROPERTY(cTimespan, mProperties, mPropertiesMeta); GET_PROPERTY(cMarkerDt, mProperties, mPropertiesMeta); GET_PROPERTY(cDecimals, mProperties, mPropertiesMeta); GET_PROPERTY(cDivisionFormat, mProperties, mPropertiesMeta); GET_PROPERTY(cMasterTimeFormat, mProperties, mPropertiesMeta); GET_PROPERTY(cColorGraphBackground, mProperties, mPropertiesMeta); mTagName = InstTimePlot::TAG_NAME; } int InstTimePlot::getFontHeight() { QFont font; font.setPointSize(cFontSize); QFontMetrics fm(font); return fm.height(); } void InstTimePlot::init(QPainter* painter) { mMargin = getFontHeight(); mSigStep = (mSignal->getMax() - mSignal->getMin()) / (cMajorCnt * cMinorCnt); mMaxLabelWidth = getLabelMaxWidth(painter); mPlotStartX = mMaxLabelWidth + 2 * PADDING; mPlotEndX = cWidth - mMargin; mPlotStartY = cHeight - mMargin; mPlotEndY = mMargin; mPlotRangeX = mPlotEndX - mPlotStartX; mPlotRangeY = mPlotStartY - mPlotEndY; mLastUpdateX = mPlotStartX; mLastUpdateY = mPlotStartY; mLastMarkerTime = 0; } quint16 InstTimePlot::getLabelMaxWidth(QPainter* painter) { QFontMetrics fontMetrics = painter->fontMetrics(); double sigTmpVal = mSignal->getMin(); int labelWidth; QString label; int maxWidth = 0; int cnt = cMajorCnt * cMinorCnt; for (int i=0; i<=cnt; ++i) { label = getLabel(sigTmpVal); sigTmpVal += mSigStep; labelWidth = fontMetrics.width(label); maxWidth = maxWidth < labelWidth ? labelWidth : maxWidth; } return maxWidth; } QString InstTimePlot::getLabel(double value) { return QString::number(value, 'f', cDecimals) + mSignal->getUnit(); } void InstTimePlot::renderLabel(QPainter* painter, double sigCur, qint32 yPos) { QString label = getLabel(sigCur); QFontMetrics fontMetrics = painter->fontMetrics(); int labelWidth = fontMetrics.width(label); int labelHeight = fontMetrics.height(); painter->drawText(mMaxLabelWidth - labelWidth + PADDING, yPos + labelHeight / 2, label); } void InstTimePlot::renderLabelsAndMajors(QPainter* painter) { double sigCur = mSignal->getMin(); int cnt = cMajorCnt * cMinorCnt; double yPos = mPlotStartY; double yStep = (double)(cHeight - 2 * mMargin) / cnt; QPen dashed = VisuMisc::getDashedPen(cColorStatic, cStaticThickness); for (int i=0; i<=cnt; ++i) { painter->setPen(dashed); if (i % cMinorCnt == 0) { renderLabel(painter, sigCur, yPos); setPen(painter, cColorStatic, cStaticThickness); } painter->drawLine(mPlotStartX, yPos, mPlotEndX, yPos); yPos -= yStep; sigCur += mSigStep; } } void InstTimePlot::setupGraphObjects() { delete mGraphPainter; mGraphPixmap = QPixmap(cWidth, cHeight); mGraphPixmap.fill(Qt::transparent); setAttribute(Qt::WA_TranslucentBackground); mGraphPainter = new QPainter(&mGraphPixmap); mGraphPainter->setRenderHint(QPainter::Antialiasing); } void InstTimePlot::renderGraphAreaBackground(QPainter* painter) { setBrush(painter, cColorGraphBackground); painter->drawRect(QRect(mPlotStartX, mPlotEndY, mPlotRangeX, mPlotRangeY)); } void InstTimePlot::renderSignalName(QPainter* painter) { painter->drawText(cWidth/2, mPlotEndY-PADDING, QString("%1").arg(mSignal->getName())); } void InstTimePlot::setupPainter(QPainter* painter) { setPen(painter, cColorStatic, cStaticThickness); setFont(painter); } void InstTimePlot::renderStatic(QPainter* painter) { clear(painter); setupPainter(painter); init(painter); renderGraphAreaBackground(painter); renderLabelsAndMajors(painter); renderSignalName(painter); setupGraphObjects(); } QString InstTimePlot::getDisplayTime(int ticks, QString format) { return QTime(0, 0, 0).addSecs(ticks / cTicksInSecond).toString(format); } double InstTimePlot::getMarkerX(quint64 timestamp) { quint64 markerTime = timestamp - (timestamp % cMarkerDt) + cMarkerDt; // round up double cor = ((double)markerTime - timestamp - cMarkerDt) * mPlotRangeX / cTimespan; return mNewUpdateX + cor; } void InstTimePlot::renderMarker(QPainter* painter, quint64 timestamp) { double markerX = getMarkerX(timestamp); if (markerX > mPlotStartX && markerX < mPlotEndX) { setPen(mGraphPainter, cColorStatic, cMarkerThickness); painter->drawLine(markerX, mPlotStartY, markerX, mPlotEndY); setFont(mGraphPainter); painter->drawText(markerX, cHeight, getDisplayTime(timestamp, cDivisionFormat)); mLastMarkerTime = timestamp; } } bool InstTimePlot::shouldRenderMarker(quint64 timestamp) { return (timestamp >= mLastMarkerTime + cMarkerDt); } void InstTimePlot::renderTimeLabel(QPainter* painter) { setPen(painter, cColorStatic); setFont(painter); quint64 timestamp = mSignal->getTimestamp(); painter->drawText(mPlotStartX, mPlotEndY - 5, "Time " + getDisplayTime(timestamp, cMasterTimeFormat)); } void InstTimePlot::renderGraphSegment(QPainter* painter) { setPen(mGraphPainter, cColorForeground, cLineThickness); mGraphPainter->drawLine(mLastUpdateX, mLastUpdateY, mNewUpdateX, mNewUpdateY); painter->drawPixmap(0, 0, mGraphPixmap); } void InstTimePlot::resetPlotToStart() { mGraphPixmap.fill(Qt::transparent); mNewUpdateX = mPlotStartX + (mNewUpdateX - mLastUpdateX); mLastUpdateX = mPlotStartX; } bool InstTimePlot::noSpaceLeftOnRight() { return (mNewUpdateX > mPlotEndX); } void InstTimePlot::calculateNewGraphPoint(quint64 timestamp) { double value = mSignal->getNormalizedValue(); quint64 dt = timestamp > mLastUpdateTime ? (timestamp - mLastUpdateTime) : 0; double dx = (double)mPlotRangeX * dt / (cTimespan); mNewUpdateX = mLastUpdateX + dx; mNewUpdateY = mPlotStartY - mPlotRangeY * value; } void InstTimePlot::updateLastValues(quint64 timestamp) { mLastUpdateX = mNewUpdateX; mLastUpdateY = mNewUpdateY; mLastUpdateTime = timestamp; } void InstTimePlot::renderDynamic(QPainter* painter) { quint64 timestamp = mSignal->getTimestamp(); calculateNewGraphPoint(timestamp); if (noSpaceLeftOnRight()) { resetPlotToStart(); } if (shouldRenderMarker(timestamp)) { renderMarker(mGraphPainter, timestamp); } renderTimeLabel(painter); renderGraphSegment(painter); updateLastValues(timestamp); } <file_sep>/includes/instruments/instdigital.h #ifndef INSTDIGITAL_H #define INSTDIGITAL_H #include "visuinstrument.h" class InstDigital : public VisuInstrument { Q_OBJECT public: explicit InstDigital( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuInstrument(parent, properties, metaProperties) { loadProperties(); } static const QString TAG_NAME; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); private: // configuration properties bool cShowSignalName; bool cShowSignalUnit; quint8 cPadding; quint8 cLeadingDigits; quint8 cDecimalDigits; // aux members QFont mFont; QString mFormat; protected: virtual void renderStatic(QPainter *painter); // Renders to pixmap_static virtual void renderDynamic(QPainter *painter); // Renders to pixmap }; #endif // INSTDIGITAL_H <file_sep>/src/mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include "visuapplication.h" #include "instanalog.h" #include "instdigital.h" #include "instlinear.h" #include "insttimeplot.h" #include "instled.h" #include "instxyplot.h" #include "ctrlbutton.h" #include "ctrlslider.h" #include "visuconfigloader.h" #include "wysiwyg/visuwidgetfactory.h" #include <QXmlStreamReader> #include <QTableWidget> #include "wysiwyg/stage.h" #include <QLabel> #include <QObject> #include <QColorDialog> #include <QLineEdit> #include <QTableWidgetItem> #include <QtGui> #include <QFileDialog> #include <QProcess> #include <QMessageBox> #include <QScrollArea> #include "visumisc.h" #include "wysiwyg/editconfiguration.h" #include "wysiwyg/visupropertieshelper.h" #include "visuappinfo.h" #include <QTextEdit> const QString MainWindow::INITIAL_EDITOR_CONFIG = "system/default.xml"; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setupMenu(); setupLayouts(); loadConfigurationFromFile(INITIAL_EDITOR_CONFIG); setupToolbarWidgets(mToolbar); setWindowTitle(tr("Configuration Editor")); showMaximized(); updateConfig(); } void MainWindow::setupMenu() { QMenu* fileMenu = ui->menuBar->addMenu(tr("&File")); QAction* open = new QAction(tr("&Open"), this); open->setShortcut(QKeySequence::Open); open->setStatusTip(tr("Open existing configuration")); fileMenu->addAction(open); connect(open, SIGNAL(triggered()), this, SLOT(openConfiguration())); mSave = new QAction(tr("&Save"), this); mSave->setDisabled(true); mSave->setShortcut(QKeySequence::Save); mSave->setStatusTip(tr("Save configuration")); fileMenu->addAction(mSave); connect(mSave, SIGNAL(triggered()), this, SLOT(saveConfiguration())); QAction* saveAs = new QAction(tr("Save &as"), this); saveAs->setShortcut(QKeySequence::SaveAs); saveAs->setStatusTip(tr("Save as new configuration")); fileMenu->addAction(saveAs); connect(saveAs, SIGNAL(triggered()), this, SLOT(saveAsConfiguration())); QMenu* signalsMenu = ui->menuBar->addMenu(tr("&Signals")); QAction* newsig = new QAction(tr("&Add"), this); newsig->setData(QVariant(-1)); newsig->setStatusTip(tr("Add new signal")); signalsMenu->addAction(newsig); connect(newsig, SIGNAL(triggered()), this, SLOT(openSignalsEditor())); mSignalsListMenu = signalsMenu->addMenu(tr("&List")); QMenu* instrumentsMenu = ui->menuBar->addMenu(tr("&Widgets")); QAction* imageAdd = new QAction(tr("&Add image"), this); imageAdd->setStatusTip(tr("Add image widget")); instrumentsMenu->addAction(imageAdd); connect(imageAdd, SIGNAL(triggered()), this, SLOT(openImageAdder())); mWidgetsListMenu = instrumentsMenu->addMenu(tr("&List")); QMenu* configMenu = ui->menuBar->addMenu(tr("&Configuration")); QAction* configRun = new QAction(tr("&Run"), this); configRun->setStatusTip(tr("Run current configuration")); configMenu->addAction(configRun); connect(configRun, SIGNAL(triggered()), this, SLOT(runConfiguration())); QAction* configParams = new QAction(tr("&Parameters"), this); configParams->setStatusTip(tr("Edit configuration parameters")); configMenu->addAction(configParams); connect(configParams, SIGNAL(triggered()), this, SLOT(openConfigurationEditor())); QAction* screenshot = new QAction(tr("Take snapshot"), this); screenshot->setStatusTip(tr("Save configuration to image")); configMenu->addAction(screenshot); connect(screenshot, SIGNAL(triggered()), this, SLOT(saveToImage())); } void MainWindow::setupLayouts() { mWindow = new QWidget(); QVBoxLayout* windowLayout = new QVBoxLayout(); mWindow->setLayout(windowLayout); setCentralWidget(mWindow); mToolbar = new QWidget(mWindow); mToolbar->setObjectName("toolbar"); mToolbar->setMinimumHeight(LAYOUT_TOOLBAR_HEIGHT); mToolbar->setStyleSheet("border: 1px solid black;"); windowLayout->addWidget(mToolbar); QWidget* workArea = new QWidget(mWindow); windowLayout->addWidget(workArea); QHBoxLayout* workAreaLayout = new QHBoxLayout(); workArea->setLayout(workAreaLayout); workAreaLayout->addStretch(); mStage = new Stage(this, workArea); mStage->setObjectName("stage"); mScrollArea = new QScrollArea(mWindow); workAreaLayout->addWidget(mScrollArea); mScrollArea->setWidget(mStage); workAreaLayout->addStretch(); mPropertiesTable = new QTableWidget(workArea); mPropertiesTable->setMaximumWidth(LAYOUT_PROPERTIES_WIDTH); mPropertiesTable->setMinimumWidth(LAYOUT_PROPERTIES_WIDTH); mPropertiesTable->verticalHeader()->hide(); mPropertiesTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); workAreaLayout->addWidget(mPropertiesTable); } void MainWindow::reloadConfiguration() { QString xml = mConfiguration->toXML(); QString configFilePath = VisuMisc::saveToFile(mTmpConfigFile, xml); loadConfigurationFromFile(configFilePath); } void MainWindow::showConfigurationWarning() { QMessageBox* box = new QMessageBox(this); box->setText(tr("Configuration file is outdated or incorrect.\n" "Configuration may contain glitches, but loading " "was continued to allow config to be repaired. " "Manual XML editing may be required to fully correct.")); box->setWindowTitle("Error"); QTextEdit* details = new QTextEdit; details->setText(VisuAppInfo::getConfigIssues().join("\n\n")); QGridLayout* layout = qobject_cast<QGridLayout*>(box->layout()); layout->addWidget(details, 1, 1); box->show(); } void MainWindow::loadConfigurationFromFile(const QString& configPath) { mConfiguration = VisuConfiguration::getClean(); try { VisuAppInfo::setConfigWrong(false); QString xml = VisuConfigLoader::loadXMLFromFile(configPath); mConfiguration->fromXML(mStage, QString(xml)); mConfigChanged = false; resetActiveWidget(); updateConfig(); // connect widgets for (VisuWidget* widget : mConfiguration->getWidgets()) { connect(widget, SIGNAL(widgetActivated(VisuWidget*)), mStage, SLOT(activateWidget(VisuWidget*))); } updateMenuSignalList(); updateMenuWidgetsList(); if (VisuAppInfo::isConfigWrong()) { showConfigurationWarning(); } } catch(ConfigLoadException e) { QMessageBox::warning( this, "Error", e.what()); } catch(...) { QMessageBox::warning( this, "Error", "Unknown exception!"); } } void MainWindow::updateConfig() { QSize configSize = mConfiguration->getSize(); QSize windowSize = mWindowSize; QSize areaSize = mScrollArea->size(); mStage->setMinimumSize(configSize); mStage->setMaximumSize(configSize); if (!windowSize.isValid()) { return; } int sliderThickness = qApp->style()->pixelMetric(QStyle::PM_ScrollBarExtent); int sliderVerticalMargin = (areaSize.width() < configSize.width() ? 0 : sliderThickness) + LAYOUT_QSCROLLAREA_MARGIN; int sliderHorizontalMargin = (areaSize.height() < configSize.height() ? 0 : sliderThickness) + LAYOUT_QSCROLLAREA_MARGIN; int maxAvailableWidth = windowSize.width() - LAYOUT_PROPERTIES_WIDTH - LAYOUT_MARGIN; int neededWidth = configSize.width() + sliderVerticalMargin; if (maxAvailableWidth > neededWidth) { mScrollArea->setMinimumWidth(neededWidth); } else { mScrollArea->setMinimumWidth(maxAvailableWidth); mScrollArea->setMaximumWidth(maxAvailableWidth); } int verticalOcupiedSpace = this->frameGeometry().height() - this->geometry().height(); verticalOcupiedSpace += LAYOUT_TOOLBAR_HEIGHT + LAYOUT_MARGIN * 2; int maxAvailableHeight = windowSize.height() - verticalOcupiedSpace; int neededHeight = configSize.height() + sliderHorizontalMargin; if (maxAvailableHeight > neededHeight ) { mScrollArea->setMinimumHeight(neededHeight); } else { mScrollArea->setMinimumHeight(maxAvailableHeight); mScrollArea->setMinimumHeight(maxAvailableHeight); } VisuMisc::setBackgroundColor(mStage, mConfiguration->getBackgroundColor()); } void MainWindow::updateMenuWidgetsList() { mWidgetsListMenu->clear(); auto widgets = mConfiguration->getWidgets(); if (widgets.size() > 0) { for (VisuWidget* widget : widgets) { if (widget != nullptr) { QString menuItemText = QString("%1 (%2)") .arg(widget->getType()) .arg(widget->getName()); QMenu* widgetMenuItem = mWidgetsListMenu->addMenu(menuItemText); QAction* select = new QAction(tr("Select"), this); select->setData(QVariant(widget->getId())); widgetMenuItem->addAction(select); connect(select, SIGNAL(triggered()), this, SLOT(activateWidgetFromMenu())); QAction* moveUp = new QAction(tr("Move up"), this); moveUp->setData(QVariant(widget->getId())); widgetMenuItem->addAction(moveUp); connect(moveUp, SIGNAL(triggered()), this, SLOT(moveWidgetUp())); QAction* moveDown = new QAction(tr("Move down"), this); moveDown->setData(QVariant(widget->getId())); widgetMenuItem->addAction(moveDown); connect(moveDown, SIGNAL(triggered()), this, SLOT(moveWidgetDown())); } } } } void MainWindow::updateMenuSignalList() { mSignalsListMenu->clear(); auto configSignals = mConfiguration->getSignals(); if (configSignals.size() > 0) { for (VisuSignal* sig : configSignals) { if (sig != nullptr) { QString label = QString("%1: %2").arg(sig->getId()).arg(sig->getName()); QMenu* tmpSig = mSignalsListMenu->addMenu(label); QAction* edit = new QAction(tr("&Edit"), this); edit->setData(QVariant(sig->getId())); tmpSig->addAction(edit); connect(edit, SIGNAL(triggered()), this, SLOT(openSignalsEditor())); QAction* del = new QAction(tr("&Delete"), this); del->setData(QVariant(sig->getId())); tmpSig->addAction(del); connect(del, SIGNAL(triggered()), this, SLOT(deleteSignal())); } } } } void MainWindow::setupToolbarWidgets(QPointer<QWidget> toolbar) { QHBoxLayout *layout = new QHBoxLayout; toolbar->setLayout(layout); layout->addWidget(VisuWidgetFactory::createWidget(this, InstAnalog::TAG_NAME)); layout->addWidget(VisuWidgetFactory::createWidget(this, InstLinear::TAG_NAME)); layout->addWidget(VisuWidgetFactory::createWidget(this, InstTimePlot::TAG_NAME)); layout->addWidget(VisuWidgetFactory::createWidget(this, InstDigital::TAG_NAME)); layout->addWidget(VisuWidgetFactory::createWidget(this, InstLED::TAG_NAME)); layout->addWidget(VisuWidgetFactory::createWidget(this, InstXYPlot::TAG_NAME)); layout->addWidget(VisuWidgetFactory::createWidget(this, CtrlButton::TAG_NAME)); layout->addWidget(VisuWidgetFactory::createWidget(this, CtrlSlider::TAG_NAME)); mConfiguration->initializeInstruments(); } void MainWindow::openImageAdder() { QString imagePath = QFileDialog::getOpenFileName(this, tr("Open image"), ".", "Image files (*.png *.jpg *.jpeg *.bmp)"); if (!imagePath.isNull()) { QFile file(imagePath); if (file.open(QIODevice::ReadOnly)) { QMap<QString, QString> properties = VisuConfigLoader::getMapFromFile(StaticImage::TAG_NAME, VisuWidget::TAG_NAME); QByteArray imgData = file.readAll(); properties[StaticImage::KEY_IMAGE] = QString(imgData.toBase64()); properties[StaticImage::KEY_FORMAT] = QFileInfo(imagePath).suffix(); QImage tmpImage; tmpImage.loadFromData(imgData, properties[StaticImage::KEY_FORMAT].toStdString().c_str()); if ((tmpImage.width() <= mStage->width()) & (tmpImage.height() <= mStage->height()) ) { properties[VisuWidget::KEY_WIDTH] = QString("%1").arg(tmpImage.width()); properties[VisuWidget::KEY_HEIGHT] = QString("%1").arg(tmpImage.height()); properties[VisuWidget::KEY_NAME] = QFileInfo(imagePath).fileName(); QMap<QString, VisuPropertyMeta> metaProperties = VisuConfigLoader::getMetaMapFromFile(StaticImage::TAG_NAME, VisuWidget::TAG_NAME); StaticImage* image = new StaticImage(mStage, properties, metaProperties); setActiveWidget(image); mConfiguration->addWidget(image); mConfigChanged = true; updateMenuWidgetsList(); } else { QMessageBox::information( this, tr("Info"), tr("Image was too large for the stage.\n" "Please try with smaller image, or increase stage resolution to %1x%2") .arg(tmpImage.width()).arg(tmpImage.height())); } } } } void MainWindow::openConfigurationEditor() { EditConfiguration* window = new EditConfiguration(this, mConfiguration); connect(window, SIGNAL(configParamsUpdated()), this, SLOT(updateConfig())); } void MainWindow::runConfiguration() { QString xml = mConfiguration->toXML(); QString configFilePath = VisuMisc::saveToFile(mTmpConfigFile, xml); QString me = QCoreApplication::applicationFilePath(); QStringList args = {configFilePath}; if (mConfiguration->getConectivity() != VisuServer::UDP_ONLY) { args.append(mConfiguration->getSerialPort()); args.append(QString("%1").arg(mConfiguration->getBaudRate())); } QProcess *process = new QProcess(this); process->start(me, args); } void MainWindow::openSignalsEditor() { if (editSignalWindow != nullptr) { disconnect(editSignalWindow, SIGNAL(signalAdded(VQPointer<VisuSignal>)), this, SLOT(addSignal(QPointer<VisuSignal>, bool))); } QAction* s = static_cast<QAction*>(sender()); int signalId = s->data().toInt(); VisuSignal* signal = nullptr; if (signalId >= 0) { signal = mConfiguration->getSignal(signalId); } editSignalWindow = new EditSignal(this, signal); connect(editSignalWindow, SIGNAL(signalAdded(QPointer<VisuSignal>,bool)), this, SLOT(addSignal(QPointer<VisuSignal>, bool))); } void MainWindow::openConfiguration() { if (!mConfigChanged || (mConfigChanged && confirmLoseChanges()) ) { QString configPath = QFileDialog::getOpenFileName(this, tr("Open configuration"), ".", "Configuration files (*.xml)"); if (!configPath.isNull()) { loadConfigurationFromFile(configPath); mConfigPath = configPath; mSave->setDisabled(false); } } } void MainWindow::saveAsConfiguration() { QString configPath = QFileDialog::getSaveFileName(this, tr("Save configuration"), ".", "Configuration files (*.xml)"); if (!configPath.isNull()) { QFile file( configPath ); QString xml = mConfiguration->toXML(); VisuMisc::saveToFile(file, xml); mConfigPath = configPath; mSave->setDisabled(false); mConfigChanged = false; } } void MainWindow::saveToImage() { QString configPath = QFileDialog::getSaveFileName(this, tr("Save configuration"), ".", "Image file (*.png)"); if (!configPath.isNull()) { QPixmap image = mStage->grab(); image.save(configPath); } } void MainWindow::saveConfiguration() { if (!mConfigPath.isNull()) { QFile file( mConfigPath ); QString xml = mConfiguration->toXML(); VisuMisc::saveToFile(file, xml); mConfigChanged = false; } } void MainWindow::keyPressEvent( QKeyEvent *event ) { if (event->matches(QKeySequence::Delete)) { deleteActiveWidget(); } } void MainWindow::deleteActiveWidget() { if (mActiveWidget != nullptr) { mConfiguration->deleteWidget(mActiveWidget); resetActiveWidget(); updateMenuWidgetsList(); } } bool MainWindow::dragOriginIsToolbar(QWidget* widget) { return widget->parent() == mToolbar; } void MainWindow::addSignal(QPointer<VisuSignal> signal, bool isNewSignal) { if (isNewSignal) { mConfiguration->addSignal(signal); } updateMenuSignalList(); } void MainWindow::deleteSignal() { QAction* s = static_cast<QAction*>(sender()); int signalId = s->data().toInt(); if (signalId >= 0) { mConfiguration->deleteSignal(signalId); updateMenuSignalList(); } } void MainWindow::refreshEditorGui(QString key) { mConfigChanged = true; if (key == VisuWidget::KEY_NAME) { updateMenuWidgetsList(); // widget renamed, update list } } void MainWindow::cellUpdated(int row, int col) { QString key = VisuPropertiesHelper::getKeyString(mPropertiesTable, row); QString value = VisuPropertiesHelper::getValueString(mPropertiesTable, row); if (mActiveWidget->updateProperties(key, value)) { setActiveWidget(mActiveWidget); } refreshEditorGui(key); VisuPropertiesHelper::updateWidgetsState(mPropertiesTable, mActiveWidget->getProperties(), mActiveWidget->getPropertiesMeta()); } VisuWidget* MainWindow::actionDataToWidget(QAction* action) { VisuWidget* widget = mConfiguration->getWidget(action->data().toInt()); return widget; } void MainWindow::activateWidgetFromMenu() { QAction* action = static_cast<QAction*>(sender()); VisuWidget* widget = actionDataToWidget(action); setActiveWidget(widget); } void MainWindow::moveWidgetUp() { QAction* action = static_cast<QAction*>(sender()); mConfiguration->moveWidgetUp(action->data().toInt()); reloadConfiguration(); } void MainWindow::moveWidgetDown() { QAction* action = static_cast<QAction*>(sender()); mConfiguration->moveWidgetDown(action->data().toInt()); reloadConfiguration(); } void MainWindow::markActiveInstrumentMenuItem(QPointer<VisuWidget> oldItem, QPointer<VisuWidget> newItem) { for(QAction* action : mWidgetsListMenu->actions()) { VisuWidget* menuWidget = actionDataToWidget(action->menu()->actions()[0]); action->setCheckable(true); if (menuWidget == oldItem) { action->setChecked(false); } if (menuWidget == newItem) { action->setChecked(true); } } } void MainWindow::resetActiveWidget() { mActiveWidget = nullptr; mPropertiesTable->clearContents(); mPropertiesTable->setEnabled(false); } void MainWindow::setActiveWidget(QPointer<VisuWidget> widget) { if (mActiveWidget != nullptr) { // remove selected style. TODO :: refactor to work with other classes mActiveWidget->setActive(false); } markActiveInstrumentMenuItem(mActiveWidget, widget); mActiveWidget = widget; mActiveWidget->setActive(true); QMap<QString, QString> properties = mActiveWidget->getProperties(); QMap<QString, VisuPropertyMeta> metaProperties = mActiveWidget->getPropertiesMeta(); disconnect(mPropertiesTable, SIGNAL(cellChanged(int,int)), this, SLOT(cellUpdated(int,int))); VisuPropertiesHelper::updateTable(mPropertiesTable, properties, metaProperties, std::make_pair(this, SLOT(propertyChange())) ); connect(mPropertiesTable, SIGNAL(cellChanged(int,int)), this, SLOT(cellUpdated(int,int))); } void MainWindow::propertyChange(int parameter) { int row = VisuPropertiesHelper::updateWidgetProperty(sender(), this); cellUpdated(row, 1); } QPointer<VisuSignal> MainWindow::getSignal() { return mConfiguration->getSignal(0); } MainWindow::~MainWindow() { delete ui; } QPointer<VisuConfiguration> MainWindow::getConfiguration() { return mConfiguration; } QPointer<VisuWidget> MainWindow::getActiveWidget() { return mActiveWidget; } void MainWindow::resizeEvent(QResizeEvent * event) { QMainWindow::resizeEvent(event); mWindowSize = size(); } void MainWindow::setChanged() { mConfigChanged = true; } bool MainWindow::confirmLoseChanges() { QMessageBox::StandardButton response = QMessageBox::question( this, "Warning", tr("There are unsaved changes that will be lost. " "Are you sure you want to proceed?\n"), QMessageBox::No | QMessageBox::Yes, QMessageBox::No); return response == QMessageBox::Yes; } void MainWindow::closeEvent(QCloseEvent* event) { if (mConfigChanged) { bool response = confirmLoseChanges(); if (response) { event->accept(); } else { event->ignore(); } } } <file_sep>/includes/controls/ctrlbutton.h #ifndef BUTTON_H #define BUTTON_H #include <QObject> #include <QWidget> #include <QMap> #include <QPushButton> #include <QUdpSocket> #include <QHBoxLayout> #include <QColor> #include "visupropertyloader.h" #include "visucontrol.h" class CtrlButton : public VisuControl { public: explicit CtrlButton( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuControl(parent, properties, metaProperties) { loadProperties(); setup(parent); } static const QString TAG_NAME; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); virtual bool refresh(const QString& key); void setup(QWidget* parent); private: Q_OBJECT QString cActionMessage; QString cCss; QPushButton* mButton; QHBoxLayout* mLayout; QColor cColorBackground; QColor cColorForeground; QColor cColorBorder; quint32 cBorderRadius; quint16 cFontSize; QString cFontType; quint8 cBorderThickness; void setupButton(QWidget* parent); QString generateCss(); private slots: void sendCommand(); }; #endif // BUTTON_H <file_sep>/src/instruments/instdigital.cpp #include "instdigital.h" #include <QPainter> #include <QFont> const QString InstDigital::TAG_NAME = "DIGITAL"; bool InstDigital::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; InstDigital::loadProperties(); return VisuInstrument::refresh(key); } void InstDigital::loadProperties() { VisuInstrument::loadProperties(); GET_PROPERTY(cShowSignalName, mProperties, mPropertiesMeta); GET_PROPERTY(cShowSignalUnit, mProperties, mPropertiesMeta); GET_PROPERTY(cPadding, mProperties, mPropertiesMeta); GET_PROPERTY(cLeadingDigits, mProperties, mPropertiesMeta); GET_PROPERTY(cDecimalDigits, mProperties, mPropertiesMeta); mTagName = InstDigital::TAG_NAME; } void InstDigital::renderStatic(QPainter* painter) { clear(painter); } void InstDigital::renderDynamic(QPainter* painter) { setFont(painter); setPen(painter, cColorForeground); QString text = QString::number(mSignal->getRealValue(), 'f', cDecimalDigits).rightJustified(cLeadingDigits, '0'); if (cShowSignalName) { text = mSignal->getName() + " = " + text; } if (cShowSignalUnit) { text += " " + mSignal->getUnit(); } painter->drawText(cPadding, cHeight - cPadding, text); } <file_sep>/includes/visudatagram.h #ifndef DATAGRAM_H #define DATAGRAM_H #include <QtGlobal> struct VisuDatagram { quint64 timestamp; quint64 rawValue; quint16 signalId; quint16 packetNumber; quint8 checksum; bool checksumOk(); }; #endif // DATAGRAM_H <file_sep>/src/wysiwyg/editconfiguration.cpp #include "wysiwyg/editconfiguration.h" #include "wysiwyg/visupropertieshelper.h" #include "visuconfigloader.h" void EditConfiguration::setup(QPointer<VisuConfiguration> configuration) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(tr("Configuration parameters")); resize(mWidth, mHeight); mConfiguration = configuration; QLayout* vlayout = new QVBoxLayout(); setLayout(vlayout); mTable = new QTableWidget(); VisuPropertiesHelper::updateTable(mTable, mConfiguration->getProperties(), mConfiguration->getPropertiesMeta(), std::make_pair(this, SLOT(propertyChange()))); mTable->setMaximumWidth(mWidth); mTable->verticalHeader()->hide(); mTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); vlayout->addWidget(mTable); QWidget* buttons = new QWidget(); QLayout* buttonsLayout = new QHBoxLayout(); buttons->setLayout(buttonsLayout); QPushButton* saveButton = new QPushButton(tr("&Save")); buttonsLayout->addWidget(saveButton); QPushButton* cancelButton = new QPushButton(tr("&Cancel")); buttonsLayout->addWidget(cancelButton); buttons->setMaximumHeight(saveButton->height()); vlayout->addWidget(buttons); show(); connect(cancelButton, SIGNAL(clicked()), this, SLOT(close())); connect(saveButton, SIGNAL(clicked()), this, SLOT(updateConfigParams())); connect(mTable, SIGNAL(cellChanged(int,int)), this, SLOT(cellUpdated(int,int))); } void EditConfiguration::updateConfigParams() { emit(configParamsUpdated()); close(); } void EditConfiguration::cellUpdated(int row, int col) { (void)col; QString key = VisuPropertiesHelper::getKeyString(mTable, row); QString value = VisuPropertiesHelper::getValueString(mTable, row); mConfiguration->updateProperties(key, value); VisuPropertiesHelper::updateWidgetsState(mTable, mConfiguration->getProperties(), mConfiguration->getPropertiesMeta()); } void EditConfiguration::propertyChange() { int row = VisuPropertiesHelper::updateWidgetProperty(sender(), this); cellUpdated(row, 1); } <file_sep>/src/statics/staticimage.cpp #include "../includes/statics/staticimage.h" #include <QLabel> #include <QDir> #include <QPainter> #include <QStyleOption> const QString StaticImage::TAG_NAME = "IMAGE"; const QString StaticImage::KEY_FORMAT = "format"; const QString StaticImage::KEY_IMAGE = "image"; bool StaticImage::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; StaticImage::loadProperties(); return StaticImage::refresh(key); } void StaticImage::loadProperties() { VisuWidget::loadProperties(); GET_PROPERTY(cImage, mProperties, mPropertiesMeta); GET_PROPERTY(cShow, mProperties, mPropertiesMeta); GET_PROPERTY(cResize, mProperties, mPropertiesMeta); } void StaticImage::paintEvent(QPaintEvent* event) { (void)event; // supress compiler warning about unused parameter if (!cShow) { return; } QPainter painter(this); if (cResize) { painter.drawImage(QRectF(0, 0, cWidth, cHeight), cImage, QRectF(0, 0, cImage.width(), cImage.height())); } else { painter.drawImage(0, 0, cImage, 0, 0); } drawActiveBox(&painter); } bool StaticImage::refresh(const QString& key) { VisuWidget::refresh(key); update(); setVisible(cShow); return false; } QImage StaticImage::getImage() { return cImage; } <file_sep>/includes/statics/staticimage.h #ifndef STATICIMAGE_H #define STATICIMAGE_H #include "visuwidget.h" #include <QHBoxLayout> class StaticImage : public VisuWidget { Q_OBJECT public: explicit StaticImage( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuWidget(parent, properties, metaProperties) { loadProperties(); mTagName = StaticImage::TAG_NAME; setVisible(cShow); } static const QString TAG_NAME; static const QString KEY_FORMAT; static const QString KEY_IMAGE; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); void paintEvent(QPaintEvent* event); virtual bool refresh(const QString& key); QImage getImage(); private: QImage cImage; bool cShow; bool cResize; }; #endif // STATICIMAGE_H <file_sep>/test/unit-tests/unit-tests.pro #------------------------------------------------- # # Project created by QtCreator 2017-02-13T21:05:54 # #------------------------------------------------- QT += widgets testlib QMAKE_CXXFLAGS += -std=c++0x TARGET = tst_instanalog CONFIG += console CONFIG -= app_bundle TEMPLATE = app INCLUDEPATH += ../../includes SOURCES += tst_instanalog.cpp DEFINES += SRCDIR=\\\"$$PWD/\\\" <file_sep>/includes/wysiwyg/visuwidgetfactory.h #ifndef VISUWIDGETFACTORY_H #define VISUWIDGETFACTORY_H #include <QMap> #include "visuwidget.h" #include "visusignal.h" class VisuWidgetFactory { public: static VisuWidget* createWidget(QWidget* parent, QString type); static VisuWidget* createWidget(QWidget* parent, QMap<QString, QString> properties); }; #endif // VISUWIDGETFACTORY_H <file_sep>/includes/instruments/instanalog.h #ifndef INSTANALOG_H #define INSTANALOG_H #include "visuinstrument.h" class InstAnalog : public VisuInstrument { Q_OBJECT public: explicit InstAnalog( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuInstrument(parent, properties, metaProperties) { loadProperties(); } static const QString TAG_NAME; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); private: static constexpr double PI = 3.141592653589793238463; static constexpr double STEPS_IN_DEGREE = 16; // configuration properties QColor cColorCircle; quint8 cLineThickness; // Thickness of geometric primitives drawn quint8 cMajorLen; // Length, in pixels, of major division marks quint8 cMinorLen; // Length, in pixels, of minor division marks quint8 cMajorCnt; // Number of major count divisions quint8 cMinorCnt; // Number of minor count divisions quint8 cArrowWidth; // Width of arrow at it's base bool cDrawCircle; // 1 / 0 to draw circle allong pointer tip quint16 cLabelRadius; // Radius of circle on which major labels are drawn double cAngleStart; // Angle of minimum value double cAngleEnd; // Angle of maximum value quint16 cNameX; // Signal label X coordinate quint16 cNameY; // Signal label Y coordinate qint16 cOffsetX; // X offset of instrument center qint16 cOffsetY; // Y offset of instrument center bool cShowLabel; quint16 cDivisionRadius; quint16 cCircleRadius; quint16 cArrowLen; double cLabelMultiplier; bool cRotateLabels; bool cCircleOffset; bool cCircleTrim; // aux propertis double mAngleSin; double mAngleCos; double mAngleLabel; double mDivisionAngle; double mDivisionAngleStep; double mSignalMajorDivisionValue; double mSignalMajorDivisionStep; double mStartLen; double mEndLen; double mStartPointX; double mStartPointY; double mEndPointX; double mEndPointY; quint16 mCenterX; quint16 mCenterY; void renderOutterCircle(QPainter* painter); void renderMajorDivision(QPainter* painter); void renderMinorDivision(QPainter* painter); void renderDivisionLine(QPainter* painter, int length); void initDivisionProperties(int length); void renderMajorLabel(QPainter* painter); double getMajorDivisionStep(); void updateDivisionAngles(); void renderCircularFeatures(QPainter* painter); void renderLabel(QPainter* painter); void setupStaticRenderProperties(quint16 totalDivisions); bool isMajorDevision(int divisionCnt); void renderMajor(QPainter* painter); void updateMajorValue(); void renderDivision(QPainter* painter, int divisionCnt); void setupProperties(); void calculateAngleOffset(); void drawTrianglePointer(QPainter* painter); protected: virtual void renderStatic(QPainter *painter); // Renders to pixmap_static virtual void renderDynamic(QPainter *painter); // Renders to pixmap }; #endif // INSTANALOG_H <file_sep>/includes/visuapplication.h #ifndef VISUAPPLICATION_H #define VISUAPPLICATION_H #include <QWidget> #include <QByteArray> #include <QString> #include "visuconfiguration.h" #include "visuserver.h" class VisuApplication : public QWidget { private: VisuConfiguration* mConfiguration; VisuServer *mServer; void setupWindow(); void loadConfiguration(QString path); public: VisuApplication(QString path); void run(); }; #endif // VISUAPPLICATION_H <file_sep>/includes/visusignal.h #ifndef SIGNAL_H #define SIGNAL_H #include <QtGlobal> #include <QVector> #include <QString> #include <QObject> #include "visuinstrument.h" #include "visudatagram.h" #include "visupropertyloader.h" #include "visupropertymeta.h" #include "visuconfigloader.h" class VisuInstrument; // forward declare Instrument class class VisuSignal : public QObject { Q_OBJECT private: // configuration properties quint16 cId; // Signal ID QString cName; // Signal name QString cUnit; // Signal unit double cFactor; // Signal factor used in real value calculation double cOffset; // Signal offset used in real value calculation double cMax; // Maximum signal value double cMin; // Minimum signal value int cSerialPlaceholder; // Index of recevied serial string bool cSerialTransform; // Apply factor and offset to serial data quint64 mTimestamp; // Last update timestamp quint64 mRawValue; // Last value QMap<QString, QString> mProperties; QMap<QString, VisuPropertyMeta> mPropertiesMeta; // methods void notifyInstruments(); signals: void initialUpdate(const VisuSignal* const); void signalUpdated(const VisuSignal* const); public: static const QString TAG_NAME; VisuSignal(const QMap<QString, QString>& properties); const QMap<QString, QString>& getProperties(); const QMap<QString, VisuPropertyMeta>& getPropertiesMeta(); void setPropertiesMeta(const QMap<QString, VisuPropertyMeta>& meta); void load(); void updateProperty(QString key, QString value); void initializeInstruments(); void datagramUpdate(const VisuDatagram& datagram); void set_raw_ralue(quint64 value); quint64 getRawValue() const; void set_timestamp(quint64 mTimestamp); quint64 getTimestamp() const; int getSerialPlaceholder() const; bool getSerialTransform() const; quint16 getId() const; void setId(quint16 id); double getFactor() const; double getOffset() const; double getRealValue() const; double getNormalizedValue() const; double getMin() const; double getMax() const; QString getName() const; QString getUnit() const; // observer interface void connectInstrument(VisuInstrument* instrument); void disconnectInstrument(VisuInstrument* instrument); }; #endif // SIGNAL_H <file_sep>/sender/sender/signal.py import time class Signal(object): def __init__(self, id): self.id = id self.raw = min self.timestamp = time.time() self.packageCnt = 0 def update(self, raw): self.raw = raw self.timestamp = time.time() ++self.packageCnt <file_sep>/includes/visupropertymeta.h #ifndef VISUPROPERTYMETA_H #define VISUPROPERTYMETA_H #include <QString> #include <QStringList> #include <QMap> class VisuPropertyMeta { public: VisuPropertyMeta() : min(std::numeric_limits<int>::min()), max(std::numeric_limits<int>::max()), defaultVal(""), type(DEFAULT), extra("") {} typedef enum { DEFAULT, ENUM, COLOR, INSTSIGNAL, READ_ONLY, INT, FLOAT, SLIDER, BOOL, FONT, IMAGE, SERIAL, SERIAL_PLACEHOLDER, HIDDEN, FIRST = DEFAULT, LAST = HIDDEN } Type; static const char* TYPES_MAP[]; double min; double max; QString defaultVal; Type type; QString extra; QString label; int order; QString depends; QString description; QStringList getEnumOptions(); bool isEnabled(const QMap<QString, QString>& properties) const; static QString stringFromType(VisuPropertyMeta::Type type); static Type typeFromString(QString typeStr); static const QString DELIMITER; static const QString KEY_MIN; static const QString KEY_MAX; static const QString KEY_TYPE; static const QString KEY_EXTRA; static const QString KEY_LABEL; static const QString KEY_DEPENDS; static const QString KEY_DEPSCRIPTION; }; #endif // VISUPROPERTYMETA_H <file_sep>/src/visusignal.cpp #include "visusignal.h" const QString VisuSignal::TAG_NAME = "signal"; VisuSignal::VisuSignal(const QMap<QString, QString>& properties) { mProperties = properties; mPropertiesMeta = VisuConfigLoader::getMetaMapFromFile( VisuSignal::TAG_NAME, VisuSignal::TAG_NAME); load(); } const QMap<QString, QString>& VisuSignal::getProperties() { return mProperties; } /** * @brief Signal::connectInstrument * Adds instrument to notify list. * @param instrument */ void VisuSignal::connectInstrument(VisuInstrument* instrument) { QObject::connect(this, SIGNAL(initialUpdate(const VisuSignal* const)), instrument, SLOT(initialUpdate(const VisuSignal* const))); QObject::connect(this, SIGNAL(signalUpdated(const VisuSignal* const)), instrument, SLOT(signalUpdated(const VisuSignal* const))); } /** * @brief Signal::disconnectInstrument * Removes instrument from notify list. * @param instrument */ void VisuSignal::disconnectInstrument(VisuInstrument* instrument) { QObject::disconnect(this, SIGNAL(initialUpdate(const VisuSignal* const)), instrument, SLOT(initialUpdate(const VisuSignal* const))); QObject::disconnect(this, SIGNAL(signalUpdated(const VisuSignal* const)), instrument, SLOT(signalUpdated(const VisuSignal* const))); } /** * @brief Signal::notifyInstruments * Notifies all instruments that signal value is changed. */ void VisuSignal::notifyInstruments() { emit signalUpdated(this); } quint16 VisuSignal::getId() const { return cId; } void VisuSignal::setId(quint16 id) { cId = id; mProperties["id"] = QString("%1").arg(id); } /** * @brief Signal::getRawValue * Returns signal raw value * @return */ quint64 VisuSignal::getRawValue() const { return mRawValue; } /** * @brief Signal::getFactor * Returns signal factor. * @return */ double VisuSignal::getFactor() const { return cFactor; } /** * @brief Signal::getOffset * Returns signal offset. * @return */ double VisuSignal::getOffset() const { return cOffset; } /** * @brief Signal::getRealValue * Returns signal real value. * @return */ double VisuSignal::getRealValue() const { return mRawValue * cFactor + cOffset; } double VisuSignal::getNormalizedValue() const { double value = (getRealValue() - cMin) / (cMax - cMin); if (value < 0.0 || value > 1.0) { value = 0.0; qDebug("Signal id=%d outside of range (min=%f, max=%f, received=%f.", cId, cMin, cMax, getRealValue()); } return value; } /** * @brief Signal::datagramUpdate * @param datagram */ void VisuSignal::datagramUpdate(const VisuDatagram& datagram) { mRawValue = datagram.rawValue; mTimestamp = datagram.timestamp; notifyInstruments(); } /** * @brief VisuSignal::initialUpdate * Called during instrument initialization, so instrument can pickup * pointer to signal and adjust its properties accordingly. */ void VisuSignal::initializeInstruments() { mRawValue = (cMin - cOffset) / cFactor; // TODO :: Use default value mTimestamp = 0; emit(initialUpdate(this)); } double VisuSignal::getMin() const { return cMin; } double VisuSignal::getMax() const { return cMax; } QString VisuSignal::getName() const { return cName; } QString VisuSignal::getUnit() const { return cUnit; } quint64 VisuSignal::getTimestamp() const { return mTimestamp; } int VisuSignal::getSerialPlaceholder() const { return cSerialPlaceholder; } bool VisuSignal::getSerialTransform() const { return cSerialTransform; } const QMap<QString, VisuPropertyMeta>& VisuSignal::getPropertiesMeta() { return mPropertiesMeta; } void VisuSignal::setPropertiesMeta(const QMap<QString, VisuPropertyMeta>& meta) { mPropertiesMeta = meta; } void VisuSignal::updateProperty(QString key, QString value) { mProperties[key] = value; load(); } void VisuSignal::load() { GET_PROPERTY(cId, mProperties, mPropertiesMeta); GET_PROPERTY(cName, mProperties, mPropertiesMeta); GET_PROPERTY(cUnit, mProperties, mPropertiesMeta); GET_PROPERTY(cFactor, mProperties, mPropertiesMeta); GET_PROPERTY(cOffset, mProperties, mPropertiesMeta); GET_PROPERTY(cMax, mProperties, mPropertiesMeta); GET_PROPERTY(cMin, mProperties, mPropertiesMeta); GET_PROPERTY(cSerialPlaceholder, mProperties, mPropertiesMeta); GET_PROPERTY(cSerialTransform, mProperties, mPropertiesMeta); } <file_sep>/src/visuserver.cpp #include "visuserver.h" #include <QUdpSocket> #include <qendian.h> #include "visuappinfo.h" #include <QRegularExpressionMatch> #include <QDateTime> const QByteArray VisuServer::DELIMITER = QByteArray("\n"); void VisuServer::handleSerialError(QSerialPort::SerialPortError serialPortError) { qDebug() << "Serial error: " << serialPortError; } VisuServer::VisuServer() { mConfiguration = VisuConfiguration::get(); mConectivity = (enum Connectivity)mConfiguration->getConectivity(); if (mConfiguration->isSerialBindToSignal()) { mSerialRegex = QRegularExpression(mConfiguration->getSerialRegex()); } if (mConectivity != SERIAL_ONLY) { mPort = mConfiguration->getPort(); QObject::connect(&mSocket, SIGNAL(readyRead()), this, SLOT(handleDatagram())); } if (mConectivity != UDP_ONLY) { mSerialPort = new QSerialPort(this); QObject::connect(mSerialPort, SIGNAL(readyRead()), this, SLOT(handleSerial())); QObject::connect(mSerialPort, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error), this, &VisuServer::handleSerialError ); } VisuAppInfo::setServer(this); } void VisuServer::sendSerial(const QByteArray& data) { if (mSerialPort != nullptr) { qint64 bytesWritten = mSerialPort->write(data); if (bytesWritten == -1) { qDebug() << QObject::tr("Failed to write the data to port %1, error: %2") .arg(mSerialPort->portName()) .arg(mSerialPort->errorString()); } else if (bytesWritten != data.size()) { qDebug() << QObject::tr("Failed to write all the data to port %1, error: %2") .arg(mSerialPort->portName()) .arg(mSerialPort->errorString()); } } } void VisuServer::parseVisuSerial() { mSerialBuffer.remove(0, mSerialBuffer.lastIndexOf(">") + 1); VisuDatagram datagram; QString serialBufferString(mSerialBuffer); QTextStream serialText(&serialBufferString); uint cs; serialText >> datagram.signalId >> datagram.packetNumber >> datagram.rawValue >> datagram.timestamp >> cs; datagram.checksum = (quint8) cs; if (datagram.checksumOk()) { updateSignal(datagram); } else { qDebug("Bad serial package."); } } void VisuServer::parseRegexSerial() { QString serialBufferString(mSerialBuffer); QRegularExpressionMatch match = mSerialRegex.match(serialBufferString); if (match.hasMatch()) { QStringList values = match.capturedTexts(); QVector<QPointer<VisuSignal>> signalsList = mConfiguration->getSignals(); for (VisuSignal* signal : signalsList) { int valueIndex = signal->getSerialPlaceholder(); if (valueIndex > 0) { VisuDatagram datagram; datagram.signalId = signal->getId(); QString value = values[valueIndex]; if (signal->getSerialTransform()) { datagram.rawValue = value.toInt(); } else { datagram.rawValue = (int)((value.toDouble() - signal->getOffset()) / signal->getFactor()); } datagram.timestamp = QDateTime::currentDateTime().toMSecsSinceEpoch(); updateSignal(datagram); } } } } void VisuServer::handleSerial() { mSerialBuffer.append(mSerialPort->readAll()); int pos = mSerialBuffer.indexOf(DELIMITER); if (pos > 0) { if (mConfiguration->isSerialBindToSignal() && mSerialRegex.isValid()) { parseRegexSerial(); } else { parseVisuSerial(); } mSerialBuffer.remove(0, pos + DELIMITER.size()); } } void VisuServer::start() { if (mConectivity != SERIAL_ONLY) { qDebug("Started UDP server on port %d.", mPort); mSocket.bind(QHostAddress::LocalHost, mPort); } if (mConectivity != UDP_ONLY) { ConfigLoadException::setContext("setting up serial port"); if (VisuAppInfo::argsSize() < 4) { throw ConfigLoadException("Serial port name or baud rate not specified"); } QString serialPortName = VisuAppInfo::getCLIArg(VisuAppInfo::CLI_Args::SERIAL_PORT_NAME); int baudRate = VisuAppInfo::getCLIArg(VisuAppInfo::CLI_Args::BAUD_RATE).toInt(); mSerialPort->setPortName(serialPortName); if ( !mSerialPort->setBaudRate(baudRate) || !mSerialPort->setDataBits(QSerialPort::Data8) || !mSerialPort->setParity(QSerialPort::NoParity) || !mSerialPort->setStopBits(QSerialPort::OneStop) || !mSerialPort->setFlowControl(QSerialPort::NoFlowControl) ) { throw ConfigLoadException(QObject::tr("Setup of %1 failed"), serialPortName); } if (!mSerialPort->open(QIODevice::ReadWrite)) { throw ConfigLoadException(QObject::tr("Failed to open port %1, error: %2") .arg(serialPortName) .arg(mSerialPort->errorString())); } else { qDebug("Listening on serial port %s at baud rate %d", serialPortName.toStdString().c_str(), baudRate); if (mConfiguration->isSerialStartEnabled()) { sendSerial(mConfiguration->getSerialStartString().toLocal8Bit()); } if (mConfiguration->isSerialPullEnabled()) { QObject::connect(&mTimer, SIGNAL(timeout()), this, SLOT(pullSerial())); mTimer.setInterval(mConfiguration->getSerialPullPeriod()); mTimer.start(); } } } } void VisuServer::stop() { QObject::disconnect(&mSocket, SIGNAL(readyRead()), this, SLOT(handleDatagram())); QObject::disconnect(mSerialPort, SIGNAL(readyRead()), this, SLOT(handleSerial())); QObject::disconnect(mSerialPort, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error), this, &VisuServer::handleSerialError ); QObject::disconnect(&mTimer, SIGNAL(timeout()), this, SLOT(pullSerial())); mSocket.close(); mSerialPort->close(); delete mSerialPort; } VisuDatagram VisuServer::createDatagramFromBuffer(const quint8* buffer) { VisuDatagram datagram; datagram.signalId = qFromBigEndian<quint16>((uchar*)buffer); buffer += 2; datagram.packetNumber = qFromBigEndian<quint16>((uchar*)buffer); buffer += 2; datagram.timestamp = qFromBigEndian<quint64>((uchar*)buffer); buffer += 8; datagram.rawValue = qFromBigEndian<quint64>((uchar*)buffer); buffer += 8; datagram.checksum = *buffer; return datagram; } void VisuServer::handleDatagram() { QByteArray buffer(DATAGRAM_SIZE, 0); char* bufferRawData = (char*)buffer.data(); QHostAddress senderAddress; quint16 senderPort; while(mSocket.hasPendingDatagrams()) { mSocket.readDatagram(bufferRawData, DATAGRAM_SIZE, &senderAddress, &senderPort); VisuDatagram datagram = createDatagramFromBuffer((const quint8*)bufferRawData); if (datagram.checksumOk()) { updateSignal(datagram); } else { qDebug("Bad UDP package."); } } } void VisuServer::updateSignal(const VisuDatagram& datagram) { VisuSignal* signal = mConfiguration->getSignal(datagram.signalId); if (signal != nullptr) { signal->datagramUpdate(datagram); } } void VisuServer::pullSerial() { sendSerial(mConfiguration->getSerialPullString().toLocal8Bit()); } <file_sep>/src/instruments/instanalog.cpp #include "instanalog.h" #include <QPainter> #include <QFontMetrics> #include <QtCore> #include <math.h> const QString InstAnalog::TAG_NAME = "ANALOG"; bool InstAnalog::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; InstAnalog::loadProperties(); return VisuInstrument::refresh(key); } void InstAnalog::loadProperties() { VisuInstrument::loadProperties(); // custom properties initializer GET_PROPERTY(cColorCircle, mProperties, mPropertiesMeta); GET_PROPERTY(cCircleRadius, mProperties, mPropertiesMeta); GET_PROPERTY(cLineThickness, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorLen, mProperties, mPropertiesMeta); GET_PROPERTY(cMinorLen, mProperties, mPropertiesMeta); GET_PROPERTY(cMajorCnt, mProperties, mPropertiesMeta); GET_PROPERTY(cMinorCnt, mProperties, mPropertiesMeta); GET_PROPERTY(cArrowWidth, mProperties, mPropertiesMeta); GET_PROPERTY(cDrawCircle, mProperties, mPropertiesMeta); GET_PROPERTY(cLabelRadius, mProperties, mPropertiesMeta); GET_PROPERTY(cAngleStart, mProperties, mPropertiesMeta); GET_PROPERTY(cAngleEnd, mProperties, mPropertiesMeta); GET_PROPERTY(cNameX, mProperties, mPropertiesMeta); GET_PROPERTY(cNameY, mProperties, mPropertiesMeta); GET_PROPERTY(cOffsetX, mProperties, mPropertiesMeta); GET_PROPERTY(cOffsetY, mProperties, mPropertiesMeta); GET_PROPERTY(cShowLabel, mProperties, mPropertiesMeta); GET_PROPERTY(cDivisionRadius, mProperties, mPropertiesMeta); GET_PROPERTY(cArrowLen, mProperties, mPropertiesMeta); GET_PROPERTY(cLabelMultiplier, mProperties, mPropertiesMeta); GET_PROPERTY(cRotateLabels, mProperties, mPropertiesMeta); GET_PROPERTY(cCircleOffset, mProperties, mPropertiesMeta); GET_PROPERTY(cCircleTrim, mProperties, mPropertiesMeta); mTagName = InstAnalog::TAG_NAME; } void InstAnalog::renderStatic(QPainter* painter) { clear(painter); setPen(painter, cColorStatic, cLineThickness); setFont(painter); setupProperties(); if (cDrawCircle) { renderOutterCircle(painter); } renderCircularFeatures(painter); if (cShowLabel) { renderLabel(painter); } } void InstAnalog::renderLabel(QPainter* painter) { painter->drawText(cNameX, cNameY, mSignal->getName()); } void InstAnalog::renderOutterCircle(QPainter* painter) { int x = cWidth / 2 - cCircleRadius; int y = cHeight / 2 - cCircleRadius; int angleStart = 0; int angleSpan = 360 * STEPS_IN_DEGREE; if (cCircleOffset) { x += cOffsetX; y += cOffsetY; } if (cCircleTrim) { angleStart = -90 * STEPS_IN_DEGREE + (cAngleEnd / PI * 180 * STEPS_IN_DEGREE); angleSpan = (360 - (cAngleStart + cAngleEnd) / PI * 180) * STEPS_IN_DEGREE; } setPen(painter, cColorCircle); setBrush(painter, cColorCircle); painter->drawEllipse( x , y , cCircleRadius * 2 , cCircleRadius * 2); setPen(painter, cColorStatic, cLineThickness); painter->drawArc( x , y , cCircleRadius * 2 , cCircleRadius * 2 , angleStart , angleSpan); } void InstAnalog::setupStaticRenderProperties(quint16 totalDivisions) { mSignalMajorDivisionValue = mSignal->getMin(); mDivisionAngle = cAngleStart; mDivisionAngleStep = (2 * PI - cAngleStart - cAngleEnd) / totalDivisions; mSignalMajorDivisionStep = getMajorDivisionStep(); } bool InstAnalog::isMajorDevision(int divisionCnt) { return (divisionCnt % cMinorCnt) == 0; } void InstAnalog::renderMajor(QPainter* painter) { renderMajorLabel(painter); renderMajorDivision(painter); } void InstAnalog::updateMajorValue() { mSignalMajorDivisionValue += mSignalMajorDivisionStep; } void InstAnalog::renderCircularFeatures(QPainter* painter) { setPen(painter, cColorStatic, cLineThickness); quint16 totalDivisions = cMajorCnt * cMinorCnt; setupStaticRenderProperties(totalDivisions); for (int i = 0; i <= totalDivisions; ++i) { renderDivision(painter, i); } } void InstAnalog::renderDivision(QPainter* painter, int divisionCnt) { updateDivisionAngles(); if (isMajorDevision(divisionCnt)) { renderMajor(painter); updateMajorValue(); } else { renderMinorDivision(painter); } } double InstAnalog::getMajorDivisionStep() { double sigMax = mSignal->getMax(); double sigMin = mSignal->getMin(); return (sigMax - sigMin) / (cMajorCnt); } void InstAnalog::updateDivisionAngles() { mAngleSin = qSin(mDivisionAngle); mAngleCos = qCos(mDivisionAngle); mDivisionAngle += mDivisionAngleStep; } void InstAnalog::renderMajorLabel(QPainter* painter) { QString label = QString("%1").arg((int)mSignalMajorDivisionValue * cLabelMultiplier); QFontMetrics font_metrics = painter->fontMetrics(); quint16 labelWidth = font_metrics.width(label); if (cRotateLabels) { double lblHalfAngleWidth = qAsin((double)labelWidth / cLabelRadius / 2); double lblPositionOffsetAngle = mDivisionAngle - mDivisionAngleStep - lblHalfAngleWidth; double lblAngleDeg = (mDivisionAngle-mDivisionAngleStep) * 360 / PI / 2 + 180 ; qint16 labelX = -cLabelRadius * qSin(lblPositionOffsetAngle) + cWidth / 2; qint16 labelY = cLabelRadius * qCos(lblPositionOffsetAngle) + cHeight / 2; painter->translate(labelX + cOffsetX, labelY + cOffsetY); painter->rotate(lblAngleDeg); painter->drawText(0, 0, label); painter->rotate(-lblAngleDeg); painter->translate(-labelX - cOffsetX, -labelY - cOffsetY); } else { quint16 labelHeight = font_metrics.height(); qint16 labelX = -cLabelRadius * mAngleSin + (cWidth - labelWidth) / 2; qint16 labelY = cLabelRadius * mAngleCos + (cHeight + labelHeight) / 2; painter->drawText(labelX + cOffsetX, labelY + cOffsetY, label); } } void InstAnalog::renderMajorDivision(QPainter* painter) { renderDivisionLine(painter, cMajorLen); } void InstAnalog::renderMinorDivision(QPainter* painter) { renderDivisionLine(painter, cMinorLen); } void InstAnalog::renderDivisionLine(QPainter* painter, int length) { initDivisionProperties(length); painter->drawLine( QPointF(mStartPointX + cOffsetX, mStartPointY + cOffsetY), QPointF(mEndPointX + cOffsetX, mEndPointY + cOffsetY) ); } void InstAnalog::initDivisionProperties(int length) { mStartLen = cDivisionRadius - cLineThickness * 2; mEndLen = mStartLen - length; mStartPointX = -mStartLen * mAngleSin + mCenterX; mStartPointY = mStartLen * mAngleCos + mCenterY; mEndPointX = -mEndLen * mAngleSin + mCenterX; mEndPointY = mEndLen * mAngleCos + mCenterY; } void InstAnalog::calculateAngleOffset() { double value = mSignal->getNormalizedValue(); double angleValue = (2 * PI - cAngleStart - cAngleEnd) * value + cAngleStart; mAngleSin = qSin(angleValue); mAngleCos = qCos(angleValue); } void InstAnalog::setupProperties() { mCenterX = cWidth / 2; mCenterY = cHeight / 2; } void InstAnalog::renderDynamic(QPainter* painter) { setPen(painter, cColorForeground); setBrush(painter, cColorForeground); calculateAngleOffset(); drawTrianglePointer(painter); } void InstAnalog::drawTrianglePointer(QPainter* painter) { qint16 endPointX = -mAngleSin * cArrowLen + mCenterX; qint16 endPointY = mAngleCos * cArrowLen + mCenterY; qint16 leftPointX = -mAngleCos * cArrowWidth + mCenterX; qint16 leftPointY = -mAngleSin * cArrowWidth + mCenterY; qint16 rightPointX = mAngleCos * cArrowWidth + mCenterX; qint16 rightPointY = mAngleSin * cArrowWidth + mCenterY; const QPointF points[3] = { QPointF(endPointX + cOffsetX, endPointY + cOffsetY), QPointF(leftPointX + cOffsetX, leftPointY + cOffsetY), QPointF(rightPointX + cOffsetX, rightPointY + cOffsetY) }; painter->drawPolygon(points, 3); } <file_sep>/includes/visuconfiguration.h #ifndef CONFIGURATION_H #define CONFIGURATION_H #include "visusignal.h" #include "visuinstrument.h" #include "ctrlbutton.h" #include "statics/staticimage.h" #include "visupropertymeta.h" #include "visuconfigloader.h" #include <QWidget> #include <QObject> #include <QXmlStreamReader> #include <QPointer> #include <vector> class VisuConfiguration : public QObject { Q_OBJECT private: static VisuConfiguration* instance; QVector<QPointer<VisuSignal>> signalsList; QVector<QPointer<VisuWidget>> widgetsList; template <typename T> static void append(T* elem, QString& xml, int tabs); void createSignalFromToken(QXmlStreamReader& xml_reader); void createConfigurationFromToken(QXmlStreamReader& xmlReader); int getFreeId(QVector<QPointer<QObject> > &list); // Properties quint16 cPort; quint16 cWidth; quint16 cHeight; QColor cColorBackground; QString cName; quint8 cConectivity; QString cSerialPort; quint32 cBaudRate; bool cSerialBindToSignal; QString cSerialRegex; bool cSerialStartEnable; QString cSerialStart; bool cPullMessageEnable; QString cPullMessage; quint32 cPullPeriod; QMap<QString, QString> mProperties; QMap<QString, VisuPropertyMeta> mPropertiesMeta; VisuConfiguration() { mPropertiesMeta = VisuConfigLoader::getMetaMapFromFile(VisuConfiguration::TAG_NAME, VisuConfiguration::TAG_NAME); } public: static VisuConfiguration* get(); static VisuConfiguration* getClean(); virtual ~VisuConfiguration(); void setConfigValues(); void fromXML(QWidget *parent, const QString& xml); QString toXML(); void initializeInstruments(); void updateProperties(const QString& key, const QString& value); void setPropertiesMeta(QMap<QString, VisuPropertyMeta> meta); QMap<QString, VisuPropertyMeta> getPropertiesMeta(); // General widget methods QPointer<VisuWidget> createWidgetFromToken(QXmlStreamReader& xmlReader, QWidget *parent); void addWidget(QPointer<VisuWidget> widget); void deleteWidget(QPointer<VisuWidget> widget); QVector<QPointer<VisuWidget>> getWidgets(); QPointer<VisuWidget> getWidget(int id); void moveWidgetUp(int id); void moveWidgetDown(int id); template <typename T> QVector<QPointer<T> > getListOf() { QVector<QPointer<T> > result; int size = widgetsList.size(); for (int i = 0 ; i < size ; ++i) { T* match = qobject_cast<T*>(widgetsList.at(i)); if (match != nullptr) { result.append(match); } } return result; } // Instrument specific methods QPointer<VisuInstrument> getInstrument(quint16 instrument_id); // Signal specific methods void addSignal(QPointer<VisuSignal> signal); void deleteSignal(QPointer<VisuSignal> signal); void deleteSignal(int signalId); QPointer<VisuSignal> getSignal(quint16 signalId); QVector<QPointer<VisuSignal>> &getSignals(); // Getters QMap<QString, QString>& getProperties(); quint16 getPort(); QString getSerialPort(); quint32 getBaudRate(); quint16 getWidth(); quint16 getHeight(); QSize getSize() const; QColor getBackgroundColor(); QString getName(); quint8 getConectivity(); bool isSerialBindToSignal(); QString getSerialRegex(); bool isSerialStartEnabled(); QString getSerialStartString(); bool isSerialPullEnabled(); QString getSerialPullString(); quint32 getSerialPullPeriod(); static const QString TAG_WIDGET; static const QString TAG_SIGNAL; static const QString TAG_NAME; static const QString ATTR_TYPE; static const QString TAG_VISU_CONFIG; static const QString TAG_WIDGETS_PLACEHOLDER; static const QString TAG_SIGNALS_PLACEHOLDER; }; #endif // CONFIGURATION_H <file_sep>/includes/wysiwyg/editconfiguration.h #ifndef EDITCLASS_H #define EDITCLASS_H #include <QHeaderView> #include <QWidget> #include <QLayout> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QTableWidget> #include <QMap> #include <QPointer> #include "visuconfiguration.h" #include "visumisc.h" class EditConfiguration : public QWidget { Q_OBJECT public: EditConfiguration(QWidget* parent, QPointer<VisuConfiguration> configuration) : QWidget(parent) { setWindowFlags(Qt::Dialog); setup(configuration); } signals: void configParamsUpdated(); public slots: void propertyChange(); private slots: void updateConfigParams(); void cellUpdated(int row, int col); private: static const int mWidth = 400; static const int mHeight = 400; QPointer<VisuConfiguration> mConfiguration; QPointer<QTableWidget> mTable; void setup(QPointer<VisuConfiguration> configuration); }; #endif // EDITCLASS_H <file_sep>/includes/visuserver.h #ifndef SERVER_H #define SERVER_H #include <QObject> #include <QUdpSocket> #include <QSerialPort> #include <QRegularExpression> #include <QTimer> #include "visuappinfo.h" #include "visusignal.h" #include "visudatagram.h" #include "visuconfiguration.h" class VisuServer : public QObject { Q_OBJECT public: enum Connectivity { UDP_AND_SERIAL, UDP_ONLY, SERIAL_ONLY }; VisuServer(); void start(); void stop(); private: quint16 mPort; enum Connectivity mConectivity; static const quint8 DATAGRAM_SIZE = 21; QUdpSocket mSocket; VisuConfiguration *mConfiguration; QTimer mTimer; QSerialPort* mSerialPort; void updateSignal(const VisuDatagram& datagram); VisuDatagram createDatagramFromBuffer(const quint8* buffer); QByteArray mSerialBuffer; QRegularExpression mSerialRegex; static const QByteArray DELIMITER; private slots: void pullSerial(); public slots: void handleDatagram(); void handleSerial(); void parseVisuSerial(); void parseRegexSerial(); void sendSerial(const QByteArray& data); void handleSerialError(QSerialPort::SerialPortError serialPortError); }; #endif // SERVER_H <file_sep>/src/wysiwyg/visupropertieshelper.cpp #include "wysiwyg/visupropertieshelper.h" #include "visumisc.h" #include <QFontDatabase> #include <QSerialPortInfo> const char* VisuPropertiesHelper::PROP_COLOR = "color"; const char* VisuPropertiesHelper::PROP_ROW = "row"; const char* VisuPropertiesHelper::PROP_KEY = "key"; const char* VisuPropertiesHelper::PROP_TYPE = "type"; double VisuPropertiesHelper::sliderToDouble(int slider) { return (double)slider / SLIDER_FACTOR; } int VisuPropertiesHelper::doubleToSlider(double value) { return (int)(value * SLIDER_FACTOR); } void VisuPropertiesHelper::setupTableWidget( QTableWidget* table, std::pair<QWidget*, const char*> widget, std::pair<QWidget*, const char*> parent, QString key, VisuPropertyMeta::Type type, int row) { widget.first->setProperty(VisuPropertiesHelper::PROP_KEY, key); widget.first->setProperty(VisuPropertiesHelper::PROP_TYPE, type); widget.first->setProperty(VisuPropertiesHelper::PROP_ROW, row); table->setCellWidget(row, VisuPropertiesHelper::COLUMN_VALUE, widget.first); if (widget.first != nullptr && widget.second != nullptr && parent.first != nullptr && parent.second != nullptr) { QObject::connect(widget.first, widget.second, parent.first, parent.second); } } std::pair<QComboBox*, const char*> VisuPropertiesHelper::setupEnumWidget(VisuPropertyMeta meta, QString value) { QComboBox* box = new QComboBox(); box->insertItems(0, meta.getEnumOptions()); box->setCurrentIndex(value.toInt()); return std::make_pair(box, SIGNAL(currentIndexChanged(int))); } std::pair<QComboBox*, const char*> VisuPropertiesHelper::setupFontWidget(VisuPropertyMeta meta, QString value) { QComboBox* box = new QComboBox(); QFontDatabase db; box->insertItems(0, db.families()); box->setCurrentText(value); return std::make_pair(box, SIGNAL(currentIndexChanged(int))); } std::pair<QCheckBox*, const char*> VisuPropertiesHelper::setupBoolWidget(VisuPropertyMeta meta, QString value) { QCheckBox* checkbox = new QCheckBox(); checkbox->setChecked(value.toInt() == 1); return std::make_pair(checkbox, SIGNAL(stateChanged(int))); } std::pair<QComboBox*, const char*> VisuPropertiesHelper::setupSignalsWidget(VisuPropertyMeta meta, QString value) { QComboBox* box = new QComboBox(); int selected = 0; int intValue = value.toInt(); QVector<QPointer<VisuSignal>> signalList = VisuConfiguration::get()->getSignals(); for (VisuSignal* visuSignal : signalList) { if (visuSignal != nullptr) { box->addItem(visuSignal->getName(), QVariant(visuSignal->getId())); if (visuSignal->getId() == intValue) { selected = box->count()-1; } } } box->setCurrentIndex(selected); return std::make_pair(box, SIGNAL(currentIndexChanged(int))); } std::pair<QComboBox*, const char*> VisuPropertiesHelper::setupImagesWidget(VisuPropertyMeta meta, QString value) { QComboBox* box = new QComboBox(); box->addItem("Use color", QVariant(-1)); QVector<QPointer<StaticImage> > list = VisuConfiguration::get()->getListOf<StaticImage>(); int selected = 0; int intValue = value.toInt(); for (StaticImage* image : list) { if (image != nullptr) { box->addItem(image->getName(), QVariant(image->getId())); if (image->getId() == intValue) { selected = box->count()-1; } } } box->setCurrentIndex(selected); return std::make_pair(box, SIGNAL(currentIndexChanged(int))); } std::pair<QComboBox*, const char*> VisuPropertiesHelper::setupSerialWidget(VisuPropertyMeta meta, QString value) { QComboBox* box = new QComboBox(); const auto portInfos = QSerialPortInfo::availablePorts(); for (const auto& port : portInfos) { if (port.isValid() && !port.isBusy()) { box->addItem(port.portName()); } } if (value != "-") { box->setCurrentText(value); } return std::make_pair(box, SIGNAL(currentIndexChanged(int))); } std::pair<QComboBox*, const char*> VisuPropertiesHelper::setupSignalPlaceholderWidget(VisuPropertyMeta meta, QString value) { QComboBox* box = new QComboBox(); QRegularExpression expression = QRegularExpression(VisuConfiguration::get()->getSerialRegex()); int captures = expression.captureCount(); box->addItem(QObject::tr("Disabled")); for (int i = 0 ; i < captures ; ++i) { QString label = QObject::tr("Expression #%1").arg(i); box->addItem(label); } box->setCurrentIndex(value.toInt()); return std::make_pair(box, SIGNAL(currentIndexChanged(int))); } std::pair<QPushButton*, const char*> VisuPropertiesHelper::setupColorWidget(VisuPropertyMeta meta, QString value) { QPushButton* btn = new QPushButton(value); QColor color = VisuMisc::strToColor(value); VisuMisc::setBackgroundColor(btn, color); btn->setProperty(VisuPropertiesHelper::PROP_COLOR, color); return std::make_pair(btn, SIGNAL(clicked())); } std::pair<QSpinBox*, const char*> VisuPropertiesHelper::setupIntWidget(VisuPropertyMeta meta, QString value) { QSpinBox* spinbox = new QSpinBox(); spinbox->setMinimum(meta.min); spinbox->setMaximum(meta.max); spinbox->setValue(value.toInt()); return std::make_pair(spinbox, SIGNAL(valueChanged(int))); } std::pair<QSlider*, const char*> VisuPropertiesHelper::setupSliderWidget(VisuPropertyMeta meta, QString value) { QSlider* slider = new QSlider(Qt::Horizontal); slider->setMinimum(VisuPropertiesHelper::doubleToSlider(meta.min)); slider->setMaximum(VisuPropertiesHelper::doubleToSlider(meta.max)); slider->setValue(VisuPropertiesHelper::doubleToSlider(value.toDouble())); return std::make_pair(slider, SIGNAL(valueChanged(int))); } std::pair<QLineEdit*, const char*> VisuPropertiesHelper::setupDefaultWidget(VisuPropertyMeta meta, QString value) { QLineEdit* edit = new QLineEdit(value); if (meta.type == VisuPropertyMeta::FLOAT) { QValidator *validator = new QDoubleValidator(meta.min, meta.max, 3); edit->setValidator(validator); } return std::make_pair(edit, SIGNAL(editingFinished())); } std::pair<QLabel*, const char*> VisuPropertiesHelper::setupReadOnlyWidget(VisuPropertyMeta meta, QString value) { QLabel* label = new QLabel(value); return std::make_pair(label, nullptr); } std::pair<QWidget*, const char*> VisuPropertiesHelper::controlFactory(VisuPropertyMeta meta, QString value) { std::pair<QWidget*, const char*> widget; switch(meta.type) { case VisuPropertyMeta::ENUM: widget = VisuPropertiesHelper::setupEnumWidget(meta, value); break; case VisuPropertyMeta::FONT: widget = VisuPropertiesHelper::setupFontWidget(meta, value); break; case VisuPropertyMeta::BOOL: widget = VisuPropertiesHelper::setupBoolWidget(meta, value); break; case VisuPropertyMeta::INSTSIGNAL: widget = VisuPropertiesHelper::setupSignalsWidget(meta, value); break; case VisuPropertyMeta::IMAGE: widget = VisuPropertiesHelper::setupImagesWidget(meta, value); break; case VisuPropertyMeta::COLOR: widget = VisuPropertiesHelper::setupColorWidget(meta, value); break; case VisuPropertyMeta::READ_ONLY: widget = VisuPropertiesHelper::setupReadOnlyWidget(meta, value); break; case VisuPropertyMeta::INT: widget = VisuPropertiesHelper::setupIntWidget(meta, value); break; case VisuPropertyMeta::SLIDER: widget = VisuPropertiesHelper::setupSliderWidget(meta, value); break; case VisuPropertyMeta::SERIAL: widget = VisuPropertiesHelper::setupSerialWidget(meta, value); break; case VisuPropertyMeta::SERIAL_PLACEHOLDER: widget = VisuPropertiesHelper::setupSignalPlaceholderWidget(meta, value); break; default: widget = VisuPropertiesHelper::setupDefaultWidget(meta, value); } return widget; } void VisuPropertiesHelper::updateTable(QTableWidget* table, const QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties, std::pair<QWidget*, const char*> object) { int cnt = 0; int maxCnt = properties.size(); table->setEnabled(true); table->clearContents(); table->setRowCount(maxCnt); table->setColumnCount(2); table->setHorizontalHeaderLabels(QStringList{"Property", "Value"}); for (auto i = properties.begin(); i != properties.end(); ++i) { QString key = i.key(); QString value = i.value(); VisuPropertyMeta meta; if (metaProperties.contains(key)) { meta = metaProperties[key]; } else { qDebug() << "Missing meta for key " << key; continue; } if (meta.type != VisuPropertyMeta::HIDDEN) { QString labelText = meta.label.isEmpty() ? key : meta.label; QTableWidgetItem* label = new QTableWidgetItem(labelText); label->setFlags(label->flags() & ~Qt::ItemIsEditable); label->setToolTip(meta.description); table->setItem(meta.order, VisuPropertiesHelper::COLUMN_PROPERTY, label); std::pair<QWidget*, const char*> widget = VisuPropertiesHelper::controlFactory(meta, value); if (widget.first != nullptr) { VisuPropertiesHelper::setupTableWidget(table, widget, object, key, meta.type, meta.order); widget.first->setEnabled(meta.isEnabled(properties)); ++cnt; } } else { table->setRowCount(table->rowCount() - 1); } } if (cnt < maxCnt) { table->setRowCount(cnt); } updateWidgetsState(table, properties, metaProperties); } QString VisuPropertiesHelper::getKeyString(QTableWidget* table, int row) { QWidget* w = table->cellWidget(row, VisuPropertiesHelper::COLUMN_VALUE); QString ret; if (w != nullptr) { ret = w->property(VisuPropertiesHelper::PROP_KEY).toString(); } return ret; } QString VisuPropertiesHelper::getValueString(QTableWidget* table, int row) { QString value; QComboBox* box; QLineEdit* edit; QPushButton* button; QSpinBox* spinbox; QSlider* slider; QCheckBox* checkbox; if ( (box = qobject_cast<QComboBox*>(table->cellWidget(row, 1))) != nullptr) { int type = box->property(VisuPropertiesHelper::PROP_TYPE).toInt(); switch (type) { case VisuPropertyMeta::FONT: case VisuPropertyMeta::SERIAL: value = box->currentText(); break; case VisuPropertyMeta::ENUM: case VisuPropertyMeta::SERIAL_PLACEHOLDER: value = QString("%1").arg(box->currentIndex()); break; default: value = QString("%1").arg(box->currentData().toInt()); } } else if ( (spinbox = qobject_cast<QSpinBox*>(table->cellWidget(row, 1))) != nullptr) { value = QString("%1").arg(spinbox->value()); } else if ( (checkbox = qobject_cast<QCheckBox*>(table->cellWidget(row, 1))) != nullptr) { value = QString("%1").arg(checkbox->isChecked()); } else if ( (edit = qobject_cast<QLineEdit*>(table->cellWidget(row, 1))) != nullptr ) { value = edit->text(); } else if ( (button = qobject_cast<QPushButton*>(table->cellWidget(row, 1))) != nullptr ) { value = button->text(); } else if ( (slider = qobject_cast<QSlider*>(table->cellWidget(row, 1))) != nullptr ) { value = QString("%1").arg(VisuPropertiesHelper::sliderToDouble(slider->value())); } else { value = table->item(row,1)->text(); } return value; } void VisuPropertiesHelper::updateWidgetsState(QTableWidget* table, const QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& propertiesMeta) { for (int i = 0 ; i < table->rowCount() ; ++i) { QString key = VisuPropertiesHelper::getKeyString(table, i); if (propertiesMeta.contains(key)) { bool enabled = propertiesMeta.value(key).isEnabled(properties); QWidget* w = table->cellWidget(i, VisuPropertiesHelper::COLUMN_VALUE); w->setEnabled(enabled); } } } int VisuPropertiesHelper::updateWidgetProperty(QObject* sender, QWidget* parent) { int row = sender->property(VisuPropertiesHelper::PROP_ROW).toInt(); QPushButton* btn; if ( (btn = qobject_cast<QPushButton*>(sender)) != nullptr ) { QColor oldColor = btn->property(VisuPropertiesHelper::PROP_COLOR).value<QColor>(); QColor newColor = QColorDialog::getColor(oldColor, parent, QObject::tr("Set color"), QColorDialog::ShowAlphaChannel); if (newColor.isValid()) { QString colorString = QString("%1,%2,%3,%4").arg(newColor.red()) .arg(newColor.green()).arg(newColor.blue()).arg(newColor.alpha()); btn->setText(colorString); VisuMisc::setBackgroundColor(btn, newColor); } } return row; } <file_sep>/src/controls/ctrlbutton.cpp #include "ctrlbutton.h" #include "visumisc.h" #include <visuserver.h> const QString CtrlButton::TAG_NAME = "BUTTON"; void CtrlButton::sendCommand() { if (VisuConfiguration::get()->getConectivity() != VisuServer::SERIAL_ONLY) { mSocket.writeDatagram( cActionMessage.toStdString().c_str(), cActionMessage.size(), mAddress, cActionPort); } if (VisuConfiguration::get()->getConectivity() != VisuServer::UDP_ONLY) { VisuServer* server = VisuAppInfo::getServer(); if (server != nullptr) { server->sendSerial(cActionMessage.toLatin1()); } } emit(widgetActivated(this)); } void CtrlButton::setupButton(QWidget* parent) { setGeometry(QRect(cX, cY, cWidth, cHeight)); mButton = new QPushButton(parent); mLayout->addWidget(mButton); refresh(""); QObject::connect(mButton, SIGNAL(pressed()), this, SLOT(sendCommand())); } bool CtrlButton::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; CtrlButton::loadProperties(); return CtrlButton::refresh(key); } void CtrlButton::loadProperties() { VisuControl::loadProperties(); GET_PROPERTY(cActionMessage, mProperties, mPropertiesMeta); GET_PROPERTY(cCss, mProperties, mPropertiesMeta); GET_PROPERTY(cColorBackground, mProperties, mPropertiesMeta); GET_PROPERTY(cColorForeground, mProperties, mPropertiesMeta); GET_PROPERTY(cColorBorder, mProperties, mPropertiesMeta); GET_PROPERTY(cBorderRadius, mProperties, mPropertiesMeta); GET_PROPERTY(cFontSize, mProperties, mPropertiesMeta); GET_PROPERTY(cFontType, mProperties, mPropertiesMeta); GET_PROPERTY(cBorderThickness, mProperties, mPropertiesMeta); } void CtrlButton::setup(QWidget *parent) { mTagName = TAG_NAME; mLayout = new QHBoxLayout(); mLayout->setContentsMargins(0,0,0,0); setLayout(mLayout); setupButton(parent); show(); } QString CtrlButton::generateCss() { QString css; css += QString("background-color: %1;").arg(VisuMisc::colorToStr(cColorBackground)); css += QString("color: %1;").arg(VisuMisc::colorToStr(cColorForeground)); css += QString("border: %1px solid %2;").arg(cBorderThickness).arg(VisuMisc::colorToStr(cColorBorder)); css += QString("border-radius: %1;").arg(cBorderRadius); css += QString("font-family: %1;").arg(cFontType); css += QString("font-size: %1px;").arg(cFontSize); css += cCss; return css; } bool CtrlButton::refresh(const QString& key) { VisuWidget::refresh(key); mButton->setText(cName); mButton->setMinimumSize(cWidth, cHeight); mButton->setMinimumSize(cWidth, cHeight); mButton->setStyleSheet(generateCss()); return false; } <file_sep>/src/visuapplication.cpp #include "visuapplication.h" #include "exceptions/configloadexception.h" #include "visuconfigloader.h" #include "visumisc.h" #include <QPainter> #include <QFile> VisuApplication::VisuApplication(QString path) { mConfiguration = VisuConfiguration::get(); loadConfiguration(path); setupWindow(); mServer = new VisuServer(); } void VisuApplication::loadConfiguration(QString path) { QByteArray xml = VisuConfigLoader::loadXMLFromFile(path); mConfiguration->fromXML(this, QString(xml)); } void VisuApplication::setupWindow() { setGeometry(100, 100, mConfiguration->getWidth(), mConfiguration->getHeight()); setWindowTitle(mConfiguration->getName()); VisuMisc::setBackgroundColor(this, mConfiguration->getBackgroundColor()); } void VisuApplication::run() { mServer->start(); } <file_sep>/src/visuinstrument.cpp #include "visuinstrument.h" #include <QPainter> #include <QStyleOption> #include "visumisc.h" bool VisuInstrument::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; VisuInstrument::loadProperties(); return VisuInstrument::refresh(key); } void VisuInstrument::loadProperties() { VisuWidget::loadProperties(); GET_PROPERTY(cSignalId, mProperties, mPropertiesMeta); GET_PROPERTY(cColorBackground, mProperties, mPropertiesMeta); GET_PROPERTY(cColorStatic, mProperties, mPropertiesMeta); GET_PROPERTY(cColorForeground, mProperties, mPropertiesMeta); GET_PROPERTY(cFontSize, mProperties, mPropertiesMeta); GET_PROPERTY(cFontType, mProperties, mPropertiesMeta); setup(); } void VisuInstrument::setup() { VisuWidget::setup(); mFirstRun = true; mPixmap = QPixmap(cWidth, cHeight); mPixmapStatic = QPixmap(cWidth, cHeight); setAttribute(Qt::WA_TranslucentBackground); setGeometry(cX, cY, cWidth, cHeight); } /** * @brief Instrument::signalUpdated * Method used by signal to notify instrument of change. * @param signal */ void VisuInstrument::signalUpdated(const VisuSignal* const signal) { this->mSignal = signal; render(); } void VisuInstrument::initialUpdate(const VisuSignal* const signal) { mFirstRun = true; signalUpdated(signal); } quint16 VisuInstrument::getId() { return cId; } quint16 VisuInstrument::getSignalId() { return cSignalId; } void VisuInstrument::render() { mPixmap.fill(Qt::transparent); if (mFirstRun) { mPixmapStatic.fill(Qt::transparent); QPainter painter_static(&mPixmapStatic); painter_static.setRenderHint(QPainter::Antialiasing); renderStatic(&painter_static); mFirstRun = false; } QPainter painter_dynamic(&mPixmap); painter_dynamic.setRenderHint(QPainter::Antialiasing); painter_dynamic.drawPixmap(0, 0, mPixmapStatic); renderDynamic(&painter_dynamic); update(); } void VisuInstrument::paintEvent(QPaintEvent* event) { (void)event; // supress compiler warning about unused parameter QPainter painter(this); // draw instrument painter.drawPixmap(0, 0, mPixmap); drawActiveBox(&painter); } void VisuInstrument::setFont(QPainter* painter) { QFont font; font.setPixelSize(cFontSize); font.setFamily(cFontType); painter->setFont(font); } void VisuInstrument::setPen(QPainter* painter, QColor color, int thickness) { QPen pen; pen.setColor(color); pen.setWidth(thickness); painter->setPen(pen); } void VisuInstrument::setBrush(QPainter* painter, QColor color) { painter->setBrush(color); } void VisuInstrument::clear(QPainter* painter) { painter->fillRect(0, 0, cWidth, cHeight, cColorBackground); } void VisuInstrument::connectSignals() { disconnectSignals(); const QVector<QPointer<VisuSignal>>& signalsList = VisuConfiguration::get()->getSignals(); auto itr = mPropertiesMeta.begin(); while (itr != mPropertiesMeta.end()) { VisuPropertyMeta meta = itr.value(); if (meta.type == VisuPropertyMeta::INSTSIGNAL) { int signalId = mProperties.value(itr.key()).toInt(); VisuSignal* sig = VisuConfiguration::get()->getSignal(signalId); if (sig != nullptr) { connectedSignals.append(sig); sig->connectInstrument(this); } } ++itr; } } void VisuInstrument::disconnectSignals() { std::for_each(connectedSignals.begin(), connectedSignals.end(), [this](QPointer<VisuSignal> sig){ sig->disconnectInstrument(this); } ); connectedSignals.clear(); } void VisuInstrument::initializeInstrument() { std::for_each(connectedSignals.begin(), connectedSignals.end(), [this](QPointer<VisuSignal> sig){ sig->initializeInstruments(); } ); } bool VisuInstrument::refresh(const QString& key) { VisuWidget::refresh(key); // Signal assigment changed, update signals map if (mPropertiesMeta[key].type == VisuPropertyMeta::INSTSIGNAL) { connectSignals(); } initializeInstrument(); return false; } <file_sep>/README.md # Visualization ## Introduction <img src="https://raw.githubusercontent.com/wiki/irajkovic/visualization/images/cpu_monitor.png" alt="Example of CPU monitor configuration"> Application is created as a general purpose control panel. It can communicate with sensors and control units via UDP and serial protocols. Idea behind application is generic control panel creation software flexible enough for any purpose (smart home, system monitoring, etc). Incoming data is shown via several types of virtual instrument widgets, while command widgets are used to send out commands. Image widgets are supported as well, to provid deep integration into domain of use. Each widget is highly customizable, providing different attributes to fine tune it's appearance and function. Any number of widgets can be arranged on the predefined area, forming layout of a control panel. This layout can be stored into XML file which contains a description off all widget properties, as well as signals that are monitored. Application will be runtime configured based on this XML file. This means that there are no hardcoded values and entire look&feel of the control panel, as well as it's functionality comes from user created XML file. Such XML file is called configuration. One major part of application is built in WYSIWYG configuration editor. This allows easy and efficient creation and modification of configurations. Any signal source that can send or receive UDP or serial package of given structure can be easily integrated. Application is developed with C++ and Qt, with intent of being highly portable to various devices and form factors. ## Wiki page For more information, visit github wiki page at: https://github.com/irajkovic/visualization/wiki ## Author Developed by <NAME> (<EMAIL>) <file_sep>/includes/instruments/instlinear.h #ifndef INSTLINEAR_H #define INSTLINEAR_H #include "visuinstrument.h" class InstLinear : public VisuInstrument { Q_OBJECT public: InstLinear( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuInstrument(parent, properties, metaProperties) { loadProperties(); } static const QString TAG_NAME; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); protected: virtual void renderStatic(QPainter *painter); // Renders to pixmap_static virtual void renderDynamic(QPainter *painter); // Renders to pixmap virtual bool refresh(const QString &key); private: // configuration properties quint8 cLineThickness; // Thickness of geometric primitives drawn quint8 cMajorLen; // Length, in pixels, of major division marks quint8 cMinorLen; // Length, in pixels, of minor division marks quint8 cMajorCnt; // Number of major count divisions quint8 cMinorCnt; // Number of minor count divisions quint16 cBarThickness; bool cHorizontal; // additional properties not related to configuration quint16 mBarLength; quint16 mMargin; void renderDivisions(QPainter* painter); void renderLabel(QPainter* painter, int sigCur, quint16 xOfs); void setupMargin(QPainter *painter); static const QString KEY_HORIZONTAL; static const int SPACING = 5; }; #endif // INSTLINEAR_H <file_sep>/includes/visuconfigloader.h #ifndef VISUCONFIGLOADER_H #define VISUCONFIGLOADER_H #include <QMap> #include <QXmlStreamReader> #include <QSharedPointer> #include "visupropertymeta.h" class VisuConfigLoader { public: VisuConfigLoader(); static QByteArray loadXMLFromFile(QString path); static QMap<QString, VisuPropertyMeta> parseMetaToMap(QXmlStreamReader& xmlReader, QString element); static QMap<QString, QString> parseToMap(QXmlStreamReader& xmlReader, QString element); static QMap<QString, QString> getMapFromFile(QString type, QString tag); static QMap<QString, VisuPropertyMeta> getMetaMapFromFile(QString type, QString tag); static const QString PATH; }; #endif // VISUCONFIGLOADER_H <file_sep>/sender/sine.py from sender.sender import * from sender.signal import * from sender.server import * import math from time import sleep import sys server = Server("127.0.0.1", 3334) sender = Sender(server) signal = Signal(0) max = 100 if len(sys.argv) == 3: signalId = int(sys.argv[1]) signal = Signal(signalId) max = int(sys.argv[2]) else: print "Wrong argument type. Usage: python {} <signalId>".format(sys.argv[0]) sys.exit() i = 0 max = max / 2 while True: signal.update(int(math.sin(math.radians(i))*max + max)) sender.send(signal) i=i+4 sleep(0.1) if i >= 360: i = 0 <file_sep>/src/visuconfiguration.cpp #include "visuconfiguration.h" #include <QVector> #include <QPushButton> #include <algorithm> #include <QSize> #include <functional> #include "visusignal.h" #include "visupropertyloader.h" #include "visuconfigloader.h" #include "visumisc.h" #include "exceptions/configloadexception.h" #include "instruments/instanalog.h" #include "instruments/instdigital.h" #include "instruments/instlinear.h" #include "instruments/insttimeplot.h" #include "instruments/instxyplot.h" #include "instruments/instled.h" #include "controls/ctrlbutton.h" #include "statics/staticimage.h" VisuConfiguration* VisuConfiguration::instance = nullptr; const QString VisuConfiguration::TAG_NAME = "configuration"; // These tags are not used, except for purpose of verification of XML structure. // Perhaps some kind of load hooks can be later triggered when reading these tags. const QString VisuConfiguration::TAG_VISU_CONFIG = "visu_config"; const QString VisuConfiguration::TAG_WIDGETS_PLACEHOLDER = "widgets"; const QString VisuConfiguration::TAG_SIGNALS_PLACEHOLDER = "signals"; #include "wysiwyg/visuwidgetfactory.h" VisuConfiguration* VisuConfiguration::get() { if (instance == nullptr) { instance = new VisuConfiguration(); } return instance; } VisuConfiguration* VisuConfiguration::getClean() { delete instance; instance = nullptr; return VisuConfiguration::get(); } VisuConfiguration::~VisuConfiguration() { for (VisuWidget* widget : widgetsList) { delete widget; } } void VisuConfiguration::createSignalFromToken(QXmlStreamReader& xmlReader) { QMap<QString, QString> properties = VisuConfigLoader::parseToMap(xmlReader, VisuSignal::TAG_NAME); VisuSignal* signal = new VisuSignal(properties); signalsList.push_back(signal); } QPointer<VisuWidget> VisuConfiguration::createWidgetFromToken(QXmlStreamReader& xmlReader, QWidget *parent) { QMap<QString, QString> properties = VisuConfigLoader::parseToMap(xmlReader, VisuWidget::TAG_NAME); VisuWidget* widget = VisuWidgetFactory::createWidget(parent, properties); addWidget(widget); widget->show(); return widget; } void VisuConfiguration::initializeInstruments() { for (int i=0; i<signalsList.size(); i++) { signalsList[i]->initializeInstruments(); } } void VisuConfiguration::createConfigurationFromToken(QXmlStreamReader& xmlReader) { mProperties = VisuConfigLoader::parseToMap(xmlReader, TAG_NAME); setConfigValues(); } void VisuConfiguration::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; setConfigValues(); } QMap<QString, QString>& VisuConfiguration::getProperties() { return mProperties; } void VisuConfiguration::setPropertiesMeta(QMap<QString, VisuPropertyMeta> meta) { mPropertiesMeta = meta; } QMap<QString, VisuPropertyMeta> VisuConfiguration::getPropertiesMeta() { return mPropertiesMeta; } void VisuConfiguration::setConfigValues() { GET_PROPERTY(cPort, mProperties, mPropertiesMeta); GET_PROPERTY(cWidth, mProperties, mPropertiesMeta); GET_PROPERTY(cHeight, mProperties, mPropertiesMeta); GET_PROPERTY(cColorBackground, mProperties, mPropertiesMeta); GET_PROPERTY(cName, mProperties, mPropertiesMeta); GET_PROPERTY(cConectivity, mProperties, mPropertiesMeta); GET_PROPERTY(cSerialPort, mProperties, mPropertiesMeta); GET_PROPERTY(cBaudRate, mProperties, mPropertiesMeta); GET_PROPERTY(cSerialBindToSignal, mProperties, mPropertiesMeta); GET_PROPERTY(cSerialRegex, mProperties, mPropertiesMeta); GET_PROPERTY(cSerialStartEnable, mProperties, mPropertiesMeta); GET_PROPERTY(cSerialStart, mProperties, mPropertiesMeta); GET_PROPERTY(cPullMessageEnable, mProperties, mPropertiesMeta); GET_PROPERTY(cPullMessage, mProperties, mPropertiesMeta); GET_PROPERTY(cPullPeriod, mProperties, mPropertiesMeta); } void VisuConfiguration::fromXML(QWidget *parent, const QString& xmlString) { QXmlStreamReader xmlReader(xmlString); while (xmlReader.tokenType() != QXmlStreamReader::EndDocument && xmlReader.tokenType() != QXmlStreamReader::Invalid) { if (xmlReader.tokenType() == QXmlStreamReader::StartElement) { ConfigLoadException::setContext("loading configuration"); if (xmlReader.name() == VisuSignal::TAG_NAME) { createSignalFromToken(xmlReader); } else if (xmlReader.name() == VisuWidget::TAG_NAME) { createWidgetFromToken(xmlReader, parent); } else if (xmlReader.name() == TAG_NAME) { createConfigurationFromToken(xmlReader); } else if (xmlReader.name() == TAG_VISU_CONFIG) { // No actions needed. } else if (xmlReader.name() == TAG_WIDGETS_PLACEHOLDER) { // No actions needed. } else if (xmlReader.name() == TAG_SIGNALS_PLACEHOLDER) { // No actions needed. } else { throw ConfigLoadException("Unknown XML node \"%1\"", xmlReader.name().toString()); } } xmlReader.readNext(); } initializeInstruments(); } QPointer<VisuSignal> VisuConfiguration::getSignal(quint16 signalId) { if(signalId >= signalsList.size()) { // We shouldn't throw unhandled exception here, as that would // mean that signal source can crash application if wrong // signal id is sent. qDebug("Signal id %d too large!", signalId); return nullptr; } return signalsList[signalId]; } QPointer<VisuInstrument> VisuConfiguration::getInstrument(quint16 instrument_id) { return qobject_cast<VisuInstrument*>(widgetsList[instrument_id]); } QVector<QPointer<VisuSignal> >& VisuConfiguration::getSignals() { return signalsList; } quint16 VisuConfiguration::getPort() { return cPort; } QString VisuConfiguration::getSerialPort() { return cSerialPort; } quint32 VisuConfiguration::getBaudRate() { return cBaudRate; } quint16 VisuConfiguration::getWidth() { return cWidth; } quint16 VisuConfiguration::getHeight() { return cHeight; } QColor VisuConfiguration::getBackgroundColor() { return cColorBackground; } QSize VisuConfiguration::getSize() const { return QSize(cWidth, cHeight); } QString VisuConfiguration::getName() { return cName; } quint8 VisuConfiguration::getConectivity() { return cConectivity; } bool VisuConfiguration::isSerialBindToSignal() { return cSerialBindToSignal; } QString VisuConfiguration::getSerialRegex() { return cSerialRegex; } bool VisuConfiguration::isSerialStartEnabled() { return cSerialStartEnable; } QString VisuConfiguration::getSerialStartString() { return cSerialStart; } bool VisuConfiguration::isSerialPullEnabled() { return cPullMessageEnable; } QString VisuConfiguration::getSerialPullString() { return cPullMessage; } quint32 VisuConfiguration::getSerialPullPeriod() { return cPullPeriod; } QVector<QPointer<VisuWidget> > VisuConfiguration::getWidgets() { return widgetsList; } QPointer<VisuWidget> VisuConfiguration::getWidget(int id) { if (id >= 0 && widgetsList.size() > id) { return widgetsList.at(id); } else { return nullptr; } } void VisuConfiguration::moveWidgetUp(int id) { int swapId = id + 1; int size = widgetsList.size(); while (swapId < size) { if (widgetsList[swapId] != nullptr) { std::swap(widgetsList[id], widgetsList[swapId]); widgetsList[id]->setId(id); widgetsList[swapId]->setId(swapId); break; } ++swapId; } } void VisuConfiguration::moveWidgetDown(int id) { int swapId = id - 1; while (id > 0) { if (widgetsList[swapId] != nullptr) { std::swap(widgetsList[id], widgetsList[swapId]); widgetsList[id]->setId(id); widgetsList[swapId]->setId(swapId); break; } --swapId; } } void VisuConfiguration::addWidget(QPointer<VisuWidget> widget) { int id = getFreeId((QVector<QPointer<QObject>>&)widgetsList); widget->setId(id); widgetsList[id] = widget; } void VisuConfiguration::deleteWidget(QPointer<VisuWidget> widget) { VisuInstrument* instrument; if ( (instrument = qobject_cast<VisuInstrument*>(widget)) != nullptr) { instrument->disconnectSignals(); } delete(widgetsList[widget->getId()]); } void VisuConfiguration::addSignal(QPointer<VisuSignal> signal) { int signalId = getFreeId((QVector<QPointer<QObject>>&)signalsList); signal->setId(signalId); signalsList[signalId] = signal; } int VisuConfiguration::getFreeId(QVector<QPointer<QObject>> &list) { auto it = std::find_if(list.begin(), list.end(), [](const QPointer<QObject>& ptr){return ptr == nullptr; }); int id = it - list.begin(); if (it == list.end()) { list.resize(id + 1); } return id; } void VisuConfiguration::deleteSignal(QPointer<VisuSignal> signal) { int signalId = signal->getId(); deleteSignal(signalId); } void VisuConfiguration::deleteSignal(int signalId) { // pointer will be cleared automaticaly by QPointer delete (signalsList[signalId]); } template <typename T> void VisuConfiguration::append(T* elem, QString& xml, int tabs) { if (elem != nullptr) { xml += VisuMisc::addElement(T::TAG_NAME, elem->getProperties(), tabs); } } QString VisuConfiguration::toXML() { QString xml; xml = VisuMisc::getXMLDeclaration(); xml += VisuMisc::openTag(TAG_VISU_CONFIG); // Configuration properties xml += VisuMisc::addElement(TAG_NAME, mProperties, 1); // Signals xml += VisuMisc::openTag(TAG_SIGNALS_PLACEHOLDER, 1); auto appendSignal = std::bind(append<VisuSignal>, std::placeholders::_1, std::ref(xml), 2); std::for_each(signalsList.begin(), signalsList.end(), appendSignal); xml += VisuMisc::closeTag(TAG_SIGNALS_PLACEHOLDER, 1); // Widgets xml += VisuMisc::openTag(TAG_WIDGETS_PLACEHOLDER, 1); auto appendWidget = std::bind(append<VisuWidget>, std::placeholders::_1, std::ref(xml), 2); std::for_each(widgetsList.begin(), widgetsList.end(), appendWidget); xml += VisuMisc::closeTag(TAG_WIDGETS_PLACEHOLDER, 1); xml += VisuMisc::closeTag(TAG_VISU_CONFIG); return xml; } <file_sep>/src/visumisc.cpp #include "visumisc.h" #include "visupropertyloader.h" void VisuMisc::setBackgroundColor(QWidget* widget, QColor color) { QString stylesheet = QString("background-color: %1;").arg(VisuMisc::colorToStr(color)); widget->setStyleSheet(stylesheet); } QString VisuMisc::getXMLDeclaration() { return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; } QString VisuMisc::addElement(QString tag, QMap<QString, QString> properties, int tabs) { QString xml = VisuMisc::openTag(tag, tabs); xml += VisuMisc::mapToString(properties, tabs + 1); xml += VisuMisc::closeTag(tag, tabs); return xml; } QString VisuMisc::openTag(QString tag, int tabs) { return QString("\t").repeated(tabs) + "<" + tag + ">\n"; } QString VisuMisc::closeTag(QString tag, int tabs) { return QString("\t").repeated(tabs) + "</" + tag + ">\n"; } QString VisuMisc::mapToString(QMap<QString, QString> properties, int tabs) { QString xml; QString whitespace = QString("\t").repeated(tabs); for (auto i = properties.begin(); i != properties.end(); ++i) { xml += whitespace + "<" + i.key() + ">"; xml += i.value(); xml += "</" + i.key() + ">\n"; } return xml; } QString VisuMisc::saveToFile(QFile &file, QString contents) { if ( file.open(QIODevice::WriteOnly) ) { QTextStream stream( &file ); stream << contents; file.close(); } return file.fileName(); } QPen VisuMisc::getDashedPen(QColor color, int thickness) { QPen dashed; dashed.setStyle(Qt::DashLine); dashed.setColor(color); dashed.setWidth(thickness); return dashed; } QColor VisuMisc::strToColor(const QString& str) { QStringList parts = str.split(","); if (parts.length() == 4) { return QColor( parts[0].toInt() , parts[1].toInt() , parts[2].toInt() , parts[3].toInt()); } return QColor::Invalid; } QString VisuMisc::colorToStr(const QColor& color) { QString colorStr = QString("rgba(%1, %2, %3, %4)") .arg(color.red()) .arg(color.green()) .arg(color.blue()) .arg((double)color.alpha()/255.0); return colorStr; } QImage VisuMisc::strToImage(const QString& str, const QString& format) { QByteArray base64Bytes; base64Bytes.append(str); QByteArray rawImageData; rawImageData = QByteArray::fromBase64(base64Bytes); QImage image; image.loadFromData(rawImageData, format.toStdString().c_str()); return image; } <file_sep>/includes/controls/ctrlslider.h #ifndef CTRLSLIDER_H #define CTRLSLIDER_H #include <QHBoxLayout> #include <QSlider> #include "visucontrol.h" class CtrlSlider : public VisuControl { Q_OBJECT public: explicit CtrlSlider( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuControl(parent, properties, metaProperties) { loadProperties(); setup(parent); } static const QString TAG_NAME; static const QString KEY_HORIZONTAL; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); virtual bool refresh(const QString& key); void setup(QWidget* parent); private: bool cHorizontal; quint32 cRange; QString cMessage; // styling QColor cColorBackground; QColor cColorForeground; QColor cColorBorder; quint32 cBorderRadius; quint16 cFontSize; QString cFontType; quint8 cBorderThickness; QString cCss; QSlider* mSlider; QHBoxLayout* mLayout; void setupSlider(QWidget* parent); QString generateCss(); private slots: void sendCommand(int value); }; #endif // CTRLSLIDER_H <file_sep>/includes/wysiwyg/stage.h #ifndef STAGE_H #define STAGE_H #include <QWidget> #include <QDragEnterEvent> #include <QDropEvent> #include <QPoint> #include <QSize> #include "mainwindow.h" class Stage : public QWidget { Q_OBJECT public: Stage(MainWindow* window, QWidget* parent = 0) : QWidget(parent) { setAcceptDrops(true); mMainWindow = window; } void dragEnterEvent(QDragEnterEvent *event); void dropEvent(QDropEvent *event); void paintEvent(QPaintEvent *event); QSize sizeHint() const; public slots: void activateWidget(VisuWidget*); private: MainWindow* mMainWindow; VisuWidget *cloneWidget(VisuWidget* sourceWidget); QPoint getNewWidgetPosition(QPoint eventPos, QPoint grabOffset, QSize instSize); }; #endif // STAGE_H <file_sep>/sender/sender/sender.py import signal import socket import time import math import sys import struct import os class Sender(object): def __init__(self, server): self.server = server self.sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP def getRawBytes(self, value): return struct.unpack("4b", struct.pack('>I', value)) def preparePackage(self, signal): signalIdBytes = self.getRawBytes(signal.id) signalPackageCntBytes = self.getRawBytes(signal.packageCnt) package = [ signalIdBytes[2], \ signalIdBytes[3], \ signalPackageCntBytes[2], \ signalPackageCntBytes[3], \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x05, \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x00, \ 0x00 ] # timestamp package_timestmap_ind = 4 timestamp = int(signal.timestamp * 100) for i in range(0, 8): package[package_timestmap_ind + i] = (timestamp >> ((7 - i) * 8)) & 0xFF #value value = signal.raw package_value_ind = 12 for i in range(0, 8): package[package_value_ind + i] = (value >> ((7 - i) * 8)) & 0xFF # checksum package[20] = 0x00 checksum = 0x00; for x in package: checksum ^= x package[20] = checksum message = ''.join(chr(x) for x in package) return message def send(self, signal): message = self.preparePackage(signal) self.sock.sendto(message, (self.server.ip, self.server.port)) print "Sending value {}".format(signal.raw) <file_sep>/src/controls/ctrlslider.cpp #include "ctrlslider.h" #include "visumisc.h" const QString CtrlSlider::TAG_NAME = "SLIDER"; const QString CtrlSlider::KEY_HORIZONTAL = "horizontal"; void CtrlSlider::sendCommand(int value) { QString message = QString("%1%2").arg(cMessage).arg(value); mSocket.writeDatagram( message.toStdString().c_str(), message.size(), mAddress, cActionPort); emit(widgetActivated(this)); } void CtrlSlider::setupSlider(QWidget* parent) { setGeometry(QRect(cX, cY, cWidth, cHeight)); mSlider = new QSlider(cHorizontal ? Qt::Horizontal : Qt::Vertical); mLayout->addWidget(mSlider); refresh(""); QObject::connect(mSlider, SIGNAL(valueChanged(int)), this, SLOT(sendCommand(int))); } bool CtrlSlider::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; CtrlSlider::loadProperties(); return CtrlSlider::refresh(key); } void CtrlSlider::loadProperties() { VisuControl::loadProperties(); GET_PROPERTY(cRange, mProperties, mPropertiesMeta); GET_PROPERTY(cMessage, mProperties, mPropertiesMeta); GET_PROPERTY(cCss, mProperties, mPropertiesMeta); GET_PROPERTY(cColorBackground, mProperties, mPropertiesMeta); GET_PROPERTY(cColorForeground, mProperties, mPropertiesMeta); GET_PROPERTY(cColorBorder, mProperties, mPropertiesMeta); GET_PROPERTY(cBorderRadius, mProperties, mPropertiesMeta); GET_PROPERTY(cFontSize, mProperties, mPropertiesMeta); GET_PROPERTY(cFontType, mProperties, mPropertiesMeta); GET_PROPERTY(cBorderThickness, mProperties, mPropertiesMeta); GET_PROPERTY(cHorizontal, mProperties, mPropertiesMeta); } void CtrlSlider::setup(QWidget *parent) { mTagName = TAG_NAME; mLayout = new QHBoxLayout(); mLayout->setContentsMargins(0,0,0,0); setLayout(mLayout); setupSlider(parent); show(); } QString CtrlSlider::generateCss() { QString css; css += QString("background-color: %1;").arg(VisuMisc::colorToStr(cColorBackground)); css += QString("color: %1;").arg(VisuMisc::colorToStr(cColorForeground)); css += QString("border: %1px solid %2;").arg(cBorderThickness).arg(VisuMisc::colorToStr(cColorBorder)); css += QString("border-radius: %1;").arg(cBorderRadius); css += QString("font-family: %1;").arg(cFontType); css += QString("font-size: %1px;").arg(cFontSize); css += cCss; return css; } bool CtrlSlider::refresh(const QString& key) { bool changed = false; if (key == KEY_HORIZONTAL) { mSlider->setOrientation(cHorizontal ? Qt::Horizontal : Qt::Vertical); std::swap(cWidth, cHeight); std::swap(mProperties[KEY_WIDTH], mProperties[KEY_HEIGHT]); changed = true; } mSlider->setMinimum(0); mSlider->setMaximum(cRange); mSlider->setMinimumSize(cWidth, cHeight); mSlider->setMinimumSize(cWidth, cHeight); mSlider->setStyleSheet(generateCss()); VisuWidget::refresh(key); VisuWidget::setup(); return changed; } <file_sep>/includes/visucontrol.h #ifndef VISUCONTROL_H #define VISUCONTROL_H #include <QMap> #include <QHostAddress> #include <QUdpSocket> #include "visuwidget.h" class VisuControl : public VisuWidget { Q_OBJECT public: explicit VisuControl(QWidget* parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuWidget(parent, properties, metaProperties) { mAddress = QHostAddress(cActionIp); } virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); virtual bool refresh(const QString& key) { (void)key; return false; } protected: QString cActionIp; quint16 cActionPort; QHostAddress mAddress; QUdpSocket mSocket; }; #endif // VISUCONTROL_H <file_sep>/src/visudatagram.cpp #include "visudatagram.h" bool VisuDatagram::checksumOk() { quint8* ptr = (quint8*)this; quint8* end = &(checksum); quint8 sum = 0x0; while (ptr != end) { sum ^= *ptr; ++ptr; } return sum == checksum; } <file_sep>/sender/cpu_usage.py from sender.sender import * from sender.signal import * from sender.server import * import sys import psutil server = Server("127.0.0.1", 3334) sender = Sender(server) signal = Signal(0) if len(sys.argv) == 2: signalId = int(sys.argv[1]) signal = Signal(signalId) else: print "Wrong argument type. Usage: python {} <signalId>".format(sys.argv[0]) sys.exit() while True: cpuUsage = int(psutil.cpu_percent(interval=0.1)) signal.update(cpuUsage) sender.send(signal) <file_sep>/src/visuappinfo.cpp #include "visuappinfo.h" VisuAppInfo* VisuAppInfo::instance = nullptr; VisuAppInfo* VisuAppInfo::getInstance() { if (instance == nullptr) { instance = new VisuAppInfo(); instance->inEditorMode = false; instance->configWrong = false; instance->server = nullptr; } return instance; } bool VisuAppInfo::isInEditorMode() { return getInstance()->inEditorMode; } void VisuAppInfo::setInEditorMode(bool mode) { getInstance()->inEditorMode = mode; } bool VisuAppInfo::isConfigWrong() { return getInstance()->configWrong; } void VisuAppInfo::setConfigWrong(bool wrong) { getInstance()->configWrong = wrong; } void VisuAppInfo::setConfigWrong(const QString& issue) { getInstance()->configWrong = true; getInstance()->configIssues.append(issue); } const QStringList& VisuAppInfo::getConfigIssues() { return getInstance()->configIssues; } int VisuAppInfo::argsSize() { return getInstance()->cliArgs.size(); } const QString& VisuAppInfo::getCLIArg(CLI_Args arg) { return getInstance()->cliArgs[(int)arg]; } void VisuAppInfo::setCLIArgs(int argc, char* argv[]) { QStringList& args = getInstance()->cliArgs; for (int i=0 ; i<argc ; ++i) { args.append(QString(argv[i])); } } void VisuAppInfo::setServer(VisuServer *srv) { getInstance()->server = srv; } VisuServer* VisuAppInfo::getServer() { return getInstance()->server; } <file_sep>/includes/mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMenu> #include <QTableWidget> #include <QMainWindow> #include <QPointer> #include <QTemporaryFile> #include <QScrollArea> #include "visusignal.h" #include "visuconfiguration.h" #include "wysiwyg/editsignal.h" class Stage; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); void setupToolbarWidgets(QPointer<QWidget> toolbar); QPointer<VisuSignal> getSignal(); void resetActiveWidget(); void setActiveWidget(QPointer<VisuWidget> widget); void setChanged(); bool dragOriginIsToolbar(QWidget *widget); void keyPressEvent( QKeyEvent *event ); QPointer<VisuConfiguration> getConfiguration(); QPointer<VisuWidget> getActiveWidget(); void updateMenuWidgetsList(); void closeEvent(QCloseEvent* event); ~MainWindow(); public slots: void cellUpdated(int row, int col); void addSignal(QPointer<VisuSignal> signal, bool isNewSignal); void deleteSignal(); void propertyChange(int parameter = 0); private: Ui::MainWindow *ui; QPointer<QWidget> mWindow; QPointer<QWidget> mToolbar; QPointer<Stage> mStage; QPointer<QScrollArea> mScrollArea; QPointer<QTableWidget> mPropertiesTable; QPointer<VisuWidget> mActiveWidget; QPointer<VisuConfiguration> mConfiguration; QPointer<EditSignal> editSignalWindow; QPointer<QMenu> mSignalsListMenu; QPointer<QMenu> mWidgetsListMenu; QTemporaryFile mTmpConfigFile; QString mConfigPath; QPointer<QAction> mSave; QSize mWindowSize; bool mConfigChanged; void resizeEvent(QResizeEvent * event); void setupMenu(); void setupLayouts(); void updateMenuSignalList(); void reloadConfiguration(); void loadConfigurationFromFile(const QString& configPath); QString configurationToXML(); void markActiveInstrumentMenuItem(QPointer<VisuWidget> oldItem, QPointer<VisuWidget> newItem); VisuWidget* actionDataToWidget(QAction* action); void refreshEditorGui(QString key); bool confirmLoseChanges(); void showConfigurationWarning(); void deleteActiveWidget(); static const QString INITIAL_EDITOR_CONFIG; static const int LAYOUT_TOOLBAR_HEIGHT = 170; static const int LAYOUT_PROPERTIES_WIDTH = 300; static const int LAYOUT_MARGIN = 50; static const int LAYOUT_QSCROLLAREA_MARGIN = 5; // Margin between child widget and QScrollArea private slots: void openConfiguration(); void saveConfiguration(); void saveAsConfiguration(); void saveToImage(); void openSignalsEditor(); void openConfigurationEditor(); void updateConfig(); void runConfiguration(); void openImageAdder(); void activateWidgetFromMenu(); void moveWidgetUp(); void moveWidgetDown(); }; #endif // MAINWINDOW_H <file_sep>/src/wysiwyg/editsignal.cpp #include "wysiwyg/editsignal.h" #include "wysiwyg/visupropertieshelper.h" #include "visusignal.h" void EditSignal::setup(QPointer<VisuSignal> visuSignal) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(tr("Signal parameters")); QLayout* vlayout = new QVBoxLayout(); setLayout(vlayout); mSignal = visuSignal; mTable = new QTableWidget() ; if (mSignal == nullptr) { QMap<QString, QString> properties = VisuConfigLoader::getMapFromFile( VisuSignal::TAG_NAME, VisuSignal::TAG_NAME); mSignal = new VisuSignal(properties); mNewSignal = true; } else { mNewSignal = false; } VisuPropertiesHelper::updateTable(mTable, mSignal->getProperties(), mSignal->getPropertiesMeta(), std::make_pair(this, SLOT(propertyChange()))); mTable->setMaximumWidth(mWidth); mTable->verticalHeader()->hide(); mTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); vlayout->addWidget(mTable); QWidget* buttons = new QWidget(); QLayout* buttonsLayout = new QHBoxLayout(); buttons->setLayout(buttonsLayout); QPushButton* saveButton = new QPushButton(tr("&Save")); buttonsLayout->addWidget(saveButton); QPushButton* cancelButton = new QPushButton(tr("&Cancel")); buttonsLayout->addWidget(cancelButton); buttons->setMaximumHeight(saveButton->height()); vlayout->addWidget(buttons); show(); connect(cancelButton, SIGNAL(clicked()), this, SLOT(close())); connect(saveButton, SIGNAL(clicked()), this, SLOT(addSignal())); } void EditSignal::addSignal() { mSignal->initializeInstruments(); emit(signalAdded(mSignal,mNewSignal)); close(); } void EditSignal::cellUpdated(int row, int col) { (void)col; QString key = VisuPropertiesHelper::getKeyString(mTable, row); QString value = VisuPropertiesHelper::getValueString(mTable, row); mSignal->updateProperty(key, value); VisuPropertiesHelper::updateWidgetsState(mTable, mSignal->getProperties(), mSignal->getPropertiesMeta()); } void EditSignal::propertyChange() { int row = VisuPropertiesHelper::updateWidgetProperty(sender(), this); cellUpdated(row, 1); } <file_sep>/sender/single.py from sender.sender import * from sender.signal import * from sender.server import * import sys if len(sys.argv) == 3: signalId = int(sys.argv[1]) signalRaw = int(sys.argv[2]) signal = Signal(signalId) server = Server("127.0.0.1", 3334) sender = Sender(server) signal.update(signalRaw) sender.send(signal) else: print "Wrong argument type. Usage: python {} <signalId> <signalRaw>".format(sys.argv[0]) <file_sep>/test/unit-tests/tst_instanalog.cpp #include <QString> #include <QtTest> #include "instruments/instanalog.h" class TestInstAnalog : public QObject { Q_OBJECT public: TestInstAnalog(); private Q_SLOTS: void testCase1(); }; TestInstAnalog::TestInstAnalog() { } void TestInstAnalog::testCase1() { QVERIFY2(true, "Failure"); } QTEST_APPLESS_MAIN(InstAnalog) #include "tst_instanalog.moc" <file_sep>/src/main.cpp #include "mainwindow.h" #include <QApplication> #include <QMessageBox> #include "visuappinfo.h" #include "visuserver.h" #include "visuapplication.h" #include "exceptions/configloadexception.h" #define DEFAULT_CONFIG "configs/default.xml" void showMessageBox(QString message) { QMessageBox::warning( NULL, "Error", message); } int main(int argc, char *argv[]) { QApplication a(argc, argv); VisuAppInfo::setCLIArgs(argc, argv); try { if (argc == 1) { VisuAppInfo::setInEditorMode(true); new MainWindow(); } else { QString configPath = VisuAppInfo::getCLIArg(VisuAppInfo::CLI_Args::CONFIG_PATH); VisuApplication *application = new VisuApplication(configPath); application->show(); application->run(); } } catch(ConfigLoadException e) { showMessageBox(e.what()); return 1; } catch(...) { showMessageBox("Unknown exception!"); return 1; } return a.exec(); } <file_sep>/src/visuwidget.cpp #include "visuwidget.h" #include "visumisc.h" #include <QMouseEvent> #include <QApplication> #include <QDrag> #include <QMimeData> #include <QStyleOption> #include <QPainter> const QString VisuWidget::OBJECT_NAME = "VisuWidget"; const QString VisuWidget::TAG_NAME = "widget"; const QString VisuWidget::KEY_ID = "id"; const QString VisuWidget::KEY_WIDTH = "width"; const QString VisuWidget::KEY_HEIGHT = "height"; const QString VisuWidget::KEY_X = "x"; const QString VisuWidget::KEY_Y = "y"; const QString VisuWidget::KEY_NAME = "name"; const QString VisuWidget::KEY_TYPE = "type"; QPoint VisuWidget::getRelativeOffset() { return mDragStartRelativePosition; } void VisuWidget::mousePressEvent(QMouseEvent * event) { if (event->button() == Qt::LeftButton && geometry().contains(event->pos())) { mDragStartPosition = event->pos(); } else if (event->button() == Qt::RightButton) { emit(widgetContextMenu(this)); } emit(widgetActivated(this)); } void VisuWidget::mouseReleaseEvent(QMouseEvent* event) { (void)event; } void VisuWidget::mouseDoubleClickEvent(QMouseEvent* event) { (void)event; emit(widgetActivated(this)); } void VisuWidget::mouseMoveEvent(QMouseEvent *event) { if (!(event->buttons() & Qt::LeftButton)) { return; } if ((event->pos() - mDragStartPosition).manhattanLength() < QApplication::startDragDistance()) { return; } QDrag *drag = new QDrag(this); drag->setHotSpot(event->pos()); mDragStartRelativePosition = event->pos(); drag->setPixmap(grab()); QMimeData *mimeData = new QMimeData; mimeData->setText(mTagName); drag->setMimeData(mimeData); drag->exec(Qt::CopyAction | Qt::MoveAction); } void VisuWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); QStyleOption option; option.initFrom(this); style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this); } void VisuWidget::drawActiveBox(QPainter* painter) { if (mActive) { QPen pen; pen.setColor(Qt::GlobalColor::black); pen.setWidth(4); painter->setPen(pen); painter->drawRect(0, 0, cWidth, cHeight); painter->setPen(VisuMisc::getDashedPen(Qt::GlobalColor::white, 4)); painter->drawRect(0, 0, cWidth, cHeight); } } bool VisuWidget::updateProperties(const QString& key, const QString& value) { mProperties[key] = value; VisuWidget::loadProperties(); return VisuWidget::refresh(key); } void VisuWidget::loadProperties() { ConfigLoadException::setInstrumentLoadContext(mProperties); GET_PROPERTY(cId, mProperties, mPropertiesMeta); GET_PROPERTY(cName, mProperties, mPropertiesMeta); GET_PROPERTY(cX, mProperties, mPropertiesMeta); GET_PROPERTY(cY, mProperties, mPropertiesMeta); GET_PROPERTY(cWidth, mProperties, mPropertiesMeta); GET_PROPERTY(cHeight, mProperties, mPropertiesMeta); setup(); } void VisuWidget::setup() { mSize = QSize(cWidth, cHeight); setMinimumSize(mSize); setMaximumSize(mSize); } quint16 VisuWidget::getId() const { return cId; } void VisuWidget::setId(quint16 id) { cId = id; mProperties[VisuWidget::KEY_ID] = QString("%1").arg(id); } QMap<QString, QString>& VisuWidget::getProperties() { return mProperties; } void VisuWidget::setPropertiesMeta(QMap<QString, VisuPropertyMeta> meta) { mPropertiesMeta = meta; } QMap<QString, VisuPropertyMeta> VisuWidget::getPropertiesMeta() { return mPropertiesMeta; } QString VisuWidget::getName() { return cName; } void VisuWidget::setName(QString name) { cName = name; } void VisuWidget::setPosition(QPoint position) { cX = position.x(); cY = position.y(); setGeometry(cX, cY, cWidth, cHeight); mProperties[VisuWidget::KEY_X] = QString("%1").arg(cX); mProperties[VisuWidget::KEY_Y] = QString("%1").arg(cY); } const QSize VisuWidget::sizeHint() { return mSize; } QString VisuWidget::getType() { return mTagName; } void VisuWidget::setActive(bool active) { mActive = active; update(); } bool VisuWidget::refresh(const QString& key) { QPoint position = pos(); if (key == VisuWidget::KEY_X) { position.setX(cX); } else if (key == VisuWidget::KEY_Y) { position.setY(cY); } setPosition(position); return false; } <file_sep>/includes/instruments/instled.h #ifndef INSTLED_H #define INSTLED_H #include "visuinstrument.h" class InstLED : public VisuInstrument { Q_OBJECT public: enum class LedCondition { BETWEEN = 0, LESS_THAN = 1, LESS_EQUAL = 2, MORE_EQUAL = 3, MORE_THAN = 4 }; explicit InstLED( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuInstrument(parent, properties, metaProperties) { loadProperties(); } static const QString TAG_NAME; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); private: // configuration properties quint8 cRadius; double cVal1; double cVal2; LedCondition cCondition; QColor cColorOn; QColor cColorOff; int cImageOn; int cImageOff; quint8 cShowSignalName; quint16 cCenterH; // aux properties double mLastValX; double mLastValY; double mCenterX; double mCenterY; protected: virtual void renderStatic(QPainter *painter); // Renders to pixmap_static virtual void renderDynamic(QPainter *painter); // Renders to pixmap }; #endif // INSTLED_H <file_sep>/includes/wysiwyg/visupropertieshelper.h #ifndef VISUPROPERTIESHELPER_H #define VISUPROPERTIESHELPER_H #include <QPalette> #include <QPushButton> #include <QColorDialog> #include <QTextStream> #include <QComboBox> #include <QLineEdit> #include <QTableWidget> #include "visupropertymeta.h" #include "visusignal.h" #include <QSharedPointer> #include <QSpinBox> #include <QSlider> #include <QLabel> #include <QCheckBox> class VisuPropertiesHelper { public: VisuPropertiesHelper(); static void updateTable(QTableWidget* table, const QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties, std::pair<QWidget*, const char*> object); static void setupTableWidget( QTableWidget* table, std::pair<QWidget*, const char*> widget, std::pair<QWidget*, const char*> parent, QString key, VisuPropertyMeta::Type type, int row); static int updateWidgetProperty(QObject* sender, QWidget* parent); static void updateWidgetsState(QTableWidget* table, const QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& propertiesMeta); static QString getValueString(QTableWidget *table, int row); static QString getKeyString(QTableWidget* table, int row); static double sliderToDouble(int slider); static int doubleToSlider(double value); static std::pair<QComboBox*, const char*> setupEnumWidget(VisuPropertyMeta meta, QString value); static std::pair<QComboBox*, const char*> setupFontWidget(VisuPropertyMeta meta, QString value); static std::pair<QCheckBox*, const char*> setupBoolWidget(VisuPropertyMeta meta, QString value); static std::pair<QComboBox*, const char*> setupSignalsWidget(VisuPropertyMeta meta, QString value); static std::pair<QComboBox*, const char*> setupImagesWidget(VisuPropertyMeta meta, QString value); static std::pair<QComboBox*, const char*> setupSerialWidget(VisuPropertyMeta meta, QString value); static std::pair<QComboBox*, const char*> setupSignalPlaceholderWidget(VisuPropertyMeta meta, QString value); static std::pair<QPushButton*, const char*> setupColorWidget(VisuPropertyMeta meta, QString value); static std::pair<QSpinBox*, const char*> setupIntWidget(VisuPropertyMeta meta, QString value); static std::pair<QSlider*, const char*> setupSliderWidget(VisuPropertyMeta meta, QString value); static std::pair<QLineEdit*, const char*> setupDefaultWidget(VisuPropertyMeta meta, QString value); static std::pair<QLabel*, const char*> setupReadOnlyWidget(VisuPropertyMeta meta, QString value); static std::pair<QWidget*, const char*> controlFactory(VisuPropertyMeta meta, QString value); static const int SLIDER_FACTOR = 100; static const int COLUMN_PROPERTY = 0; static const int COLUMN_VALUE = 1; static const char* PROP_COLOR; static const char* PROP_ROW; static const char* PROP_KEY; static const char* PROP_TYPE; }; #endif // VISUPROPERTIESHELPER_H <file_sep>/includes/visupropertyloader.h #ifndef VISU_HELPER_H #define VISU_HELPER_H #include "exceptions/configloadexception.h" #include <QColor> #include <QImage> #include "visupropertymeta.h" #define GET_PROPERTY(KEY, MAP, METAMAP) \ VisuPropertyLoader::set( KEY, \ VisuPropertyLoader::transformKey(#KEY),\ MAP, \ METAMAP) namespace VisuPropertyLoader { QString transformKey(const QString& key); void checkIfKeyExists(QString key, QMap<QString, QString> properties); void handleMissingKey(const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties); // handles all integer numeric types template <typename T> void set( T& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties) { handleMissingKey(key, properties, metaProperties); property = (T)properties[key].toLongLong(); } // specializations below void set( double& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties); void set( QString& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties); void set( QColor& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties); void set( QImage& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties); void set( bool& property, const QString& key, QMap<QString, QString>& properties, const QMap<QString, VisuPropertyMeta>& metaProperties); } #endif // VISU_HELPER_H <file_sep>/includes/exceptions/configloadexception.h #ifndef FILENOTFOUNDEXCEPTION_H #define FILENOTFOUNDEXCEPTION_H #include <exception> #include <QString> #include <QMap> class ConfigLoadException : public std::exception { private: static QString context; QString message; public: ConfigLoadException(QString desc, QString arg = "") { message = arg == "" ? QString(desc) : QString(desc).arg(arg); if (!ConfigLoadException::context.isEmpty()) { message += ", when " + ConfigLoadException::context + "."; } } QString getMessage() { return message; } virtual const char* what() const throw() { return message.toLatin1().data(); } static void setContext(QString context) { ConfigLoadException::context = context; } static void setInstrumentLoadContext(QMap<QString, QString> properties) { int id = properties.contains("id") ? properties["id"].toInt() : -1; QString name = properties.contains("name") ? properties["name"] : QString("Unknown"); ConfigLoadException::context = QString("loading %1 widget (id: %2)") .arg(name).arg(id); } static QString getInstrumentLoadContext() { return ConfigLoadException::context; } ~ConfigLoadException() throw() { } }; #endif // FILENOTFOUNDEXCEPTION_H <file_sep>/src/visucontrol.cpp #include "visucontrol.h" bool VisuControl::updateProperties(const QString &key, const QString &value) { mProperties[key] = value; VisuControl::loadProperties(); return VisuControl::refresh(key); } void VisuControl::loadProperties() { VisuWidget::loadProperties(); GET_PROPERTY(cActionIp, mProperties, mPropertiesMeta); GET_PROPERTY(cActionPort, mProperties, mPropertiesMeta); } <file_sep>/includes/instruments/instxyplot.h #ifndef INSTXYPLOT_H #define INSTXYPLOT_H #include "visuinstrument.h" class InstXYPlot : public VisuInstrument { Q_OBJECT public: explicit InstXYPlot( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuInstrument(parent, properties, metaProperties) { loadProperties(); mSignalX = nullptr; mSignalY = nullptr; } static const QString TAG_NAME; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); static const int SIGNAL_FIRST = 0; static const int SIGNAL_SECOND = 1; static const int MARGIN = 2; private: // configuration properties quint16 cSignalIdY; quint16 cBallSize; quint16 cMajorCntX; quint16 cMajorCntY; quint16 cMajorLenX; quint16 cMajorLenY; quint16 cPadding; quint8 cDecimals; bool cReverseX; bool cReverseY; // aux properties double mLastValX; double mLastValY; double mCenterX; double mCenterY; const VisuSignal *mSignalX; const VisuSignal *mSignalY; void renderSingleAxis(QPainter* painter, int sigInd, int divisions, int length); void renderAxis(QPainter* painter); void renderBall(QPainter* painter); protected: virtual void renderStatic(QPainter *painter); // Renders to pixmap_static virtual void renderDynamic(QPainter *painter); // Renders to pixmap }; #endif // INSTXYPLOT_H <file_sep>/src/visupropertymeta.cpp #include "visupropertymeta.h" const QString VisuPropertyMeta::KEY_MIN = "min"; const QString VisuPropertyMeta::KEY_MAX = "max"; const QString VisuPropertyMeta::KEY_TYPE = "type"; const QString VisuPropertyMeta::KEY_EXTRA = "extra"; const QString VisuPropertyMeta::KEY_LABEL = "label"; const QString VisuPropertyMeta::KEY_DEPENDS = "depends"; const QString VisuPropertyMeta::KEY_DEPSCRIPTION = "description"; const QString VisuPropertyMeta::DELIMITER = ","; #include <QtCore> const char* VisuPropertyMeta::TYPES_MAP[] = { "", "enum", "color", "signal", "read_only", "int", "float", "slider", "bool", "font", "image", "serial", "serial_placeholder", "hidden" }; QStringList VisuPropertyMeta::getEnumOptions() { return extra.split(VisuPropertyMeta::DELIMITER); } bool VisuPropertyMeta::isEnabled(const QMap<QString, QString>& properties) const { bool ret = true; int pos; if ((pos = depends.indexOf("==")) != -1) { ret = properties[depends.mid(0, pos)].toInt() == depends.mid(pos + 2).toInt(); } else if ((pos = depends.indexOf("!=")) != -1) { ret = properties[depends.mid(0, pos)].toInt() != depends.mid(pos + 2).toInt(); } else if ((pos = depends.indexOf('>')) != -1) { ret = properties[depends.mid(0, pos)].toInt() > depends.mid(pos + 1).toInt(); } if ((pos = depends.indexOf('<')) != -1) { ret = properties[depends.mid(0, pos)].toInt() < depends.mid(pos + 1).toInt(); } return ret; } QString VisuPropertyMeta::stringFromType(VisuPropertyMeta::Type type) { return VisuPropertyMeta::TYPES_MAP[type]; } VisuPropertyMeta::Type VisuPropertyMeta::typeFromString(QString typeStr) { VisuPropertyMeta::Type ret = VisuPropertyMeta::DEFAULT; const char** const begin = std::begin(VisuPropertyMeta::TYPES_MAP); const char** const end = std::end(VisuPropertyMeta::TYPES_MAP); const char** it = std::find_if( begin, end, [&typeStr](const char* ptr) { return typeStr == ptr; } ); if (it != end) { ret = (VisuPropertyMeta::Type)(it - begin); } return ret; } <file_sep>/src/wysiwyg/visuwidgetfactory.cpp #include "wysiwyg/visuwidgetfactory.h" #include "visusignal.h" #include "mainwindow.h" #include "instled.h" #include "insttimeplot.h" #include "instlinear.h" #include "instdigital.h" #include "instanalog.h" #include "instxyplot.h" #include "ctrlbutton.h" #include "ctrlslider.h" #include "visuconfigloader.h" VisuWidget* VisuWidgetFactory::createWidget(QWidget* parent, QString type) { QMap<QString, QString> properties = VisuConfigLoader::getMapFromFile(type, VisuWidget::TAG_NAME); return VisuWidgetFactory::createWidget(parent, properties); } VisuWidget* VisuWidgetFactory::createWidget(QWidget* parent, QMap<QString, QString> properties) { QString type = properties[VisuWidget::KEY_TYPE]; QMap<QString, VisuPropertyMeta> metaProperties = VisuConfigLoader::getMetaMapFromFile(type, VisuWidget::TAG_NAME); VisuWidget* widget = nullptr; if (type == InstAnalog::TAG_NAME) { widget = new InstAnalog(parent, properties, metaProperties); } else if (type == InstDigital::TAG_NAME) { widget = new InstDigital(parent, properties, metaProperties); } else if (type == InstLinear::TAG_NAME) { widget = new InstLinear(parent, properties, metaProperties); } else if (type == InstTimePlot::TAG_NAME) { widget = new InstTimePlot(parent, properties, metaProperties); } else if (type == InstLED::TAG_NAME) { widget = new InstLED(parent, properties, metaProperties); } else if (type == InstXYPlot::TAG_NAME) { widget = new InstXYPlot(parent, properties, metaProperties); } else if (type == CtrlButton::TAG_NAME) { widget = new CtrlButton(parent, properties, metaProperties); } else if (type == CtrlSlider::TAG_NAME) { widget = new CtrlSlider(parent, properties, metaProperties); } else if (type == StaticImage::TAG_NAME) { widget = new StaticImage(parent, properties, metaProperties); } else { ; // Do nothing } if (widget != nullptr) { widget->setPropertiesMeta(metaProperties); VisuInstrument* visuWidget = qobject_cast<VisuInstrument*>(widget); if (visuWidget != nullptr) { visuWidget->connectSignals(); } } return widget; } <file_sep>/includes/instruments/insttimeplot.h #ifndef INSTTIMEPLOT_H #define INSTTIMEPLOT_H #include "visuinstrument.h" #include <QTime> class InstTimePlot : public VisuInstrument { Q_OBJECT public: explicit InstTimePlot( QWidget *parent, QMap<QString, QString> properties, QMap<QString, VisuPropertyMeta> metaProperties) : VisuInstrument(parent, properties, metaProperties) { loadProperties(); mGraphPainter = nullptr; } static const QString TAG_NAME; virtual bool updateProperties(const QString &key, const QString &value); void loadProperties(); private: // configuration properties quint8 cLineThickness; quint8 cStaticThickness; quint8 cMarkerThickness; quint8 cMajorLen; quint8 cMinorLen; quint8 cMajorCnt; quint8 cMinorCnt; quint8 cDecimals; QString cDivisionFormat; QString cMasterTimeFormat; quint64 cTicksInSecond; quint64 cTimespan; // total time quint64 cMarkerDt; // time between markers QColor cColorGraphBackground; // other properties quint16 mPlotStartX; quint16 mPlotStartY; quint16 mPlotEndX; quint16 mPlotEndY; quint16 mPlotRangeX; quint16 mPlotRangeY; quint64 mLastUpdateTime; quint64 mLastMarkerTime; double mLastUpdateX; double mLastUpdateY; double mNewUpdateX; double mNewUpdateY; QRect mTimestampRect; QPixmap mGraphPixmap; // pixmap to contain graph QPainter* mGraphPainter; quint16 mMargin; quint16 mMaxLabelWidth; double mSigStep; static const int PADDING = 5; //px int getFontHeight(); quint16 getLabelMaxWidth(QPainter* painter); void renderLabelsAndMajors(QPainter* painter); QString getLabel(double value); QString getDisplayTime(int ticks, QString format); void renderLabel(QPainter* painter, double sigCur, qint32 yPos); void renderMarker(QPainter* painter, quint64 timestamp); bool shouldRenderMarker(quint64 timestamp); void renderTimeLabel(QPainter* painter); void renderGraphSegment(QPainter* painter); void resetPlotToStart(); bool noSpaceLeftOnRight(); void init(QPainter* painter); void setupGraphObjects(); void renderGraphAreaBackground(QPainter* painter); void renderSignalName(QPainter* painter); void setupPainter(QPainter* painter); double getMarkerX(quint64 timestamp); void calculateNewGraphPoint(quint64 timestamp); void updateLastValues(quint64 timestamp); protected: virtual void renderStatic(QPainter *painter); // Renders to pixmap_static virtual void renderDynamic(QPainter *painter); // Renders to pixmap }; #endif // INSTTIMEPLOT_H
d63c0ac5915151e98a12287598a707b3a229b189
[ "Markdown", "INI", "Python", "C", "C++" ]
67
C++
lzhice/visualization
568f110f221c6c4e081b07016a0499e28176cf21
efdb9597d7dc8f3ab90b852cf330a9dd4741e644
refs/heads/master
<file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "bytes" "encoding/json" "io" "testing" "github.com/pborman/uuid" "github.com/Sirupsen/logrus" ) func TestLoggerFactoryGetLogger(t *testing.T) { // WARNING: This test mucks with the default global logger. So it must be run serially. var originalWriter io.Writer = logrus.StandardLogger().Out var originalFormatter logrus.Formatter = logrus.StandardLogger().Formatter // Create a formatter that includes the logger name var formatter *Formatter = NewFormatter() formatter.SetInjectContextLogger(true) // Create a logrus logger to a buffer var buffer *bytes.Buffer = new(bytes.Buffer) logrus.SetOutput(buffer) logrus.SetFormatter(formatter) // Obtain a named logger for the default global logrus logger var expectedLoggerName string = "my_logger_name-" + uuid.New() var expectedMessage string = "Hello World-" + uuid.New() var logger *Logger = GetLogger(expectedLoggerName) logger.InfoBuilder().SetMessage(expectedMessage).Log() // Unmarshal the buffer and interrogate the results for the logger name and message unmarshallAndIterrogate(t, buffer, expectedLoggerName, expectedMessage) // Restore the original writer on the default global logger logrus.SetOutput(originalWriter) logrus.SetFormatter(originalFormatter) } func TestLoggerFactoryGetLoggerForLogger(t *testing.T) { t.Parallel() // Create a formatter that includes the logger name var formatter *Formatter = NewFormatter() formatter.SetInjectContextLogger(true) // Create a logrus logger to a buffer var buffer *bytes.Buffer = new(bytes.Buffer) var logrusLogger *logrus.Logger = &logrus.Logger{ Out: buffer, Formatter: formatter, Level: logrus.InfoLevel, } // Obtain a named logger for the custom logrus logger var expectedLoggerName string = "my_logger_name-" + uuid.New() var expectedMessage string = "Hello World-" + uuid.New() var logger *Logger = GetLoggerForLogger(expectedLoggerName, logrusLogger) logger.InfoBuilder().SetMessage(expectedMessage).Log() // Unmarshal the buffer and interrogate the results for the logger name and message unmarshallAndIterrogate(t, buffer, expectedLoggerName, expectedMessage) } func unmarshallAndIterrogate(t *testing.T, b *bytes.Buffer, l string, m string) { var err error var rootNode map[string]interface{} if err = json.Unmarshal(b.Bytes(), &rootNode); err != nil { t.Errorf("Unmarshal failed because %v in buffer %v", err, b) return } if node, ok := rootNode["data"].(map[string]interface{}); ok { if value, ok := node["message"].(string); ok { if value != m { t.Errorf("Expected message not found; message=%v", node) } } else { t.Errorf("Message node not found; buffer=%v", b) } } else { t.Errorf("Data node not found; buffer=%v", b) } if node, ok := rootNode["context"].(map[string]interface{}); ok { if value, ok := node["logger"].(string); ok { if value != l { t.Errorf("Expected logger name not found; message=%v", node) } } else { t.Errorf("Logger node not found; buffer=%v", b) } } else { t.Errorf("Context node not found; buffer=%v", b) } }<file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "github.com/Sirupsen/logrus" ) var ( _ LogBuilder = (*DefaultLogBuilder)(nil) ) // DefaultLogBuilder is the default LogBuilder implementation that satisfies the LogBuilder contract. type DefaultLogBuilder struct { logger *logrus.Logger level logrus.Level event string loggerName string message string err error data map[string]interface{} context map[string]interface{} } func NewDefaultLogBuilder(l *logrus.Logger, v logrus.Level, n string) *DefaultLogBuilder { return &DefaultLogBuilder{ logger: l, level: v, loggerName: n, data: make(map[string]interface{}), context: make(map[string]interface{})} } func (dlb *DefaultLogBuilder) SetEvent(event string) LogBuilder { dlb.event = event return dlb } func (dlb *DefaultLogBuilder) SetMessage(message string) LogBuilder { dlb.message = message return dlb } func (dlb *DefaultLogBuilder) SetError(err error) LogBuilder { dlb.err = err return dlb } func (dlb *DefaultLogBuilder) AddData(key string, value interface{}) LogBuilder { dlb.data[key] = value return dlb } func (dlb *DefaultLogBuilder) AddContext(key string, value interface{}) LogBuilder { dlb.context[key] = value return dlb } func (dlb *DefaultLogBuilder) Log() { var entry *logrus.Entry = MarkerMaps.Encode( dlb.logger, dlb.event, dlb.loggerName, dlb.data, dlb.context, dlb.err, ) output(entry, dlb.message, dlb.logger, dlb.level) } func output(e *logrus.Entry, m string, l *logrus.Logger, v logrus.Level) { switch v { default: e.Info(m) case logrus.DebugLevel: e.Debug(m) case logrus.InfoLevel: e.Info(m) case logrus.WarnLevel: e.Warn(m) case logrus.ErrorLevel: e.Error(m) case logrus.FatalLevel: e.Fatal(m) case logrus.PanicLevel: e.Panic(m) } }<file_sep>package main import ( "errors" "os" "github.com/pborman/uuid" "github.com/Sirupsen/logrus" "github.com/vjkoskela/gosteno" "time" "fmt" ) // Execute this using the command: ./performance > /dev/null // // The result is a single line of output to standard error with the elapsed seconds. func main() { // Configure logrus logrus.SetOutput(os.Stdout) logrus.SetFormatter(new(gosteno.Formatter)) logrus.SetLevel(logrus.DebugLevel) // Create steno logger var logger *gosteno.Logger = gosteno.GetLogger("performance.main") // Precreate output data var err error = errors.New("This is an error") var uuid1 string = uuid.New() var uuid2 string = uuid.New() // Execute test var iterations int = 100000 var start time.Time = time.Now() for i := 0; i < iterations; i++ { logger.InfoBuilder(). SetEvent("performance_event"). SetMessage("This is a message from the steno logger"). SetError(err). AddContext("requestId", uuid1). AddData("userId", uuid2). Log() } var end time.Time = time.Now() var elapsed float64 = float64(end.Sub(start).Nanoseconds()) os.Stderr.WriteString(fmt.Sprintf("Elapsed %f seconds\n", elapsed / 1000000000.0)) } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import "github.com/Sirupsen/logrus" // Marker interface. type Marker interface { // Parse event name from event. ParseEvent(e *logrus.Entry) string // Parse logger from event. ParseLoggerName(e *logrus.Entry) string // Parse data from event ParseData(e *logrus.Entry) map[string]interface{} // Parse context from event ParseContext(e *logrus.Entry) map[string]interface{} // Parse error from event ParseError(e *logrus.Entry) error } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "io" "github.com/Sirupsen/logrus" ) var ( noopLogBuilder LogBuilder = new(NoOpLogBuilder) ) // Logger implementation. Interface compatible with standard Go log and github.com/Sirupsen/logrus. However, the power // of the implementation is in the methods returning LogBuilder instances. The "Print" methods are mapped to the info // level. As with other implementations fatal will exit and panic will halt. type Logger struct { name string logger *logrus.Logger } func NewLogger(n string, l *logrus.Logger) *Logger { if (l == nil) { l = logrus.StandardLogger() } return &Logger{name: n, logger: l} } // ** Log Builder ** // Debug with LogBuilder. Recommended. func (l *Logger) DebugBuilder() LogBuilder { if l.logger.Level >= logrus.DebugLevel { return createLogBuilder(l.logger, logrus.DebugLevel, l.name) } else { return noopLogBuilder } } // Info with LogBuilder. Recommended. func (l *Logger) InfoBuilder() LogBuilder { if l.logger.Level >= logrus.InfoLevel { return createLogBuilder(l.logger, logrus.InfoLevel, l.name) } else { return noopLogBuilder } } // Warn with LogBuilder. Recommended. func (l *Logger) WarnBuilder() LogBuilder { if l.logger.Level >= logrus.WarnLevel { return createLogBuilder(l.logger, logrus.WarnLevel, l.name) } else { return noopLogBuilder } } // Warning with LogBuilder. Recommended. func (l *Logger) WarningBuilder() LogBuilder { return l.WarnBuilder() } // Error with LogBuilder. Recommended. func (l *Logger) ErrorBuilder() LogBuilder { if l.logger.Level >= logrus.ErrorLevel { return createLogBuilder(l.logger, logrus.ErrorLevel, l.name) } else { return noopLogBuilder } } // Fatal with LogBuilder. Recommended. This implementation like the standard library causes the program to exit. func (l *Logger) FatalBuilder() LogBuilder { if l.logger.Level >= logrus.FatalLevel { return createLogBuilder(l.logger, logrus.FatalLevel, l.name) } else { return noopLogBuilder } } // Panic with LogBuilder. Recommended. This implementation like the standard library causes the program to panic. func (l *Logger) PanicBuilder() LogBuilder { if l.logger.Level >= logrus.PanicLevel { return createLogBuilder(l.logger, logrus.PanicLevel, l.name) } else { return noopLogBuilder } } // ** Go Log Compatibility ** // Print from standard Go log library. Provided for compatibility. func (l *Logger) Print(args ...interface{}) { if l.logger.Level >= logrus.InfoLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Info() } } // Printf from standard Go log library. Provided for compatibility. func (l *Logger) Printf(format string, args ...interface{}) { if l.logger.Level >= logrus.InfoLevel { l.logger.Infof(format, args...) } } // Println from standard Go log library. Provided for compatibility. func (l *Logger) Println(args ...interface{}) { if l.logger.Level >= logrus.InfoLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Info() } } // Panic from standard Go log library. This implementation like the standard library causes the program to panic. // Provided for compatibility. func (l *Logger) Panic(args ...interface{}) { if l.logger.Level >= logrus.PanicLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Panic() } } // Panicf from standard Go log library. This implementation like the standard library causes the program to panic. // Provided for compatibility. func (l *Logger) Panicf(format string, args ...interface{}) { if l.logger.Level >= logrus.PanicLevel { l.logger.Panicf(format, args...) } } // Panicln from standard Go log library. This implementation like the standard library causes the program to panic. // Provided for compatibility. func (l *Logger) Panicln(args ...interface{}) { if l.logger.Level >= logrus.PanicLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Panic() } } // Fatal from standard Go log library. This implementation like the standard library causes the program to exit. // Provided for compatibility. func (l *Logger) Fatal(args ...interface{}) { if l.logger.Level >= logrus.FatalLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Fatal() } } // Fatalf from standard Go log library. This implementation like the standard library causes the program to exit. // Provided for compatibility. func (l *Logger) Fatalf(format string, args ...interface{}) { if l.logger.Level >= logrus.FatalLevel { l.logger.Fatalf(format, args...) } } // Fatalln from standard Go log library. This implementation like the standard library causes the program to exit. // Provided for compatibility. func (l *Logger) Fatalln(args ...interface{}) { if l.logger.Level >= logrus.FatalLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Fatal() } } // Output from standard Go log library. This is mapped to Info without the stack trace. Provided for compatibility. func (l *Logger) Output(calldepth int, s string) error { l.Info(s) return nil } // Flags from standard Go log library. This is a no-op. Provided for compatibility. func (l *Logger) Flags() int { return 0; } // SetFlags from standard Go log library. This is a no-op. Provided for compatibility. func (l *Logger) SetFlags(flag int) { // No-op } // Prefix from standard Go log library. This is a no-op. Provided for compatibility. func (l *Logger) Prefix() string { return "" } // SetPrefix from standard Go log library. This is a no-op. Provided for compatibility. func (l *Logger) SetPrefix(prefix string) { // No-op } // SetOutput from standard Go log library. This is a no-op. Provided for compatibility. func SetOutput(w io.Writer) { // No-op } // Flags from standard Go log library. This is a no-op. Provided for compatibility. func Flags() int { return 0; } // SetFlags from standard Go log library. This is a no-op. Provided for compatibility. func SetFlags(flag int) { // No-op } // Prefix from standard Go log library. This is a no-op. Provided for compatibility. func Prefix() string { return "" } // SetPrefix from standard Go log library. This is a no-op. Provided for compatibility. func SetPrefix(prefix string) { // No-op } // Output from standard Go log library. This is a no-op. Provided for compatibility. func Output(calldepth int, s string) error { // No-op (there is no default global logger) return nil } // ** github.com/Sirupsen/logrus Compatibility ** // Debug from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Debug(args ...interface{}) { if l.logger.Level >= logrus.DebugLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Debug() } } // Debugf from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Debugf(format string, args ...interface{}) { if l.logger.Level >= logrus.DebugLevel { l.logger.Debugf(format, args...) } } // Debugln from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Debugln(args ...interface{}) { if l.logger.Level >= logrus.DebugLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Debug() } } // Info from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Info(args ...interface{}) { if l.logger.Level >= logrus.InfoLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Info() } } // Infof from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Infof(format string, args ...interface{}) { if l.logger.Level >= logrus.InfoLevel { l.logger.Infof(format, args...) } } // Infoln from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Infoln(args ...interface{}) { if l.logger.Level >= logrus.InfoLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Info() } } // Warn from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Warn(args ...interface{}) { if l.logger.Level >= logrus.WarnLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Warn() } } // Warnf from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Warnf(format string, args ...interface{}) { if l.logger.Level >= logrus.WarnLevel { l.logger.Warnf(format, args...) } } // Warnln from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Warnln(args ...interface{}) { if l.logger.Level >= logrus.WarnLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Warn() } } // Warning from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Warning(args ...interface{}) { l.Warn(args...) } // Warningf from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Warningf(format string, args ...interface{}) { l.Warnf(format, args...) } // Warningln from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Warningln(args ...interface{}) { l.Warnln(args...) } // Error from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Error(args ...interface{}) { if l.logger.Level >= logrus.ErrorLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Error() } } // Errorf from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Errorf(format string, args ...interface{}) { if l.logger.Level >= logrus.ErrorLevel { l.logger.Errorf(format, args...) } } // Errorln from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) Errorln(args ...interface{}) { if l.logger.Level >= logrus.ErrorLevel { MarkerMaps.Encode( l.logger, "", // event name l.name, // logger name map[string]interface{}{ "args": args, }, map[string]interface{}{}, nil, ).Error() } } // WithField from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) WithField(key string, value interface{}) *logrus.Entry { return logrus.NewEntry(l.logger).WithField(key, value) } // WithFields from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) WithFields(fields logrus.Fields) *logrus.Entry { return logrus.NewEntry(l.logger).WithFields(fields) } // WithError from github.com/Sirupsen/logrus library. Provided for compatibility. func (l *Logger) WithError(err error) *logrus.Entry { return logrus.NewEntry(l.logger).WithError(err) } // ** Private implementation ** func createLogBuilder(l *logrus.Logger, v logrus.Level, n string) LogBuilder { var lb *DefaultLogBuilder = NewDefaultLogBuilder(l, v, n) return lb } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno var ( _ LogBuilder = (*NoOpLogBuilder)(nil) ) // NoOpLogBuilder is a LogBuilder implementation that satisfies the LogBuilder contract without empty implementations. type NoOpLogBuilder struct { } func (nolb *NoOpLogBuilder) SetEvent(event string) LogBuilder { return nolb } func (nolb *NoOpLogBuilder) SetMessage(message string) LogBuilder { return nolb } func (nolb *NoOpLogBuilder) SetError(err error) LogBuilder { return nolb } func (nolb *NoOpLogBuilder) AddData(key string, value interface{}) LogBuilder { return nolb } func (nolb *NoOpLogBuilder) AddContext(key string, value interface{}) LogBuilder { return nolb } func (nolb *NoOpLogBuilder) Log() { return } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "github.com/Sirupsen/logrus" ) const ( EVENT_DATA_EVENT_KEY string = "event" EVENT_DATA_LOGGER_KEY string = "logger" EVENT_DATA_DATA_KEY string = "data" EVENT_DATA_CONTEXT_KEY string = "context" EVENT_DATA_ERROR_KEY string = "error" ) var ( _ Marker = (*MapsMarker)(nil) ) // Maps marker implementation. type MapsMarker struct { } // Encode. func (smm *MapsMarker) Encode( logger *logrus.Logger, event string, loggerName string, data map[string]interface{}, context map[string]interface{}, err error) *logrus.Entry { var entry *logrus.Entry = logrus.NewEntry(logger).WithFields(logrus.Fields{ MarkerKey: smm, EVENT_DATA_EVENT_KEY: event, EVENT_DATA_LOGGER_KEY: loggerName, EVENT_DATA_DATA_KEY: data, EVENT_DATA_CONTEXT_KEY: context, EVENT_DATA_ERROR_KEY: err,}) return entry } // Parse event name from event. func (smm *MapsMarker) ParseEvent(e *logrus.Entry) string { var v interface{} v = e.Data[EVENT_DATA_EVENT_KEY] switch v := v.(type) { default: return "" case string: return v } } // Parse logger name from event. func (smm *MapsMarker) ParseLoggerName(e *logrus.Entry) string { var v interface{} v = e.Data[EVENT_DATA_LOGGER_KEY] switch v := v.(type) { default: return "" case string: return v } } // Parse data from event. func (smm *MapsMarker) ParseData(e *logrus.Entry) map[string]interface{} { var v interface{} v = e.Data[EVENT_DATA_DATA_KEY] switch v := v.(type) { default: return nil case map[string]interface{}: return v } } // Parse context from event. func (smm *MapsMarker) ParseContext(e *logrus.Entry) map[string]interface{} { var v interface{} v = e.Data[EVENT_DATA_CONTEXT_KEY] switch v := v.(type) { default: return nil case map[string]interface{}: return v } } // Parse data from event. func (smm *MapsMarker) ParseError(e *logrus.Entry) error { var v interface{} v = e.Data[EVENT_DATA_ERROR_KEY] switch v := v.(type) { default: return nil case error: return v } } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "testing" "github.com/Sirupsen/logrus" "errors" ) // TODO: // 1) Test Fatal and Panic methods using a mock logrus logger. // 2) Test no-op stub methods from standard logger. // 3) Test output method to info w/o stack trace method from standard logger. const ( loggerTestDataPath = "./testdata/logger_test/" ) var ( loggerTestFormatter *Formatter = NewFormatter() ) func TestLoggerDebugBuilder(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerDebugBuilder", logrus.DebugLevel, loggerTestFormatter) logger.DebugBuilder().SetMessage("TestLoggerDebugBuilder").Log() HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerDebugBuilder.expected.json") } func TestLoggerDebugBuilderLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerDebugBuilderLevelSuppressed", logrus.InfoLevel, loggerTestFormatter) logger.DebugBuilder().SetMessage("TestLoggerDebugBuilderLevelSuppressed").Log() HelperTestVerifyEmpty(t, buffer) } func TestLoggerInfoBuilder(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerInfoBuilder", logrus.InfoLevel, loggerTestFormatter) logger.InfoBuilder().SetMessage("TestLoggerInfoBuilder").Log() HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerInfoBuilder.expected.json") } func TestLoggerInfoBuilderLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerInfoBuilderLevelSuppressed", logrus.WarnLevel, loggerTestFormatter) logger.InfoBuilder().SetMessage("TestLoggerInfoBuilderLevelSuppressed").Log() HelperTestVerifyEmpty(t, buffer) } func TestLoggerWarnBuilder(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarnBuilder", logrus.WarnLevel, loggerTestFormatter) logger.WarnBuilder().SetMessage("TestLoggerWarnBuilder").Log() HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWarnBuilder.expected.json") } func TestLoggerWarnBuilderLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarnBuilderLevelSuppressed", logrus.ErrorLevel, loggerTestFormatter) logger.WarnBuilder().SetMessage("TestLoggerWarnBuilderLevelSuppressed").Log() HelperTestVerifyEmpty(t, buffer) } func TestLoggerWarningBuilder(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarningBuilder", logrus.WarnLevel, loggerTestFormatter) logger.WarningBuilder().SetMessage("TestLoggerWarningBuilder").Log() HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWarningBuilder.expected.json") } func TestLoggerWarningBuilderLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarningBuilderLevelSuppressed", logrus.ErrorLevel, loggerTestFormatter) logger.WarningBuilder().SetMessage("TestLoggerWarningBuilderLevelSuppressed").Log() HelperTestVerifyEmpty(t, buffer) } func TestLoggerErrorBuilder(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerErrorBuilder", logrus.ErrorLevel, loggerTestFormatter) logger.ErrorBuilder().SetMessage("TestLoggerErrorBuilder").Log() HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerErrorBuilder.expected.json") } func TestLoggerErrorBuilderLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerErrorBuilderLevelSuppressed", logrus.FatalLevel, loggerTestFormatter) logger.ErrorBuilder().SetMessage("TestLoggerErrorBuilderLevelSuppressed").Log() HelperTestVerifyEmpty(t, buffer) } func TestLoggerPrint(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerPrint", logrus.InfoLevel, loggerTestFormatter) logger.Print("TestLoggerPrint") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerPrint.expected.json") } func TestLoggerPrintLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerPrintLevelSuppressed", logrus.WarnLevel, loggerTestFormatter) logger.Print("TestLoggerPrintLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerPrintf(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerPrintf", logrus.InfoLevel, loggerTestFormatter) logger.Printf("%sLogger%s", "Test", "Printf") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerPrintf.expected.json") } func TestLoggerPrintfLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerPrintfLevelSuppressed", logrus.WarnLevel, loggerTestFormatter) logger.Printf("TestLoggerPrintfLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerPrintln(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerPrintln", logrus.InfoLevel, loggerTestFormatter) logger.Println("TestLoggerPrintln") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerPrintln.expected.json") } func TestLoggerPrintlnLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerPrintlnLevelSuppressed", logrus.WarnLevel, loggerTestFormatter) logger.Print("TestLoggerPrintlnLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerDebug(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerDebug", logrus.DebugLevel, loggerTestFormatter) logger.Debug("TestLoggerDebug") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerDebug.expected.json") } func TestLoggerDebugLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerDebugLevelSuppressed", logrus.InfoLevel, loggerTestFormatter) logger.Debug("TestLoggerDebugLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerDebugf(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerDebugf", logrus.DebugLevel, loggerTestFormatter) logger.Debugf("%sLogger%s", "Test", "Debugf") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerDebugf.expected.json") } func TestLoggerDebugfLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerDebugfLevelSuppressed", logrus.InfoLevel, loggerTestFormatter) logger.Debugf("TestLoggerDebugfLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerDebugln(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerDebugln", logrus.DebugLevel, loggerTestFormatter) logger.Debugln("TestLoggerDebugln") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerDebugln.expected.json") } func TestLoggerDebuglnLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerDebuglnLevelSuppressed", logrus.InfoLevel, loggerTestFormatter) logger.Debug("TestLoggerDebuglnLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerInfo(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerInfo", logrus.InfoLevel, loggerTestFormatter) logger.Info("TestLoggerInfo") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerInfo.expected.json") } func TestLoggerInfoLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerInfoLevelSuppressed", logrus.WarnLevel, loggerTestFormatter) logger.Info("TestLoggerInfoLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerInfof(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerInfof", logrus.InfoLevel, loggerTestFormatter) logger.Infof("%sLogger%s", "Test", "Infof") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerInfof.expected.json") } func TestLoggerInfofLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerInfofLevelSuppressed", logrus.WarnLevel, loggerTestFormatter) logger.Infof("TestLoggerInfofLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerInfoln(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerInfoln", logrus.InfoLevel, loggerTestFormatter) logger.Infoln("TestLoggerInfoln") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerInfoln.expected.json") } func TestLoggerInfolnLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerInfolnLevelSuppressed", logrus.WarnLevel, loggerTestFormatter) logger.Info("TestLoggerInfolnLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerWarn(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarn", logrus.WarnLevel, loggerTestFormatter) logger.Warn("TestLoggerWarn") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWarn.expected.json") } func TestLoggerWarnLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarnLevelSuppressed", logrus.ErrorLevel, loggerTestFormatter) logger.Warn("TestLoggerWarnLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerWarnf(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarnf", logrus.WarnLevel, loggerTestFormatter) logger.Warnf("%sLogger%s", "Test", "Warnf") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWarnf.expected.json") } func TestLoggerWarnfLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarnfLevelSuppressed", logrus.ErrorLevel, loggerTestFormatter) logger.Warnf("TestLoggerWarnfLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerWarnln(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarnln", logrus.WarnLevel, loggerTestFormatter) logger.Warnln("TestLoggerWarnln") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWarnln.expected.json") } func TestLoggerWarnlnLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarnlnLevelSuppressed", logrus.ErrorLevel, loggerTestFormatter) logger.Warn("TestLoggerWarnlnLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerWarning(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarning", logrus.WarnLevel, loggerTestFormatter) logger.Warning("TestLoggerWarning") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWarning.expected.json") } func TestLoggerWarningLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarningLevelSuppressed", logrus.ErrorLevel, loggerTestFormatter) logger.Warning("TestLoggerWarningLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerWarningf(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarningf", logrus.WarnLevel, loggerTestFormatter) logger.Warningf("%sLogger%s", "Test", "Warningf") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWarningf.expected.json") } func TestLoggerWarningfLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarningfLevelSuppressed", logrus.ErrorLevel, loggerTestFormatter) logger.Warningf("TestLoggerWarningfLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerWarningln(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarningln", logrus.WarnLevel, loggerTestFormatter) logger.Warningln("TestLoggerWarningln") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWarningln.expected.json") } func TestLoggerWarninglnLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWarninglnLevelSuppressed", logrus.ErrorLevel, loggerTestFormatter) logger.Warning("TestLoggerWarninglnLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerError(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerError", logrus.ErrorLevel, loggerTestFormatter) logger.Error("TestLoggerError") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerError.expected.json") } func TestLoggerErrorLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerErrorLevelSuppressed", logrus.FatalLevel, loggerTestFormatter) logger.Error("TestLoggerErrorLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerErrorf(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerErrorf", logrus.ErrorLevel, loggerTestFormatter) logger.Errorf("%sLogger%s", "Test", "Errorf") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerErrorf.expected.json") } func TestLoggerErrorfLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerErrorfLevelSuppressed", logrus.FatalLevel, loggerTestFormatter) logger.Errorf("TestLoggerErrorfLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerErrorln(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerErrorln", logrus.ErrorLevel, loggerTestFormatter) logger.Errorln("TestLoggerErrorln") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerErrorln.expected.json") } func TestLoggerErrorlnLevelSuppressed(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerErrorlnLevelSuppressed", logrus.FatalLevel, loggerTestFormatter) logger.Error("TestLoggerErrorlnLevelSuppressed") HelperTestVerifyEmpty(t, buffer) } func TestLoggerWithField(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWithField", logrus.InfoLevel, loggerTestFormatter) logger.WithField("foo", "bar").Info("TestLoggerWithField") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWithField.expected.json") } func TestLoggerWithFields(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWithFields", logrus.InfoLevel, loggerTestFormatter) logger.WithFields(logrus.Fields{"foo": "bar", "one": 1, "pi": 3.14,}).Info("TestLoggerWithFields") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWithFields.expected.json") } func TestLoggerWithError(t *testing.T) { t.Parallel() logger, buffer := HelperTestGetLogger("TestLoggerWithError", logrus.InfoLevel, loggerTestFormatter) logger.WithError(errors.New("This is an error")).Info("TestLoggerWithError") HelperTestVerify(t, buffer, loggerTestDataPath + "TestLoggerWithError.expected.json") } <file_sep>go-steno ======== <a href="https://raw.githubusercontent.com/vjkoskela/gosteno/master/LICENSE"> <img src="https://img.shields.io/hexpm/l/plug.svg" alt="License: Apache 2"> </a> <a href="https://travis-ci.org/vjkoskela/gosteno/"> <img src="https://travis-ci.org/vjkoskela/gosteno.png" alt="Travis Build"> </a> Implementation of [ArpNetworking's LogbackSteno](https://github.com/ArpNetworking/logback-steno) for [Go](https://golang.org). Extends [Sirupsen's logrus](https://github.com/Sirupsen/logrus) logging implementation with a [Steno compatible](testdata/steno.schema.json) Formatter as well as providing named Logger instances and a fluent log builder. Dependency ---------- First, retrieve the library into your workspace: go> go get github.com/vjkoskela/gosteno To use the library in your project(s) simply import it: ```go import "github.com/vjkoskela/gosteno" ``` Formatter --------- Create the formatter as follows: ```go var formatter *gosteno.Formatter = gosteno.NewFormatter() ``` The gosteno.Formatter supports a subset of the options available in [LogbackSteno](https://github.com/ArpNetworking/logback-steno): * LogEventName - Set the default event name. The default is "log". * InjectContextProcess - Add the process identifier to the context block. The default is true. * InjectContextHost - Add the host name to the context block. The default is true. * InjectContextLogger - Add the logger name to the context block. The default is false. (1) _Note 1_: Injecting additional key-value pairs into context is not strictly compliant with the current definition of Steno.<br> These may be configured after instantiating the Formatter. For example: ```go formatter.SetInjectContextLogger(true) ``` Logrus ------ The underlying logging implementation is [logrus](https://github.com/Sirupsen/logrus). At minimum you must set the formatter; however, you may also want to configure the writer and minimum output level. For example to configure the global logger instance: ```go logrus.SetOutput(os.Stdout) logrus.SetFormatter(formatter) logrus.SetLevel(logrus.DebugLevel) ``` Alternatively, you may create a new [logrus](https://github.com/Sirupsen/logrus) logger and configure that. For example: ``` var logrusLogger *logrus.Logger = &logrus.Logger{ Out: os.Stdout, Formatter: formatter, Level: logrus.ErrorLevel, } ``` Logger ------ Instantiate a named Logger instance for each particular logging context. By default the Logger is bound to the global default [logrus](https://github.com/Sirupsen/logrus) logger instance. For example: ```go var logger *gosteno.Logger = gosteno.GetLogger("http.server") ``` Alternatively, you may bind a Logger instance to particular [logrus](https://github.com/Sirupsen/logrus) logger instance: ```go var logger *gosteno.Logger = gosteno.GetLoggerForLogger("http.server", logrusLogger) ``` Log Builder ----------- Aside from providing a full set of logging methods compatible with Go's standard logging and with the [logrus](https://github.com/Sirupsen/logrus) logger, gosteno.Logger also provides access to buildable logs: ```go logger.DebugBuilder().SetMessage("This is a log builder debug message").Log() logger.InfoBuilder().SetEvent("my_event").SetMessage("This is a log builder info message with event").Log() logger.WarnBuilder(). SetEvent("my_event"). SetMessage("This is a warn builder info message with event and error"). SetError(errors.New("This is also another error")). Log() logger.ErrorBuilder(). SetEvent("my_event"). SetMessage("This is a log builder info message with event, error, data and context"). SetError(errors.New("This is also another error")). AddContext("requestId", uuid.New()). AddData("userId", uuid.New()). Log() ``` This produces output like this: ```json {"time":"2016-01-08T17:45:35.895560313-08:00","name":"log","level":"debug","data":{"message":"This is a log builder debug message"},"context":{"host":"Mac-Pro.local","processId":"16358","logger":"examples.main"},"id":"e4c0f58d-74c1-425e-8f8c-017f03bc0171","version":"0"} {"time":"2016-01-08T17:45:35.895584789-08:00","name":"my_event","level":"info","data":{"message":"This is a log builder info message with event"},"context":{"host":"Mac-Pro.local","processId":"16358","logger":"examples.main"},"id":"5f7acb89-c498-4b30-b0d4-248de0d8e060","version":"0"} {"time":"2016-01-08T17:45:35.895611498-08:00","name":"my_event","level":"warn","data":{"message":"This is a warn builder info message with event and error"},"context":{"host":"Mac-Pro.local","processId":"16358","logger":"examples.main"},"exception":{"type":"error","message":"This is also another error","backtrace":[]},"id":"b75fd67c-2831-4aff-8dff-277393da6eed","version":"0"} {"time":"2016-01-08T17:45:35.895643617-08:00","name":"my_event","level":"crit","data":{"message":"This is a log builder info message with event, error, data and context","userId":"bb486dfd-d7c5-4e3f-8391-c39d9fee6cac"},"context":{"requestId":"3186ea94-bca3-4a75-8ba2-b01151e9935c","host":"Mac-Pro.local","processId":"16358","logger":"examples.main"},"exception":{"type":"error","message":"This is also another error","backtrace":[]},"id":"67c13e4d-12de-4ae4-8606-271d6e4ae13f","version":"0"} ``` For more examples please see [performance.go](performance/performance.go). Performance ----------- Some very non-scientific relative benchmarking was performed against the Arpnetworking LogbackSteno Java implementation. Go with error, mind you it's effectively just a string with no stack trace: ``` Elapsed 2.236446 seconds Elapsed 2.198458 seconds Elapsed 2.356763 seconds Elapsed 2.196019 seconds Elapsed 2.206734 seconds ``` Average = 2.238884 seconds Java with exception for error, which includes the message and a stack trace: ``` Elapsed 10.815678 seconds Elapsed 11.896151 seconds Elapsed 10.839127 seconds Elapsed 11.803035 seconds Elapsed 10.903178 seconds ``` Average = 11.2514338 seconds Java without exception for error: ``` Elapsed 2.790097 seconds Elapsed 1.639426 seconds Elapsed 1.470144 seconds Elapsed 1.612253 seconds Elapsed 1.575005 seconds ``` Average = 1.817385 seconds The gosteno implementation is 5.025 times _faster_ when exceptions are logged in Java and 1.232 times _slower_ when they are not. The cost of stack trace generation and encoding in Java is not surprising; however, the scale of the improvement with it disabled is. Finally, although this is neither a complete nor rigorous performance test it does provide an interesting baseline. The next step would be to compare serialization times including complex data structures as that will simulate real world usage more closely. Details: * JDK/JRE version 1.8.0_66 * GO version 1.5.2 * 3.5 Ghz 6-Core Intel Xeon E5 * 32 GB 1866 Mhz DDR ECC * Mac OS X with El Capitan * Loggers configured to stdout redirected in bash to /dev/null Development ----------- To build the library locally you must satisfy these prerequisites: * [Go](https://golang.org/) Next, fork the repository, get and build: Getting and Building: ```bash go> go get github.com/$USER/gosteno go> go install github.com/$USER/gosteno ``` Testing: ```bash go> go test -coverprofile=coverage.out github.com/$USER/gosteno go> go tool cover -html=coverage.out ``` To use the local forked version in your project simply import it: ```go import "github.com/$USER/gosteno" ``` _Note:_ The above assumes $USER is the name of your Github organization containing the fork. License ------- Published under Apache Software License 2.0, see LICENSE &copy; <NAME>, 2016 <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "bytes" "io/ioutil" "encoding/json" "reflect" "testing" "github.com/Sirupsen/logrus" "github.com/xeipuuv/gojsonschema" ) var ( stenoSchemaLoader = gojsonschema.NewReferenceLoader("file://./testdata/steno.schema.json") ) func HelperTestGetLogger(n string, l logrus.Level, f *Formatter) (*Logger, *bytes.Buffer) { var buffer *bytes.Buffer = new(bytes.Buffer) var logrusLogger *logrus.Logger = &logrus.Logger{ Out: buffer, Formatter: f, Level: l, } return GetLoggerForLogger(n, logrusLogger), buffer } func HelperTestVerifyEmpty(t *testing.T, actualBuffer *bytes.Buffer) { if actualBuffer.Len() > 0 { t.Errorf("Expected actual buffer to be empty but contains %s", actualBuffer.String()) return } } func HelperTestVerify(t *testing.T, actualBuffer *bytes.Buffer, actualFile string) { HelperTestVerifyIgnoreContext(t, actualBuffer, actualFile, []string{}) } func HelperTestVerifyIgnoreContext(t *testing.T, actualBuffer *bytes.Buffer, actualFile string, ignoreContextKeysForSchema []string) { var err error var expectedBuffer []byte var result *gojsonschema.Result; if expectedBuffer, err = ioutil.ReadFile(actualFile); err != nil { t.Errorf("Failed to read actual file %s", actualFile) return } var expectedRootNode map[string]interface{} if err = json.Unmarshal(expectedBuffer, &expectedRootNode); err != nil { t.Errorf("Unmarshal of expected failed because %v in buffer %s", err, string(expectedBuffer[:])) return } var actualAsString string = actualBuffer.String() var actualRootNode map[string]interface{} if err = json.Unmarshal([]byte(actualAsString), &actualRootNode); err != nil { t.Errorf("Unmarshal of actual failed because %v in buffer %s", err, actualAsString) return } var actualForValidationRootNode map[string]interface{} if err = json.Unmarshal([]byte(actualAsString), &actualForValidationRootNode); err != nil { t.Errorf("Unmarshal of actual failed because %v in buffer %s", err, actualAsString) return } hideIgnoredKeys(actualForValidationRootNode, ignoreContextKeysForSchema) var actualForValidationAsByteArray []byte if actualForValidationAsByteArray, err = json.Marshal(actualForValidationRootNode); err != nil { t.Errorf("Remarshal of actual failed because %v for %s", err, actualForValidationRootNode) return } var actualForValidationJsonLoader = gojsonschema.NewStringLoader(string(actualForValidationAsByteArray)) if result, err = gojsonschema.Validate(stenoSchemaLoader, actualForValidationJsonLoader); err != nil { t.Errorf("Validation against json schema failed because %v", err) return } else if !result.Valid() { t.Errorf("Actual log message is not valid steno because %v actual is %s", result.Errors(), actualAsString) return } normalize(actualRootNode) if !reflect.DeepEqual(expectedRootNode, actualRootNode) { t.Errorf("Actual log message does not match expected; expected is %v but actual was %v ", expectedRootNode, actualRootNode) return } } func hideIgnoredKeys(r map[string]interface{}, ignoreContextKeys []string) { if node, ok := r["context"].(map[string]interface{}); ok { for i := range ignoreContextKeys { delete(node, ignoreContextKeys[i]) } } } func normalize(r map[string]interface{}) { if _, ok := r["id"]; ok { r["id"] = "<ID>" } if _, ok := r["time"]; ok { r["time"] = "<TIME>" } if node, ok := r["context"].(map[string]interface{}); ok { if _, ok := node["host"]; ok { node["host"] = "<HOST>" } if _, ok := node["processId"]; ok { node["processId"] = "<PROCESS_ID>" } } } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "bytes" "encoding/json" "os" "strconv" "time" "github.com/pborman/uuid" "github.com/Sirupsen/logrus" ) const ( globalDefaultEventName = "log" ) var ( newLine = []byte("\n") hostname = "<UNKNOWN>" processId = "<UNKNOWN>" ) func init() { var value string var err error // Hostname value, err = os.Hostname() if (err == nil) { hostname = value } // Process id processId = strconv.Itoa(os.Getpid()) } type Formatter struct { logEventName string injectContextHost bool injectContextProcess bool injectContextLogger bool } func NewFormatter() *Formatter { return &Formatter{ logEventName: globalDefaultEventName, injectContextHost: true, injectContextProcess: true, injectContextLogger: false, } } func (sf *Formatter) Format(e *logrus.Entry) (result []byte, err error) { var initialStenoBuffer []byte = make([]byte, 0, 512) var initialUserBuffer []byte = make([]byte, 0, 256) var stenoBuffer *bytes.Buffer = bytes.NewBuffer(initialStenoBuffer) var userBuffer *bytes.Buffer = bytes.NewBuffer(initialUserBuffer) var value []byte // Begin steno wrapper if _, err = stenoBuffer.WriteString("{"); err != nil { return } if err = writeKeyStringValue(stenoBuffer, "time", sf.getTime(e)); err != nil { return } if err = writeKeyStringValue(stenoBuffer, "name", sf.getEventName(e, sf.logEventName)); err != nil { return } if err = writeKeyStringValue(stenoBuffer, "level", sf.getLevel(e)); err != nil { return } // Encode user data; handle errors more gracefully by encoding them into the buffer if possible if value, err = sf.getData(e); err != nil { if err = writeError(stenoBuffer, err); err != nil { return } } else if err = writeKeyJsonValue(userBuffer, "data", value); err != nil { if err = writeError(stenoBuffer, err); err != nil { return } } else { if value, err = sf.getContext(e); err != nil { if err = writeError(stenoBuffer, err); err != nil { return } } else if err = writeKeyJsonValue(userBuffer, "context", value); err != nil { if err = writeError(stenoBuffer, err); err != nil { return } } else { if value, err = sf.getError(e); err != nil { if err = writeError(userBuffer, err); err != nil { return } } else if value != nil { if err = writeKeyJsonValue(userBuffer, "exception", value); err != nil { if err = writeError(stenoBuffer, err); err != nil { return } } else if _, err = stenoBuffer.Write(userBuffer.Bytes()); err != nil { return } } else if _, err = stenoBuffer.Write(userBuffer.Bytes()); err != nil { return } } } // Complete steno wrapper if err = writeKeyStringValue(stenoBuffer, "id", uuid.New()); err != nil { return } if err = writeKeyStringValue(stenoBuffer, "version", "0"); err != nil { return } stenoBuffer.Write(newLine); result = stenoBuffer.Bytes() result[len(result) - len(newLine) - 1] = '}' return } func (sf *Formatter) LogEventName() string { return sf.logEventName } func (sf *Formatter) SetLogEventName(v string) { sf.logEventName = v } func (sf *Formatter) InjectContextHost() bool { return sf.injectContextHost } func (sf *Formatter) SetInjectContextHost(v bool) { sf.injectContextHost = v } func (sf *Formatter) InjectContextProcess() bool { return sf.injectContextProcess } func (sf *Formatter) SetInjectContextProcess(v bool) { sf.injectContextProcess = v } func (sf *Formatter) InjectContextLogger() bool { return sf.injectContextLogger } func (sf *Formatter) SetInjectContextLogger(v bool) { sf.injectContextLogger = v } func (sf *Formatter) getTime(e *logrus.Entry) string { return e.Time.UTC().Format(time.RFC3339Nano) } func (sf *Formatter) getEventName(e *logrus.Entry, defaultName string) string { var marker interface{} = e.Data[MarkerKey] switch marker := marker.(type) { default: return defaultName case *MapsMarker: var name string if name = marker.ParseEvent(e); name != "" { return name } return defaultName } } func (sf *Formatter) getLevel(e *logrus.Entry) string { switch e.Level { case logrus.DebugLevel: return "debug" case logrus.InfoLevel: return "info" case logrus.WarnLevel: return "warn" case logrus.ErrorLevel: return "crit" case logrus.FatalLevel: return "fatal" case logrus.PanicLevel: return "fatal" } return "unknown" } func (sf *Formatter) getData(e *logrus.Entry) (jsonBytes []byte, err error) { var data map[string]interface{} var marker interface{} = e.Data[MarkerKey] var hasValidMarker bool = true switch marker := marker.(type) { default: hasValidMarker = false data = e.Data case *MapsMarker: data = marker.ParseData(e) } var buffer bytes.Buffer if _, err = buffer.WriteString("{"); err != nil { return } if e.Message != "" { if err = writeKeyStringValue(&buffer, "message", e.Message); err != nil { return } } for key, value := range data { // Favor explicit message in event (if not empty) over any data with the same key if key == "message" && e.Message != "" { continue } // Suppress error in event if processing raw event data (e.g. without valid marker) if key == logrus.ErrorKey && !hasValidMarker { continue } var valueJsonBytes []byte if valueJsonBytes, err = json.Marshal(value); err != nil { return } if err = writeKeyJsonValue(&buffer, key, valueJsonBytes); err != nil { return } } if buffer.Len() == 1 { if _, err = buffer.WriteString("}"); err != nil { return } jsonBytes = buffer.Bytes() } else { jsonBytes = buffer.Bytes() jsonBytes[len(jsonBytes) - 1] = '}' } return } func (sf *Formatter) getContext(e *logrus.Entry) (jsonBytes []byte, err error) { var context map[string]interface{} var loggerName string var marker interface{} = e.Data[MarkerKey] switch marker := marker.(type) { default: context = nil loggerName = "" case *MapsMarker: context = marker.ParseContext(e) loggerName = marker.ParseLoggerName(e) } var buffer bytes.Buffer if _, err = buffer.WriteString("{"); err != nil { return } for key, value := range context { var valueJsonBytes []byte if valueJsonBytes, err = json.Marshal(value); err != nil { return } if err = writeKeyJsonValue(&buffer, key, valueJsonBytes); err != nil { return } } if sf.injectContextHost { if err = writeKeyStringValue(&buffer, "host", hostname); err != nil { return } } if sf.injectContextProcess { if err = writeKeyStringValue(&buffer, "processId", processId); err != nil { return } } if sf.injectContextLogger && loggerName != "" { if err = writeKeyStringValue(&buffer, "logger", loggerName); err != nil { return } } if buffer.Len() == 1 { if _, err = buffer.WriteString("}"); err != nil { return } jsonBytes = buffer.Bytes() } else { jsonBytes = buffer.Bytes() jsonBytes[len(jsonBytes) - 1] = '}' } return } func (sf *Formatter) getError(e *logrus.Entry) (jsonBytes []byte, err error) { var entryError error var marker interface{} = e.Data[MarkerKey] switch marker := marker.(type) { default: entryError = nil if logrusError, ok := e.Data[logrus.ErrorKey].(error); ok { entryError = logrusError } case *MapsMarker: entryError = marker.ParseError(e) } if entryError != nil { var buffer bytes.Buffer if _, err = buffer.WriteString("{"); err != nil { return } if err = writeKeyStringValue(&buffer, "type", "error"); err != nil { return } if err = writeKeyStringValue(&buffer, "message", entryError.Error()); err != nil { return } if err = writeKeyJsonValue(&buffer, "backtrace", []byte("[]")); err != nil { return } jsonBytes = buffer.Bytes() jsonBytes[len(jsonBytes) - 1] = '}' } return } func writeKeyStringValue(buffer *bytes.Buffer, key string, value string) (err error) { var bytes []byte if bytes, err = json.Marshal(key); err != nil { return } else if _, err = buffer.Write(bytes); err != nil { return } if _, err = buffer.WriteString(":"); err != nil { return } if bytes, err = json.Marshal(value); err != nil { return } else if _, err = buffer.Write(bytes); err != nil { return } if _, err = buffer.WriteString(","); err != nil { return } return nil } func writeKeyJsonValue(buffer *bytes.Buffer, key string, jsonBytes []byte) (err error) { var bytes []byte if bytes, err = json.Marshal(key); err != nil { return } else if _, err = buffer.Write(bytes); err != nil { return } if _, err = buffer.WriteString(":"); err != nil { return } if _, err = buffer.Write(jsonBytes); err != nil { return } if _, err = buffer.WriteString(","); err != nil { return } return nil } func writeError(buffer *bytes.Buffer, internalError error) (err error) { var internalErrorAsMap = map[string]interface{} { "message": internalError.Error(), } var bytes []byte if bytes, err = json.Marshal(internalErrorAsMap); err != nil { return } if _, err = buffer.Write(bytes); err != nil { return } if _, err = buffer.WriteString(","); err != nil { return } return nil } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno // LogBuilder interface for assembling log messages. type LogBuilder interface { // Event setter. SetEvent(string) LogBuilder // Message setter. SetMessage(string) LogBuilder // Error setter. SetError(error) LogBuilder // Data adder. AddData(string, interface{}) LogBuilder // Context adder. AddContext(string, interface{}) LogBuilder // Log message. Log() }<file_sep>package main import ( "errors" "os" "github.com/pborman/uuid" "github.com/Sirupsen/logrus" "github.com/vjkoskela/gosteno" ) func main() { // Creation Option 1: Default Underlying Logrus Logger (recommended) // NOTE: The logrus logger and the logger factory are "decoupled" via the global default logrus logger var logrusLogger *logrus.Logger = logrus.StandardLogger() var formatter *gosteno.Formatter = gosteno.NewFormatter() formatter.SetInjectContextLogger(true) logrus.SetOutput(os.Stdout) logrus.SetFormatter(formatter) logrus.SetLevel(logrus.DebugLevel) var logger *gosteno.Logger = gosteno.GetLogger("examples.main") // Creation Option 2: New Underlying Logrus Logger /* var formatter *gosteno.Formatter = gosteno.NewFormatter() formatter.SetInjectContextLogger(true) var logrusLogger *logrus.Logger = &logrus.Logger{ Out: os.Stdout, Formatter: formatter, Level: logrus.DebugLevel, } var logger *gosteno.Logger = gosteno.GetLoggerForLogger("test.main", logrusLogger) */ // Sample code: Existing standard Go logging logger.Debug("This is a vanilla debug message") logger.Info("This is a vanilla info message") logger.Warn("This is a vanilla warn message") logger.Error("This is a vanilla error message") // Sample code: Existing github.com/Sirupsen/logrus logging logger.WithField("foo", "bar").Info("This is a logrus info message with a single field") logger.WithFields(logrus.Fields{ "foo": "bar", "one": 1, "pi": 3.14, "array": []string{"a","b","c"}, "map": map[string]interface{}{"one":1,"two":2,"three":3,}, }).Info("This is a logrus info message with multiple fields") logger.WithError(errors.New("This is an error")).Warn("This is a logrus warn message with an error") logger.WithField("foo", "bar").WithError(errors.New("This is an error")).Error("This is a logrus error message with a single field and error") // Sample code: Log builder logger.DebugBuilder().SetMessage("This is a log builder debug message").Log() logger.InfoBuilder().SetEvent("my_event").SetMessage("This is a log builder info message with event").Log() logger.WarnBuilder(). SetEvent("my_event"). SetMessage("This is a warn builder info message with event and error"). SetError(errors.New("This is also another error")). Log() logger.ErrorBuilder(). SetEvent("my_event"). SetMessage("This is a log builder info message with event, error, data and context"). SetError(errors.New("This is also another error")). AddContext("requestId", uuid.New()). AddData("userId", uuid.New()). Log() // Sample code: Manual event encoding // NOTE: Provided for completeness, this is _not_ recommended logger.WithFields(logrus.Fields{ gosteno.MarkerKey: gosteno.MarkerMaps, "data": map[string]interface{}{ "foo": "bar", "one": 1, "pi": 3.14, "array": []string{"a","b","c"}, "map": map[string]interface{}{"one":1,"two":2,"three":3,}, }, "context": map[string]interface{}{ "requestId": uuid.New(), }, "error": errors.New("This is an error"), }).Info("This was encoded by hand") // Sample code: Assisted event encoding // NOTE: Provided for completeness, this is _not_ recommended gosteno.MarkerMaps.Encode( logrusLogger, "custom_event", // event name "my_logger", // logger name map[string]interface{}{ "bar": "foo", "two": 2, "2pi": 6.28, "array": []string{"a","b","c"}, "map": map[string]interface{}{"one":1,"two":2,"three":3,}, }, map[string]interface{}{ "requestId": uuid.New(), }, errors.New("This is also an error"), ).Info("This used was encoded by the marker") } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "testing" "github.com/Sirupsen/logrus" "errors" ) type subWidget struct { Name string } type widget struct { Name string Parts *[]subWidget } // TODO: // 1) Test catastropic failure resulting in no log message. // 2) Test data/context serialization failure resulting in skeleton message. const ( formatterTestDataPath = "./testdata/formatter_test/" ) func TestFormatterDefaults(t *testing.T) { var formatter *Formatter = NewFormatter() if v := formatter.InjectContextHost(); v != true { t.Errorf("Incorrect default value for injectContextHost %v", v) } if v := formatter.InjectContextLogger(); v != false { t.Errorf("Incorrect default value for injectContextLogger %v", v) } if v := formatter.InjectContextProcess(); v != true { t.Errorf("Incorrect default value for injectContextProcess %v", v) } if v := formatter.LogEventName(); v != "log" { t.Errorf("Incorrect default value for log event name %v", v) } } func TestFormatterLevelMapping(t *testing.T) { var formatter *Formatter = NewFormatter() if v := formatter.getLevel(&logrus.Entry{Level: logrus.DebugLevel}); v != "debug" { t.Errorf("Incorrect level for DebugLevel %v", v) } if v := formatter.getLevel(&logrus.Entry{Level: logrus.InfoLevel}); v != "info" { t.Errorf("Incorrect level for InfoLevel %v", v) } if v := formatter.getLevel(&logrus.Entry{Level: logrus.WarnLevel}); v != "warn" { t.Errorf("Incorrect level for WarnLevel %v", v) } if v := formatter.getLevel(&logrus.Entry{Level: logrus.ErrorLevel}); v != "crit" { t.Errorf("Incorrect level for ErrorLevel %v", v) } if v := formatter.getLevel(&logrus.Entry{Level: logrus.FatalLevel}); v != "fatal" { t.Errorf("Incorrect level for FatalLevel %v", v) } if v := formatter.getLevel(&logrus.Entry{Level: logrus.PanicLevel}); v != "fatal" { t.Errorf("Incorrect level for PanicLevel %v", v) } } func TestFormatterGlobalDefaultEventName(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() logger, buffer := HelperTestGetLogger("TestFormatterGlobalDefaultEventName", logrus.DebugLevel, formatter) logger.DebugBuilder().SetMessage("TestFormatterGlobalDefaultEventName").Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterGlobalDefaultEventName.expected.json") } func TestFormatterConfiguredDefaultEventName(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() formatter.SetLogEventName("default_event") logger, buffer := HelperTestGetLogger("TestFormatterConfiguredDefaultEventName", logrus.DebugLevel, formatter) logger.DebugBuilder().SetMessage("TestFormatterConfiguredDefaultEventName").Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterConfiguredDefaultEventName.expected.json") } func TestFormatterSpecifiedEventName(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() formatter.SetLogEventName("default_event") logger, buffer := HelperTestGetLogger("TestFormatterSpecifiedEventName", logrus.DebugLevel, formatter) logger.DebugBuilder().SetEvent("custom_event").SetMessage("TestFormatterSpecifiedEventName").Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterSpecifiedEventName.expected.json") } func TestFormatterEnableLoggerName(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() formatter.SetInjectContextLogger(true) logger, buffer := HelperTestGetLogger("TestFormatterEnableLoggerName", logrus.DebugLevel, formatter) logger.DebugBuilder().SetMessage("TestFormatterEnableLoggerName").Log() HelperTestVerifyIgnoreContext(t, buffer, formatterTestDataPath + "TestFormatterEnableLoggerName.expected.json", []string{"logger"}) } func TestFormatterDisableProcess(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() formatter.SetInjectContextProcess(false) logger, buffer := HelperTestGetLogger("TestFormatterDisableProcess", logrus.DebugLevel, formatter) logger.DebugBuilder().SetMessage("TestFormatterDisableProcess").Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterDisableProcess.expected.json") } func TestFormatterDisableHost(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() formatter.SetInjectContextHost(false) logger, buffer := HelperTestGetLogger("TestFormatterDisableHost", logrus.DebugLevel, formatter) logger.DebugBuilder().SetMessage("TestFormatterDisableHost").Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterDisableHost.expected.json") } func TestFormatterEmptyContext(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() formatter.SetInjectContextHost(false) formatter.SetInjectContextProcess(false) logger, buffer := HelperTestGetLogger("TestFormatterEmptyContext", logrus.DebugLevel, formatter) logger.DebugBuilder().SetMessage("TestFormatterEmptyContext").Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterEmptyContext.expected.json") } func TestFormatterComplexContext(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() formatter.SetInjectContextHost(false) formatter.SetInjectContextProcess(false) logger, buffer := HelperTestGetLogger("TestFormatterComplexContext", logrus.DebugLevel, formatter) logger.DebugBuilder(). AddContext("foo", "bar"). AddContext("one", 1). AddContext("pi", 3.14). AddContext("map", map[string]interface{}{"a":"A","b":"B",}). AddContext("list", []int{1,2}). AddContext("obj", createWidget("TestFormatterComplexContext")). SetMessage("TestFormatterComplexContext"). Log() HelperTestVerifyIgnoreContext( t, buffer, formatterTestDataPath + "TestFormatterComplexContext.expected.json", []string{"foo", "one", "pi", "map", "list", "obj"}) } func TestFormatterEmptyData(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() logger, buffer := HelperTestGetLogger("TestFormatterEmptyData", logrus.DebugLevel, formatter) logger.DebugBuilder().Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterEmptyData.expected.json") } func TestFormatterComplexData(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() formatter.SetInjectContextHost(false) formatter.SetInjectContextProcess(false) logger, buffer := HelperTestGetLogger("TestFormatterComplexData", logrus.DebugLevel, formatter) logger.DebugBuilder(). AddData("foo", "bar"). AddData("one", 1). AddData("pi", 3.14). AddData("map", map[string]interface{}{"a":"A","b":"B",}). AddData("list", []int{1,2}). AddData("obj", createWidget("TestFormatterComplexData")). SetMessage("TestFormatterComplexData"). Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterComplexData.expected.json") } func TestFormatterWithError(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() logger, buffer := HelperTestGetLogger("TestFormatterWithError", logrus.DebugLevel, formatter) logger.DebugBuilder().SetError(errors.New("This is an error")).SetMessage("TestFormatterWithError").Log() HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterWithError.expected.json") } func TestFormatterWithLogrusError(t *testing.T) { t.Parallel() var formatter *Formatter = NewFormatter() logger, buffer := HelperTestGetLogger("TestFormatterWithLogrusError", logrus.DebugLevel, formatter) logger.WithError(errors.New("This is an error")).Debug("TestFormatterWithLogrusError") HelperTestVerify(t, buffer, formatterTestDataPath + "TestFormatterWithLogrusError.expected.json") } func createWidget(name string) (widget) { var parts []subWidget = make([]subWidget, 2, 2) parts[0] = *new(subWidget) parts[0].Name = name + "-1" parts[1] = *new(subWidget) parts[1].Name = name + "-2" var w *widget = new(widget) w.Name = name w.Parts = &parts return *w }<file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "errors" "reflect" "testing" "github.com/Sirupsen/logrus" ) var ( logger *logrus.Logger = logrus.New() mm *MapsMarker = new(MapsMarker) emptyEntry *logrus.Entry = logrus.NewEntry(logger) ) func TestMapsMarkerEncode(t *testing.T) { t.Parallel() var expectedEvent string = "my_event" var expectedLoggerName string = "my_logger" var expectedData map[string]interface{} = map[string]interface{}{"foo":"bar","one":1,"pi":3.14,} var expectedContext map[string]interface{} = map[string]interface{}{"bar":"foo","two":2,"2pi":6.28,} var expectedError error = errors.New("this is an error") var e *logrus.Entry = mm.Encode( logger, expectedEvent, expectedLoggerName, expectedData, expectedContext, expectedError) if e.Data["event"] != expectedEvent { t.Errorf("Encode failed to encode event") } if e.Data["logger"] != expectedLoggerName { t.Errorf("Encode failed to encode logger") } if !reflect.DeepEqual(e.Data["data"], expectedData) { t.Errorf("Encode failed to encode data") } if !reflect.DeepEqual(e.Data["context"], expectedContext) { t.Errorf("Encode failed to encode context") } if e.Data["error"] != expectedError { t.Errorf("Encode failed to encode error") } } func TestMapsMarkerParseName(t *testing.T) { t.Parallel() var expectedName string = "my_event" var e *logrus.Entry = logrus.WithField("event", expectedName) var actualName string if actualName = mm.ParseEvent(e); actualName != expectedName { t.Errorf("ParseEvent failed; expected '%s' instead actual '%s'", expectedName, actualName) } if actualName = mm.ParseEvent(emptyEntry); actualName != "" { t.Errorf("ParseEvent failed; expected nil instead actual '%s'", actualName) } } func TestMapsMarkerParseLoggerName(t *testing.T) { t.Parallel() var expectedLoggerName string = "my_logger" var e *logrus.Entry = logrus.WithField("logger", expectedLoggerName) var actualLoggerName string if actualLoggerName = mm.ParseLoggerName(e); actualLoggerName != expectedLoggerName { t.Errorf("ParseLoggerName failed; expected '%s' instead actual '%s'", expectedLoggerName, actualLoggerName) } if actualLoggerName = mm.ParseLoggerName(emptyEntry); actualLoggerName != "" { t.Errorf("ParseLoggerName failed; expected nil instead actual '%s'", actualLoggerName) } } func TestMapsMarkerParseData(t *testing.T) { t.Parallel() var expectedData map[string]interface{} = map[string]interface{}{"foo":"bar","one":1,"pi":3.14,} var e *logrus.Entry = logrus.WithField("data", expectedData) var actualData map[string]interface{} if actualData = mm.ParseData(e); !reflect.DeepEqual(actualData, expectedData) { t.Errorf("ParseData failed; expected '%v' instead actual '%v'", expectedData, actualData) } if actualData = mm.ParseData(emptyEntry); actualData != nil { t.Errorf("ParseData failed; expected nil instead actual '%v'", actualData) } } func TestMapsMarkerParseContext(t *testing.T) { t.Parallel() var expectedContext map[string]interface{} = map[string]interface{}{"foo":"bar","one":1,"pi":3.14,} var e *logrus.Entry = logrus.WithField("context", expectedContext) var actualContext map[string]interface{} if actualContext = mm.ParseContext(e); !reflect.DeepEqual(actualContext, expectedContext) { t.Errorf("ParseContext failed; expected '%v' instead actual '%v'", expectedContext, actualContext) } if actualContext = mm.ParseContext(emptyEntry); actualContext != nil { t.Errorf("ParseContext failed; expected nil instead actual '%v'", actualContext) } } func TestMapsMarkerParseError(t *testing.T) { t.Parallel() var expectedError error = errors.New("this is an error") var e *logrus.Entry = logrus.WithField("error", expectedError) var actualError error if actualError = mm.ParseError(e); actualError != expectedError { t.Errorf("ParseLoggerError failed; expected '%s' instead actual '%s'", expectedError, actualError) } if actualError = mm.ParseError(emptyEntry); actualError != nil { t.Errorf("ParseLoggerError failed; expected nil instead actual '%s'", expectedError, actualError) } } <file_sep>/* Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gosteno import ( "errors" "testing" ) func TestNoOpLogBuilder(t *testing.T) { t.Parallel() var nolb LogBuilder = new(NoOpLogBuilder) var r LogBuilder if r = nolb.SetEvent("event"); r != nolb { t.Error("SetEvent did not return nolb") } if r = nolb.SetError(errors.New("an error")); r != nolb { t.Error("SetError did not return nolb") } if r = nolb.SetMessage("message"); r != nolb { t.Error("SetMessage did not return nolb") } if r = nolb.AddData("k", "v"); r != nolb { t.Error("AddData did not return nolb") } if r = nolb.AddContext("k", "v"); r != nolb { t.Error("AddData did not return nolb") } }
a6b18dc2013a64e4deef6f205916f2a59f9d43ea
[ "Markdown", "Go" ]
16
Go
vjkoskela/gosteno
0c748325dfdf41b86cf66d71c72514edd93c1a54
0b8890a5d3ca7141e71ce402fc95f6af520f50d4
refs/heads/master
<repo_name>ctestabu/GNL<file_sep>/GNL/get_next_line.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ctestabu <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/21 14:25:10 by ctestabu #+# #+# */ /* Updated: 2019/04/21 14:25:10 by ctestabu ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" #include "libft.h" int get_next_line(const int fd, char **line) { static char *stack[OPEN_MAX]; int ret; char *heap; int i; } static int readfile(int fd, char *heap, char **stack, char **line) { char *temp_stack; int ret; ret = read(fd, heap, BUFF_SIZE); while (ret) { heap[ret] = '\0'; if(*stack) { *temp_stack = stack; } } return (ret); } static int get_line(char **stack, char **line) //{ // char *tmp_stack; // char *strchr_stack; // int i; // // i = 0; // strchr_stack = *stack; // while (strchr_stack[i] != '\n') // if (!strchr_stack[i++]) // return (0); // tmp_stack = &strchr_stack[i]; // *tmp_stack = '\0'; // *line = ft_strdup(*stack); // *stack = ft_strdup(tmp_stack + 1); // return (1); //}
13313eb260fd36ad5e5bd844437555f855f930fb
[ "C" ]
1
C
ctestabu/GNL
14abd2363a5aab76d2b53f0ce1b82eae9e7bb050
2c0e4caa0ee388842e3766578eb4f16f7999640d
refs/heads/main
<file_sep>var express = require("express"); var server = express(); var bodyParser = require("body-parser"); const morgan = require('morgan'); const model = { clients: {}, reset: function() { this.clients = {} }, addAppointment: function (name, date) { // Update date object date = {...date, status: 'pending'} // If the client is new, add him to the client list if (!this.clients.hasOwnProperty([name])) { this.clients = { ...this.clients, [name]: [date] } } else { // If the client is NOT new, add his new appointment this.clients[name].push(date) } }, attend: function (name, date) { const client = this.clients[name]; const match = client.find(appointment => appointment.date === date) match.status = 'attended'; }, expire: function (name, date) { const client = this.clients[name]; const match = client.find(appointment => appointment.date === date) match.status = 'expired'; }, cancel: function (name, date) { const client = this.clients[name]; const match = client.find(appointment => appointment.date === date) match.status = 'cancelled'; }, erase: function (name, selector) { const statusCodes = ['attended', 'cancelled', 'pending', 'expired']; let client = this.clients[name]; // If selector is a status if (statusCodes.includes(selector)) { // Save deleted appointment(s) for later const deleted = client.filter(appointment => appointment.status === selector) // Delete appointment(s) this.clients[name] = client.filter(appointment => appointment.status !== selector) return deleted; } else { // selector is a date // Save deleted appointment for later const deleted = client.filter(appointment => appointment.date === selector) // Delete appointment this.clients[name] = client.filter(appointment => appointment.date !== selector) return deleted; } }, getAppointments: function (name, status) { // If status is NOT given if (!status) return this.clients[name]; // If status is given const appointments = this.clients[name].filter(appointment => appointment.status === status); return appointments; }, getClients: function () { const clientList = []; for (let client in this.clients) { clientList.push(client); } return clientList; } }; server.use(bodyParser.json()); //server.use(express.json()); server.use(morgan('tiny')); // Routes server.get('/api', getClients); server.post('/api/Appointments', createAppointment); server.get('/api/Appointments/clients', getAllClients); server.get('/api/Appointments/:name', getClientAppointments); server.get('/api/Appointments/:name/erase', deleteAppointment); server.get('/api/Appointments/getAppointments/:name', getAppointments); // Internal functions function getClients(req, res) { const clients = model.clients res.status(200).send(clients); } function createAppointment(req, res) { //console.log(req.body) const name = req.body.client; const date = req.body.appointment; if (!name) return res.status(400).send('the body must have a client property'); if(typeof name !== 'string') return res.status(400).send('client must be a string'); model.addAppointment(name, date); const newAppointment = model.clients[name].find(appointment => appointment.date === date.date) //console.log("New Appointment: ", newAppointment); res.status(200).send(newAppointment); } function getClientAppointments(req, res) { const name = req.params.name; const date = req.query.date const option = req.query.option const validOptions = ['attend', 'expire', 'cancel'] const client = model.clients[name]; // Respond with 400 if client does not exist if(!client) return res.status(400).send('the client does not exist'); // If client does exist, but does not have an appointment for this date const dateMatch = client.find(appointment => appointment.date === date); if (!dateMatch) return res.status(400).send('the client does not have a appointment for that date'); // If option is not 'attend', 'cancel' or 'expire', respond with 400 and string if (!validOptions.includes(option)) return res.status(400).send('the option must be attend, expire or cancel'); // PERFORM STATUS UPDATES // console.log("Re.query: ", req.query) // console.log("name: ", name); // console.log("date: ", date); // console.log("option: ", option); // console.log("DateMatch: ", dateMatch); if (option === 'attend') { //console.log("The option is ATTEND") dateMatch.status = 'attended'; //console.log("Updated dateMatch: ", dateMatch); //console.log("The client's appointments: ", client) return res.status(200).send(dateMatch); } if (option === 'expire') { dateMatch.status = 'expired'; return res.status(200).send(dateMatch); } if (option === 'cancel') { dateMatch.status = 'cancelled'; return res.status(200).send(dateMatch); } } function deleteAppointment(req, res) { const name = req.params.name; const date = req.query.date; const client = model.clients[name]; //const statusCodes = ["pending", "attended", "expired", "cancelled"]; // console.log("Name: ", name); // console.log("Date: ", date); // console.log("Client Appointments: ", client); // Respond 400 if client does not exist if (!client) return res.status(400).send('the client does not exist'); // Save deleted appointmens for later const deleted = model.erase(name, date) return res.status(200).send(deleted); // Alternative method: for Javascript practice! //------------------------------------------------------------------------------------------ // Check if 'date' parameter is a date or a status // if (statusCodes.includes(date)) { // It is a status code // // Save deleted appointmens for later // const deleted = model.clients[name].filter(appointment => appointment.status === date); // // Eliminate all the client's appointments that have the given status code // model.clients[name] = model.clients[name].filter(appointment => appointment.status !== date); // // Return deleted appointments // return res.status(200).send(deleted); //} // Date is a date // Save appointment to delete for later // const deleted = model.clients[name].filter(appointment => appointment.date === date); // // Delete appointment // model.clients[name] = model.clients[name].filter(appointment => appointment.date !== date); // res.status(200).send(deleted); } function getAppointments(req, res) { const name = req.params.name; const status = req.query.status; // Get appointments with selected status //const selectedAppointments = model.clients[name].filter(appointment => appointment.status === status); const selectedAppointments = model.getAppointments(name, status); res.status(200).send(selectedAppointments); } function getAllClients(req, res) { const clients = model.getClients(); console.log(clients) res.status(200).send(clients); } server.listen(9000, () => console.log('Server running at port 9000')); module.exports = { model, server }; const modelTest = { clients: { monty: [{date: 'lunes'}, {date: 'martes'}] } }
93650ecc453ed32bd2c360fd8f89d92dd292493f
[ "JavaScript" ]
1
JavaScript
donmonty/RepasoM3-main
4640dc93d9c41b97938867ec2c33d01b8e290393
163270ff35eea1aaffa6e948a6073b013d66b837
refs/heads/main
<file_sep>#include <iostream> #include <ctime> /// <summary> /// TripleX Small Game to learn C++ || cl main.cpp /EHsc <- Removes Unnecessary Warnings /// </summary> void PrintIntroduction(int Difficulty) { //print welcome messages to the terminal :: Statements std::cout << "\n In the medieval times, there was one lockpicker who stood out the most. " << Difficulty; std::cout << " going by the name of locki. He entered every dungeon in search of chests to be openend.\n"; std::cout << "Going into the dungeon locki sees a level " << Difficulty << " chest before him! \n"; std::cout << "You need to enter the correct codes to continue...\n\n"; } bool PlayGame(int Difficulty) { PrintIntroduction(Difficulty); //Declare 3 number code :: DECLARATION STATEMENTS const int CodeA = rand() % Difficulty + Difficulty; const int CodeB = rand() % Difficulty + Difficulty; const int CodeC = rand() % Difficulty + Difficulty; const int CodeSum = CodeA + CodeB + CodeC; const int CodeProduct = CodeA * CodeB * CodeC; //Print sum and product to the terminal std::cout << std::endl; std::cout << "+ There are 3 numbers in the code\n"; std::cout << "+ The codes add-up to: " << CodeSum << std::endl; std::cout << "+ The codes multiply to give: " << CodeProduct << std::endl; int GuessA, GuessB, GuessC; std::cin >> GuessA >> GuessB >> GuessC; int GuessSum = GuessA + GuessB + GuessC; int GuessProduct = GuessA * GuessB * GuessC; if (GuessSum == CodeSum && GuessProduct == CodeProduct) { std::cout << "\n*** You Opened the Chest!!, You go deeper into the dungeon, in search of more glory and gold ***"; return true; } else { std::cout << "\n*** You broke your lockpicks, you have to retry that chest again before going anyfurther. ***"; return false; } } int main() { srand(time(NULL)); //Creates new seed based on time of day; int LevelDifficulty = 1; const int MaxDifficulty = 10; while (LevelDifficulty <= MaxDifficulty) { bool BLevelComplete = PlayGame(LevelDifficulty); std::cin.clear(); //Clears any errors; std::cin.ignore(); //Discards the buffer; if (BLevelComplete) { ++LevelDifficulty; } } std::cout << "\n*** Congratulations! You made it out of the dungeon with plenty of gold and glory! You can even call yourself rich! ***\n"; return 0; }
e0f080fa7bf26cc545ce039ca6635d8baca9a8a9
[ "C++" ]
1
C++
Pimmez/TripleX
18634fcd423bef0bf17fb519af57145873f8ae65
641ef910a1baac20c59d8833fe8f30b95afdcf68
refs/heads/master
<file_sep><?php $filename_replace = array('\\', '/', '*', '|', '?', '<', '>', '"', ':'); $maximum_matching = 10; $matching_start = '<div class="matching_section">'; $matching_seta_start = '<ul id="set_a">'; $matching_setb_start = '<ul id="set_b">'; $matching_sets_end = '</ul>'; $matching_end = '</div> <div class="single_column cards_section"> <button id="exit" class="return_to_home full_button" onclick="">Exit</button> </div>'; /**END MATCH**/ $tile_start = '<div class="tile_section"><ul id="card_tiles">'; $tile_end = '</ul></div>'; $tile_bottom = ' <div class="single_column cards_section"> <button id="exit" class="return_to_home full_button">Exit</button> </div>'; /**END TILE**/ $choice_start = '<div class="single_column answer_section"><div id="mc_answer">'; $choice_start_bottom = '</div> </div>'; $choice_end = '<div class="single_column choice_section"><ul id="mc_choices"> <li></li> <li></li> <li></li> </ul>'; $choice_end_bottom = '<button id="next" class="full_button" action="start">Start</button> <button id="exit" class="return_to_home full_button">Exit</button> </div>'; /**END CHOICE**/ $classic_start = '<div class="single_column cards_section"> <div id="qa_cards" class="classic_box"> <ul> <li id="question"></li> <li id="answer"></li> </ul> </div> <button id="next" class="full_button" action="start">Start</button> </div> <div class="single_column score_section"> <div id="tools" class="classic_box"> <div id="progress_bar"> <div id="current_progress"> <div id="right_progress"></div> <div id="wrong_progress"></div> </div> </div> </div> <button id="correct" class="half_button right_half">Correct</button> <button id="wrong" class="half_button">Wrong</button> <button id="exit" class="return_to_home full_button">Exit</button>'; $classic_end = '</div>'; function check_title_file(){ if(file_exists('title_file.txt') === false){ $titles_project = fopen('title_file.txt', "w"); if($titles_project){ fclose($titles_project); }else{ exit; } } } function init($filename){ $titles_file = file_get_contents($filename.'.txt'); if($titles_file === false){ return false; }else{ $titles_series = explode("||", $titles_file); return array_filter($titles_series); } } function valid_filename($filename){ global $filename_replace; return str_replace($filename_replace, '', $filename); } function break_apart_cards($array_of_cards){ $cards_array = array(); if(count($array_of_cards)){ foreach($array_of_cards as $single_set){ $q_and_a = explode("::", $single_set); $cards_array['question'][] = $q_and_a[0]; $cards_array['answer'][] = $q_and_a[1]; } } return $cards_array; } function generate_random_different_num($min, $max){ if(func_num_args() > 2){ $not_equal_to = func_get_arg(2); $random = rand($min, $max); if(in_array($random, $not_equal_to, TRUE)){ return generate_random_different_num($min, $max, $not_equal_to); }else{ return $random; } }else{ return rand($min, $max); } } check_title_file(); if(isset($_GET['project_title']) === true && isset($_GET['action']) === true){ $project_title = $_GET['project_title']; $project_titles = init('title_file'); if($project_titles === false){ }else{ //check for creating new project if($_GET['action'] == 'add'){ $project_result; if(empty($project_title) === true || strlen($project_title) > 30){ $project_result = 'The project title must be 1-30 characters long. <a href="index.html">Try again.</a>'; }elseif(in_array(strtolower($project_title), array_map('strtolower', $project_titles)) === true){ $project_result = 'That project title already exists. <a href="index.html">Try again.</a>'; }else{ $new_project_filename = valid_filename($project_title); $new_project = fopen($new_project_filename.'.txt', "w"); fclose($new_project); $new_project_file = file_put_contents('title_file.txt', $new_project_filename.'||', FILE_APPEND); if ($new_project_file === FALSE){ $project_result = 'There was an error trying to create the project. <a href="index.html">Try again.</a>'; }else{ $project_result = '<h4>'.$project_title.'</h4>'; } } echo $project_result; //check for deleting projects }elseif($_GET['action'] == 'delete'){ $project_titles_str = file_get_contents('title_file.txt'); //delete from title_file.txt if($project_titles_str){ $newtitles_content = str_replace($project_title.'||', '', $project_titles_str); $new_project_file = file_put_contents('title_file.txt', $newtitles_content); if($new_project_file){ //delete the file $del_file = unlink($project_title.'.txt'); if($del_file){ $total_proj = init('title_file'); if($total_proj === false){ }else{ if(count($total_proj) > 0){ foreach($total_proj as $position=>$title){ if(strlen($title) > 0){ echo '<li class="project_title"><input type="radio" onclick="enableButtons(\'projects_page\', \'projects_disabled\')" name="project_title" value="'.$title.'" id="item_'.$position.'"/><label for="item_'.$position.'">'.$title.'</label></li>'; } } }else{ echo '<li class="nothing">You currently have no projects.</li>'; } } }else{ echo 'There was an error trying to create the project. <a href="index.html">Try again.</a>'; } }else{ echo 'There was an error trying to create the project. <a href="index.html">Try again.</a>'; } } }elseif($_GET['action'] == 'check' && isset($_GET['mode']) === true){ $mode = $_GET['mode']; if(in_array($project_title, $project_titles)){ $project_contents = init($project_title); //shuffle cards first shuffle($project_contents); $cards_contents = break_apart_cards($project_contents); $min = 0; if(count($cards_contents)){ if($mode == 'matching'){ //echo $matching_start; $matching_seta_middle = ''; $matching_setb_middle = ''; for($i = count($cards_contents['question']); $i > 0; $i--){ $max = count($cards_contents['question']) - 1; $random_number_a = generate_random_different_num($min, $max); $random_number_b = generate_random_different_num($min, $max); $matching_seta_middle .= '<li class="individual_card q_card"><div>'.$cards_contents['question'][$random_number_a].'</div></li>'; $matching_setb_middle .= '<li class="individual_card a_card"><div>'.$cards_contents['answer'][$random_number_b].'</div></li>'; unset($cards_contents['question'][$random_number_a]); unset($cards_contents['answer'][$random_number_b]); $cards_contents['question'] = array_values($cards_contents['question']); $cards_contents['answer'] = array_values($cards_contents['answer']); } echo $matching_start; echo $matching_seta_start; echo $matching_seta_middle; echo $matching_sets_end; echo $matching_setb_start; echo $matching_setb_middle; echo $matching_sets_end; echo $matching_end; }elseif($mode == 'tile'){ $tile_middle = ''; $merge_q_a = array_merge($cards_contents['question'], $cards_contents['answer']); for($i = count($merge_q_a); $i > 0; $i--){ $max = count($merge_q_a) - 1; $random_number = generate_random_different_num($min, $max); $tile_middle .= '<li class="individual_card"><div>'.$merge_q_a[$random_number].'</div></li>'; unset($merge_q_a[$random_number]); $merge_q_a = array_values($merge_q_a); } echo $tile_start; echo $tile_middle; echo $tile_end; echo $tile_bottom; }elseif($mode == 'choice'){ echo $choice_start; if(count($cards_contents['answer']) >= 3){ $choices = ''; foreach($cards_contents['question'] as $index=>$content){ $max = count($cards_contents['answer']) - 1; $different = array($index); $random_1 = generate_random_different_num($min, $max, $different); $different_2 = array($index, $random_1); $random_2 = generate_random_different_num($min, $max, $different_2); $three_random_choices = array($cards_contents['answer'][$index], $cards_contents['answer'][$random_1], $cards_contents['answer'][$random_2]); shuffle($three_random_choices); $choices .= '<input type="hidden" class="hidden_cards" question="'.$content.'" choices="'.implode('::', $three_random_choices).'"/>'; } echo $choices; }else{ echo '<span class="not_enough">You do not have enough cards in this project.</span>'; } echo $choice_start_bottom; echo $choice_end; echo $choice_end_bottom; }else{ //last one $classic_middle = ''; foreach($cards_contents['question'] as $index=>$content){ $classic_middle .= '<input type="hidden" class="hidden_cards" question="'.$content.'"/>'; } echo $classic_start; echo $classic_middle; echo $classic_end; } }else{ echo 'There are no cards yet in '.$project_title.'. <a href="index.html">Go back</a> and add to your project.'; } }else{ echo 'You have no project named '.$project_title; } } } }elseif(isset($_GET['card_title']) === true && empty($_GET['card_title']) === false && isset($_GET['card_question']) === true && empty($_GET['card_question']) === false && isset($_GET['card_answer']) === true && empty($_GET['card_answer']) === false && isset($_GET['action']) === true){ //check for creating new cards if($_GET['action'] == 'add'){ $card_title = $_GET['card_title']; $card_question = $_GET['card_question']; $card_answer = $_GET['card_answer']; $action_result = file_put_contents($card_title.'.txt', $card_question.'::'.$card_answer.'||', FILE_APPEND); if ($action_result === FALSE){ //output error message echo 'Error'; }else{ //output new card $new_cardslist = init($card_title); if(count($new_cardslist) > 0){ foreach($new_cardslist as $position=>$title){ if(strlen($title) > 0){ $question = substr($title, 0, strpos($title, '::')); $answer = substr($title, strpos($title, '::') + 2, strlen($title)); if(isset($_GET['new']) === true){ echo '<li>Q:'.$question.'<hr/>A:'.$answer.'</li>'; }else{ echo '<li class="project_cards" id="qa_'.$position.'"><input type="radio" name="card_number" value="qa_'.$position.'" onclick="chooseCard(\'qa_'.$position.'\')"/>Q:<textarea class="question_text projects_disabled" disabled>'.$question.'</textarea><hr/>A:<textarea class="answer_text projects_disabled" disabled>'.$answer.'</textarea></li>'; } } } }else{ echo '<li class="nothing">You currently have no projects.</li>'; } } //check for editing cards }elseif($_GET['action'] == 'edit' && isset($_GET['prev']) === true && empty($_GET['prev']) === false){ $card_title = $_GET['card_title']; $previous_line = $_GET['prev']; $new_question = $_GET['card_question']; $new_answer = $_GET['card_answer']; $prev_content = file_get_contents($card_title.'.txt'); $new_content = str_replace($previous_line, $new_question.'::'.$new_answer, $prev_content); $action_result = file_put_contents($card_title.'.txt', $new_content); if ($action_result === FALSE){ //output error message echo 'Error'; }else{ //output new card $new_cardslist = init($card_title); if(count($new_cardslist) > 0){ foreach($new_cardslist as $position=>$title){ if(strlen($title) > 0){ $question = substr($title, 0, strpos($title, '::')); $answer = substr($title, strpos($title, '::') + 2, strlen($title)); echo '<li class="project_cards" id="qa_'.$position.'"><input type="radio" name="card_number" value="qa_'.$position.'" onclick="chooseCard(\'qa_'.$position.'\')"/>Q:<textarea class="question_text projects_disabled" disabled>'.$question.'</textarea><hr/>A:<textarea class="answer_text projects_disabled" disabled>'.$answer.'</textarea></li>'; } } }else{ echo '<li class="nothing">You currently have no projects.</li>'; } } //check for deleting cards }elseif($_GET['action'] == 'delete'){ $card_title = $_GET['card_title']; $del_question = $_GET['card_question']; $del_answer = $_GET['card_answer']; $prev_content = file_get_contents($card_title.'.txt'); $new_content = str_replace($del_question.'::'.$del_answer.'||', '', $prev_content); $action_result = file_put_contents($card_title.'.txt', $new_content); if ($action_result === FALSE){ //output error message echo 'Error'; }else{ //output new card $new_cardslist = init($card_title); if(count($new_cardslist) > 0){ foreach($new_cardslist as $position=>$title){ if(strlen($title) > 0){ $question = substr($title, 0, strpos($title, '::')); $answer = substr($title, strpos($title, '::') + 2, strlen($title)); echo '<li class="project_cards" id="qa_'.$position.'"><input type="radio" name="card_number" value="qa_'.$position.'" onclick="chooseCard(\'qa_'.$position.'\')"/>Q:<textarea class="question_text projects_disabled" disabled>'.$question.'</textarea><hr/>A:<textarea class="answer_text projects_disabled" disabled>'.$answer.'</textarea></li>'; } } }else{ echo '<li class="nothing">You currently have no projects.</li>'; } } } //for checking card a and card b }elseif(isset($_GET['ref']) === true && empty($_GET['ref']) === false && isset($_GET['first_card']) === true && empty($_GET['first_card']) === false && isset($_GET['second_card']) === true && empty($_GET['second_card']) === false && isset($_GET['action']) === true && $_GET['action'] === 'check'){ $title_ref = $_GET['ref']; $first_card = $_GET['first_card']; $second_card = $_GET['second_card']; $ref_cards = init($title_ref); $indiv_cards = break_apart_cards($ref_cards); $search_first_as_q = array_search($first_card, $indiv_cards['question']); $search_first_as_a = array_search($first_card, $indiv_cards['answer']); if($search_first_as_q !== false){ echo ($search_first_as_q === array_search($second_card, $indiv_cards['answer']))?'1':''; }else{ echo ($search_first_as_a === array_search($second_card, $indiv_cards['question']))?'1':''; } //for return answer card b to card a }elseif(isset($_GET['ref']) === true && empty($_GET['ref']) === false && isset($_GET['q']) === true && empty($_GET['q']) === false){ $title_ref = $_GET['ref']; $question = $_GET['q']; $ref_cards = init($title_ref); $indiv_cards = break_apart_cards($ref_cards); if(in_array($question, $indiv_cards['question'])){ $correct_index = array_search($question, $indiv_cards['question']); echo $indiv_cards['answer'][$correct_index]; }else{ echo 'NOT THERE'; } //for showing project titles }elseif(isset($_GET['title']) === true){ $total_proj = init('title_file'); if($total_proj === false){ }else{ if(count($total_proj) > 0){ foreach($total_proj as $position=>$title){ if(strlen($title) > 0){ echo '<li class="project_title"><input type="radio" onclick="enableButtons(\'projects_page\', \'projects_disabled\')" name="project_title" value="'.$title.'" id="item_'.$position.'"/><label for="item_'.$position.'">'.$title.'</label></li>'; } } }else{ echo '<li class="nothing">You currently have no projects.</li>'; } } //for showing project title cards }elseif(isset($_GET['cards']) === true){ $proj_cards = init($_GET['cards']); if($proj_cards === false){ }else{ if(count($proj_cards) > 0){ foreach($proj_cards as $position=>$title){ $title_len = strlen($title); if($title_len > 0){ $question = substr($title, 0, strpos($title, '::')); $answer = substr($title, strpos($title, '::') + 2, strlen($title)); echo '<li class="project_cards" id="qa_'.$position.'"><input type="radio" name="card_number" value="qa_'.$position.'" onclick="chooseCard(\'qa_'.$position.'\')"/>Q:<textarea class="question_text projects_disabled" disabled>'.$question.'</textarea><hr/>A:<textarea class="answer_text projects_disabled" disabled>'.$answer.'</textarea></li>'; } } }else{ echo '<li class="nothing">You currently have no cards.</li>'; } } } ?><file_sep> var page_container = document.getElementById('page_container'); var home_page = document.getElementById('home_page'); var login_page = document.getElementById('login_page'); var projects_page = document.getElementById('projects_page'); var config_page = document.getElementById('config_page'); var create_page = document.getElementById('create_page'); var edit_page = document.getElementById('edit_page'); var register_user = true; var login_user = true; var local_projects = document.getElementById('local_projects'); var web_projects = document.getElementById('web_projects'); var node, selected_project, selected_answer, selected_question; var return_buttons, page_title, input_controls; var pixel_unit = 10; var time_unit = 1; //borrowed from stackoverflow Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; function slideFromDown(element, target_top_padding){ var current_top_padding = window.getComputedStyle(element, null).getPropertyValue('padding-top').replace('px', ''); if (current_top_padding > target_top_padding){ if(current_top_padding != target_top_padding && current_top_padding < pixel_unit){ element.style.paddingTop = (current_top_padding - current_top_padding) + "px"; }else{ element.style.paddingTop = (current_top_padding - pixel_unit) + "px"; } window.setTimeout(function() { slideFromDown(element, target_top_padding); }, time_unit); }else{ return true; } } function showPage(page_tbs){ hidePage(); notId(page_tbs, "page"); slideFromDown(page_container, "0px"); } function showHomePage(){ showPage(home_page); } function notId(element, element_class){ var id = element.getAttribute('id'); var child_nodes = element.parentNode.getElementsByClassName(element_class); for(i = 0; i<child_nodes.length; i++){ if(child_nodes[i].getAttribute('id') != id){ child_nodes[i].style.display = "none"; }else{ child_nodes[i].style.display = "block"; } } } function hidePage(){ page_container.style.paddingTop = "100%"; } function sendDataGet(file_name, element_container, get_string, return_function){ var xmlhttp; if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else{ // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ if(return_function){ return_function(xmlhttp.responseText); } element_container.innerHTML = xmlhttp.responseText; } } var send_to_url = changeArrayToUrlString(get_string); xmlhttp.open("GET", file_name + '?' + send_to_url, false); xmlhttp.send(); } function sendDataPost(file_name, element_container, post_string){ var xmlhttp_post; if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp_post=new XMLHttpRequest(); }else{ // code for IE6, IE5 xmlhttp_post=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp_post.onreadystatechange=function(){ if (xmlhttp_post.readyState==4 && xmlhttp_post.status==200){ element_container.innerHTML = xmlhttp_post.responsetext; } } var send_to_url = changeArrayToUrlString(post_string); xmlhttp_post.open("POST", file_name, true); xmlhttp_post.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp_post.send(send_to_url); } function changeArrayToUrlString(change_array){ var stringed_array = ''; var key; var i = 0; for(key in change_array){ if(change_array[key] instanceof Array){ changeArrayToUrlString(change_array[key]); }else{ stringed_array += key + '=' + change_array[key]; if(Object.size(change_array) > 1 && i < Object.size(change_array) -1){ stringed_array += '&'; } } i++; } return stringed_array; } function blurControl(element){ var default_val = element.getAttribute('default'); var element_id = element.getAttribute('id'); var element_val = element.value; if(element_val.replace(/^\s+|\s+$/g,'') == '' || element_val.replace(/^\s+|\s+$/g,'') == default_val){ element.value = default_val; setPasswordAsText(element); addErrorNotif(element_id); }else{ var input_type = element.getAttribute('id'); if(input_type == 'email'){ if(validEmail(element_val) === false){ addErrorNotif(element_id); }else{ addRightNotif(element_id); } }else if(input_type == 'password'){ if(validAlphaNumeric(element_val) === false){ addErrorNotif(element_id); }else{ addRightNotif(element_id); } blurControl(document.getElementById('confirm_password')); }else if(input_type == 'confirm_password'){ if(element_val != document.getElementById('password').value || validAlphaNumeric(element_val) === false){ addErrorNotif(element_id); }else{ addRightNotif(element_id); } }else{ addRightNotif(element_id); } } } function focusControl(element){ var default_val = element.getAttribute('default'); if(default_val == element.value.replace(/^\s+|\s+$/g,'')){ element.value = ''; } setTextAsPassword(element); } function validAlphaNumeric(element_value){ var regex_alpha_numeric = /^[A-Za-z0-9]*$/; return regex_alpha_numeric.test(element_value); } function validLength(element_value, length){ if(element_value.length > length){ return true; } return false; } function validEmail(email){ var regex_email = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex_email.test(email); } function validValue(element_id){ var element_value = document.getElementById(element_id); if(element_value.value == element_value.getAttribute('default')){ return true; } return false; } function checkIfPassword(element){ return (' ' + element.className + ' ').indexOf('password_control') > -1; } function setPasswordAsText(element){ if(checkIfPassword(element)){ element.setAttribute('type', 'text'); } } function setTextAsPassword(element){ if(checkIfPassword(element)){ element.setAttribute('type', 'password'); } } // borrowed from a stackoverflow user function whichChild(elem){ var i= 0; while((elem = elem.previousSibling) !=null){ if(elem.nodeType === 1){ i++; } } return i; } function containErrorNotif(class_name, class_content){ var notif_container = document.getElementsByClassName('notif_section'); if(notif_container){ for(i = 0; i < notif_container.length; i++){ var input_elements = notif_container[i].parentNode.getElementsByTagName('input'); if(input_elements){ var list_elements = ''; for(j = 0; j < input_elements.length; j++){ list_elements += '<li class="' + class_name + '">' + class_content + '</li>'; } notif_container[i].innerHTML = '<ul>' + list_elements + '</ul>'; } } } } function addErrorNotif(elem_id){ var element = document.getElementById(elem_id); var child_position = whichChild(element); var error_container = document.getElementById(elem_id).parentNode.getElementsByClassName('notif_section')[0]; if(error_container){ var child_error = error_container.getElementsByTagName('li')[child_position]; replaceOrAddClass(child_error, 'error', 'right'); child_error.innerHTML = '&#10006;'; } } function addRightNotif(elem_id){ var element = document.getElementById(elem_id); var child_position = whichChild(element); var right_container = document.getElementById(elem_id).parentNode.getElementsByClassName('notif_section')[0]; if(right_container){ var child_right = right_container.getElementsByTagName('li')[child_position]; replaceOrAddClass(child_right, 'right', 'error'); child_right.innerHTML = '&#10004;'; } } function replaceOrAddClass(element, new_class, old_class){ reg = new RegExp('(\\s|^)'+ old_class +'(\\s|$)') if(element.className.match(reg)){ element.className = element.className.replace(reg, ' ' + new_class + ''); }else{ reg_2 = new RegExp('(\\s|^)'+ new_class +'(\\s|$)'); if(element.className.match(reg_2) == null){ new_class = " " + new_class; element.className += " " + new_class; } } } /********/ /**INIT**/ /********/ function init(){ get_return_buttons(); } init(); showHomePage(); containErrorNotif('required', '&#42;'); var input_control = document.getElementsByTagName("input"); for(i = 0; i < input_control.length; i++){ input_control[i].onfocus = function(){ focusControl(this); } input_control[i].onblur = function(){ blurControl(this); } } var password_control = document.getElementsByClassName("password_control") for(i = 0; i < password_control.length; i++){ setPasswordAsText(password_control[i]); } //when user hits the local button var local_button = document.getElementById('local'); if(local_button){ local_button.onclick = function(){ var param = new Array(); param['title'] = 0; sendDataGet('parse.php', local_projects, param); //TODO //getFileContents('parse.php', web_projects, 'popular'); showPage(projects_page); } } //when user hits the online button var online_button = document.getElementById('online'); if(online_button){ online_button.onclick = function(){ showPage(login_page); } } //when user hits the start button var start_button = document.getElementById('start'); if(start_button){ start_button.onclick = function(){ selected_project = getSelected('project_title'); showPage(config_page); } } //when user hits the new project button var new_button = document.getElementById('new_project'); if(new_button){ new_button.onclick = function(){ showPage(create_page); } } //when user hits the start game button var game_button = document.getElementById('game'); if(game_button){ game_button.onclick = function(){ var project_title = getSelected('project_title'); var mode = getSelected('game_type'); console.log(project_title); console.log(mode); window.location = 'game.html?title=' + project_title + '&mode=' + mode; } } //when user hits return to home button function get_return_buttons(){ return_buttons = document.getElementsByClassName('return_to_home'); page_title = document.getElementsByTagName('title')[0].innerHTML; input_controls = document.getElementsByTagName('input'); for(i = 0; i < return_buttons.length; i++){ return_buttons[i].onclick = return_to_home; } } function return_to_home(){ if(page_title.indexOf('Study') !== -1){ window.location = 'index.html'; }else if(page_title.indexOf('Home') !== -1){ showHomePage(); disableButtons('page_container', 'projects_disabled'); for(j = 0; j < input_controls.length; j++){ input_controls[j].checked = false; } document.getElementById('add_title_container').innerHTML = '<input type="text" id="add_title" default="Enter project title" value="Enter project title" onblur="blurControl(this)" onfocus="focusControl(this)"/>'; } } /*******************/ /**users functions**/ /*******************/ //logging in var login_button = document.getElementById('login_button'); if(login_button){ var login = document.getElementById('login'); login_button.onclick = function(){ var login_controls = login.getElementsByTagName('input'); if(login_controls){ var login_details = new Array(); for(i = 0; i < login_controls.length; i++){ //validate the input fields blurControl(login_controls[i]); login_details[i] = [login_controls[i].getAttribute('id'), login_controls[i].value]; } //if correct, ajax it to parse.php if(login.getElementsByClassName('error').length < 1){ console.log('ready for ajax'); //TODO } } } } //registering var register_button = document.getElementById('register_button'); if(register_button){ var register = document.getElementById('register'); register_button.onclick = function(){ var register_controls = register.getElementsByTagName('input'); if(register_controls){ var register_details = new Array(); for(i = 0; i < register_controls.length; i++){ //validate the input fields blurControl(register_controls[i]); register_details.push([register_controls[i].getAttribute('id'), register_controls[i].value]); } if(register.getElementsByClassName('error').length < 1){ //if correct, ajax it to parse.php } } } } /**********************/ /**projects functions**/ /**********************/ //creating new project var add_project = document.getElementById('add_project'); if(add_project){ add_project.onclick = function(){ var add_title = document.getElementById('add_title'); var title_value = add_title.value; var post_string = new Array(); post_string['project_title'] = title_value; post_string['action'] = 'add'; sendDataGet('parse.php', add_title.parentNode, post_string, function(response){ if(response.indexOf('<h4>') !== -1){ enableButtons('create_page', 'projects_disabled'); } }); } } //borrowed from a stackoverflow user function getSelected(name) { var elements = document.getElementsByName(name); for (i=0; i<elements.length; ++i) if (elements[i].checked) return elements[i].value; } function enableButtons(parent_container, button_class){ var project_disabled = document.getElementById(parent_container).getElementsByClassName(button_class); if(project_disabled){ for(j=0; j<project_disabled.length; ++j){ project_disabled[j].disabled = false; } } } function disableButtons(parent_container, button_class){ var project_enabled = document.getElementById(parent_container).getElementsByClassName(button_class); if(project_enabled){ for(i=0; i<project_enabled.length; ++i){ project_enabled[i].disabled = true; } } } //selecting a project function chooseCard(radio_container){ var radio_cards = document.getElementById(radio_container).parentNode.getElementsByTagName('input'); var question_text = document.getElementById(radio_container).getElementsByClassName('question_text')[0]; var answer_text = document.getElementById(radio_container).getElementsByClassName('answer_text')[0]; selected_question = question_text.value; selected_answer = answer_text.value; if(radio_cards){ for(j=0; j<radio_cards.length; ++j){ if(radio_cards[j].checked === false){ disableButtons(radio_cards[j].value, 'projects_disabled'); } } } enableButtons('existing_buttons', 'projects_disabled'); enableButtons(radio_container, 'projects_disabled'); } //deleting project var delete_project = document.getElementById('delete_project'); if(delete_project){ delete_project.onclick = function(){ //confirm if user was conscious when he/she clicked the delete button var del_projecttitle = getSelected('project_title'); var projects_container = document.getElementById('local_projects'); var do_delete = confirm("Do you really want to delete " + del_projecttitle + "?"); if(do_delete){ //get the variables needed var project_cards = new Array(); project_cards['project_title'] = del_projecttitle; project_cards['action'] = 'delete'; //send using sendDataGet() sendDataGet('parse.php', projects_container, project_cards); } } } //editing a project var edit_project = document.getElementById('edit_project'); if(edit_project){ edit_project.onclick = function(){ //get the necessary variables var edit_projecttitle = getSelected('project_title'); var edittitle_container = document.getElementById('edit_page').getElementsByTagName('h3')[0]; var cards_container = document.getElementById('edit_page').getElementsByClassName('content_list')[0]; var project_cards = new Array(); project_cards['cards'] = edit_projecttitle; edittitle_container.innerHTML = edit_projecttitle; sendDataGet('parse.php', cards_container, project_cards); showPage(edit_page); } } var edit_add_card = document.getElementById('edit_add_card'); if(edit_add_card){ edit_add_card.onclick=function(){ //get the necessary variables var edit_question = document.getElementById('edit_question'); var edit_question_val = edit_question.value; var edit_answer = document.getElementById('edit_answer'); var edit_answer_val = edit_answer.value; var edit_projecttitle = document.getElementById('edit_page').getElementsByTagName('h3')[0].innerHTML; var cards_container = document.getElementById('edit_page').getElementsByClassName('content_list')[0]; if(edit_question_val !== '' && edit_answer_val !== ''){ var project_cards = new Array(); project_cards['card_title'] = edit_projecttitle; project_cards['card_question'] = edit_question_val; project_cards['card_answer'] = edit_answer_val; project_cards['action'] = 'add'; sendDataGet('parse.php', cards_container, project_cards, function(response){ if(response.indexOf('li') !== -1){ var addcard_textarea = document.getElementById('edit_page').getElementsByTagName('textarea'); for(i = 0; i < addcard_textarea.length; i++){ addcard_textarea[i].value = ''; } }else{ cards_container.innerHTML = 'An error ocurred. <a href="index.html">Try again.</a>'; } }); }else{ alert('Enter a value for question and answer'); } } } //adding a card var add_card = document.getElementById('add_card'); if(add_card){ add_card.onclick = function(){ var add_question = document.getElementById('add_question'); var add_question_val = add_question.value; var add_answer = document.getElementById('add_answer'); var add_answer_val = add_answer.value; var addcard_title = document.getElementById('add_title_container').getElementsByTagName('h4')[0]; if(add_question_val !== '' && add_answer_val !== ''){ var card_string = new Array(); card_string['card_title'] = addcard_title.innerHTML; card_string['card_question'] = add_question_val; card_string['card_answer'] = add_answer_val; card_string['action'] = 'add'; card_string['new'] = 'true'; console.log(card_string) sendDataGet('parse.php', '', card_string, function(response){ console.log(response) var create_cardlist = document.getElementById('create_page').getElementsByClassName('content_list')[0]; if(response.indexOf('li') !== -1){ if(create_cardlist){ console.log(create_cardlist) cardlist = create_cardlist.innerHTML; console.log(cardlist) create_cardlist.innerHTML = cardlist + response; var addcard_textarea = document.getElementById('create_page').getElementsByTagName('textarea'); for(i = 0; i < addcard_textarea.length; i++){ addcard_textarea[i].value = ''; } } }else{ create_cardlist.innerHTML = 'An error ocurred. <a href="index.html">Try again.</a>'; } }); }else{ alert('Enter a value for question and answer'); } } } //deleting a card var delete_existcard = document.getElementById('delete_existcard'); if(delete_existcard){ delete_existcard.onclick=function(){ var card_position = getSelected('card_number'); var project_filename = document.getElementById('edit_page').getElementsByTagName('h3')[0].innerHTML; var del_question = document.getElementById(card_position).getElementsByClassName('question_text')[0].innerHTML; var del_answer = document.getElementById(card_position).getElementsByClassName('answer_text')[0].innerHTML; var cards_container = document.getElementById('edit_page').getElementsByClassName('content_list')[0]; var card_string = new Array(); card_string['card_title'] = project_filename; card_string['card_question'] = del_question; card_string['card_answer'] = del_answer; card_string['action'] = 'delete'; console.log(card_string); sendDataGet('parse.php', cards_container, card_string); } } //editing a card var edit_existcard = document.getElementById('edit_existcard'); if(edit_existcard){ edit_existcard.onclick=function(){ var card_position = getSelected('card_number'); var old_line = selected_question + '::' + selected_answer; var project_filename = document.getElementById('edit_page').getElementsByTagName('h3')[0].innerHTML; var current_question = document.getElementById(card_position).getElementsByClassName('question_text')[0].value; var current_answer = document.getElementById(card_position).getElementsByClassName('answer_text')[0].value; var cards_container = document.getElementById('edit_page').getElementsByClassName('content_list')[0]; if(current_question !== '' && current_answer !== ''){ var card_string = new Array(); card_string['card_title'] = project_filename; card_string['card_question'] = current_question; card_string['card_answer'] = current_answer; card_string['prev'] = old_line; card_string['action'] = 'edit'; console.log(card_string); sendDataGet('parse.php', cards_container, card_string); }else{ alert('Enter a value for question and answer'); } } }<file_sep>KyuKards is a fun twist to learning with using flash cards. Create flash cards. Then use it in varying study game modes (classic, matching, tile, multiple choice). Currently, there is only local functionality available (given you have a server to install and run php).
f9d8eeaf7162255d8be71bf56f94d2e2b49ee824
[ "JavaScript", "Markdown", "PHP" ]
3
PHP
nagyistoce/kyukards
41253c3b6e5cf47090dad354e4ffa4ce3678ccd4
8db42a4c06ceb90102e98a8ab3345d539310915b
refs/heads/master
<file_sep>import re running = True print("\nWelcome to The Multiplication Table!") while running: max_val = input("\nChoose your highest number: ") # Continues running if anything but int is input max_val = re.sub(r'[^\d]+', '', max_val) if max_val == "": continue max_val = int(max_val) # Determines max number of digits per integer in table max_length = len(str(max_val ** 2)) # Columns for i in range(1, max_val + 1): # Rows for j in range(1, max_val + 1): print(str((j * i)).ljust(max_length, ' '), end=" "), print() <file_sep>You remember those multiplication tables from elementary school, right? The ones where you choose a number on the top row and one on the side and see where they meet on the chart? Good. It would be easy enough to just write it out, but let's try using Python to our advantage. Goal Create a program that prints out a multiplication table for the numbers 1 through 9. It should include the numbers 1 through 9 on the top and left axises, and it should be relatively easy to find the product of two numbers. Do not simply write out every line manually (ie print('7 14 21 28 35 49 56 63') ). Sub-goals As your products get larger, your columns will start to get crooked from the number of characters on each line. Clean up your table by evenly spacing columns so it is very easy to find the product of two numbers. Allow the user to choose a number to change the size of the table (so if they type in 12, the table printed out should be a 12x12 multiplication table).
9b77d4994463073f015d1e2a94e52294dfc2bf4c
[ "Python", "Text" ]
2
Python
jsusca/Multiplication_Table
65590d2f8d7c717059c2ba664f608d5c6b71a414
03e8dd82260f1c24e299d002e48d949f659d3b80
refs/heads/master
<file_sep>namespace Shyjus.BrowserDetection { /// <summary> /// A type representing the browser information. /// </summary> public interface IBrowser { /// <summary> /// Gets the device type. /// Possible values are /// 1. Desktop /// 2. Tablet /// 3. Mobile /// </summary> string DeviceType { get; } /// <summary> /// Gets the browser name. /// Ex:"Chrome" /// </summary> string Name { get; } /// <summary> /// Gets the operating system. /// Ex:"Windows" /// </summary> string OS { get; } /// <summary> /// Gets the browser version. /// </summary> string Version { get; } } }<file_sep>namespace DemoApp.Middleware { using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Shyjus.BrowserDetection; /// <summary> /// A custom middle-ware which uses the browser detection feature. /// This sample returns a string when the request is coming form non-chromium based EDGE browser. /// </summary> public class MyCustomMiddlewareUsingBrowserDetection { private RequestDelegate next; public MyCustomMiddlewareUsingBrowserDetection(RequestDelegate next) { this.next = next; } public async Task InvokeAsync(HttpContext httpContext, IBrowserDetector browserDetector) { var browser = browserDetector.Browser; var isTestingMiddleware = httpContext.Request.Query.ContainsKey("mwcheck") || httpContext.Request.Query.ContainsKey("middlewarecheck") || httpContext.Request.Query.ContainsKey("middleware-check"); httpContext.Request.Query.ContainsKey("middleware"); httpContext.Request.Query.ContainsKey("mw"); httpContext.Request.Query.ContainsKey("mw-check"); if (browser.Name == BrowserNames.Edge && isTestingMiddleware) { await httpContext.Response.WriteAsync("Have you tried the new chromuim based edge ?"); } else { await this.next.Invoke(httpContext); } } } } <file_sep>namespace BrowserDetector.Tests { using Shyjus.BrowserDetection; using Shyjus.BrowserDetection.Tests; using Xunit; /// <summary> /// Tests for Chrome. /// </summary> public class ChromeTests { [Fact] public void Chrome_IPad() { var isChrome = Chrome.TryParse(UserAgents.Chrome_IPad, out var browser); Assert.True(isChrome); Assert.Equal(BrowserNames.Chrome, browser.Name); Assert.Equal(DeviceTypes.Tablet, browser.DeviceType); Assert.Equal(OperatingSystems.IOS, browser.OS); } [Fact] public void Chrome_IPhone() { var isChrome = Chrome.TryParse(UserAgents.Chrome_IPhone, out var browser); Assert.True(isChrome); Assert.Equal(DeviceTypes.Mobile, browser.DeviceType); Assert.Equal(OperatingSystems.IOS, browser.OS); } [Fact] public void Chrome_Windows_Desktop() { var isChrome = Chrome.TryParse(UserAgents.Chrome_Windows, out var browser); Assert.True(isChrome); Assert.Equal(DeviceTypes.Desktop, browser.DeviceType); Assert.Equal(OperatingSystems.Windows, browser.OS); } [Fact] public void Chrome_Windows_Desktop_32Bit() { var isChrome = Chrome.TryParse(UserAgents.Chrome_Windows32, out var browser); Assert.True(isChrome); Assert.Equal(DeviceTypes.Desktop, browser.DeviceType); Assert.Equal(OperatingSystems.Windows, browser.OS); } [Fact] public void Chrome_OSX_Desktop() { var isChrome = Chrome.TryParse(UserAgents.Chrome_OSX, out var browser); Assert.True(isChrome); Assert.Equal(DeviceTypes.Desktop, browser.DeviceType); Assert.Equal(OperatingSystems.MacOSX, browser.OS); } [Fact] public void Chrome_Pixel3() { var isChrome = Chrome.TryParse(UserAgents.Chrome_Pixel3, out var browser); Assert.True(isChrome); Assert.Equal(DeviceTypes.Mobile, browser.DeviceType); Assert.Equal(OperatingSystems.Android, browser.OS); } [Fact] public void Chrome_Galaxy_Note8_Mobile() { var isChrome = Chrome.TryParse(UserAgents.Chrome_Galaxy_Note8_Mobile, out var browser); Assert.True(isChrome); Assert.Equal(DeviceTypes.Mobile, browser.DeviceType); Assert.Equal(OperatingSystems.Android, browser.OS); } [Fact] public void Chrome_GalaxyTabS4() { var isChrome = Chrome.TryParse(UserAgents.Chrome_GalaxyTabS4, out var browser); Assert.True(isChrome); Assert.Equal(DeviceTypes.Tablet, browser.DeviceType); Assert.Equal(OperatingSystems.Android, browser.OS); } } } <file_sep>namespace Shyjus.BrowserDetection { using System; /// <summary> /// A type representing the FireFox browser instance. /// </summary> internal class Firefox : Browser { private Firefox(ReadOnlySpan<char> userAgent, string version) : base(userAgent, version) { } public string Platform { get; } /// <inheritdoc/> public override string Name => BrowserNames.Firefox; /// <summary> /// Tries to build a Firefox browser instance from the user agent passed in and /// returns a value that indicates whether the parsing succeeded. /// </summary> /// <param name="userAgent">The user agent value.</param> /// <param name="result">A Firefox browser instance.</param> /// <returns>A boolean value that indicates whether the parsing succeeded.</returns> public static bool TryParse(ReadOnlySpan<char> userAgent, out Firefox result) { // Desktop version of Firefox. var fireFoxVersion = GetVersionIfKeyPresent(userAgent, "Firefox/"); if (fireFoxVersion != null) { result = new Firefox(userAgent, fireFoxVersion); return true; } // IOS version of Firefox. var fxiosVersion = GetVersionIfKeyPresent(userAgent, "FxiOS/"); if (fxiosVersion != null) { result = new Firefox(userAgent, fxiosVersion); return true; } result = null; return false; } } } <file_sep>namespace Shyjus.BrowserDetection { public static class DeviceTypes { public const string Desktop = "Desktop"; public const string Mobile = "Mobile"; public const string Tablet = "Tablet"; } } <file_sep>namespace Shyjus.BrowserDetection { public class OperatingSystems { public const string Windows = "Windows"; public const string Android = "Android"; public const string MacOSX = "OSX"; public const string IOS = "IOS"; } } <file_sep>using BenchmarkDotNet.Running; using System; namespace BrowserDetector.Benchmarks { class Program { static void Main(string[] args) { var summary = BenchmarkRunner.Run<DetectorBenchmarks>(); Console.WriteLine("Benchmark done."); } } //dotnet run -c Release -- --job short --runtimes clr core --filter BrowserDetector.Benchmarks } <file_sep>namespace Shyjus.BrowserDetection { using System; /// <summary> /// Represents an instance of Edge Browser /// </summary> internal class InternetExplorer : Browser { public InternetExplorer(ReadOnlySpan<char> userAgent, string version) : base(userAgent, version) { } public override string Name => BrowserNames.InternetExplorer; /// <summary> /// Tries to build an instance of InternetExplorer browser from the user agent passed in and /// returns a value that indicates whether the parsing succeeded. /// </summary> /// <param name="userAgent">The user agent value.</param> /// <param name="result">An instance of EdgeChromium browser.</param> /// <returns>A boolean value that indicates whether the parsing succeeded.</returns> public static bool TryParse(ReadOnlySpan<char> userAgent, out InternetExplorer result) { var tridentVersion = GetVersionIfKeyPresent(userAgent, "Trident/"); if (tridentVersion != null) { result = new InternetExplorer(userAgent, tridentVersion); return true; } result = null; return false; } } } <file_sep>namespace Shyjus.BrowserDetection { using System; /// <summary> /// Represents an instance of EdgeChromium Browser. /// </summary> internal class EdgeChromium : Browser { public EdgeChromium(ReadOnlySpan<char> userAgent, string version) : base(userAgent, version) { } /// <inheritdoc/> public override string Name => BrowserNames.EdgeChromium; /// <summary> /// Tries to build a EdgeChromium browser instance from the user agent passed in and /// returns a value that indicates whether the parsing succeeded. /// </summary> /// <param name="userAgent">The user agent value.</param> /// <param name="result">An EdgeChromium browser instance.</param> /// <returns>A boolean value that indicates whether the parsing succeeded.</returns> public static bool TryParse(ReadOnlySpan<char> userAgent, out EdgeChromium result) { var edgChromiumVersion = GetVersionIfKeyPresent(userAgent, "Edg/"); if (edgChromiumVersion != null) { result = new EdgeChromium(userAgent, edgChromiumVersion); return true; } result = null; return false; } } } <file_sep>namespace Shyjus.BrowserDetection { using System; /// <summary> /// Represents an instance of Instagram Browser /// Sample user agent string: Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Instagram 172.16.58.3.121 (iPhone9,3; iOS 12_4_1; tr_TR; tr-TR; scale=2.00; 750x1334; 224680684) /// </summary> internal class Instagram : Browser { public Instagram(ReadOnlySpan<char> userAgent, string version) : base(userAgent, version) { } /// <inheritdoc/> public override string Name => BrowserNames.Instagram; /// <summary> /// Populates a Instagram browser object from the userAgent value passed in. A return value indicates the parsing and populating the browser instance succeeded. /// </summary> /// <param name="userAgent">User agent value.</param> /// <param name="result">When this method returns True, the result will contain a Instagram object populated.</param> /// <returns>True if parsing succeeded, else False.</returns> public static bool TryParse(ReadOnlySpan<char> userAgent, out Instagram result) { var instagramIndex = userAgent.IndexOf("Instagram ".AsSpan()); // Instagram should have "Instagram" words in it. if (instagramIndex > -1) { var instagramVersion = GetVersionIfKeyPresent(userAgent, "Instagram "); if (instagramVersion != null) { result = new Instagram(userAgent, instagramVersion); return true; } } result = null; return false; } } } <file_sep>namespace Shyjus.BrowserDetection { internal class Platforms { public const string Windows10 = "Windows NT 10.0"; public const string Pixel3 = "Pixel 3"; public const string SMT835 = "SM-T835"; public const string iPhone = "iPhone"; public const string iPad = "iPad"; public const string Macintosh = "Macintosh"; } } <file_sep>namespace Shyjus.BrowserDetection { using System; /// <summary> /// A helper to detect the platform. /// </summary> internal static class PlatformDetector { internal static (string Platform, string OS, bool MobileDetected) GetPlatformAndOS(ReadOnlySpan<char> userAgentString) { // Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537. // Platform starts with a "(". So get it's index var platformSearhKeyStartIndex = " (".AsSpan(); // The index of substring where platform part starts var platformSubstringStartIndex = userAgentString.IndexOf(platformSearhKeyStartIndex) + platformSearhKeyStartIndex.Length; // Get substring which starts with platform part (Trim out anything before platform) var platformSubstring = userAgentString.Slice(platformSubstringStartIndex); // Find end index of end character of platform part. var platFormPartEndIndex = platformSubstring.IndexOf(';'); // For 32 bit, no ";" present, so get the closing ")"; if (platFormPartEndIndex == -1) { platFormPartEndIndex = platformSubstring.IndexOf(')'); } // Get the platform part slice var platformSlice = platformSubstring.Slice(0, platFormPartEndIndex); // OS part is between two ";" after platform slice // Get the sub slice which is after platform var osSubString = platformSubstring.Slice(platFormPartEndIndex + 2); // ';' length +' ' length // Find the end index of platform end character from the os sub slice var osPartEndIndex = osSubString.IndexOf(')'); // Get the OS part slice var operatingSystemSlice = osSubString.Slice(0, osPartEndIndex); // If OS part starts with "Linux", check for next segment to get android veersion //Linux; Android 9; Pixel 3 // Linux; Android 8.1.0; SM-T835 var platform = platformSlice.ToString(); var isMobileSlicePresent = userAgentString.IndexOf("Mobile".AsSpan()) > -1; var os = GetReadableOSName(platform, operatingSystemSlice.ToString()); return (Platform: platform, OS: os, MobileDetected: isMobileSlicePresent); } /// <summary> /// Gets a readable OS name from the platform & operatingSystem info. /// For some cases, the "operatingSystem" param value is not enought and we rely on the platform param value. /// </summary> /// <param name="platform"></param> /// <param name="operatingSystem"></param> /// <returns>The OS name.</returns> private static string GetReadableOSName(string platform, string operatingSystem) { if (platform == Platforms.iPhone || platform == Platforms.iPad) { return OperatingSystems.IOS; } // If platform starts with "Android" (Firefox galaxy tab4) if (platform == "Android") { return OperatingSystems.Android; } if (platform == "Macintosh") { return OperatingSystems.MacOSX; } if (platform.StartsWith("Windows NT")) { return OperatingSystems.Windows; } if (platform == "Pixel 3") { return OperatingSystems.Android; } // Pixel 3 if (platform == "Linux" && operatingSystem.IndexOf("Android", StringComparison.OrdinalIgnoreCase) > -1) { return OperatingSystems.Android; } return operatingSystem; } } } <file_sep>``` ini BenchmarkDotNet=v0.11.5, OS=Windows 10.0.18362 Intel Xeon CPU E5-1650 v4 3.60GHz, 1 CPU, 12 logical and 6 physical cores .NET Core SDK=3.0.100-preview9-014004 [Host] : .NET Core 2.2.6 (CoreCLR 4.6.27817.03, CoreFX 4.6.27818.02), 64bit RyuJIT DefaultJob : .NET Core 2.2.6 (CoreCLR 4.6.27817.03, CoreFX 4.6.27818.02), 64bit RyuJIT ``` | Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |--------------- |---------:|----------:|----------:|-------:|------:|------:|----------:| | Chrome_Windows | 1.057 us | 0.0015 us | 0.0014 us | 0.0324 | - | - | 208 B | | Safari_Windows | 1.093 us | 0.0205 us | 0.0192 us | 0.0286 | - | - | 192 B | <file_sep>using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Shyjus.BrowserDetection; namespace DemoApp.Controllers { public class HomeController : Controller { private readonly IBrowserDetector browserDetector; public HomeController(IBrowserDetector browserDetector, IHttpContextAccessor a) { this.browserDetector = browserDetector; } public IActionResult Index() { var browser = this.browserDetector.Browser; // Use browser object as needed. return View(); } [Route("headers")] public IActionResult Headers() { return View(); } } } <file_sep>namespace Shyjus.BrowserDetection { using System; /// <summary> /// Represents an instance of Opera Browser. /// </summary> internal class Opera : Browser { public Opera(ReadOnlySpan<char> userAgent, string version) : base(userAgent, version) { } public override string Name => BrowserNames.Opera; /// <summary> /// Tries to build an instance of Opera browser from the user agent passed in and /// returns a value that indicates whether the parsing succeeded. /// </summary> /// <param name="userAgent">The user agent value.</param> /// <param name="result">An instance of Opera browser.</param> /// <returns>A boolean value that indicates whether the parsing succeeded.</returns> public static bool TryParse(ReadOnlySpan<char> userAgent, out Opera result) { var operaVersion = GetVersionIfKeyPresent(userAgent, "OPR/"); var operaTouchVersion = GetVersionIfKeyPresent(userAgent, " OPT/"); if (operaVersion != null) { result = new Opera(userAgent, operaVersion); return true; } if (operaTouchVersion != null) { result = new Opera(userAgent, operaVersion); return true; } result = null; return false; } } } <file_sep>namespace Shyjus.BrowserDetection { using System; /// <summary> /// Represents an instance of Chrome Browser /// has both "Safari" and "Chrome" in UA /// Sample user agent string: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 /// </summary> internal class Chrome : Browser { public Chrome(ReadOnlySpan<char> userAgent, string version) : base(userAgent, version) { } /// <inheritdoc/> public override string Name => BrowserNames.Chrome; /// <summary> /// Populates a Chrome browser object from the userAgent value passed in. A return value indicates the parsing and populating the browser instance succeeded. /// </summary> /// <param name="userAgent">User agent value</param> /// <param name="result">When this method returns True, the result will contain a Chrome object populated</param> /// <returns>True if parsing succeeded, else False</returns> public static bool TryParse(ReadOnlySpan<char> userAgent, out Chrome result) { var chromeIndex = userAgent.IndexOf("Chrome/".AsSpan()); var safariIndex = userAgent.IndexOf("Safari/".AsSpan()); var crIOS = userAgent.IndexOf("CriOS/".AsSpan()); // Chrome should have both "Safari" and "Chrome" words in it. if ((safariIndex > -1 && chromeIndex > -1) || (safariIndex > -1 && crIOS > -1)) { var fireFoxVersion = GetVersionIfKeyPresent(userAgent, "Chrome/"); if (fireFoxVersion != null) { result = new Chrome(userAgent, fireFoxVersion); return true; } var chromeIosVersion = GetVersionIfKeyPresent(userAgent, "CriOS/"); if (chromeIosVersion != null) { result = new Chrome(userAgent, chromeIosVersion); return true; } } result = null; return false; } } } <file_sep>namespace Shyjus.BrowserDetection { using System; internal abstract class Browser : IBrowser { private readonly string platform; protected Browser(ReadOnlySpan<char> userAgent, string version) { this.Version = version; var platform = PlatformDetector.GetPlatformAndOS(userAgent); this.platform = platform.Platform; this.OS = platform.OS; // Get the device type from platform info. this.DeviceType = this.GetDeviceType(platform); } /// <inheritdoc/> public abstract string Name { get; } /// <inheritdoc/> public string DeviceType { get; } /// <inheritdoc/> public string Version { get; } /// <inheritdoc/> public string OS { get; } /// <summary> /// Gets the version segment from user agent for the key passed in. /// </summary> /// <param name="userAgent">The user agent value.</param> /// <param name="key">The key to use for looking up the version segment.</param> /// <returns>The version segment.</returns> protected static string GetVersionIfKeyPresent(ReadOnlySpan<char> userAgent, string key) { var keyStartIndex = userAgent.IndexOf(key.AsSpan()); if (keyStartIndex == -1) { return null; } var sliceWithVersionPart = userAgent.Slice(keyStartIndex + key.Length); var endIndex = sliceWithVersionPart.IndexOf(' '); if (endIndex > -1) { return sliceWithVersionPart.Slice(0, endIndex).ToString(); } return sliceWithVersionPart.ToString(); } /// <summary> /// Gets the device type from the platform information. /// </summary> /// <param name="platform">The platform information.</param> /// <returns>The device type value.</returns> private string GetDeviceType((string Platform, string OS, bool MobileDetected) platform) { if (this.platform == Platforms.iPhone) { return DeviceTypes.Mobile; } else if (this.platform == Platforms.iPad || this.platform == "GalaxyTabS4") { return DeviceTypes.Tablet; } // IPad also has Mobile in it. So make sure to check that first if (platform.MobileDetected) { return DeviceTypes.Mobile; } else if (this.platform == Platforms.Macintosh || this.platform.StartsWith("Windows NT")) { return DeviceTypes.Desktop; } // Samsung Chrome_GalaxyTabS4 does not have "Mobile", but it has Linux and Android. if (this.platform == "Linux" && platform.OS == "Android" && platform.MobileDetected == false) { return DeviceTypes.Tablet; } return string.Empty; } } } <file_sep>namespace Shyjus.BrowserDetection { using System; internal class Safari : Browser { public Safari(ReadOnlySpan<char> userAgent, string version) : base(userAgent, version) { } public override string Name => BrowserNames.Safari; /// <summary> /// Populates a Safari browser object from the userAgent value passed in. A return value indicates the parsing and populating the browser instance succeeded. /// </summary> /// <param name="userAgent">User agent value</param> /// <param name="result">When this method returns True, the result will contain a Safari object populated</param> /// <returns>True if parsing succeeded, else False</returns> /// <exception cref="ArgumentNullException">Thrown when userAgent parameter value is null</exception> public static bool TryParse(ReadOnlySpan<char> userAgent, out Safari result) { var chromeIndex = userAgent.IndexOf("Chrome/".AsSpan()); var safariIndex = userAgent.IndexOf("Safari/".AsSpan()); // Safari UA does not have the word "Chrome/" if (safariIndex > -1 && chromeIndex == -1) { var fireFoxVersion = GetVersionIfKeyPresent(userAgent, "Safari/"); if (fireFoxVersion != null) { result = new Safari(userAgent, fireFoxVersion); return true; } } result = null; return false; } } } <file_sep>namespace Shyjus.BrowserDetection { using System; /// <summary> /// Represents an instance of Edge Browser. /// </summary> internal class Edge : Browser { public Edge(ReadOnlySpan<char> userAgent, string version) : base(userAgent, version) { } /// <inheritdoc/> public override string Name => BrowserNames.Edge; /// <summary> /// Tries to create an Edge browser object from the user agent passed in. /// </summary> /// <param name="userAgent">The user agent.</param> /// <param name="result">An instance of Edge browser, if parsing was successful.</param> /// <returns>A boolean value indicating whether the parsing was successful.</returns> public static bool TryParse(ReadOnlySpan<char> userAgent, out Browser result) { var edgeVersion = GetVersionIfKeyPresent(userAgent, "Edge/"); var edgeIosVersion = GetVersionIfKeyPresent(userAgent, "EdgiOS/"); var edgeAndroidVersion = GetVersionIfKeyPresent(userAgent, "EdgA/"); var version = edgeVersion ?? edgeIosVersion ?? edgeAndroidVersion; if (version == null) { result = null; return false; } result = new Edge(userAgent, version); return true; } } } <file_sep>namespace Microsoft.Extensions.DependencyInjection { using System; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection.Extensions; using Shyjus.BrowserDetection; /// <summary> /// Extension methods for setting up browser detection services in an <see cref="IServiceCollection" />. /// </summary> public static class BrowserDetectionServiceCollectionExtensions { /// <summary> /// Adds browser detection services to the specified <see cref="IServiceCollection" />. /// </summary> /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddBrowserDetection(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpContextAccessor, HttpContextAccessor>()); services.AddScoped<IBrowserDetector, BrowserDetector>(); return services; } } }<file_sep>namespace BrowserDetector.Benchmarks { using System; using BenchmarkDotNet.Attributes; using Shyjus.BrowserDetection; [MemoryDiagnoser] public class DetectorBenchmarks { private readonly string chromeWindows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"; private readonly string safariWindows = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2"; [Benchmark] public string Chrome_Windows() { return Detector.GetBrowser(this.chromeWindows.AsSpan()).Name; } [Benchmark] public string Safari_Windows() { return Detector.GetBrowser(this.safariWindows.AsSpan()).Name; } } } <file_sep>namespace Shyjus.BrowserDetection { using System; using Microsoft.AspNetCore.Http; /// <summary> /// A class to get browser and platform information. /// </summary> public sealed class BrowserDetector : IBrowserDetector { private readonly Lazy<IBrowser> browser; private readonly IHttpContextAccessor httpContextAccessor; /// <summary> /// Initializes a new instance of the <see cref="BrowserDetector"/> class. /// </summary> /// <param name="httpContextAccessor">The IHttpContextAccessor instance.</param> public BrowserDetector(IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor = httpContextAccessor; this.browser = this.GetBrowserLazy(); } /// <summary> /// Gets the browser information. /// </summary> public IBrowser Browser => this.browser.Value; private Lazy<IBrowser> GetBrowserLazy() { return new Lazy<IBrowser>(() => { return this.GetBrowser(); }); } /// <summary> /// Gets the IBrowser instance. /// </summary> /// <returns>The IBrowser instance.</returns> private IBrowser GetBrowser() { var userAgentStringSpan = this.httpContextAccessor.HttpContext.Request.Headers["User-Agent"][0].AsSpan(); return Detector.GetBrowser(userAgentStringSpan); } } } <file_sep>namespace Shyjus.BrowserDetection { internal class Headers { public const string UserAgent = "User-Agent"; } } <file_sep>namespace BrowserDetector.Tests { using Shyjus.BrowserDetection; using Shyjus.BrowserDetection.Tests; using Xunit; /// <summary> /// Tests for Instagram. /// </summary> public class InstagramTests { [Fact] public void Instagram_IPad() { var isInstagram = Instagram.TryParse(UserAgents.Instagram_IPad, out var browser); Assert.True(isInstagram); Assert.Equal(BrowserNames.Instagram, browser.Name); Assert.Equal(DeviceTypes.Tablet, browser.DeviceType); Assert.Equal(OperatingSystems.IOS, browser.OS); } [Fact] public void Instagram_IPhone() { var isChrome = Instagram.TryParse(UserAgents.Instagram_IPhone, out var browser); Assert.True(isChrome); Assert.Equal(DeviceTypes.Mobile, browser.DeviceType); Assert.Equal(OperatingSystems.IOS, browser.OS); } } }
5a48d78de5f58109c4e7c167e5dbb7ff24b1e45b
[ "Markdown", "C#" ]
24
C#
alicoskun/BrowserDetector
e3ea187caf17a3f8ed4496d66cb7d4abb5fa77d6
30f0d9ae0b2c268d1b781e21496e83432ee40b04
refs/heads/master
<repo_name>BenMtl/squid<file_sep>/examples/test.py from squid import * import time rgb = Squid(18, 23, 24) rgb.set_color(RED) time.sleep(2) rgb.set_color(GREEN) time.sleep(2) rgb.set_color(BLUE) time.sleep(2) rgb.set_color(WHITE) time.sleep(2) rgb.set_color(WHITE, 300) time.sleep(2)<file_sep>/build/lib.linux-armv6l-2.7/squid.py #squid.py Library import RPi.GPIO as GPIO import time WHITE = (30, 30, 30) OFF = (0, 0, 0) RED = (100, 0, 0) GREEN = (0, 100, 0) BLUE = (0, 0, 100) YELLOW = (50, 50, 0) PURPLE = (50, 0, 50) CYAN = (0, 50, 50) class Squid: RED_PIN = 0 GREEN_PIN = 0 BLUE_PIN = 0 red_pwm = 0 green_pwm = 0 blue_pwm = 0 def __init__(self, red_pin, green_pin, blue_pin): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) self.RED_PIN, self.GREEN_PIN, self.BLUE_PIN = red_pin, green_pin, blue_pin GPIO.setup(self.RED_PIN, GPIO.OUT) self.red_pwm = GPIO.PWM(self.RED_PIN, 500) self.red_pwm.start(0) GPIO.setup(self.GREEN_PIN, GPIO.OUT) self.green_pwm = GPIO.PWM(self.GREEN_PIN, 500) self.green_pwm.start(0) GPIO.setup(self.BLUE_PIN, GPIO.OUT) self.blue_pwm = GPIO.PWM(self.BLUE_PIN, 500) self.blue_pwm.start(0) def set_red(self, brightness): self.red_pwm.ChangeDutyCycle(brightness) def set_green(self, brightness): self.green_pwm.ChangeDutyCycle(brightness) def set_blue(self, brightness): self.blue_pwm.ChangeDutyCycle(brightness) def set_color(self, (r, g, b), brightness = 100): self.set_red(r * brightness / 100) self.set_green(g * brightness / 100) self.set_blue(b * brightness / 100) <file_sep>/examples/test_button.py from button import * import time b = Button(7) while True: if b.is_pressed(): print(time.time())<file_sep>/build/lib.linux-armv6l-2.7/button.py #squid.py Library import RPi.GPIO as GPIO import time class Button: BUTTON_PIN = 0 DEBOUNCE = 0 def __init__(self, button_pin, debounce=0.05): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) self.BUTTON_PIN = button_pin self.DEBOUNCE = debounce print(debounce) GPIO.setup(self.BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) def is_pressed(self): now = time.time() if GPIO.input(self.BUTTON_PIN) == False: time.sleep(self.DEBOUNCE) # wait for button release while not GPIO.input(self.BUTTON_PIN): pass return True return False <file_sep>/setup.py from distutils.core import setup setup(name='squid', version='1.0', py_modules=['squid', 'button']) <file_sep>/README.md Squid ===== The Raspberry Squid is an RGB LED with built-in resistors and header lead sockets that can fit directly onto GPIO pins of a Raspberry Pi. The Squid has its own library to make it super easy to mix colors on the RGB LED. After the library documentation that follows, you will find instructions on how to create your own Squid. Please feel free to make a squid for your own use, but please don't make them to resell. If you don't want to make your own Squid, you can buy a ready made Raspberry Squid from http://www.monkmakes.com and you will also find it for same on Amazon. # An RGB LED Python Library. Please note that GPIO Zero, the standard Raspberry Pi GPIO library, directly supports RGB LEDs like the Raspberry Squid. So you may just prefer to use this: https://gpiozero.readthedocs.io/en/stable/api_output.html#rgbled Squid is a Python library to drive the Raspberry Squid RGB LED. Or in fact any common cathode RGB LED. The library also includes code for switch debouncing. Something that you may find useful if you have the Raspberry Squid's companion the Raspberry Button. The Raspberry Squid is an RGB LED with built-in series resistors and sockets on the end of color-coded flying leads that will plug directly onto the GPIO header of a Raspberry Pi. ![Raspberry Squid](http://www.simonmonk.org/wp-content/uploads/2014/09/squid_on_b_plus_1-web-1024x437.jpg) The Raspberry Button follows the same concept, but has a push switch with protection resistor built into the leads. ![Raspberry Squid](http://www.monkmakes.com/wp-content/uploads/2015/09/button-web.jpg) # Installation To install the library on your Raspberry Pi, enter the following commands in LX Terminal. For Python 2 use: ``` $ git clone https://github.com/simonmonk/squid.git $ cd squid $ sudo python setup.py install ``` For Python 3 use: ``` $ git clone https://github.com/simonmonk/squid.git $ cd squid $ sudo python3 setup.py install ``` # Connect the RGB LED Plug in a Squid or connect up an RGB LED as follows: + Black, Common cathode of the LED to GND (the one between GPIO 18 and 23 is most convenient) + Red squid lead to GPIO18 + Green squid lead to GPIO23 + Blue squid lead to GPIO24 # Try the Test Programs There are two test programs, one (test.py) that simply turns the LED red, green, blue, white and then bright white. The other test program (gui.py) opens a TkInter window with three sliders to control the red, green and blue chanels of the LED. First change to the examples directory using the command: ``` $ cd examples ``` To run **test** enter the following command: ``` $ sudo python test.py ``` To run **gui.py** enter the following command: ``` $ sudo python gui.py ``` This will open up the window below. Dragging the sliders about will allow you to mix any color. Note that this esample program requires a graphical interface so you cannot run it from SSH. ![GUI Example](http://www.simonmonk.org/wp-content/uploads/2014/09/sliders_gui.png) # API Documentation You can probably find all you need to know by looking at the source code for the examples. ## Importing the library ``` from squid import * ``` ## Creating an Instance ``` rgb = Squid(18, 23, 24) ``` The three parameters are the pins connected to the red, green and blue LEDs. ## set_color ``` rgb.set_color(RED) ``` The color can be one of the following constants: WHITE, OFF, RED, GREEN, BLUE, YELLOW, PURPLE and CYAN. You can also just provide an array containing R, G and B values each between 0 and 100, like this: ``` rgb.set_color([100, 50, 10]) ``` An optional second argument allows you specify the brightness of the color. The value of 100 is equivalent to one of the LEDs only being on at full brightness, thus if you make your R, G and B values add up to 100, then you can reasonably set the brightness value between 0 and 300. ``` rgb.set_color(CYAN, 300) ``` ## set_red(duty), set_green(duty), set_blue(duty) These methods allow you to set the three channels separately. They take one parameter which is the duty cycle for that channel of betweem 0.0 (off) and 1.0 (full brightness). ## set_color_rgb(rgb_string) This method sets the LED color to an internet color value of the form #FF0000. That is a # followed by a six digit hexadecimal string. The six digit string comprises three two character hex value for the red, green and blue channels. ``` rgb.set_color('#FF0000') # red ``` # Connect a Raspberry Button Plug in a switch between the following pins (it does not matter which way around the leads are): + GND + GPIO 25 ## Importing the library ``` from button import * ``` ## Creating an Instance ``` button = Button(25) ``` The parameter is the pin that the button is connected to. There is also an optional second parameter of the debounce period (in seconds) to prevent false triggerings due to contact bouncing. ``` button = Button(25, debounce=0.1) ``` ## checking for button press ``` button.is_pressed() ``` This will return true if the button is pressed and will block and wait until the button has been released and the debounce period has elapsed. Check out the example programs in the /examples folder of this library. # How to Make Your Own Squid ## You will need To make your own Squid, you will need the following parts: + An RGB common cathode diffuse LED (the bigger the better) + 3 x 470 Ohm resistors + Red, green, blue and black Female to Female jumper wires cut in half + 4 short lenths of heat shrink You will also need soldering equipment and a hot air gun. ![Parts](http://simonmonk.org/wp-content/uploads/2015/04/01_parts-copy.jpg) ## Step 1. Prepare the LED Leave the longest lead (common cathode) untouched, but trim the other leads as shown below. ![Preparing the LED](http://simonmonk.org/wp-content/uploads/2015/04/02_helping-hands-copy.jpg) A apir of helping hands will - well - help. ## Step 2. Solder on the resistors Trim the resistor leads and solder one end to each of the three short anode leads on the LED. ![Soldering the Resistors](http://simonmonk.org/wp-content/uploads/2015/04/04_soldering_r-copy.jpg) When all the resistors are soldered, it will look like this. ![soldering the Resistors](http://simonmonk.org/wp-content/uploads/2015/04/05_soldering_resistors-copy.jpg) ## Step 3. Solder on the header wires Slip the heat shrink sleaving over the wires BEFORE soldering the wires to the resistor wires and the common cathode. Use red for the red anode, green for bgreen and blue for blue and use a black wire for the common cathode. ![soldering the header wires](http://simonmonk.org/wp-content/uploads/2015/04/07_all_leads-copy.jpg) ## Step 4. Shrink the sleave Push the heat shrink sleaves right up to the body of the LED and then shrink the wires using a hot air gun. ![shrinking the sleave](http://simonmonk.org/wp-content/uploads/2015/04/10_after_hot_air-copy.jpg)
06a3c3d5ee4bfebf784d335e6347f5a62ba82090
[ "Markdown", "Python" ]
6
Python
BenMtl/squid
dcaaf0faa917f0b78ea2870b3ba79da2ae080c1f
659493b3d8e18824ef6a83cd075e13101f962ea4
refs/heads/master
<repo_name>Alx-Ang/Alexis_Angeles_Segundo_IC_0602_Taller_SO<file_sep>/Unidad_1/Programa_Desarrollo_1_Competencia_1/cola.h #include <stdio.h> //#include <conio.h> #include <stdlib.h> #include "proceso.h" typedef struct nodo { struct proceso info; struct nodo *sig; }nodo; struct nodo *raiz=NULL; struct nodo *fondo=NULL; int vacia() { if (raiz == NULL) return 1; else return 0; } void insertar(proceso x) { struct nodo *nuevo; nuevo=(nodo*)malloc(sizeof(struct nodo)); nuevo->info=x; nuevo->sig=NULL; if (vacia()) { raiz = nuevo; fondo = nuevo; } else { fondo->sig = nuevo; fondo = nuevo; } } proceso extraer() { if (!vacia()) { proceso informacion = raiz->info; struct nodo *bor = raiz; if (raiz == fondo) { raiz = NULL; fondo = NULL; } else { raiz = raiz->sig; } free(bor); return informacion; } else{ printf("error al desnecolar"); } } void imprimir() { struct nodo *reco = raiz; printf("Listado de todos los elementos de la cola.\n"); while (reco != NULL) { printf("%i - ", reco->info.pdi); reco = reco->sig; } printf("\n"); } int contar() { int con=0; struct nodo *reco = raiz; while (reco != NULL) { reco = reco->sig; con++; } return con; } void liberar() { struct nodo *reco = raiz; struct nodo *bor; while (reco != NULL) { bor = reco; reco = reco->sig; free(bor); } } <file_sep>/Unidad_[3,4]/Practica_1_Competencia_[3,4]/lista_enlazada.h #ifndef __LISTA_ENLAZADA_H #define __LISTA_ENLAZADA_H #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct nodo{ char palabra[100]; struct nodo *ant; struct nodo *sig; }nodo; typedef struct lista { struct nodo *ini; struct nodo *fin; }lista; int esta_vacia(lista *l); void ingresar_dato(lista *l,char palabras[100]); void imprimir_lista(lista *l); void imprimir_lista_r(lista *l); void limpiar_nodo(nodo *n); void limpiar_lista(lista *l); void ordenar(lista *l,int n); #endif<file_sep>/Unidad_1/Programa_Desarrollo_Reto_Competencia_1/Indices.h typedef struct Indices{ int pais; int cliente; }Indices; Indices crear_indice(){ Indices in; in.pais=-1; in.cliente=-1; return in; } <file_sep>/Unidad_2/Ejercicio_1_Competencia_2/Ejercicio1.c #include<stdio.h> int main(){ char x; char *p; char y; char *puntero; // Inicializar x con el char x x = 'x'; //Asignar la direccion en memoria de la variable "x" al puntero "p" p = &x; // Imprimir el contenido del puntero "p" printf("Contenido del puntero p = %c", *p); // Sumarle 1 al contenido del punter "p" *p = *p + 1; // Imprimir el contenido del puntero "p" printf("\nContenido del puntero p = %c", *p); // Sumar 2 al contenido del puntero "p" y almacenarlo en el mismo puntero "p" *p = *p + 2; // Imprimir el contenido del puntero "p" printf("\nContenido del puntero p = %c", *p); // Inicializar la variable y con valor 'y' y = 'y'; // Asignar la direccion en memoria de la variable "y" al puntero "puntero" puntero = &y; printf("\nContenido del puntero 'puntero' = %c\n", *puntero); } <file_sep>/Unidad_1/Programa_Desarrollo_Reto_Competencia_1/Cliente.h #include <stdio.h> #include <string.h> #include<stdbool.h> typedef struct Cliente { char nombre[30]; char sexo; double saldo; bool ocupado; }Cliente; char validarSexo(char sexo); double validarSaldo(double saldo); bool setOcupado(Cliente c); Cliente crear_cliente(char nombre[],char sexo, double saldo){ Cliente cliente_c; if (strlen(nombre)==0 && sexo=='\0' && !saldo) { strcpy(cliente_c.nombre,""); cliente_c.sexo='\0'; cliente_c.saldo=0.0; cliente_c.ocupado=false; }else{ strcpy(cliente_c.nombre,nombre); cliente_c.sexo=validarSexo(sexo); cliente_c.saldo=validarSaldo(saldo); cliente_c.ocupado=true; } return cliente_c; } Cliente setTodosDatos(Cliente origen,Cliente cliente){ strcpy(origen.nombre,cliente.nombre); origen.sexo=validarSexo(cliente.sexo); origen.saldo=validarSaldo(cliente.saldo); origen.ocupado=setOcupado(origen); return origen; } char validarSexo(char sexo){ if(sexo!='M' && sexo!='F'){ sexo ='\0'; } return sexo; } double validarSaldo(double saldo){ if(saldo <= 0.0){ saldo = 0.0; } return saldo; } bool tieneSaldo(Cliente c){ return c.saldo > 0.0; } bool tieneDatos(Cliente c){ if( strlen(c.nombre)==0|| c.sexo == '\0' || strcmp(c.nombre," ")==0){ return false; }else { return true; } } bool setOcupado(Cliente c){ if(tieneDatos(c)==false){ strcpy(c.nombre,""); c.sexo='\0'; c.saldo=0.0; return false; } else{ return true; } } bool isOcupado(Cliente c) { return c.ocupado; } Cliente eliminar(Cliente c){ strcpy(c.nombre,""); c.sexo='\0'; c.saldo=0.0; c.ocupado=false; return c; } Cliente cambiarNombre(Cliente c, char nuevoNombre[]){ if(strlen(nuevoNombre) != 0 && strcmp(nuevoNombre," ")!=0){ strcpy(c.nombre,nuevoNombre); } c.ocupado=setOcupado(c); return c; } Cliente cambiarSexo(Cliente c ,char sexo){ if(sexo == 'M' || sexo == 'F'){ c.sexo = sexo; } c.ocupado=setOcupado(c); return c; } Cliente abonarSaldo(Cliente c, double cuanto){ if(tieneDatos(c)) { if(cuanto > 0.0){ c.saldo += cuanto; } else{ printf("\tImposible, no puedes abonar saldos negativos o nada."); } } return c; } Cliente retirarSaldo(Cliente c, double cuanto){ if(tieneDatos(c)){ if(cuanto > 0.0){ if(tieneSaldo(c)){ if(c.saldo >= cuanto) c.saldo -= cuanto; else printf("\tImposible, tu saldo es insuficiente para retirar %f.",cuanto); } else printf("\tImposible, no hay saldo."); } else printf("\tImposible, no puedes retirar saldos negativos o nada."); } return c; } void imprimirCliente(Cliente c){ printf("-> Nombre: |%s\n| -> Sexo: |%c\n| -> Saldo: |%f\n| -> Ocupado: |%d|\n",c.nombre,c.sexo,c.saldo,c.ocupado); } <file_sep>/Unidad_[3,4]/Practica_Final_Competencia_[3,4]/servidor_funciones.h #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <unistd.h> struct sockaddr_in servidor; int iniciar_socket_puerto(int puerto); int aceptar(int crear_sokcet); char * leer(int aceptado,int tam); void enviar(int aceptado,char *texto); char *hacer_suma(char *num1, char *num2); <file_sep>/Unidad_[3,4]/Practica_Final_Competencia_[3,4]/Makefile all: gcc -g -c -Wall servidor_funciones.c -o servidor_funciones.o gcc -g -c -Wall servidor.c -o servidor.o gcc -g -Wall servidor.o servidor_funciones.o -o servidor gcc -g -c -Wall cliente_funciones.c -o cliente_funciones.o gcc -g -c -Wall cliente.c -o cliente.o gcc -g -Wall cliente.o cliente_funciones.o -o cliente clean: rm *.o rm cliente rm servidor <file_sep>/Unidad_2/Ejercicio_1_Competencia_2/Ejercicio2.c #include<stdio.h> int main(){ // Crear un array de tipo caracter de tamaño 5 y de nombre arrayChar char arrayChar[5]; int i = 0; // Iniciarlizarlo de a-e for(int car = 97; car < 102; car++){ arrayChar[i] = car; i++; } // Crear un puntero hacia un char de nombre punteroChar e inicializarlo con arrayChar char *punteroChar; punteroChar = &arrayChar[0]; // printf("\nDireccion de punteroChar = %p", &punteroChar); // printf("\nContenido de PunteroChar = %c", punteroChar); // punteroChar = punteroChar + 1; // printf("\nContenido de PunteroChar = %c", punteroChar); // Crear un puntero hacia un char de nombre punteroCharDos e inicializarlo con la direccion del primer elemento (index) del array "arrayChar" char *punteroCharDos; punteroCharDos = &arrayChar[0]; // Imprimir el contenido del primer elemento del array "arrayChar" printf("\nContenido [0] de arrayChar = %c", arrayChar[0]); // Imprimir el contenido del primer elemento del puntero punteroChar printf("\nContenido del primer elemento de punteroChar = %c", *punteroChar); // Imprimir el contenido del primer elemento del puntero punteroCharDos printf("\nContenido del primer elemento de punteroCharDos = %c", *punteroCharDos); // Imprimir el contenido del quinto elemento del array "arrayChar" printf("\nContenido del quinto elemento de arrayChar = %c", arrayChar[4]); //Imprimir el contendo del quinto elemento del puntero "punteroChar" con aritmetica de punteros // punteroChar = *(punteroChar + 4); printf("\nContenido del quinto elemento de punteroChar con aritmetica de punteros = %c", *(punteroChar + 4)); // Imprimir el contenido del quinto elemento del puntero "punteroCharDos" con aritmética de punteros // punteroCharDos = *(punteroCharDos + 4); printf("\nContenido del quinto elemento de punteroCharDos con arimética de punteros = %c", *(punteroCharDos + 4)); // Usar una estructura repetitiva para imprimir el contenido de todos los elementos de "punteroCharDos" con aritmética de punteros for (i = 0; i < 5; i++){ printf("\nContenido [%i] de punteroCharDos = %c", i, *(punteroCharDos + i)); } printf("\n"); // Usar una estructura repetitiva para imprimir el contenido de todos los elementos del puntero punteroCharDos con aritmética de punteros for (int i = 0; i < 5; i++){ printf("\nContenido [%i] de punteroCharDos = %c", i, *(punteroCharDos + i)); } // No entendí esto ultimo de imprimirlo dos veces printf("\n"); return 0; } <file_sep>/Unidad_2/Programa_Desarrollo_1_Competencia_2/scheduler.c #include "scheduler.h" #include <pthread.h> static int buscarIndex_empty(array_procesos *_array); static void initArray(array_procesos *_array); static bool isOk_ID_Process(array_procesos *_array, process _t); process *crear_Proceso(int _id, int _delay, char *_nombreProceso, FN_ACCION _proceso_realizar, int _estado){ process *_p = (process *)malloc(sizeof(process)); _p->id = _id; _p->delay = _delay; strcpy(_p->nombrePROCESO, _nombreProceso); _p->proceso_realizar = _proceso_realizar; _p->estado = _estado; return _p; } void agregar_Proceso(array_procesos *_array, process _p){ int _index = buscarIndex_empty(_array); bool id_ok = isOk_ID_Process(_array, _p); if(_index != -1){ if(id_ok != false){ _array[_index].proceso = _p; _array[_index].empty = false; printf("Se agrego a [_array] el proceso [%s] con id [%d] <---- OK\n", _array[_index].proceso.nombrePROCESO, _array[_index].proceso.id); cont_procesos++; } else{ printf("El ID [%d] ya se encuentra asociado a un Proceso...\n", _p.id); } } else{ printf("NO hay index disponible...\n"); } } void ejecutar_Procesos(array_procesos *_array){ pthread_t tid[cont_procesos]; printf("-----> Procesos = [%d]\n", cont_procesos); for(int i = 0; i < cont_procesos; i++){ if(_array[i].proceso.estado == ACTIVO){ printf("<=================================================================================>\n"); printf("\tEl proceso de nombre [%s], con ID [%d], se encuentra realizando su [PROCESO], con un delay de [%d] segundo(s)\n", _array[i].proceso.nombrePROCESO, _array[i].proceso.id, _array[i].proceso.delay); // Crea un hilo que ejecutará el programa-función pthread_create(&tid[i],NULL, _array[i].proceso.proceso_realizar, NULL); printf("<=================================================================================>\n"); for(int j = 0; j < _array[i].proceso.delay; j++){ sleep(1); } pthread_join(tid[i], NULL); } else if(_array[i].proceso.estado == NO_ACTIVO){ printf("<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>\n"); printf("\tEl proceso de nombre [%s], con ID [%d], SE ENCUENTRA EN ESTADO NO ACTIVO\n", _array[i].proceso.nombrePROCESO, _array[i].proceso.id); printf("<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>\n"); } else{ ; } } } array_procesos *crear_ArrayProcesos(void){ array_procesos *array = (array_procesos *)malloc(sizeof(array_procesos)*MAX_PROCESOS); initArray(array); return array; } /* PRIVATE FUNCTIONS */ static bool isOk_ID_Process(array_procesos *_array, process _p){ bool id_Ok = true; for(int i = 0; i < MAX_PROCESOS; i++){ if(_array[i].proceso.id == _p.id){ id_Ok = false; break; } } return id_Ok; } static void initArray(array_procesos *_array){ for(int i = 0; i < MAX_PROCESOS; i++){ _array[i].proceso.id = -1; _array[i].empty = true; } } static int buscarIndex_empty(array_procesos *_array){ int _index_empty = -1; for(int i = 0; i < MAX_PROCESOS; i++){ if(_array[i].empty == true){ _index_empty = i; break; } } return _index_empty; } <file_sep>/Unidad_[3,4]/Practica_1_Competencia_[3,4]/principal.c #include "manejar_archivo.h" int main(int argc, char const *argv[]) { lista *lis; lis=(lista *)malloc(sizeof(struct lista)); int i=0; if ((char *)argv[1]==NULL){ printf("Archivo de entrada no especificado\n"); }else if (existe_archivo((char *)argv[1])==1){ if (tiene_archivos((char *)argv[1])>0) { printf("El archivo [%s] si existe el archivo\n",argv[1]); i=leer_archivo_asignar((char *)argv[1],lis); ordenar(lis,i+1); if (existe_archivo((char *)argv[2])==1) { printf("El archivo [%s] de salida ya existe -> se proseguira a escribir\n",argv[1]); }else if((char *)argv[2]==NULL){ printf("El archivo de salida no esta especificados\n"); }else{ printf("El archivo [%s] de salida no existe -> se creara\n",argv[1]); crear_archivo((char *)argv[2]); printf("--->Se procegira a escribir en el archivo...\n"); } if (existe_archivo((char *)argv[2])==1){ escribir_archivo((char*)argv[2],lis); printf("Leyendo Archivo [%s] ...\n",argv[2]); leer_archivo((char*)argv[2]); printf("\n"); } }else{ printf("El archivo [%s] se encutra vacio\n",argv[1]); } }else{ printf("El archivo [%s] de entrada especificado no existe\n",argv[1]); } return 0; } <file_sep>/Unidad_1/Programa_Desarrollo_Reto_Competencia_1/EntradaDatos.h #include <stdio.h> #include <stdbool.h> int entero(char mensaje[]){ bool control=false; int entero=-1; while(!control){ printf(" %s ",mensaje); scanf("%i",&entero); fflush( stdin ); control = true; } return entero; } char* cadena(char mensaje[]){ printf(" %s ",mensaje); char* cadenas; scanf("%s",&cadenas); fflush( stdin ); return cadenas; } double doble(char mensaje[]){ bool control = false; double dobles = -1.0; while(!control){ printf(" %s ",mensaje); scanf("%lf",&dobles); control = true; } return dobles; } <file_sep>/Unidad_[3,4]/Practica_Final_Competencia_[3,4]/cliente_funciones.h #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> int conectar_cliente_servidor(char *ip,int puerto); void enviar_datos(int conexion, char *numero); void recibir_datos(int conexion); char * optener_numero();<file_sep>/Unidad_2/Practica_1_Competencia_2/eliminarGrupos.sh #!/bin/bash ROOT_UID=0 SUCCESS=0 if [ "$UID" -ne "$ROOT_UID" ]; then echo "Se debe estar como root para ejecutar este script"; exit $E_NOROOT fi file=$1 #verficacion de que se ingrese le archivo if [ "${file}X" = "X" ]; then echo "Debe indicar el archivo del listado con Nombres de grupo a ingresar..."; exit 1 fi #fucnicion que elinminara el grupo eliminar(){ grupo=$1 groupdel $grupo if [ "$?" -ne "$SUCCESS" ]; then echo "EL GRUPO [$grupo] no se boorro !!!" echo "___________________________________________" else echo "EL GRUPO [$grupo] se borro corectamente!!!!" echo "___________________________________________" fi } while IFS=: read grupo do eliminar "$grupo" done < $file <file_sep>/Unidad_2/Programa_Desarrollo_1_Competencia_2/Makefile all: gcc -g -c -Wall main.c -o main.o -lpthread gcc -g -c -Wall scheduler.c -o scheduler.o -lpthread gcc -g -Wall main.o scheduler.o -o application -lpthread clean: rm *.o rm application <file_sep>/Unidad_[3,4]/Practica_Final_Competencia_[3,4]/cliente_funciones.c #include "cliente_funciones.h" int total_ca=10,i=0; int optener_total_cadena(){ return i; } int conectar_cliente_servidor(char *ip,int puerto){ struct sockaddr_in cliente; int conexion=0; if ((conexion = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); } cliente.sin_family = AF_INET; cliente.sin_port = htons(puerto); if(inet_pton(AF_INET,ip, &cliente.sin_addr)<=0) { printf("\nInvalid address/ Address not supported \n"); } if (connect(conexion, (struct sockaddr *)&cliente, sizeof(cliente)) < 0) { printf("\nConexion fallida\n"); exit(EXIT_FAILURE); } return conexion; } void enviar_datos(int conexion, char *numero){ send(conexion, numero, strlen(numero) , 0 ); } void recibir_datos(int conexion){ char buffer[1024]; bzero((char*)&buffer,sizeof(buffer)); read( conexion , buffer, 1024); printf("Resultado: %s\n",buffer); } char * optener_numero(){ total_ca=10,i=0; int j,total_ca_an; char *str_d=(char *)malloc(sizeof(char)*total_ca); char *r; char ca; while(ca!='\n'){ scanf("%c",&ca); if ((ca>=48 && ca<=57 )|| ca=='\n') { if(i<total_ca){ str_d[i]=ca; }else{ r=(char *)malloc(sizeof(char)*total_ca); for (j = 0; j <= total_ca; ++j) { r[j]=str_d[j]; } free(str_d); total_ca_an=total_ca; total_ca=total_ca+10; str_d=(char *)malloc(sizeof(char)*total_ca); for (j = 0; j <= total_ca_an; ++j) { str_d[j]=r[j]; } free(r); str_d[i]=ca; } }else{ printf("Se detecto un caracter..\n"); exit(EXIT_FAILURE); } i++; } j=0; str_d[i-1]='\0'; return str_d; } <file_sep>/Unidad_1/Programa_Desarrollo_Reto_Competencia_1/SystemBanc.c #include <stdio.h> #include "Banco.h" #include "EntradaDatos.h" #include <string.h> #include "Indices.h" #define MOSTRAR_MENU_PRIN 0 #define LIMITE_PAISES 5 #define ALTA 1 #define BAJA 2 #define MOSTRAR_TODO 3 #define MOSTRAR_ESPECIFICO 4 #define MOSTRAR_OCUPADOS 5 #define ABONAR 6 #define RETIRAR 7 #define BUSCAR_ID_VACIO_ESTRUCTURA 8 #define ESTA_LLENA_ESTRUCTURA 9 #define ESTA_VACIA_ESTRUCTURA 10 #define IMPRIMIR_NOM_PAISES 11 #define MOSTRAR_LONGITUDES 12 #define ACTUALIZAR 13 #define SALIR 14 #define ACTUALIZAR_MOSTRAR_MENU 0 #define ACTUALIZAR_NOMBRE 1 #define ACTUALIZAR_SEXO 2 #define SALIR_ACTUALIZAR 3 char* pedirNombrePais(int inicio, char mensaje[], Banco banco[]); bool estaNombreRepetido(int inicio, char nombrePais[], Banco banco[]); void mostrarLongitudes(Banco banco[],int num_b){ int i,j; for(i=0;i<num_b;i++){ printf("\t--> Del Pais %s, existen %i clientes.\n",banco[i].nombrePais,getTotalClientes(banco[i])); } } void imprimirTodo(Banco banco[],int num_b){ int i; for(i = 0; i < num_b; i++){ printf("----------------------------------------------------------------------------------------------------------------\n"); printTodosClientes(banco[i],i); } sleep(2); printf("----------------------------------------------------------------------------------------------------------------\n"); } void imprimirSoloOcupados(Banco banco[],int num_b){ int contador = 0,i; for(i = 0; i < num_b; i++){ if(printSoloOcupados(banco[i],i)) contador++; } if(contador == 0){ printf("\t\t ---> No existen clientes que mostrar..."); } } void introducirPaises(Banco banco[],int num_b){ int i; char snum[5]; for(i = 0; i < num_b; i++){ char mensaje[50] = "Introduce el nombre del Pais "; sprintf(snum,"%d",i); strcat(mensaje, snum); strcat(mensaje,": "); char pais[30]; strcpy(pais,pedirNombrePais(i, mensaje, banco)); char paisa[20]; strcpy(mensaje,"\tIntroduce el total de clientes del pais "); strcat(mensaje,pais); strcat(mensaje,": "); strcpy(paisa,pais); int num_clie=validarRango(1, LIMITE_CLIENTES, mensaje); banco[i] = crear_banco(pais,num_clie); } } int validarRango(int inicio, int fin, char mensaje[]){ int numero = entero(mensaje); while(numero < inicio || numero > fin){ if(numero < inicio || numero > fin){ printf("\t\tNo esta dentro del Rango..."); printf("\t\t\t--> El rango va de %i a %i",inicio,fin); } numero = entero(mensaje); } return numero; } char* pedirNombrePais(int inicio, char mensaje[], Banco banco[]){ char nombrePais[30]; printf("%s",mensaje); scanf("%s",&nombrePais); fflush(stdin); while(estaNombreRepetido(inicio, nombrePais, banco)){ if(estaNombreRepetido(inicio, nombrePais, banco)){ printf("\t\tEl nombre %s ya se encuentra registrado...",nombrePais); printf("\t\t\t--> Intenta de nuevo."); } printf("%s",mensaje); scanf("%s",&nombrePais); } return nombrePais; } bool estaNombreRepetido(int inicio, char nombrePais[], Banco banco[]){ bool se_encuentra = false; int i; for(i = inicio; i > 0; i--){ if(strcmp(banco[i-1].nombrePais,nombrePais)==0) { se_encuentra = true; break; } } return se_encuentra; } int getIndicePais(char nombrePais[], Banco banco[],int tam_ban){ int indexPais = -1,i; for(i = 0; i < tam_ban; i++){ if(strcmp(banco[i].nombrePais,nombrePais)==0){ indexPais = i; break; } } return indexPais; } bool hayVacioTodaEstructura(Banco banco[], int num_ban){ bool hayLugar = false; int i; for(i=0;i<num_ban;i++){ if (isTodoOcupado(banco[i])) { hayLugar = true; break; } } return hayLugar; } Indices indiceVacioTodaEstructura(Banco banco[],int num_ban) { Indices temp = crear_indice(); int i; for(i = 0; i < num_ban; i++) { int indice = indiceVacio(banco[i]); if(indice != -1) { temp.pais = i; temp.cliente = indice; break; } } return temp; } bool estaTodoLlenoEstructura(Banco banco[],int num_ban){ bool all_lleno = true; int i; for (i=0;i<num_ban;i++) { if (existeEspacioVacio(banco[i])) { all_lleno = false; break; } } return all_lleno; } bool estaTodoVacioEstructura(Banco banco[],int num_ban){ bool all_vacio = true; int i; for (i=0;i<num_ban;i++) { if (existeEspacioOcupado(banco[i])) { all_vacio = false; break; } } return all_vacio; } int indiceVacioPaisEspecifico(int pais, Banco banco[]){ return indiceVacio(banco[pais]); } bool seEncuentraNombre(char nombrePais[], Banco banco[],int num_ban){ bool se_encuntra = false; int i; for (i=0;i<num_ban;i++) { if (strcmp(banco[i].nombrePais,nombrePais)==0) { se_encuntra = true; break; } } return se_encuntra; } char* pedirNombrePaisString(char mensaje[], Banco banco[],int num_ban){ char nombrePais[30]; printf("%s",mensaje); scanf("%s",&nombrePais); while(!seEncuentraNombre(nombrePais, banco,num_ban)){ if(!seEncuentraNombre(nombrePais, banco,num_ban)){ printf("\t\tEl nombre %s no se encuentra registrado...",nombrePais); printf("\t\t\t--> Intenta de nuevo."); } printf("%s",mensaje); scanf("%s",&nombrePais); } return nombrePais; } void instrucciones(){ printf("\n-------------------------------\n"); printf("---- Menú ----\n"); printf(" 0 Mostrar menú.\n"); printf(" 1 Dar de alta Cliente.\n"); printf(" 2 Dar de baja Cliente.\n"); printf(" 3 Mostrar todos los clientes.\n"); printf(" 4 Mostrar cliente en especifico.\n"); printf(" 5 Mostrar solo clientes dados de alta.\n"); printf(" 6 Abonar saldo a cliente.\n"); printf(" 7 Retirar saldo de cliente.\n"); printf(" 8 Buscar indice vacio en toda la estructura.\n"); printf(" 9 Mostrar si esta toda llena la estructura.\n"); printf(" 10 Mostrar si esta toda vacia la estructura.\n"); printf(" 11 Mostrar nombre de paises.\n"); printf(" 12 Mostrar longitudes.\n"); printf(" 13 Actualizar datos de cliente especifico.\n"); printf(" 14 Salir.\n"); printf("-------------------------------\n"); } void instrucciones_actualizar(){ printf("\n-------------------------------\n"); printf("---- Menú Actualizar ----\n"); printf(" 0 Mostrar menú.\n"); printf(" 1 Actualizar Nombre.\n"); printf(" 2 Actualizar Sexo.\n"); printf(" 3 Regresar a ménu principal.\n"); printf("-------------------------------\n"); } void imprimirPaises(Banco banco[],int tam_ban){ printf("---------------------------------------------------------------------\n"); printf("\tLos paises son: "); int i; for(i = 0; i < tam_ban; i++){ printf("País [%i] %s",i,banco[i].nombrePais); } printf("---------------------------------------------------------------------\n"); } void saltoLinea(){ printf("\n"); } int main(int argc, char const *argv[]) { int eleccion,tam_ban; Banco banco[tam_ban=validarRango(1, LIMITE_PAISES, "Introduce el numero de paises: ")]; introducirPaises(banco,tam_ban); saltoLinea(); mostrarLongitudes(banco,tam_ban); saltoLinea(); instrucciones(); eleccion = entero(" Elija una opción: "); fflush(stdin); while(eleccion != SALIR){ switch(eleccion){ case ALTA: printf(" --- Opción alta ---\n"); if(hayVacioTodaEstructura(banco,tam_ban)){ char nombre_pais[30]; strcpy(nombre_pais,pedirNombrePaisString("\tIntroduce el nombre del pais: ", banco,tam_ban)); int id_pais = getIndicePais(nombre_pais, banco,tam_ban); int cliente = indiceVacioPaisEspecifico(id_pais, banco); if(cliente != -1){ char clientenom[30]; char sexo2; printf("Introduce nombre del cliente: "); scanf("%s",&clientenom); fflush(stdin); printf("Introduce el Sexo: "); scanf("%c",&sexo2); fflush(stdin); double sueldo=doble("Introduce el Sueldo: "); Cliente temp = crear_cliente(clientenom,sexo2,sueldo); banco[id_pais].clientes=setEspecificoCliente(banco[id_pais],cliente, temp); } else printf("No existe indice vacio en el pais %s.\n",banco[id_pais].nombrePais); } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta completamente llena."); printf("---------------------------------------------------------------------\n"); } break; case BAJA: printf(" --- Opción baja ---\n"); if(!estaTodoVacioEstructura(banco,tam_ban)){ char nombre_pais3[30]; strcpy(nombre_pais3,pedirNombrePaisString("\tIntroduce el nombre del pais: ", banco,tam_ban)); int pais3 = getIndicePais(nombre_pais3, banco,tam_ban); int cliente3 = validarRango(0, (banco[pais3].tam_clientes)-1, "\tIntroduce el indice del cliente: "); if(getIsOcupadoCliente(banco[pais3],cliente3)){ printf("\t--> Cliente %s dado de baja.\n",getNombreCliente(banco[pais3],cliente3)); eliminarCliente(banco[pais3],cliente3); } else printf("\tEl cliente %i del pais %s no tiene datos.\n",cliente3,banco[pais3].nombrePais ); } else { printf("---------------------------------------------------------------------\n"); printf("\t\t La estructura esta toda vacia.\n"); printf("---------------------------------------------------------------------\n"); } break; case MOSTRAR_TODO: printf(" --- Opción mostrar todo ---\n"); imprimirTodo(banco,tam_ban); break; case MOSTRAR_MENU_PRIN: instrucciones(); break; } eleccion = entero(" Elija una opción: "); } printf("--- Fin de la Ejecución del Sistema ---\n"); return 0; } <file_sep>/Unidad_2/Programa_Desarrollo_1_Competencia_2/scheduler.h #ifndef __SCHEDULER_H #define __SCHEDULER_H #include <stdint.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #define MAX_STRING 100 #define MAX_PROCESOS 100 #define UN_SEGUNDO 1 #define DOS_SEGUNDOS 2 #define TRES_SEGUNDOS 3 #define CUATRO_SEGUNDOS 4 #define ACTIVO 1 #define NO_ACTIVO 0 int cont_procesos; typedef struct PROCESS process; typedef struct ARRAY_PROCESS array_procesos; /* Puntero a función que no retorna y no recibe nada. */ typedef void (*FN_ACCION)(void); // Definición de la estructura PROCESS struct PROCESS{ int id; int delay; char nombrePROCESO[MAX_STRING]; FN_ACCION proceso_realizar; int estado; }; struct ARRAY_PROCESS{ process proceso; int empty; }; process *crear_Proceso(int _id, int _delay, char *_nombreProceso, FN_ACCION _proceso_realizar, int _estado); void agregar_Proceso(array_procesos *_array, process _p); void ejecutar_Procesos(array_procesos *_array); array_procesos *crear_ArrayProcesos(void); #endif <file_sep>/Unidad_[3,4]/Practica_Final_Competencia_[3,4]/servidor_funciones.c #include "servidor_funciones.h" int iniciar_socket_puerto(int puerto){ int crear_sokcet,opt=0; if ((crear_sokcet=socket(AF_INET,SOCK_STREAM,0))<0) { perror("crear_sokcet"); exit(EXIT_FAILURE); }else{ printf("Socket creado\n"); } if (setsockopt(crear_sokcet,SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt,sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } servidor.sin_family= AF_INET; servidor.sin_addr.s_addr= INADDR_ANY; servidor.sin_port = htons(puerto); if (bind(crear_sokcet,(struct sockaddr *)&servidor,sizeof(servidor))<0){ perror("bind failed"); exit(EXIT_FAILURE); } if (listen(crear_sokcet,3)<0) { perror("Error en la escucha"); exit(EXIT_FAILURE); }else{ printf("Servidor al eschuca en el puerto %d\n",ntohs(servidor.sin_port) ); } return crear_sokcet; } int aceptar(int crear_sokcet){ int socketlen=sizeof(servidor); int aceptado; if ((aceptado=accept(crear_sokcet,(struct sockaddr*)&servidor,(socklen_t*)&socketlen))<0) { perror("Error de aceptacion"); exit(EXIT_FAILURE); } return aceptado; } char* leer(int aceptado,int tam){ char buffer[tam],*buffer1; bzero((char*)&buffer,sizeof(buffer)); read(aceptado,buffer,tam); buffer1=buffer; return buffer1; } void enviar(int aceptado,char *texto){ send(aceptado, texto , strlen(texto) , 0 ); printf("Enviando Respuesta...\n"); } char * hacer_suma(char *num1, char *num2){ int n1=0,n2=0,j=0,c=0,i=0,s=0,rc=0,rc2; char car; char *r,*respaldo; while(num1[n1]!='\0'){ n1++; } while(num2[n2]!='\0'){ n2++; } if (n1>=n2) { r=(char *)malloc(n1); rc=n1; rc2=rc; r[rc2]='\0'; rc2--; n1--; n2--; }else{ r=(char *)malloc(n2); rc=n2; rc2=rc; r[rc2]='\0'; rc2--; n2--; n1--; } while(n2>=0 && n1 >=0){ i=num1[n1]-48; j=num2[n2]-48; if ((s=i+j+c)>9) { c=1; car=(s-10)+48; r[rc2]=car; n2--; n1--; rc2--; }else{ c=0; car=s+48; r[rc2]=car; n2--; n1--; rc2--; } } if (n1>=0){ while(n1>=0){ i=num1[n1]-48; if ((s=i+c)>9) { c=1; car=(s-10)+48; r[n1]=car; n1--; }else{ c=0; car=s+48; r[n1]=car; n1--; } } }else{ while(n2>=0){ j=num2[n2]-48; if ((s=j+c)>9) { c=1; car=(s-10)+48; r[n2]=car; n2--; }else{ c=0; car=s+48; r[n2]=car; n2--; } } } free(num1); free(num2); if (c==1) { respaldo=(char*)malloc(rc); for (i= 0; i <=rc; ++i) { respaldo[i]=r[i]; } free(r); r=(char*)malloc(sizeof(char)*(rc+1)); r[0]=c+48; for (i = 0; i <= rc; ++i) { r[i+1]=respaldo[i]; } free(respaldo); } printf("Resultado = %s\n",r); return r; } <file_sep>/Unidad_2/Programa_Desarrollo_1_Competencia_2/main.c #include "scheduler.h" #include <pthread.h> #include <stdlib.h> void reproducir_musica(void); void abrir_youtube(void); void escribir_texto_word(void); void descargar_archivo(void); void subiendo_archivo(void); void compilando_programa(void); void ejecutando_programa(void); void usando_terminal(void); int main(int argc, char const *argv[]){ process *p1 = crear_Proceso(1, UN_SEGUNDO, "Proceso_1", reproducir_musica, ACTIVO); //<-- process *p2 = crear_Proceso(6, DOS_SEGUNDOS, "Proceso_1", abrir_youtube, ACTIVO); process *p3 = crear_Proceso(5, TRES_SEGUNDOS, "Proceso_2", escribir_texto_word, NO_ACTIVO); //<-- process *p4 = crear_Proceso(4, TRES_SEGUNDOS, "Proceso_3", descargar_archivo, NO_ACTIVO); //<-- process *p5 = crear_Proceso(3, TRES_SEGUNDOS, "Proceso_4", subiendo_archivo, NO_ACTIVO); process *p6 = crear_Proceso(4, TRES_SEGUNDOS, "Proceso_5", compilando_programa, NO_ACTIVO); process *p7 = crear_Proceso(0, TRES_SEGUNDOS, "Proceso_6", ejecutando_programa, ACTIVO); //<-- process *p8 = crear_Proceso(2, CUATRO_SEGUNDOS, "Proceso_7", usando_terminal, ACTIVO); //<-- process *p9 = crear_Proceso(5, CUATRO_SEGUNDOS, "Proceso_8", usando_terminal, NO_ACTIVO); //<-- /* pthread_t thread_id; pthread_create(&thread_id, NULL, reproducir_musica, NULL); Los atributos al crear un thread son:. -> Puntero al Identificador -> Atributos -> Función que ejecutará el Hilo -> Argumento que reciba la función Si el hilo fue creado con éxito la función devuelve pthread_create devolverá un 0 Se puede comprobar usando un if if (0 != pthread(&thread_id, NULL, FUNCTION, NULL)) return -1 // en caso de fallar, devuelve -1 pthread_create(&thread_id, NULL, abrir_youtube, NULL); pthread_create(&thread_id, NULL, escribir_texto_word, NULL); pthread_join(thread_id, NULL); pthread_exit(NULL); */ array_procesos *array = crear_ArrayProcesos(); agregar_Proceso(array, *p1); agregar_Proceso(array, *p2); agregar_Proceso(array, *p3); agregar_Proceso(array, *p4); agregar_Proceso(array, *p5); agregar_Proceso(array, *p6); agregar_Proceso(array, *p7); agregar_Proceso(array, *p8); agregar_Proceso(array, *p9); ejecutar_Procesos(array); free(array); free(p1); free(p2); free(p3); free(p4); free(p5); free(p6); free(p7); free(p8); free(p9); return 0; } void reproducir_musica(void){ printf("Reproduciendo Música\n"); system("gnome-terminal -- bash -c qmmp"); printf("PID: %i\n", getpid()); } void abrir_youtube(void){ printf("Usando Youtube\n"); system("xdg-open http://www.youtube.com"); printf("PID: %i\n", getpid()); } void escribir_texto_word(void){ printf("Escribiendo Texto en Word\n"); system("gnome-terminal -- bash -c vim test.txt"); printf("PID: %i\n", getpid()); } void descargar_archivo(void){ printf("Descargando Archivo\n"); printf("PID: %i\n", getpid()); } void subiendo_archivo(void){ printf("Subiendo Archivo\n"); printf("PID: %i\n", getpid()); } void compilando_programa(void){ printf("Compilando programa\n"); printf("PID: %i\n", getpid()); } void ejecutando_programa(void){ printf("Ejecutando Python\n"); system("gnome-terminal -- bash -c python3"); printf("PID: %i\n", getpid()); } void usando_terminal(void){ printf("Usando la terminal\n"); system("gnome-terminal"); printf("PID: %i\n", getpid()); } <file_sep>/Unidad_[3,4]/Practica_1_Competencia_[3,4]/manejar_archivo.h #ifndef __MANEJAR_ARCHIVO_H #define __MANEJAR_ARCHIVO_H #include "lista_enlazada.h" int existe_archivo(char *nombre); void crear_archivo(char *nombre); void escribir_archivo(char *nombre, lista *l); int leer_archivo_asignar(char *nombre,lista *l); int leer_archivo(char *nombre); int tiene_archivos(char *nombre); void cerrar_archivo(FILE *archivo); #endif<file_sep>/Unidad_[3,4]/Practica_1_Competencia_[3,4]/lista_enlazada.c #include "lista_enlazada.h" int esta_vacia(lista *l){ if (l->fin==NULL) { return 1; }else{ return 0; } } void ingresar_dato(lista *l,char palabras[100]){ nodo *nuevo; nuevo=(nodo*)malloc(sizeof(struct nodo)); strcpy(nuevo->palabra,palabras); nuevo->ant=NULL; nuevo->sig=NULL; if (esta_vacia(l)==1) { l->ini=nuevo; l->fin=nuevo; }else{ nuevo->ant=l->fin; l->fin->sig=nuevo; l->fin=nuevo; } } void imprimir_lista(lista *l){ nodo *temp=l->ini; while(temp!=NULL){ printf("%s->",temp->palabra); temp=temp->sig; } printf("\n"); } void imprimir_lista_r(lista *l){ nodo *temp=l->fin; while(temp!=NULL){ printf("%s->",temp->palabra); temp=temp->ant; } printf("\n"); } void limpiar_nodo(nodo *n){ free(n); } void limpiar_lista(lista *l){ free(l); } void ordenar(lista *l,int n){ int z,v; nodo *aux,*aux2,*aux3,*temp,*temp2; temp=l->ini; temp2=l->ini->sig; for (z = 1; z < n; ++z) { temp=l->ini; temp2=l->ini->sig; for (v = 0; v <(n-z); ++v) { if (strcasecmp(temp->palabra,temp2->palabra)>0) { aux2=temp->ant; aux3=temp2->sig; aux=temp; temp=temp2; temp2=aux; if (aux2==NULL) { temp->sig=aux; temp->ant=NULL; temp2->ant=temp; temp2->sig=aux3; if (aux3==NULL) { temp2->sig=NULL; }else{ temp2->sig=aux3; aux3->ant=temp2; } }else{ aux2->sig=temp; temp->sig=aux; temp->ant=aux->ant; temp2->ant=temp; if (aux3==NULL) { temp2->sig=NULL; }else{ temp2->sig=aux3; aux3->ant=temp2; } } } if(v==0){ l->ini=temp; } if(temp2->sig!=NULL){ temp=temp2; temp2=temp2->sig; } } if (z==1) { l->fin=temp2; } } } <file_sep>/Unidad_[3,4]/Practica_1_Competencia_[3,4]/Makefile all: gcc -g -c -Wall principal.c -o principal.o gcc -g -c -Wall lista_enlazada.c -o lista_enlazada.o gcc -g -c -Wall manejar_archivo.c -o manejar_archivo.o gcc -g -Wall principal.o lista_enlazada.o manejar_archivo.o -o ejecutable clean: rm *.o rm ejecutable <file_sep>/Unidad_[3,4]/Practica_Final_Competencia_[3,4]/servidor.c #include "servidor_funciones.h" int main(int argc, char const *argv[]) { if (argc==2) { int servidor,cliente,c=0,i; servidor=iniciar_socket_puerto(atoi(argv[1])); cliente=aceptar(servidor); char *cadena,*num1,*num2,*res; cadena=leer(cliente,1024); while(cadena[c]!='\0'){ c++; } num1=(char*)malloc(c); for (i = 0; i <= c; ++i) { num1[i]=cadena[i]; } printf("Primer valor recibido= %s\n", num1); fflush(stdin); cadena=leer(cliente,1024); while(cadena[c]!='\0'){ c++; } num2=(char*)malloc(c); for (i = 0; i <= c; ++i) { num2[i]=cadena[i]; } printf("Segundo valor recibido= %s\n", num2); res=hacer_suma(num1,num2); enviar(cliente,res); free(res); close(servidor); close(cliente); }else{ printf("Falta puerto <PUERTO>\n"); } return 0; } <file_sep>/Unidad_1/Programa_Desarrollo_Reto_Competencia_1/Banco.h #include "Cliente.h" #include <string.h> #include <stdbool.h> #include <stdlib.h> #define LIMITE_CLIENTES 10 typedef struct Banco { char nombrePais[30]; struct Cliente *clientes; int tam_clientes; }Banco; Cliente* construirClientes(Banco ban, int tam_cliente); int getTotalClientes(Banco ban); bool getIsOcupadoCliente(Banco ban,int index); void printCliente(Banco ban ,int index); void imprimirEspecifico(Banco ban,int cliente); Banco crear_banco(char nombrePais[], int tam_cliente){ Banco ban; ban.tam_clientes=tam_cliente; strcpy(ban.nombrePais,nombrePais); ban.clientes= (Cliente *)malloc (tam_cliente*sizeof(ban.clientes)); ban.clientes=construirClientes(ban,tam_cliente); return ban; } Cliente* construirClientes(Banco ban ,int tam_cliente){ int i; Cliente c[tam_cliente]; char nombre[30]="\0"; for(i = 0; i <ban.tam_clientes; i++){ c[i] = crear_cliente(nombre,'\0',0.0); } return c; } //---- int getTotalClientes(Banco ban){ return ban.tam_clientes; } bool isTodoOcupado(Banco ban){ bool todo_ocupado = false; int contador = 0,i; for(i = 0; i < ban.tam_clientes; i++){ if(getIsOcupadoCliente(ban,i)){ contador++; } } if(contador == ban.tam_clientes) todo_ocupado = true; return todo_ocupado; } bool getIsOcupadoCliente(Banco ban,int index){ return isOcupado(ban.clientes[index]); } bool isTodoVacio(Banco ban){ bool todo_vacio = false; int contador = 0,i; for(i = 0; i < ban.tam_clientes; i++){ if(getIsOcupadoCliente(ban,i)){ contador++; } } if(contador == ban.tam_clientes) todo_vacio = true; return todo_vacio; } bool existeEspacioVacio(Banco ban){ bool existeVacio = false; int i=0; for(i = 0; i < getTotalClientes(ban); i++){ if(!getIsOcupadoCliente(ban,i)){ existeVacio = true; break; } } return existeVacio; } bool existeEspacioOcupado(Banco ban){ bool existeOcupado = false; int i; for(i = 0; i < getTotalClientes(ban); i++){ if(getIsOcupadoCliente(ban,i)){ existeOcupado = true; break; } } return existeOcupado; } int indiceVacio(Banco ban){ int index_vacio = -1; int i; for(i = 0; i < ban.tam_clientes; i++){ if(!getIsOcupadoCliente(ban,i)){ index_vacio = i; break; } } return index_vacio; } bool printSoloOcupados(Banco ban,int pais){ bool imprimio = false; if(existeEspacioOcupado(ban)){ imprimio = true; printf("----------------------------------------------------------------------------------------------------------------\n"); printf("\tDel pais [%i] %s los clientes disponibles son: ",pais,ban.nombrePais); int i; for(i = 0; i < getTotalClientes(ban); i++){ if(getIsOcupadoCliente(ban,i)){ printf("El cliente %i es: ",i); printCliente(ban,i); } } printf("----------------------------------------------------------------------------------------------------------------\n"); } return imprimio; } void printTodosClientes(Banco ban,int pais){ printf("\tDel pais [%i] %s: \n",pais,ban.nombrePais); int i; for(i = 0; i < ban.tam_clientes; i++){ printf("El cliente %i es: \n",i); printCliente(ban,i); } } void imprimirEspecifico(Banco ban,int cliente){ printf("----------------------------------------------------------------------------------------------------------------\n"); printf("\tDel pais %s: ",ban.nombrePais); printCliente(ban,cliente); printf("----------------------------------------------------------------------------------------------------------------\n"); } void printCliente(Banco ban ,int index){ imprimirCliente(ban.clientes[index]); } char* getNombrePais(Banco ban) { char* nom; strcpy(nom,ban.nombrePais); return nom; } void setNombrePais(Banco ban,char nombrePais[]) { strcpy(ban.nombrePais,nombrePais); } Cliente getEspecificoCliente(Banco ban,int index){ return ban.clientes[index]; } Cliente* setEspecificoCliente(Banco ban,int index, Cliente cliente){ Cliente *c=ban.clientes; int i; for(i = 0; i <ban.tam_clientes; i++){ if(i==index){ c[i]=setTodosDatos(c[index],cliente); } } return c; } char* getNombreCliente(Banco ban,int index){ char*nom; strcpy(nom,ban.clientes[index].nombre); return nom; } char getSexoCliente(Banco ban,int index){ return ban.clientes[index].sexo; } double getSaldoCliente(Banco ban,int index){ return ban.clientes[index].saldo; } void eliminarCliente(Banco ban,int index){ eliminar(ban.clientes[index]); } void cambiarNombreCliente(Banco ban,int index, char nuevoNombre[]){ cambiarNombre(ban.clientes[index],nuevoNombre); } void cambiarSexoCliente(Banco ban,int index, char nuevoSexo){ cambiarSexo(ban.clientes[index],nuevoSexo); } void abonarSaldoCliente(Banco ban,int index, double cuanto){ abonarSaldo(ban.clientes[index],cuanto); } void retirarSaldoCliente(Banco ban,int index, double cuanto){ retirarSaldo(ban.clientes[index],cuanto); } <file_sep>/Unidad_1/Programa_Desarrollo_1_Competencia_1/planificador.c #include <stdio.h> //#include <windows.h> //#include "proceso.h" #include "cola.h" /*typedef struct proceso { int pdi; char estatus; int llegada; int tim_uso; } proceso; proceso crear(int pdi, char estatus,int llegada, int uso){ proceso pros; pros.estatus=estatus; pros.llegada=llegada; pros.pdi=pdi; pros.tim_uso=uso; return pros; }*/ //asignar estado en el que se encuentra void asignar_es(int num_pro,proceso arreglo[],int pdi,char estado){ int i=0; for(i=0;i<num_pro;i++){ if(arreglo[i].pdi==pdi){ arreglo[i].estatus=estado; } } } //buscar si hay llegada en el timpo que el reloj va void verificar(int reloj_time, proceso arreglo[],int num_pro){ int i=0; for(i=0;i<num_pro;i++){ if(arreglo[i].llegada==reloj_time){ insertar(arreglo[i]); } } } //verificar que todos ahn terminado int verificar_todos_finalizado(proceso arreglo[],int num_pro){ int i=0,v=0; for(i=0;i<num_pro;i++){ if(arreglo[i].estatus=='T'){ v++; } } if(v==num_pro){ return 1; }else{ return -1; } } int main(int argc, char const *argv[]) { int pdi; char estatus; // I=iniciado E= en ejcucion, S= espera, T=terminado int llegada; int tim_uso; int num_pro=0; int quantum; int i; //-------------------------------------- printf("NUMERO DE PROCESOS A SIMULAR: "); scanf("%i",&num_pro); fflush(stdin); proceso cola[num_pro]; printf("INGRESA EL VALOR DEL QUANTUM: "); scanf("%i",&quantum); fflush(stdin); for(i=0;i<num_pro;i++){ printf("\n\nINGRESA EL 'PDI' O IDENTIFICADOR DEL PROCESO %i: ",i+1); scanf("%i",&pdi); fflush(stdin); printf("INGRESA EL TIEMPO DE LLEGADA DEL PROCESO %i: ",i+1); scanf("%i",&llegada); fflush(stdin); printf("INGRESA EL TIEMPO DE USO DEL PROCESO %i: ",i+1); scanf("%i",&tim_uso); fflush(stdin); estatus='I'; cola[i]=crear(pdi,estatus,llegada,tim_uso); } //ordenado de la cola resceptora de datos int z,v,comparaciones=0,aux; for(z = 1; z < num_pro; ++z) { for( v = 0; v < (num_pro - z); v++) { comparaciones++; if(cola[v].llegada > cola[v+1].llegada){ aux = cola[v].llegada; cola[v].llegada = cola[v + 1].llegada; cola[v + 1].llegada = aux; } } } ///inciar con el proceso int reloj=0; int cont=1; proceso p_uso; //printf("xdxd%i",p_uso.pdi); if(num_pro!=0){ while(verificar_todos_finalizado(cola,num_pro)==-1){ verificar(reloj,cola,num_pro); //printf("\n"); //imprimir(); if(contar()!=0&&cont-1==0){ p_uso=extraer(); //printf("\n\nEJECUTANDO EL PROCESO %i EN EL LAPSO DE TIEMPO %i-%i",p_uso.pdi,reloj,reloj+1); //Sleep(2000); //cont++; } if(p_uso.estatus!='\0'){ if(p_uso.tim_uso>quantum){ if(cont==quantum){ printf("\nMAYOR FINAL EJECUTANDO EL PROCESO %i EN EL LAPSO DE TIEMPO %i-%i\n",p_uso.pdi,reloj,reloj+1); p_uso.tim_uso-=cont; p_uso.estatus='S'; asignar_es(num_pro,cola,p_uso.pdi,'S'); insertar(p_uso); cont=1; p_uso.estatus='\0'; sleep(2); /*for(i=0;i<num_pro;i++){ printf("\n\nPDI= %i",cola[i].pdi); printf("\nTIEMPO DE USO= %i",cola[i].tim_uso); printf("\nTIEMPO DE LLEGADA = %i",cola[i].llegada); printf("\nESTATUS = %c",cola[i].estatus); printf("\n\n\n"); }*/ } /*//validacion cuando es un Q de 1 else if(cont > quantum){ p_uso.tim_uso-=cont-1; p_uso.estatus='E'; asignar_es(num_pro,cola,p_uso.pdi,'E'); insertar(p_uso); cont=1; p_uso.estatus='\0'; }*/ else{ printf("\nMAYOR EJECUTANDO EL PROCESO %i EN EL LAPSO DE TIEMPO %i-%i",p_uso.pdi,reloj,reloj+1); asignar_es(num_pro,cola,p_uso.pdi,'E'); sleep(2); cont++; } }else if(p_uso.tim_uso<=quantum){ if(cont==p_uso.tim_uso){ printf("\nMENOR FINAL EJECUTANDO EL PROCESO %i EN EL LAPSO DE TIEMPO %i-%i\n",p_uso.pdi,reloj,reloj+1); p_uso.tim_uso-=cont; p_uso.estatus='T'; asignar_es(num_pro,cola,p_uso.pdi,'T'); cont=1; p_uso.estatus='\0'; sleep(2); /*for(i=0;i<num_pro;i++){ printf("\n\nPDI= %i",cola[i].pdi); printf("\nTIEMPO DE USO= %i",cola[i].tim_uso); printf("\nTIEMPO DE LLEGADA = %i",cola[i].llegada); printf("\nESTATUS = %c",cola[i].estatus); printf("\n\n\n"); }*/ } /*//validacion cuando es un Q de 1 else if(cont > quantum){ p_uso.tim_uso-=cont-1; p_uso.estatus='T'; asignar_es(num_pro,cola,p_uso.pdi,'T'); cont=1; p_uso.estatus='\0'; }*/else { printf("\nMENOR EJECUTANDO EL PROCESO %i EN EL LAPSO DE TIEMPO %i-%i",p_uso.pdi,reloj,reloj+1); asignar_es(num_pro,cola,p_uso.pdi,'E'); sleep(2); cont++; } } }else { printf("\nEN ESPERA DE NUEVO PROCESO ..."); sleep(2); } /*if(cola[0].tim_uso<=quantum){ if() }*/ reloj++; } }else{ printf("\nNO SE ENCONTRARON PROCESOS."); } printf("\n"); //imprimir(); //------------------------------------------- //imprimir datos /*for(i=0;i<num_pro;i++){ printf("\n\nPDI= %i",cola[i].pdi); printf("\nTIEMPO DE USO= %i",cola[i].tim_uso); printf("\nTIEMPO DE LLEGADA = %i",cola[i].llegada); printf("\nESTATUS = %c",cola[i].estatus); printf("\n\n\n"); }*/ /* //ejemplo proceso pro; pro.estatus='F'; pro.llegada=2; pro.pdi=23; pro.tim_uso=4; //ejemplo de uso de cola con proceso insertar(pro); imprimir(); printf("\n"); //proceso per= extraer(); //printf("%c",per.estatus); printf("%i",contar());*/ /*cola[0].pdi=5; cola[0].estatus='I'; cola[0].llegada=0; cola[0].tim_uso=5;*/ /*cola[1]=crear(7,'L',3,9); Sleep(1000); printf("El estado de la cola es de %c\n",cola[0].estatus); Sleep(1000); printf("hola\n"); Sleep(1000); printf("El estado de la cola es de %c\n",cola[1].estatus);*/ return 0; } <file_sep>/Unidad_2/Practica_1_Competencia_2/ingresar_Usuarios.sh #!/bin/bash ROOT_UID=0 #el idnentificador delm usuario root simpre es 0 SUCCESS=0 #verificar que este en modo root if [ "$UID" -ne "$ROOT_UID" ] then echo "Se debe estar como root para ejecutar este script" exit $E_NOTROOT fi #alamcenando el archivo enviado como parametro en la variabel file file=$1 #verificar que el apartado de el archivo no este vacio if [ "${file}X" = "X" ]; then echo "Debe indicar el archivo del listado con Nombres de grupo a ingresar..." exit 1 fi #verificar existencia de usuario verificarUsuario(){ usuario=$1 id=$2 #la -q significa quiet o silencio para que no imprima nanda if grep -q "$usuario" /etc/passwd ; then #si esta return 1 else #no esta return 0 fi } #verificar existencia de grupo verificarGrupo(){ idgrupo=$1 #la -q significa quiet o silencio para que no imprima nanda if grep -q "$idgrupo" /etc/group; then #si esta return 1 else #no esta return 0 fi } crearUsuario(){ contra=$2 echo "----------------------------------------------------" echo "El shell: $7" verificarUsuario "$1" "$3" if [ "$?" = "0" ];then echo "El usaurio [$1] no exite..." verificarGrupo "$4" if [ "$?" -eq "1" ]; then if [ "$2" = "" ]; then contra=$1 fi echo "El Grupo [$4] si existe..." echo "Contrsena: $contra" echo "Directorio: $6" echo "USO DE BASH" if [ "$3" = "" ]; then useradd -m -d $6 -c $5 -g $4 -s $7 -p $(echo $contra | openssl passwd -6 -stdin) $1 else useradd -m -d $6 -c $5 -g $4 -s $7 -u $3 -p $(echo $contra | openssl passwd -6 -stdin) $1 fi #permite pedir al primer inicio de sesion que cambie la contrasena chage -d 0 $1 if [ $? -eq $SUCCESS ]; then echo "USUARIO CREADO CORECTAMENTE !!!" else echo "ERROR AL CREAR EL USUARIO!!!" fi else echo "-> El grupo [$4] no se encuentra -> El <$1> no se puede crear" fi else echo "-> El usuario [$1] ya se encuentra creado -> El <$1> no se puede crear" echo "----------------------------------------------------" fi } #leer archivo while IFS=: read nombre passw id gid info hdir cshell do crearUsuario "$nombre" "$passw" "$id" "$gid" "$info" "$hdir" "$cshell" done < ${file} <file_sep>/Unidad_1/Programa_Desarrollo_1_Competencia_1/proceso.h typedef struct proceso { int pdi; char estatus; int llegada; int tim_uso; } proceso; proceso crear(int pdi, char estatus,int llegada, int uso){ proceso pros; pros.estatus=estatus; pros.llegada=llegada; pros.pdi=pdi; pros.tim_uso=uso; return pros; } <file_sep>/Unidad_[3,4]/Practica_Final_Competencia_[3,4]/cliente.c #include "cliente_funciones.h" int main(int argc, char const *argv[]) { if (argc ==3) { int puerto=atoi(argv[2]),cliente_conexion; char *num; char *ip=(char *)argv[1]; cliente_conexion=conectar_cliente_servidor(ip,puerto); printf("Ingrese el primer numero: "); num=optener_numero(); enviar_datos(cliente_conexion, num); fflush(stdin); printf("Ingrese el segundo numero: "); num=optener_numero(); enviar_datos(cliente_conexion, num); recibir_datos(cliente_conexion); close(cliente_conexion); }else{ printf("Faltan parametros <host(ip)> <puerto>\n"); } return 0; } <file_sep>/Unidad_[3,4]/Practica_1_Competencia_[3,4]/manejar_archivo.c #include "manejar_archivo.h" int existe_archivo(char *nombre){ FILE *archivo; int i=0; archivo= fopen(nombre,"r"); if (archivo==NULL){ }else{ i=1; } return i; } void crear_archivo(char *nombre){ FILE *archivo; archivo=fopen(nombre,"w"); if (archivo==NULL) { printf("----Archivo no creado----\n"); }else{ printf("----Archivo creado-----\n"); cerrar_archivo(archivo); } } void escribir_archivo(char *nombre, lista *l){ FILE *archivo; archivo=fopen(nombre,"w"); if (archivo==NULL) { printf("No se pudo escribir en el archivo\n"); }else{ nodo *temp=l->ini; while(temp!=NULL){ fputs(temp->palabra,archivo); if (temp->sig!=NULL) { fputs("\n",archivo); } temp=temp->sig; } printf("<--Se termino de escribir-->\n"); } cerrar_archivo(archivo); } int leer_archivo_asignar(char *nombre, lista *l){ FILE *archivo; archivo=fopen(nombre,"r"); char cadena[100]; int i=0,c=0; if (archivo==NULL) { printf("No se pudo leer el archivo\n"); }else{ char caracter; while((caracter=fgetc(archivo))!=EOF){ if (caracter!=' '&& caracter!='\n' && caracter!=0) { cadena[i]=caracter; i++; }else{ cadena[i]='\0'; i=0; if(cadena[0]!=0){ c++; ingresar_dato(l,cadena); } } } cadena[i]='\0'; if(cadena[0]!=0){ ingresar_dato(l,cadena); } } cerrar_archivo(archivo); return c; } int leer_archivo(char *nombre){ FILE *archivo; archivo=fopen(nombre,"r"); int i=0; if (archivo==NULL) { printf("No se pudo leer el archivo\n"); }else{ char caracter; while((caracter=fgetc(archivo))!=EOF){ printf("%c",caracter); } } cerrar_archivo(archivo); return i; } int tiene_archivos(char *nombre){ FILE *archivo; archivo=fopen(nombre,"r"); int i=1; fseek( archivo, 0, SEEK_END ); if (ftell( archivo ) == 0 ) { i--; } cerrar_archivo(archivo); return i; } void cerrar_archivo(FILE *archivo){ fclose(archivo); }
5c64ac2e1d1b44178059212d6d3b69f6fea3ee89
[ "C", "Makefile", "Shell" ]
29
C
Alx-Ang/Alexis_Angeles_Segundo_IC_0602_Taller_SO
f93ce5055a36b28eb2ad2c9a723b9328d4226922
de3a623fcce78168aad43917608561fc37ed9a66
refs/heads/main
<repo_name>Justlesia/get_next_line<file_sep>/README.md Study project for 21 School (42cursus), 2020. (without bonus) This project will not only allow you to add a very convenient function to your collection, but it will also allow you to learn a highly interesting new concept in C programming: static variables. <file_sep>/get_next_line_utils.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbrenton <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/19 22:28:35 by sbrenton #+# #+# */ /* Updated: 2020/11/19 22:40:07 by sbrenton ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" size_t ft_strlen(const char *s) { size_t l; l = 0; while (s[l] != '\0') l++; return (l); } char *ft_strdup(const char *s) { size_t l; size_t n; char *res; l = ft_strlen(s); if (!(res = (char *)malloc(l + 1))) return (NULL); n = 0; while (n < l) { res[n] = s[n]; n++; } res[n] = '\0'; return (res); } char *ft_strjoin(char const *s1, char const *s2) { size_t n; size_t s1_len; size_t s2_len; char *res; if (!s1 || !s2) return (NULL); s1_len = ft_strlen(s1); s2_len = ft_strlen(s2); if (!(res = (char *)malloc(s1_len + s2_len + 1))) return (NULL); n = 0; while (n < s1_len) { res[n] = s1[n]; n++; } n = 0; while (n < s2_len) { res[n + s1_len] = s2[n]; n++; } res[n + s1_len] = '\0'; return (res); }
d3b6e9e01d2a28dc27c5cf6a003028fd43f0d9bf
[ "Markdown", "C" ]
2
Markdown
Justlesia/get_next_line
4a4f8f7b4c4681092fb8839f7d2b712bfe4cf1f5
eaba0dfcbccafe6fce0c324486a83cf6b4c8b4e7
refs/heads/master
<file_sep># Colorimeter This is a simple example of how to connect an Angular 4 application to a Particle Photon. You can read more about [this post on my website](http://acostanza.com/2017/10/17/angular-4-app-photon-iot-colorimeter/). ## Start project Run `ng serve` ## Questions? Send me an email at <EMAIL> <file_sep>import { Injectable } from '@angular/core' import { HttpClient, HttpHeaders } from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/map'; @Injectable() export class StartService { constructor(private http: HttpClient) {}; go(): Observable<any> { let token = '<KEY>'; let deviceId = 'YYYYYYYYYYYYYYYYYYYYYY'; let headers = { headers : new HttpHeaders().set('Content-Type', 'application/json') }; return this.http.post('https://api.particle.io/v1/devices/'+deviceId+'/go?access_token='+token,{'arg':' '},headers) .map(response => { return response; }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import {StartService} from './start.service'; @Component({ selector: 'app-start', templateUrl: './start.component.html', styleUrls: ['./start.component.css'], providers:[StartService] }) export class StartComponent implements OnInit { constructor(private ss: StartService) { } start():void { this.ss.go().subscribe(res => { console.log(res); }); } ngOnInit() { } }
6c97f28e3a790cf8a58e91405f5a9aa713e92095
[ "Markdown", "TypeScript" ]
3
Markdown
adcostanza/colorimeter-angular
ef6213cb63b738d98050ae10d4e0a7422a872ab6
d5e232315cd7ec167449af61bd184dc2d7523773
refs/heads/master
<repo_name>cezarystefanski/csddApps<file_sep>/app.js //TODO: add blog module, get jQuery from bower modules var App = function () { "use strict"; var version = "0.0.1", githubLink = "https://", mainAppContext = this; this.logger = function (module, error, params) { var errorMsg = module + ": "; if (error === "optionsLacking") { errorMsg = "Options object lacking information:"; params.forEach(function (elem) { errorMsg += " " + elem; }); } else if (error === "noOptions") { errorMsg += "No options object"; } else if (error === "no$") { errorMsg += "No jQuery present"; } else if (error === "noContainer") { errorMsg += "No such DOM element: " + params; } else if (error === "noChildren") { errorMsg += params + " has no children elements"; } else if (error === "initFailed") { errorMsg += "Initialization failed"; } else if (error === "wrongDataType") { errorMsg += "Wrong data type/types in the options object"; } if (error) { window.console.error(errorMsg); } else { if (module) { window.console.info("csddApps " + module + " v." + version + " Github: " + githubLink); } else { window.console.info("csddApps v." + version + " Github: " + githubLink); } } }; this.Slider = function (options) { var sliderOpts = {}, moduleName = "cSlider", self = this, prepareSlides = function (numberOfSlides, slides, $) { var widthOfOne = 100 / numberOfSlides + "%"; slides.each(function () { $(this).css({ "width" : widthOfOne, "float" : "left" }); $(this).children().css({ "width" : "100%" }); }); }, createSlider = function (options) { var $, $container, $slides, sliderName = "cSlider", slideName = "cSlide", upperContainerName = "cSliderContainer", iterator, noOfSlides, $sliderUpperContainer, $wrapper; if (typeof window.jQuery !== "function") { self.log("no$"); return; } else { $ = window.jQuery; } $container = $(options.sliderContainer); if (!$container.length) { self.log("noContainer", options.sliderContainer); return; } $sliderUpperContainer = $("<div></div>").addClass(upperContainerName).css({ "width" : "100%", "overflow" : "hidden" }); $container.addClass(sliderName); $slides = $container.children(); if (!$slides.length) { self.log("noChildren", options.sliderContainer); return; } $wrapper = $container.parent(); $sliderUpperContainer.append($container); $wrapper.append($sliderUpperContainer); iterator = 1; $slides.addClass(slideName).each(function () { $(this).attr("data-slide_number", iterator); iterator = iterator + 1; }); noOfSlides = iterator - 1; $container.css({ "width" : noOfSlides * 100 + "%", "transition" : "all 800ms cubic-bezier(0.77, 0, 0.175, 1)", "transform" : "translateZ(0)", "marginLeft" : "0%" }); prepareSlides(noOfSlides, $slides, $); }; this.log = function (error, params) { return mainAppContext.logger(moduleName, error, params); }; /** * Initialises the slider and stores the options into a local private var * the method is exposed from the constructor for ready use * @param options as an object containing properties -> * sliderContainer (a jQuery selector) * autoScroll (a boolean) */ this.init = function (options) { var optionsLacking = []; if (!options) { this.log("noOptions"); return; } if (!options.hasOwnProperty("sliderContainer")) { optionsLacking.push("sliderContainer"); } if (!options.hasOwnProperty("autoScroll")) { optionsLacking.push("autoScroll"); } if (!options.hasOwnProperty("sliderContainer") || !options.hasOwnProperty("autoScroll")) { this.log("optionsLacking", optionsLacking); } else { sliderOpts.sliderContainer = options.sliderContainer; sliderOpts.autoScroll = options.autoScroll; createSlider(sliderOpts); } }; /** * if the options are inserted directly to the constructor * run the initialization automatically */ if (options) { this.init(options); } }; /** * Constructs a Facebook page plugin and appends it to a chosen container * @param options go like this: {container: *String* jQuery container || MANDATORY, * page: *String* facebook page ID (the xxx in facebook.com/xxx) || MANDATORY, * fWidth: *Integer* width in pixels || defaults to 340px, * fHeight: *Integer* height in pixels || defaults to 500px, * hideCover: *Boolean* hide or show cover photo || defaults to false, * showFacePile: *Boolean* show which friends liked this? || defaults to true, * adaptWidth : *Boolean* if the container width is smaller than width, should it adapt || defaults to true} * @constructor */ this.FacebookPlugin = function (options) { var moduleName = "cFacebook", fbOpts = { tabs: ["timeline"] }, self = this, $fbSDK = '<div id="fb-root"></div>' + '<script>(function(d, s, id) {' + 'var js, fjs = d.getElementsByTagName(s)[0];' + 'if (d.getElementById(id)) return;' + 'js = d.createElement(s); js.id = id;' + 'js.src = "//connect.facebook.net/pl_PL/sdk.js#xfbml=1&version=v2.5";' + 'fjs.parentNode.insertBefore(js, fjs);' + "}(document, 'script', 'facebook-jssdk'));</script>", checkJQuery = function () { if (typeof window.jQuery === "function") { return true; } }, constructOptions = function (options, $, def) { var optionsLacking = []; if (!options) { self.log("noOptions"); return def.reject(); } if (!options.hasOwnProperty("container")) { optionsLacking.push("container"); } if (!options.hasOwnProperty("page")) { optionsLacking.push("page"); } if (!options.container || !options.page) { self.log("optionsLacking", optionsLacking); return def.reject(); } fbOpts.container = options.container; fbOpts.page = options.page; fbOpts.fWidth = options.fWidth || 340; fbOpts.fHeight = options.fHeight || 500; fbOpts.hideCover = options.hideCover || false; fbOpts.showFacePile = options.showFacePile || true; fbOpts.adaptWidth = options.adaptWidth || true; if (typeof options.page !== "string" || typeof fbOpts.fWidth !== "number" || typeof fbOpts.fHeight !== "number" || typeof fbOpts.hideCover !== "boolean" || typeof fbOpts.showFacePile !== "boolean" || typeof fbOpts.adaptWidth !== "boolean") { self.log("wrongDataType"); return def.reject(); } return def.resolve(); }, insertSDK = function ($) { $('body').prepend($fbSDK); }, createWidget = function ($) { var $container, $widget, page, width, height, cover, tabs, facepile, adaptWidth; $container = $(fbOpts.container); if (!$container.length) { self.log("noContainer", options.sliderContainer); return; } $widget = $("<div></div>").addClass("fb-page"); page = "https://www.facebook.com/" + fbOpts.page; width = fbOpts.fWidth; height = fbOpts.fHeight; cover = fbOpts.hideCover; tabs = fbOpts.tabs.join(","); facepile = fbOpts.showFacePile; adaptWidth = fbOpts.adaptWidth; $widget.attr({ "data-href" : page, "data-width" : width, "data-height" : height, "data-hide-cover" : cover, "data-tabs" : tabs, "data-show-facepile" : facepile, "data-adapt-container-width" : adaptWidth }); $container.append($widget); }; this.init = function (options) { var is$ = checkJQuery(), $, isOptionsDone; if (is$) { $ = window.jQuery; isOptionsDone = $.Deferred(); constructOptions(options, $, isOptionsDone); $.when(isOptionsDone).done(function () { insertSDK($); createWidget($); }).fail(function () { self.log("initFailed"); }); } }; this.log = function (error, params) { return mainAppContext.logger(moduleName, error, params); }; if (options) { this.init(options); } }; this.setCookie = function (cname, cvalue, exdays) { var d = new Date(), expires; d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + "; " + expires; }; this.getCookie = function (cname) { var name = cname + "=", ca = document.cookie.split(';'), i, caLength = ca.length, c; for (i = 0; i < caLength; i += 1) { c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1); } if (c.indexOf(name) === 0) { return c.substring(name.length, c.length); } } return ""; }; this.logger(); }; <file_sep>/README.md # csddApps Helper apps for creating websites (and JS self-training to boot!)
47c122db41bb0bd0f9f69d399601f450a8d22af4
[ "JavaScript", "Markdown" ]
2
JavaScript
cezarystefanski/csddApps
412b36b4de8da5acb534c67a86456e824f5c3ea3
cef73fd220b01a51e13b86d433ceb929cbdfc004
refs/heads/master
<file_sep>import { Component, ElementRef, ViewChild } from '@angular/core'; import { chart } from 'highcharts'; import * as Highcharts from 'highcharts'; @Component({ selector: 'app-sm-highcharts', templateUrl: './sm-highcharts.component.html', styleUrls: ['./sm-highcharts.component.css'] }) export class SmHighchartsComponent { title = 'Highcharts + Angular 5 Demo'; @ViewChild('chartTarget') chartTarget: ElementRef; chart: Highcharts.ChartObject; ngAfterViewInit() { const options: Highcharts.Options = { chart: { type: 'line' }, title: { text: 'Seasonality Profile' }, xAxis: { categories: ['1', '2', '3','4', '5', '6','7', '8', '9'] }, yAxis: { title: { text: '' } }, series: [{ name: 'Input Values', data: [0.81, 1.1, 1.2, 1.3, 1.4, 1.2, 0.5, 0.9, 2.0] }, { name: 'Normalized Values', data: [1.5, 1.7, 1.3, 1.1, 1.5, 0.7, 0.3, 2.1, 1.8] }] }; this.chart = chart(this.chartTarget.nativeElement, options); } addSeries(){ this.chart.addSeries({ name:'Balram', data:[2,3,7] }) } }<file_sep>"# AngularPOC" <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { AppMaterialModule } from './app-material/app-material.module'; import { SmLibTreeComponent } from './sm-lib-tree/sm-lib-tree.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { SmHighchartsComponent } from './sm-highcharts/sm-highcharts.component'; import { SmGridComponent } from './sm-grid/sm-grid.component'; @NgModule({ declarations: [ AppComponent, SmLibTreeComponent, SmHighchartsComponent, SmGridComponent ], imports: [ BrowserModule, AppMaterialModule, BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit } from '@angular/core'; declare var dhtmlXGridObject: any; @Component({ selector: 'app-sm-grid', templateUrl: './sm-grid.component.html', styleUrls: ['./sm-grid.component.css'] }) export class SmGridComponent implements OnInit { constructor() { } ngOnInit() { this.loadDhtmlxGrid(); } loadDhtmlxGrid(){ var myGrid = new dhtmlXGridObject('gridbox'); myGrid.setImagePath("src/assets/DhtmlxGrid/codebase/imgs/"); myGrid.setHeader("Period,1,2,3,4,5",null, ["text-align:center;","text-align:center;","text-align:center","text-align:center" ,"text-align:center","text-align:center"]); //myGrid.setInitWidths("80,150,100,80,80,80,80,100"); //myGrid.setColAlign("left,left,left,right,center,left,center,center"); //myGrid.setColTypes("ro,ed,ed,price,,co,ra,ro"); //myGrid.setColSorting("int,str,str,int,str,str,str,date"); //myGrid.setSkin("skyblue"); myGrid.enableAutoWidth(true); myGrid.enableAutoHeight(true); myGrid.init(); myGrid.addRow(1,"Input Values,1,2,3,4,5"); myGrid.addRow(2,"Normalized Values,1,2,3,4,5"); } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SmGridComponent } from './sm-grid.component'; describe('SmGridComponent', () => { let component: SmGridComponent; let fixture: ComponentFixture<SmGridComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SmGridComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SmGridComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
5fc4d698a7b91d22c5f2718d47eb8643e1652bb7
[ "Markdown", "TypeScript" ]
5
TypeScript
SrikanthEnuguru/Angular-POC
486caa1c77a4c5bafbf7a15e7dfec5e57e60bd6e
7dced6a50421ef862ed1280cda29091a9ba79410
refs/heads/main
<repo_name>Mnabawy/crud-app<file_sep>/frontend/src/app/service/data.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private httpClient: HttpClient) { } getDate() { return this.httpClient.get('http://127.0.0.1:8000/api/employees'); } insertData(data: any) { return this.httpClient.post('http://127.0.0.1:8000/api/addEmployee', data); } deleteData(id: any) { return this.httpClient.delete("http://127.0.0.1:8000/api/deleteEmployee/" + id) } getEmployeeById(id: any) { return this.httpClient.get("http://127.0.0.1:8000/api/employee/" + id) } updateData(id:any, data:any) { return this.httpClient.put("http://127.0.0.1:8000/api/updateEmployee/"+id, data) } }
8753877bc19add9e427adc021dd598344195b3eb
[ "TypeScript" ]
1
TypeScript
Mnabawy/crud-app
15dca600d6b97751fdbf4e0298cbec40a3fb33b1
605865787ca4583b9fec0b8e713229a52182c742
refs/heads/master
<repo_name>barkalovnik123/barkalovnik123.github.io<file_sep>/aboutscript.js // замена текста в основном блоке. function mainblock() { if (document.getElementById('lang').innerText == 'English version') { document.getElementById('mainonindex').innerHTML = ` <h3> Я <NAME> (barkalovnik123)! Начинающий программист и разработчик игр =) Внизу сайта вы можете найти ссылки на мои соц-сети </h3> `; document.getElementById('logopage').innerHTML = ` <big> <img src="images/not.png" wight="32" height="32" align="right"> Обо мне <img src="images/not.png" wight="32" height="32" align="left"> </big> `; } else if (document.getElementById('lang').innerText == 'Русская версия') { document.getElementById('mainonindex').innerHTML = ` <h3> I am <NAME> (barkalovnik123)! I am an young and novice programmer and game-developer! In the end of every page you can find links on my social medias! </h3> `; document.getElementById('logopage').innerHTML = ` <big> <img src="images/not.png" wight="32" height="32" align="right"> About <img src="images/not.png" wight="32" height="32" align="left"> </big> `; } }<file_sep>/scrscript.js // замена текста в основном блоке. function mainblock() { if (document.getElementById('lang').innerText == 'English version') { document.getElementById('mainonindex').innerHTML = ` <h3>Здесь вы найдёте скринсейверы, сделанные мною</h3> <h2> <div class="indiv"> Простите, пока нет скринсейверов =( Они были, но пока прекратили существование из-за окончания срока поддержки технологии Flash </div> </h2> `; document.getElementById('logopage').innerHTML = ` <big> <img src="images/scr.png" wight="32" height="32" align="right"> Скринсейверы <img src="images/scr.png" wight="32" height="32" align="left"> </big> `; } else if (document.getElementById('lang').innerText == 'Русская версия') { document.getElementById('mainonindex').innerHTML = ` <h3>Here are screensavers made by me</h3> <h2> <div class="indiv"> Sorry, no screensavers yet =( They were, but stopped working 'cause of Flash's EoL </div> </h2>`; document.getElementById('logopage').innerHTML = ` <big> <img src="images/scr.png" wight="32" height="32" align="right"> Screensavers <img src="images/scr.png" wight="32" height="32" align="left"> </big> `; } }<file_sep>/script.js function Lang() { if (document.getElementById('lang').innerText == 'Русская версия') { // меню document.getElementById('menu').innerHTML = ` <ul class="ulleft"> <a href="games.html"> <li class="gradientred"> Игры </li> </a> <a href="drawings.html"> <li class="gradientblue"> Рисунки </li> </a> <a href="scr.html"> <li class="gradientyellow"> Скринсейверы </li> </a> <a href="about.html"> <li class="gradientwhite"> О себе </li> </a> <a href="index.html"> <li class="gradientgreen"> Главная </li> </a> </ul>`; // новостной блок document.getElementById('newsblock').innerHTML = ` <div class="prokrutka" id="prokrutka"> <em> <string> НОВОСТИ </string> </em> <p class="date">27.08.20</p> <p>Новая версия сайта!</p> <p class="date">22.08.20</p> <p>Написал новые скринсейверы! Скоро появятся!</p> </div>`; // заголовки блоков с новостями и меню document.getElementById('logosDeBlocks').innerHTML = ` <!-- LOGO МЕНЮ--> <h2 class="menulogo" id="menulogo"> --- МЕНЮ --- </h2> <!--logo новостей--> <h2 class="newlogo" id="newslogo"> - НОВОСТИ - </h2>`; // футтер document.getElementById('futter').innerHTML = ` <a href="https://www.instagram.com/nikita.barkalov/"> <button id="instagrambutton"> Я в Instagram </button> </a> <a href="https://scratch.mit.edu/users/barkalovnik123/"> <button id="scratchbutton"> Я в Scratch </button> </a> <a href="https://gamejolt.com/@barkalovnik123"> <button id="okbutton"> Я в GameJolt </button> </a> <a href="https://ok.ru/profile/561185208059"> <button id="okbutton"> Я в ОК </button> </a> <a href="https://twitter.com/barkalovnik123"> <button id="okbutton"> Я в Twitter </button> </a> <a href="https://barkalovnik123.tumblr.com/"> <button id="okbutton"> Я в Tumblr </button> </a> <a href="https://vk.com/barkalovnik123"> <button id="okbutton"> Я в VK </button> </a> <p id="writedby"> Сайт написан barkalovnik123 на html+css+javascript. Хостинг - github. </p>`; // мобильное меню document.getElementById('mobileMenu1').innerHTML = ` <ul> <li id="mobileMenu2"> </li> </ul>`; document.getElementById('mobileMenu2').innerHTML = 'Меню' + document.getElementById('menu').innerHTML; // надпись на кнопке смены языка document.getElementById('lang').innerText = "English version" } else if (document.getElementById('lang').innerText = "English version") { // меню document.getElementById('menu').innerHTML = ` <ul class="ulleft"> <a href="games.html"> <li class="gradientred"> Games </li> </a> <a href="drawings.html"> <li class="gradientblue"> Drawings </li> </a> <a href="scr.html"> <li class="gradientyellow"> Screensavers </li> </a> <a href="about.html"> <li class="gradientwhite"> About </li> </a> <a href="index.html"> <li class="gradientgreen"> Main </li> </a> </ul>`; // новостной блок document.getElementById('newsblock').innerHTML = ` <div class="prokrutka" id="prokrutka"> <em> <string> News </string> </em> <p class="date">27.08.20</p> <p>New version o' my site!</p> <p class="date">22.08.20</p> <p>Writed new scrs! Coming soon!</p> </div>`; // заголовки блоков с новостями и меню document.getElementById('logosDeBlocks').innerHTML = ` <!-- LOGO МЕНЮ--> <h2 class="menulogo" id="menulogo"> ----Menu---- </h2> <!--logo новостей--> <h2 class="newlogo" id="newslogo"> -What's new- </h2>`; // футтер document.getElementById('futter').innerHTML = ` <a href="https://www.instagram.com/nikita.barkalov/"> <button id="instagrambutton"> My Instagram </button> </a> <a href="https://scratch.mit.edu/users/barkalovnik123/"> <button id="scratchbutton"> My Scratch </button> </a> <a href="https://gamejolt.com/@barkalovnik123"> <button id="okbutton"> My GameJolt </button> </a> <a href="https://ok.ru/profile/561185208059"> <button id="okbutton"> My OK </button> </a> <a href="https://twitter.com/barkalovnik123"> <button id="okbutton"> My Twitter </button> </a> <a href="https://barkalovnik123.tumblr.com/"> <button id="okbutton"> My Tumblr </button> </a> <a href="https://vk.com/barkalovnik123"> <button id="okbutton"> My VK </button> </a> <p id="writedby"> Site is written by barkalovnik123 (<NAME>) using HTML + CSS + JavaScript. GitHub used as a host. </p>`; // мобильное меню document.getElementById('mobileMenu1').innerHTML = ` <ul> <li id="mobileMenu2"> </li> </ul>`; document.getElementById('mobileMenu2').innerHTML = 'Menu' + document.getElementById('menu').innerHTML; // надпись на кнопке смены языка document.getElementById('lang').innerText = "Русская версия" } }<file_sep>/tools_for_learning/scriptbook.js //Это для книги function saveToLocal() { // функция для сохранения в локалСтор var day = document.getElementById("day_id").value; var month = document.getElementById("month_id").value; var year = document.getElementById("year_id").value; if (day == "" || month == "" || year == "") { // Если пользователь ничего не ввёл, просим ввести и выходим из функции alert("Введите дату!"); return } var theKey = day + month + year; // Соединяем день месяц и год в один ключ localStorage.setItem(theKey, document.getElementById("text_pole").value); // Сохраняем if (!document.getElementById("selection").innerHTML.includes(theKey)) { // Добавляем в выпадающий списко document.getElementById("selection").innerHTML = document.getElementById("selection").innerHTML + `<option>${theKey}</option>` } } function loadFromLocal() { // Функция для загрузки данных из локалСтор var load_day = document.getElementById("day_id").value; var load_month = document.getElementById("month_id").value; var load_year = document.getElementById("year_id").value; if (load_day == "" || load_month == "" || load_year == "") { // Если пользователь ничего не ввёл, просим ввести и выходим из функции alert("Введите дату!"); return } var load_theKey = load_day + load_month + load_year; // объединяем в ключ // Выводим данные в поле ввода document.getElementById("text_pole").value = localStorage.getItem(load_theKey); } function autoLoad() { // Функуия для загрузки даты из выпадающего списка if (document.getElementById("selection").value.length == 6) { var values = document.getElementById("selection").value.match(/.{1,2}/g); // Разделяем на массив по два символа // Выводи document.getElementById("day_id").value = values[0]; document.getElementById("month_id").value = values[1]; document.getElementById("year_id").value = values[2]; } } // Загружаем записи из локалСтор в выпадающий список var localKeys = Object.keys(localStorage); for (var i = 0; i < localKeys.length; i++) { if (localKeys[i].length == 6) { document.getElementById("selection").innerHTML = document.getElementById("selection").innerHTML + `<option>${localKeys[i]}</option>`; } } alert(`Здравствуйте! Введите дату (в каждом поле по две цифры) Делайте записи и сохраняйте их кнопкой "Сохранить" После этого вы сможете снова открыть набранный текст, выбрав дату в выпадающем списке и нажав кнопку "Загрузить" Не стоит использовать данный инструмент для хранения паролей. Данный инструмент можно использовать как альтернативу обычной записной книге, а также некоторым стационарным программам. Так как не требует скачки, в любой момент можно открыть в своём веб-браузере. Система дат позволяет систематизировать записи. Хранение записей на компьютере имеет свои преимущества: их не так легко потерять.`)<file_sep>/tools_for_learning/scriptcalc.js function calculate() { //определяем наши ФО var fg1 = +document.getElementById("i1").value; var fg2 = +document.getElementById("i2").value; var fg3 = +document.getElementById("i3").value; var fg4 = +document.getElementById("i4").value; var fg5 = +document.getElementById("i5").value; var fg6 = +document.getElementById("i6").value; var fg7 = +document.getElementById("i7").value; var fg8 = +document.getElementById("i8").value; var fg9 = +document.getElementById("i9").value; var fg10 = +document.getElementById("i10").value; //определяем СОРы var ourSAS1 = +document.getElementById("sas1").value; var ourSAS2 = +document.getElementById("sas2").value; var ourSAS3 = +document.getElementById("sas3").value; var ourSAS4 = +document.getElementById("sas4").value; var maxSAS1 = +document.getElementById("maxsas1").value; var maxSAS2 = +document.getElementById("maxsas2").value; var maxSAS3 = +document.getElementById("maxsas3").value; var maxSAS4 = +document.getElementById("maxsas4").value; //определяем СОЧи var SAQ = +document.getElementById("saq").value; var maxSAQ = +document.getElementById("maxsaq").value; //определяем сумму ФО и их кол-во var fgSum = fg1*1+fg2*2+fg3*3+fg4*4+fg5*5+fg6*6+fg7*7+fg8*8+fg9*9+fg10*10; var fgAmount = fg1+fg2+fg3+fg4+fg5+fg6+fg7+fg8+fg9+fg10; // определяем сумму СОЧ и сумму максимальных оценок СОЧ var ourSASSum = ourSAS1+ourSAS2+ourSAS3+ourSAS4; var maxSASSum = maxSAS1+maxSAS2+maxSAS3+maxSAS4; // считаем результат if (document.getElementById("year").checked) { // Если выбрали гол var result = (((ourSASSum + fgSum) / (maxSASSum + fgAmount * 10)) * 50) + ((SAQ / maxSAQ) * 50); } else if (document.getElementById("half_year").checked) { // Если выбрали полугодие var result = ((ourSASSum + fgSum) / (maxSASSum + fgAmount * 10)) * 100; } var five_mark = 0; //Формирование пятибальной оценки if (document.getElementById("grade_high").checked) { if (result > 0 && result < 40) { five_mark = 2; } else if (result >= 40 && result < 65) { five_mark = 3; } else if (result >= 65 && result < 85) { five_mark = 4; } else if (result >= 85 && result <= 100) { five_mark = 5; } } else if (document.getElementById("grade_small").checked) { if (result > 0 && result < 21) { five_mark = 2; } else if (result >= 21 && result < 51) { five_mark = 3; } else if (result >= 51 && result < 81) { five_mark = 4; } else if (result >= 81 && result <= 100) { five_mark = 5; } } // Вывод document.getElementById("results").innerHTML = `Процентная оценка: ${result+"%"}; <br> Пятибальная оценка: ${five_mark}`; } // Прячем или показываем определенные поля ввода в соответствии с выбраными критериями (тип оценивания и класс) function change() { if (document.getElementById("year").checked) { document.getElementById("be_hidden").style.display = "block"; document.getElementById("be_hidden2").style.display = "block"; } else if (document.getElementById("half_year").checked) { document.getElementById("be_hidden").style.display = "none"; document.getElementById("be_hidden2").style.display = "none"; } } // Функции для показа полей ввода ФО, СОР, СОЧ. Сделано для удобства пользователя: они разворачиваются по нажатию на кнопку function showOrHideFG() { if (document.getElementById("FGForm").style.display == "none") { document.getElementById("FGForm").style.display = "block"; } else { document.getElementById("FGForm").style.display = "none"; } } function showOrHideSAS() { if (document.getElementById("SASForm").style.display == "none") { document.getElementById("SASForm").style.display = "block"; } else { document.getElementById("SASForm").style.display = "none"; } } function showOrHideSAQ() { if (document.getElementById("SAQForm").style.display == "none") { document.getElementById("SAQForm").style.display = "block"; } else { document.getElementById("SAQForm").style.display = "none"; } } // с самого начала они спрятаны. Показаны будут по нажатию document.getElementById("FGForm").style.display = "none"; document.getElementById("SASForm").style.display = "none"; document.getElementById("SAQForm").style.display = "none"; alert(`Здравствуйте! Выберите ваш класс и тип оценивания по предмету. После чего введите количество определенных отметок ФО, а также СОР и СОЧ (Если какие-либо отметки отсутствуют, оставьте поле пустым). После нажмите на "Вычислить", вы получите свой процентный балл по предмету, а также пятибальную отметку. Данный инструмент можно использовать для прогнозирования оценки, контроля успеваемости и может помочь в постановке приоритетов в учёбе`)<file_sep>/drawingsscript.js // замена текста в основном блоке. function mainblock() { if (document.getElementById('lang').innerText == 'English version') { document.getElementById('mainonindex').innerHTML = ` <h3>Здесь находятся мои рисунки! =3</h3> <h2>Также большинство моих работ находятся в моём <a href="https://www.instagram.com/nikita.barkalov/">Инстаграме</a></h2> <img src="images/paint1.jpg" class="frame imagesindrawings"> <img src="images/paint2.jpg" class="frame imagesindrawings"> <img src="images/paint3.png" class="frame imagesindrawings"> <img src="images/paint4.jpg" class="frame imagesindrawings"> <img src="images/paint5.png" class="frame imagesindrawings"> <img src="images/paint6.jpg" class="frame imagesindrawings"> <img src="images/paint7.jpg" class="frame imagesindrawings"> <img src="images/paint8.jpg" class="frame imagesindrawings"> <img src="images/paint9.png" class="frame imagesindrawings"> <img src="images/paint10.png" class="frame imagesindrawings"> <img src="images/paint11.jpg" class="frame imagesindrawings"> <img src="images/paint12.png" class="frame imagesindrawings"> <img src="images/paint13.png" class="frame imagesindrawings"> `; document.getElementById('logopage').innerHTML = ` <big> <img src="images/draw.png" wight="32" height="32" align="right"> Рисунки <img src="images/draw.png" wight="32" height="32" align="left"> </big> `; } else if (document.getElementById('lang').innerText == 'Русская версия') { document.getElementById('mainonindex').innerHTML = ` <h3>Here are my drawings! =3</h3> <h2>Also most of my works can be found on my <a href="https://www.instagram.com/nikita.barkalov/">Insta!</a></h2> <img src="images/paint1.jpg" class="frame imagesindrawings"> <img src="images/paint2.jpg" class="frame imagesindrawings"> <img src="images/paint3.png" class="frame imagesindrawings"> <img src="images/paint4.jpg" class="frame imagesindrawings"> <img src="images/paint5.png" class="frame imagesindrawings"> <img src="images/paint6.jpg" class="frame imagesindrawings"> <img src="images/paint7.jpg" class="frame imagesindrawings"> <img src="images/paint8.jpg" class="frame imagesindrawings"> <img src="images/paint9.png" class="frame imagesindrawings"> <img src="images/paint10.png" class="frame imagesindrawings"> <img src="images/paint11.jpg" class="frame imagesindrawings"> <img src="images/paint12.png" class="frame imagesindrawings"> <img src="images/paint13.png" class="frame imagesindrawings"> `; document.getElementById('logopage').innerHTML = ` <big> <img src="images/draw.png" wight="32" height="32" align="right"> DRAWINGS <img src="images/draw.png" wight="32" height="32" align="left"> </big> `; } }<file_sep>/scriptindex.js // замена текста в основном блоке. function mainblock() { if (document.getElementById('lang').innerText == 'English version') { document.getElementById('mainonindex').innerHTML = ` <h2 id="text1"> Приветствую вас на своём сайте! </h2> <br> <p id="text2"> На нём вы найдетё игры, программы, рисунки и тому подобное, </p> <p id="text3"> Сделанное barkalovnik123 (Никитой Баркаловым). </p> <p id="text4"> По сути говоря, данный сайт исполняет роль портфолио. </p> <h2 id="text5"> Быстрые ссылки на страницы сайта: </h2> <p> <a href="games.html" id="gamesme"> -------Игры------- </a> </p> <p> <a href="drawings.html" id="drawme"> -----Рисунки----- </a> </p> <p> <a href="scr.html" id="scrme"> Скринсейверы </a> </p> <p> <a href="about.html" id="aboutme"> ------О себе------ </a> </p>`; document.getElementById('logopage').innerHTML = ` <big> <img src="images/bulb.png" wight="32" height="32" align="right"> ГЛАВНАЯ <img src="images/bulb.png" wight="32" height="32" align="left"> </big> `; } else if (document.getElementById('lang').innerText == 'Русская версия') { document.getElementById('mainonindex').innerHTML = ` <h2 id="text1"> Hello everyone! This is barkalovnik123's site </h2> <br> <p id="text2"> Here is games, drawings, programms and others, </p> <p id="text3"> writed by barkalovnik123 (<NAME>). </p> <p id="text4"> So, it is something like portpholio. </p> <h2 id="text5"> Fast links: </h2> <p> <a href="games.html" id="gamesme"> -------Games------- </a> </p> <p> <a href="drawings.html" id="drawme"> -----Drawings----- </a> </p> <p> <a href="scr.html" id="scrme"> Screensavers </a> </p> <p> <a href="about.html" id="aboutme"> ------About me------ </a> </p>`; document.getElementById('logopage').innerHTML = ` <big> <img src="images/bulb.png" wight="32" height="32" align="right"> Main <img src="images/bulb.png" wight="32" height="32" align="left"> </big> `; } }
1009d6fe35657d0d1f8eb1e89b5b883ee47e4e3c
[ "JavaScript" ]
7
JavaScript
barkalovnik123/barkalovnik123.github.io
2c18288fa0fd6953b31d315926ff8b57b423d092
8fdab5433d65814456e3e7df9cca7ea9476fe2c1
refs/heads/master
<repo_name>Naddy706/FoodWasteManagment_Project<file_sep>/app/src/main/java/com/creativodevelopers/foodwastagemanagment/myevent_adapter.java package com.creativodevelopers.foodwastagemanagment; import android.app.Activity; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; public class myevent_adapter extends ArrayAdapter { private final Activity context; private final List<String> subtitle; public myevent_adapter(Activity context, List<String> subtitle) { super(context, R.layout.show_events_list, subtitle); // TODO Auto-generated constructor stub this.context=context; this.subtitle=subtitle; } TextView Title, Description,Date , Time , Location, Id; Button Interested; ImageView EventImage; public View getView(final int position, final View view, ViewGroup parent) { LayoutInflater inflater=context.getLayoutInflater(); View itemView=inflater.inflate(R.layout.show_events_list, null,true); Title = itemView.findViewById(R.id.title); Description = itemView.findViewById(R.id.description); Date= itemView.findViewById(R.id.date); Time=itemView.findViewById(R.id.time); Location=itemView.findViewById(R.id.location); EventImage= itemView.findViewById(R.id.Eventimage); Interested=itemView.findViewById(R.id.interested); Id=itemView.findViewById(R.id.id); Title.setText(myeventsfragment.Title.get(position)); Description.setText(myeventsfragment.Description.get(position)); Date.setText(myeventsfragment.Date.get(position)); Time.setText(myeventsfragment.Time.get(position)); Location.setText(myeventsfragment.Location.get(position)); Picasso.get().load(myeventsfragment.event_Image.get(position)).placeholder(R.drawable.eventimage).into(EventImage); Interested.setText("View Location"); Interested.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(context,WaypointNavigationActivity.class); i.putExtra("lat", myeventsfragment.lat.get(position)); i.putExtra("long", myeventsfragment.log.get(position)); context.startActivity(i); } }); return itemView; }; }<file_sep>/app/src/main/java/com/creativodevelopers/foodwastagemanagment/myEvent.java package com.creativodevelopers.foodwastagemanagment; public class myEvent { String EventKey,FoodKey,UserKey; public myEvent(String eventKey, String foodKey, String userKey) { EventKey = eventKey; FoodKey = foodKey; UserKey = userKey; } public myEvent() { } public String getEventKey() { return EventKey; } public void setEventKey(String eventKey) { EventKey = eventKey; } public String getFoodKey() { return FoodKey; } public void setFoodKey(String foodKey) { FoodKey = foodKey; } public String getUserKey() { return UserKey; } public void setUserKey(String userKey) { UserKey = userKey; } } <file_sep>/README.md # FoodWasteManagment_Project ## final year Diploma project ### Check AdminPanel in my Repository > firebase auth > 2 Apps > One for Admin organizing events > Add event , ADD Location from MapBox > User to be Continue <file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' android { compileSdkVersion 28 buildToolsVersion "28.0.0" defaultConfig { applicationId "com.creativodevelopers.foodwastagemanagment" minSdkVersion 23 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support:design:28.+' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation "com.google.firebase:firebase-core:15.0.2" implementation "com.google.firebase:firebase-ml-vision:15.0.0" implementation "com.google.firebase:firebase-appindexing:15.0.0" implementation "com.google.android.gms:play-services-ads:15.0.0" implementation "com.google.android.gms:play-services-maps:15.0.0" implementation "com.google.android.gms:play-services-places:15.0.0" implementation "com.google.android.gms:play-services-location:15.0.0" implementation "com.google.firebase:firebase-auth:15.0.0" implementation "com.google.firebase:firebase-database:15.0.0" implementation "com.firebaseui:firebase-ui-database:1.0.1" implementation "com.google.firebase:firebase-storage:15.0.2" implementation "com.google.firebase:firebase-messaging:15.0.2" implementation 'com.android.support:support-v4:28.+' implementation 'de.hdodenhof:circleimageview:3.0.1' implementation 'com.soundcloud.android:android-crop:1.0.1@aar' implementation 'com.squareup.picasso:picasso:2.71828' implementation 'com.firebaseui:firebase-ui-auth:3.3.1' implementation 'com.firebaseui:firebase-ui-database:3.3.1' implementation 'com.hbb20:ccp:2.1.9' implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:8.6.2' implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:8.5.0-SNAPSHOT' implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-places-v8:0.9.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-offline-v8:0.6.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-localization-v8:0.11.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-markerview-v8:0.3.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-annotation-v8:0.7.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.42.4' implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.42.4' implementation "com.mapbox.mapboxsdk:mapbox-android-core:1.3.0" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } apply plugin: 'com.google.gms.google-services' <file_sep>/settings.gradle include ':app' rootProject.name='Food Wastage Managment'
ce6317250c1e6532294d7df40fe33ce9074caa54
[ "Markdown", "Java", "Gradle" ]
5
Java
Naddy706/FoodWasteManagment_Project
75e19608267b2a14b98f95daa7bcbfdc32e10653
5229cc314453b614522b280070422bbbcf0adc0f
refs/heads/master
<file_sep>package com.example.exercise3; import android.content.Intent; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public EditText editText; public Button in,out,sp,json,xml; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { editText= (EditText) findViewById(R.id.show); in= (Button) findViewById(R.id.in); out = (Button) findViewById(R.id.out); json=findViewById(R.id.Json); xml=findViewById(R.id.XML); sp=findViewById(R.id.SP); in.setOnClickListener(this); out.setOnClickListener(this); sp.setOnClickListener(this); json.setOnClickListener(this); xml.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.in: String Text=editText.getText().toString(); String environment= Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(environment)) { File sd_path=Environment.getExternalStorageDirectory(); File file=new File(sd_path,"lzm.txt"); String str=editText.getText().toString(); FileOutputStream file_out; try{ //输出流输出到file文件 file_out=new FileOutputStream(file); //输出流写入文字 file_out.write(str.getBytes()); //关闭输出流 file_out.close(); Toast.makeText(this,"写入成功",Toast.LENGTH_LONG).show(); }catch (Exception e) { e.printStackTrace(); } } break; case R.id.out: environment = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(environment)) { File sd_path=Environment.getExternalStorageDirectory(); File file=new File(sd_path,"lzm.txt"); FileInputStream file_in; try{ file_in=new FileInputStream(file); BufferedReader buff_read=new BufferedReader(new InputStreamReader(file_in)); String str=buff_read.readLine(); file_in.close(); editText.setText(str); Toast.makeText(this,str,Toast.LENGTH_LONG).show(); }catch (Exception e) { e.printStackTrace(); } } break; case R.id.SP: Intent intent=new Intent(this,SharePreference.class); startActivity(intent); break; case R.id.Json: Intent intent1=new Intent(this,JSON.class); startActivity(intent1); break; case R.id.XML: Intent intent2=new Intent(this,XML.class); startActivity(intent2); break; default:break; } } } <file_sep>package com.example.exercise3; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.List; public class XML extends AppCompatActivity implements View.OnClickListener { private TextView xml_city_name,xml_weaher_info; private Button xml_beijing,xml_shanghai,xml_guangzhou; private ImageView xml_weather_img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_xml); init(); } private void init() { xml_city_name= findViewById(R.id.xml_city_name); xml_weaher_info=findViewById(R.id.xml_weather_info); xml_weather_img=findViewById(R.id.xml_weather_img); xml_beijing=(Button)findViewById(R.id.xml_beijing); xml_guangzhou=(Button)findViewById(R.id.xml_guangzhou); xml_shanghai=(Button)findViewById(R.id.xml_shanghai); xml_beijing.setOnClickListener(this); xml_guangzhou.setOnClickListener(this); xml_shanghai.setOnClickListener(this); xml_city_name.setText("北京"); xml_weaher_info.setText("晴 26℃/32℃ 98 3级"); xml_weather_img.setImageResource(R.drawable.sun); } @Override public void onClick(View view) { InputStream xml=this.getClass().getClassLoader().getResourceAsStream("assets/weather.xml"); List<City> cities=null; try{ cities=CityService.getCitys(xml); }catch (IOException e) { e.printStackTrace(); }catch (XmlPullParserException e) { e.printStackTrace(); } switch (view.getId()) { case R.id.xml_beijing: for(City city:cities) { if(city.getId()==2) { xml_city_name.setText(city.getName()); xml_weaher_info.setText(city.toString()); xml_weather_img.setImageResource(R.drawable.sun); } } break; case R.id.xml_shanghai: for(City city:cities) { if(city.getId()==1) { xml_city_name.setText(city.getName()); xml_weaher_info.setText(city.toString()); xml_weather_img.setImageResource(R.drawable.cloud_sun); } } Log.e(null,"test"); break; case R.id.xml_guangzhou: for(City city:cities) { if(city.getId()==3) { xml_city_name.setText(city.getName()); xml_weaher_info.setText(city.toString()); xml_weather_img.setImageResource(R.drawable.cloud_sun); } } Log.e(null,"test"); break; default:break; } } } <file_sep># JSON-XML_Resolve Android 小实验——xml和Json解析
b75a67be803bc141a4f636bc1de6aeaf3901f888
[ "Markdown", "Java" ]
3
Java
liaozeming/JSON-XML_Resolve
aff8f7696ab692614ed44b1097b074ded458e4a0
58ca112aab8f41557676644137094029a6800948
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WebApiPaises.Models; namespace WebApiPaises.Controllers { [Route("api/PaisApi/{PaisId}/Provincias")] [ApiController] public class ProvinciasApiController : ControllerBase { private readonly ApplicationDbContext context; public ProvinciasApiController(ApplicationDbContext context) { this.context = context; } [HttpGet] public IEnumerable<Provincia> Get(int paisId) { return context.Provincias .Where(m=>m.PaisId==paisId) .ToList(); } [HttpGet("{id}", Name = "provinciaById")] public IActionResult GetById(int id) { var provincias = context.Provincias.FirstOrDefault(m => m.Id == id); if (provincias == null) { return NotFound(); } return Ok(provincias); } [HttpPost] public IActionResult Post([FromBody] Provincia provincia) { if (ModelState.IsValid) { context.Provincias.Add(provincia); context.SaveChanges(); return new CreatedAtRouteResult("provinciaById", new { id = provincia.Id }, provincia); } return BadRequest(ModelState); } [HttpPut("{id}")] public IActionResult Put([FromBody] Provincia provincia, int id) { if (provincia.Id != id) { return BadRequest(); } context.Entry(provincia).State = EntityState.Modified; context.SaveChanges(); return Ok(); } [HttpDelete("{id}")] public IActionResult Delete(int id) { var provincia = context.Provincias.FirstOrDefault(m => m.Id == id); if (provincia == null) { return NotFound(); } context.Provincias.Remove(provincia); context.SaveChanges(); return Ok(); } } }<file_sep># apiPaises sin terminar
5f16a30d437e58dc6085e362ec21738cd44b21f9
[ "Markdown", "C#" ]
2
C#
sergio-balanda/apiPaises
1c0ebf44e057846fa253f484711d14d66d350f31
b761766808541e4423de407a41584786a528830f
refs/heads/master
<file_sep># -*- coding:utf-8 -*- import re import numpy as np import pandas as pd import jieba import time import gc def word_cut(data): stoplist = [line.strip() for line in open('../data/stopword.txt').readlines()] # jieba.load_userdict('userdict.txt') def get_cut(text): r1 = '()' # 应该考虑多种括号,【】,[], (), () r2 = '[a-zA-Z0-9’!"#$%&\'()();‘’*+,-./::;<=>?@,。?★、…【】《》?“”‘’![\\]^_`{|}~]+' r3 = '\s+' seg="\n".join(text) seg_list = jieba.cut(re.sub(r3, "", re.sub(r2, "", re.sub(r1, "", seg))), cut_all=False) words = ' '.join(seg_list) words = [word for word in words.split() if word not in stoplist and len(word)>=2] words = ' '.join(words) if len(words) == 0: return False else: return words user_id = [item.split(',')[0] for item in open(data)] texts = [get_cut(item.split(',')[1:]) for item in open(data) if get_cut(item)] df_data = pd.concat([pd.DataFrame(user_id), pd.DataFrame(texts)], axis=1) df_data.columns = ['id', 'text'] return df_data def main(): start = time.clock() # get train data train = word_cut("../data/Train_DataSet.csv") label = pd.read_csv("../data/Train_DataSet_Label.csv") df_data = pd.merge(train, label, on='id') df_data.to_csv("train.csv", index=False) # train model # predict end = time.clock() print('Program over, time cost is %s' % (end-start)) if __name__ == "__main__": main()
b4e8be59b56cef4a3ffa93ae0d015de870b5bb4b
[ "Python" ]
1
Python
Ming-H/SenAna
3770a982c89beedda87611b2301ca7554567bc17
2848a54a2c1ce198c06a0cb561adbc638b0f9898
refs/heads/master
<repo_name>edu-kajiwara/05-lesson-database-access-u21611357<file_sep>/src/main/java/com/example/demo/DemoApplication.java package com.example.demo; import com.example.demo.DAO.UserDAO; import lombok.val; import com.example.demo.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Autowired UserDAO userDao; @Override public void run(String... strings) throws Exception { val newUser = new User("12345678","山田太郎"); userDao.insertUser(newUser); } }
43fc218371bdf98267812f0d1f17ecdeff9db7b7
[ "Java" ]
1
Java
edu-kajiwara/05-lesson-database-access-u21611357
43964d2f310c811cdc4e35652352b48b7d0ec517
613d06305049aa7347983943b4728d358ed9d94a
refs/heads/master
<file_sep>json.extract! match_player, :id, :user_id, :match_id, :created_at, :updated_at json.url match_player_url(match_player, format: :json) <file_sep>class PlayerCard < ApplicationRecord end <file_sep>class MatchPlayersController < ApplicationController before_action :set_match_player, only: [:show, :edit, :update, :destroy] # GET /match_players # GET /match_players.json def index @match_players = MatchPlayer.all end # GET /match_players/1 # GET /match_players/1.json def show end # GET /match_players/new def new @match_player = MatchPlayer.new end # GET /match_players/1/edit def edit end # POST /match_players # POST /match_players.json def create @match_player = MatchPlayer.new(match_player_params) respond_to do |format| if @match_player.save format.html { redirect_to @match_player, notice: 'Match player was successfully created.' } format.json { render :show, status: :created, location: @match_player } else format.html { render :new } format.json { render json: @match_player.errors, status: :unprocessable_entity } end end end # PATCH/PUT /match_players/1 # PATCH/PUT /match_players/1.json def update respond_to do |format| if @match_player.update(match_player_params) format.html { redirect_to @match_player, notice: 'Match player was successfully updated.' } format.json { render :show, status: :ok, location: @match_player } else format.html { render :edit } format.json { render json: @match_player.errors, status: :unprocessable_entity } end end end # DELETE /match_players/1 # DELETE /match_players/1.json def destroy @match_player.destroy respond_to do |format| format.html { redirect_to match_players_url, notice: 'Match player was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_match_player @match_player = MatchPlayer.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def match_player_params params.require(:match_player).permit(:user_id, :match_id) end end <file_sep># SetGame Web application for SetGame <file_sep>class Match < ApplicationRecord has_many :match_players has_many :rounds validates :name, presence: true end <file_sep>require "application_system_test_case" class MatchPlayersTest < ApplicationSystemTestCase setup do @match_player = match_players(:one) end test "visiting the index" do visit match_players_url assert_selector "h1", text: "Match Players" end test "creating a Match player" do visit match_players_url click_on "New Match Player" fill_in "Match", with: @match_player.match_id fill_in "User", with: @match_player.user_id click_on "Create Match player" assert_text "Match player was successfully created" click_on "Back" end test "updating a Match player" do visit match_players_url click_on "Edit", match: :first fill_in "Match", with: @match_player.match_id fill_in "User", with: @match_player.user_id click_on "Update Match player" assert_text "Match player was successfully updated" click_on "Back" end test "destroying a Match player" do visit match_players_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Match player was successfully destroyed" end end <file_sep>class Round < ApplicationRecord belongs_to :match end <file_sep>json.array! @match_players, partial: 'match_players/match_player', as: :match_player <file_sep>require "application_system_test_case" class RoundsTest < ApplicationSystemTestCase setup do @round = rounds(:one) end test "visiting the index" do visit rounds_url assert_selector "h1", text: "Rounds" end test "creating a Round" do visit rounds_url click_on "New Round" fill_in "Locked", with: @round.locked fill_in "Match", with: @round.match_id fill_in "Winner", with: @round.winner click_on "Create Round" assert_text "Round was successfully created" click_on "Back" end test "updating a Round" do visit rounds_url click_on "Edit", match: :first fill_in "Locked", with: @round.locked fill_in "Match", with: @round.match_id fill_in "Winner", with: @round.winner click_on "Update Round" assert_text "Round was successfully updated" click_on "Back" end test "destroying a Round" do visit rounds_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Round was successfully destroyed" end end <file_sep>json.extract! round, :id, :match_id, :winner, :locked, :created_at, :updated_at json.url round_url(round, format: :json) <file_sep>require "application_system_test_case" class PlayerCardsTest < ApplicationSystemTestCase setup do @player_card = player_cards(:one) end test "visiting the index" do visit player_cards_url assert_selector "h1", text: "Player Cards" end test "creating a Player card" do visit player_cards_url click_on "New Player Card" fill_in "Card", with: @player_card.card_id fill_in "Round", with: @player_card.round_id fill_in "User", with: @player_card.user_id click_on "Create Player card" assert_text "Player card was successfully created" click_on "Back" end test "updating a Player card" do visit player_cards_url click_on "Edit", match: :first fill_in "Card", with: @player_card.card_id fill_in "Round", with: @player_card.round_id fill_in "User", with: @player_card.user_id click_on "Update Player card" assert_text "Player card was successfully updated" click_on "Back" end test "destroying a Player card" do visit player_cards_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Player card was successfully destroyed" end end <file_sep>json.extract! player_card, :id, :user_id, :card_id, :round_id, :created_at, :updated_at json.url player_card_url(player_card, format: :json) <file_sep>json.partial! "match_players/match_player", match_player: @match_player <file_sep>class MatchPlayer < ApplicationRecord belongs_to :match belongs_to :user validates :user_id, presence: true validates :match_id, presence: true end <file_sep>require 'test_helper' class MatchPlayersControllerTest < ActionDispatch::IntegrationTest setup do @match_player = match_players(:one) end test "should get index" do get match_players_url assert_response :success end test "should get new" do get new_match_player_url assert_response :success end test "should create match_player" do assert_difference('MatchPlayer.count') do post match_players_url, params: { match_player: { match_id: @match_player.match_id, user_id: @match_player.user_id } } end assert_redirected_to match_player_url(MatchPlayer.last) end test "should show match_player" do get match_player_url(@match_player) assert_response :success end test "should get edit" do get edit_match_player_url(@match_player) assert_response :success end test "should update match_player" do patch match_player_url(@match_player), params: { match_player: { match_id: @match_player.match_id, user_id: @match_player.user_id } } assert_redirected_to match_player_url(@match_player) end test "should destroy match_player" do assert_difference('MatchPlayer.count', -1) do delete match_player_url(@match_player) end assert_redirected_to match_players_url end end <file_sep>class HomePagesController < ApplicationController skip_before_action :authenticate_user! def index end def about end def terms end def privacy end end <file_sep>Rails.application.routes.draw do root 'home_pages#index' get 'home_pages/index' get 'home_pages/about' get 'home_pages/terms' get 'home_pages/privacy' resources :player_cards resources :rounds resources :match_players resources :matches resources :cards devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
e8b3b0772826d55f1f92b9a141c5e0b6686ac1f2
[ "Markdown", "Ruby" ]
17
Ruby
JijoBose/SetGame
28dd04abfae611e24b7de09f4a6cb007f93034a8
53adf8073183455d8ed98ddf7f0ef1ab60dfe98a
refs/heads/master
<repo_name>mlycookie/Car<file_sep>/app/src/main/java/edu/qau/car/LsjyZjmActivity.java //package edu.qau.car; // //import android.app.Activity; //import android.content.SharedPreferences; //import android.os.Bundle; //import android.preference.PreferenceManager; //import android.view.View; //import android.widget.EditText; //import android.widget.ImageButton; //import android.widget.TextView; // //public class LsjyZjmActivity extends Activity { // // private ImageButton fh; //// private ImageButton tc; // private TextView userInfo; // private EditText search; // // public void cjlb(View view) { // CjlbActivity.actionStart(this, 0); // } // // public void fjcl(View view) { // CjlbActivity.actionStart(this, 1); // } // // public void hgcl(View view) { // CjlbActivity.actionStart(this, 2); // } // // public void search(View view) { // CjlbActivity.actionStart(this, search.getText().toString()); // } // // public void back(View view) { // finish(); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_zjm); // // fh = (ImageButton) findViewById(R.id.fh); // search = (EditText) findViewById(R.id.search); // userInfo = (TextView) findViewById(R.id.user_info); // // String flag= getIntent().getStringExtra("flag"); // String flagStr =""; // switch(flag){ // case "R1" : // flagStr = "行车制动"; // break; // case "R2": // flagStr = "坡道驻车"; // break; // } // // SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this); // SharedPreferences.Editor editor = sharedPreferences.edit(); // editor .putString("lsjy",flag); // editor.putString("lsjyStr",flagStr); // editor.commit(); // // userInfo.setText( PreferencesUtils.getUserLsyInfo(this) ); // // } // //} <file_sep>/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion '26.0.2' aaptOptions{ cruncherEnabled = false useNewCruncher = false } defaultConfig { applicationId "edu.qau.car" minSdkVersion 15 targetSdkVersion 23 compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:support-v4:25.3.1' compile files('libs/gson.jar') compile files('libs/ksoap2-android-assembly-2.4-jar-with-dependencies.jar') compile files('libs/okhttp-3.1.2.jar') compile files('libs/okio-1.6.0.jar') compile files('libs/picasso-2.5.2.jar') } <file_sep>/app/src/main/java/edu/qau/car/bean/Cjlb.java package edu.qau.car.bean; import android.os.Parcel; import android.os.Parcelable; public class Cjlb implements Parcelable { public static final Parcelable.Creator<Cjlb> CREATOR = new Creator<Cjlb>() { @Override public Cjlb[] newArray(int size) { return new Cjlb[size]; } @Override public Cjlb createFromParcel(Parcel source) { Cjlb cjlb = new Cjlb(); cjlb.jylsh = source.readString(); cjlb.hphm = source.readString(); cjlb.ccrq = source.readString(); cjlb.hpzl = source.readString(); cjlb.zt = source.readInt(); cjlb.syr = source.readString(); cjlb.json = source.readString(); cjlb.jycs = source.readString(); cjlb.clsbdh = source.readString(); cjlb.hpzlNum = source.readInt(); cjlb.xzcdh = source.readInt(); cjlb.jyxm = source.readString(); cjlb.isdpdt = source.readInt(); cjlb.isdp = source.readInt(); cjlb.isls = source.readInt(); cjlb.ispdzc = source.readInt(); return cjlb; } }; @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(jylsh); dest.writeString(hphm); dest.writeString(ccrq); dest.writeString(hpzl); dest.writeInt(zt); dest.writeString(syr); dest.writeString(json); dest.writeString(jycs); dest.writeString(clsbdh); dest.writeInt(hpzlNum); dest.writeInt(xzcdh); dest.writeString(jyxm); dest.writeInt(isdpdt); dest.writeInt(isdp); dest.writeInt(isls); dest.writeInt(ispdzc); } private String jyxm; private String jylsh; private String hphm; private String ccrq; private String hpzl; private int hpzlNum; private int zt; private String syr; private String json; private String jycs; private String clsbdh; private int xzcdh; private int isdpdt; private int isdp; private int isls; private int ispdzc; public int getIsls() { return isls; } public void setIsls(int isls) { this.isls = isls; } public int getIspdzc() { return ispdzc; } public void setIspdzc(int ispdzc) { this.ispdzc = ispdzc; } public int getIsdpdt() { return isdpdt; } public void setIsdpdt(int isdpdt) { this.isdpdt = isdpdt; } public int getIsdp() { return isdp; } public void setIsdp(int isdp) { this.isdp = isdp; } public String getJyxm() { return jyxm; } public void setJyxm(String jyxm) { this.jyxm = jyxm; } public int getXzcdh() { return xzcdh; } public void setXzcdh(int xzcdh) { this.xzcdh = xzcdh; } public int getHpzlNum() { return hpzlNum; } public void setHpzlNum(int hpzlNum) { this.hpzlNum = hpzlNum; } public String getClsbdh() { return clsbdh; } public void setClsbdh(String clsbdh) { this.clsbdh = clsbdh; } public String getJycs() { return jycs; } public void setJycs(String jycs) { this.jycs = jycs; } public String getJson() { return json; } public void setJson(String json) { this.json = json; } @Override public int describeContents() { return 0; } public String getHpzl() { return hpzl; } public void setHpzl(String hpzl) { this.hpzl = hpzl; } public int getZt() { return zt; } public void setZt(int zt) { this.zt = zt; } public String getSyr() { return syr; } public void setSyr(String syr) { this.syr = syr; } public String getJylsh() { return jylsh; } public void setJylsh(String jylsh) { this.jylsh = jylsh; } public String getHphm() { return hphm; } public void setHphm(String hphm) { this.hphm = hphm; } public String getCcrq() { return ccrq; } public void setCcrq(String ccrq) { this.ccrq = ccrq; } } <file_sep>/app/src/main/java/edu/qau/car/XmlCallback.java package edu.qau.car; import org.json.JSONObject; public interface XmlCallback { String getUri(); String getNamespace(); String getMethodName(); String getXml(); String getXtlb(); String getJkxlh(); String getJkid(); String getPara(); void callback(String obj); } <file_sep>/.gradle/2.14.1/taskArtifacts/cache.properties #Thu Feb 01 09:25:49 CST 2018 <file_sep>/app/src/main/java/edu/qau/car/JyxmActivity.java package edu.qau.car; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.angmarch.views.NiceSpinner; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import edu.qau.car.bean.Cjlb; import edu.qau.car.bean.Jyxm; import edu.qau.car.bean.Wgjyxm; public class JyxmActivity extends Activity implements OnClickListener { private ImageButton zzs1; private ImageButton zzs2; private ImageButton zzs3; private ImageButton zzs4; private ImageButton zzs5; private ImageButton zzs6; private ImageButton qdxs1; private ImageButton qdxs2; private ImageButton qdxs3; private ImageButton qdxs4; private ImageButton qdxs5; private ImageButton zczs1; private ImageButton zczs2; private ImageButton zczs3; private ImageButton zczs4; private ImageButton zczs5; private ImageButton zczs6; private ImageButton zczw1; private ImageButton zczw2; private ImageButton zczw3; private ImageButton zczw4; private ImageButton zczw5; private int zzs; private int qdxs; private int zczs; private int zczw; private EditText mEt_qdxs; private EditText mEt_zczw; @Override public void onClick(View v) { switch (v.getId()) { case R.id.zzs1: clear(zzs1, zzs2, zzs3, zzs4, zzs5, zzs6); zzs1.setImageResource(R.drawable.yi_p); zzs = 1; break; case R.id.zzs2: clear(zzs1, zzs2, zzs3, zzs4, zzs5, zzs6); zzs2.setImageResource(R.drawable.er_p); zzs = 2; break; case R.id.zzs3: clear(zzs1, zzs2, zzs3, zzs4, zzs5, zzs6); zzs3.setImageResource(R.drawable.san_p); zzs = 3; break; case R.id.zzs4: clear(zzs1, zzs2, zzs3, zzs4, zzs5, zzs6); zzs4.setImageResource(R.drawable.si_p); zzs = 4; break; case R.id.zzs5: clear(zzs1, zzs2, zzs3, zzs4, zzs5, zzs6); zzs5.setImageResource(R.drawable.wu_p); zzs = 5; break; case R.id.zzs6: clear(zzs1, zzs2, zzs3, zzs4, zzs5, zzs6); zzs6.setImageResource(R.drawable.liu_p); zzs = 6; break; // case R.id.zczw1: // clear(zczw1, zczw2, zczw3, zczw4, zczw5); // zczw1.setImageResource(R.drawable.yi_p); // zczw = 1; // break; // case R.id.zczw2: // clear(zczw1, zczw2, zczw3, zczw4, zczw5); // zczw2.setImageResource(R.drawable.er_p); // zczw = 2; // break; // case R.id.zczw3: // clear(zczw1, zczw2, zczw3, zczw4, zczw5); // zczw3.setImageResource(R.drawable.san_p); // zczw = 3; // break; // case R.id.zczw4: // clear(zczw1, zczw2, zczw3, zczw4, zczw5); // zczw4.setImageResource(R.drawable.si_p); // zczw = 4; // break; // case R.id.zczw5: // clear(zczw1, zczw2, zczw3, zczw4, zczw5); // zczw5.setImageResource(R.drawable.wu_p); // zczw = 5; // break; case R.id.zczs1: clear(zczs1, zczs2, zczs3, zczs4, zczs5, zczs6); zczs1.setImageResource(R.drawable.yi_p); zczs = 1; break; case R.id.zczs2: clear(zczs1, zczs2, zczs3, zczs4, zczs5, zczs6); zczs2.setImageResource(R.drawable.er_p); zczs = 2; break; case R.id.zczs3: clear(zczs1, zczs2, zczs3, zczs4, zczs5, zczs6); zczs3.setImageResource(R.drawable.san_p); zczs = 3; break; case R.id.zczs4: clear(zczs1, zczs2, zczs3, zczs4, zczs5, zczs6); zczs4.setImageResource(R.drawable.si_p); zczs = 4; break; case R.id.zczs5: clear(zczs1, zczs2, zczs3, zczs4, zczs5, zczs6); zczs5.setImageResource(R.drawable.wu_p); zczs = 5; break; case R.id.zczs6: clear(zczs1, zczs2, zczs3, zczs4, zczs5, zczs6); zczs6.setImageResource(R.drawable.liu_p); zczs = 6; break; // case R.id.qdxs1: // clear(qdxs1, qdxs2, qdxs3, qdxs4, qdxs5); // qdxs1.setImageResource(R.drawable.yi_p); // qdxs = 1; // break; // case R.id.qdxs2: // clear(qdxs1, qdxs2, qdxs3, qdxs4, qdxs5); // qdxs2.setImageResource(R.drawable.er_p); // qdxs = 2; // break; // case R.id.qdxs3: // clear(qdxs1, qdxs2, qdxs3, qdxs4, qdxs5); // qdxs3.setImageResource(R.drawable.san_p); // qdxs = 3; // break; // case R.id.qdxs4: // clear(qdxs1, qdxs2, qdxs3, qdxs4, qdxs5); // qdxs4.setImageResource(R.drawable.si_p); // qdxs = 4; // break; // case R.id.qdxs5: // clear(qdxs1, qdxs2, qdxs3, qdxs4, qdxs5); // qdxs5.setImageResource(R.drawable.wu_p); // qdxs = 5; // break; default: break; } } private NiceSpinner zdly; private LinkedList<Jyxm> zdlyList = new LinkedList<Jyxm>(); private NiceSpinner qzdz; private LinkedList<Jyxm> qzdzList = new LinkedList<Jyxm>(); private NiceSpinner qzsl; private LinkedList<String> qzslList = new LinkedList<String>(Arrays.asList( "1", "2", "3", "4", "5", "6","--")); private NiceSpinner syxz; private LinkedList<Jyxm> syxzList = new LinkedList<Jyxm>(); private Type type = new TypeToken<LinkedList<Jyxm>>() { }.getType(); private Gson gson = new Gson(); public void clear(ImageButton yi, ImageButton er, ImageButton san, ImageButton si, ImageButton wu) { wu.setImageResource(R.drawable.wu_n); si.setImageResource(R.drawable.si_n); san.setImageResource(R.drawable.san_n); er.setImageResource(R.drawable.er_n); yi.setImageResource(R.drawable.yi_n); } public void clear(ImageButton yi, ImageButton er, ImageButton san, ImageButton si, ImageButton wu, ImageButton liu) { clear(yi, er, san, si, wu); liu.setImageResource(R.drawable.liu_n); } public void next(View view) { new XmlAsyncTask().execute(new XmlCallback() { String foramt = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><hpzl>%s</hpzl><hphm>%s</hphm><wgjcjyy>%s</wgjcjyy><wgjcjyysfzh>%s</wgjcjyysfzh><lcbds>%s</lcbds><zzs>%s</zzs><qdxs>%s</qdxs><zczs>%s</zczs><zczw>%s</zczw><zdly>%s</zdly><qzdz>%s</qzdz><qzsl>%s</qzsl><syxz>%s</syxz><ygddtz>%s</ygddtz><dlxj>%s</dlxj><mz>%s</mz><szxz>%s</szxz></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { String hpzl = cjlb.getHpzlNum() + ""; if (hpzl.length() == 1) { hpzl = "0" + hpzl; } User user = PreferencesUtils.getUser(JyxmActivity.this); String zdly_dmz = zdlyList.get(zdly.getSelectedIndex()).getDMSM1(); if (zdly_dmz.contains("-")) zdly_dmz = ""; else zdly_dmz = zdlyList.get(zdly.getSelectedIndex()).getDMZ(); String qzdz_dmz = qzdzList.get(qzdz.getSelectedIndex()).getDMSM1(); if (qzdz_dmz.contains("-")) qzdz_dmz = ""; else qzdz_dmz = qzdzList.get(qzdz.getSelectedIndex()).getDMZ(); String qzsl_dmz = qzslList.get(qzsl.getSelectedIndex()); if (qzsl_dmz.contains("-")) qzsl_dmz = ""; String syxz_dmz = syxzList.get(syxz.getSelectedIndex()).getDMSM1(); if (syxz_dmz.contains("-")) syxz_dmz= ""; else syxz_dmz = syxzList.get(syxz.getSelectedIndex()).getDMZ(); String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), hpzl, cjlb.getHphm(), user.getXM(), user.getSFZMHM(), lcbds.getText().toString(), zzs, qdxs, zczs, zczw, zdly_dmz, qzdz_dmz, qzsl_dmz, syxz_dmz, ygddtz.isChecked() ? 1 : 0, dlxj.isChecked() ? 1 : 0, mz.isChecked() ? 1 : 0, szxz.isChecked() ? 1 : 0); Log.w("getXml--car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F26"; } @Override public void callback(String obj) { String code = XmlUtils.getValue(obj, "code"); if ("1".equals(code)) { Log.w("callback--car", flag + ""); if (flag == 0) { PzActivity.actionStart(JyxmActivity.this, cjlb); } else { TjjgActivity.actionStart(JyxmActivity.this, cjlb); } } else { String message = XmlUtils.getValue(obj, "message"); Toast.makeText(JyxmActivity.this, message, Toast.LENGTH_LONG).show(); } } @Override public String getPara() { return "WriteXmlDoc"; } }); } public static void actionStart(final Context context, final Cjlb cjlb, final int flag) { new WsAsyncTask().execute(new WsCallback() { @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return null; } @Override public String getXml() { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); String format = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jyjgbh>%s</jyjgbh><sfzh>%s</sfzh><loginid>%s</loginid></vehispara></root>"; User user = PreferencesUtils.getUser(context); String xml = String.format(format, user.getJCZBH(), user.getSFZMHM(), sharedPreferences.getString("loginid", "")); Log.w("car", xml); return xml; } @Override public String getXtlb() { return "17"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F24"; } @Override public void callback(JSONObject obj) { try { if (obj != null && obj.getBoolean("ok")) { JSONArray zdly = obj.getJSONArray("Table"); JSONArray qzdz = obj.getJSONArray("Table1"); JSONArray syxz = obj.getJSONArray("Table2"); Intent intent = new Intent(context, JyxmActivity.class); intent.putExtra("bean", cjlb); intent.putExtra("zdly", zdly.toString()); intent.putExtra("qzdz", qzdz.toString()); intent.putExtra("syxz", syxz.toString()); intent.putExtra("flag", flag); getInfo(context,cjlb,intent); // context.startActivity(intent); } else { Toast.makeText(context, "访问网络失败", Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Toast.makeText(context, "访问网络失败", Toast.LENGTH_LONG).show(); } } }); } public static void getInfo(final Context context, final Cjlb cjlb , final Intent intent) { new WsAsyncTask().execute(new WsCallback() { @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return null; } @Override public String getXml() { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); String format = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><jyxm>%s</jyxm></vehispara></root>"; User user = PreferencesUtils.getUser(context); String xml = String.format(format, cjlb.getJylsh(), user.getJCZBH(), PreferencesUtils.getJyxm(context)); Log.w("car", xml); return xml; } @Override public String getXtlb() { return "17"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F28"; } @Override public void callback(JSONObject obj) { try { if (obj != null && obj.getBoolean("ok")) { JSONArray info = obj.getJSONArray("Table"); if(info!=null && info.length() > 0 ){ intent.putExtra("info", info.get(0).toString()); context.startActivity(intent); } } else { Toast.makeText(context, "访问网络失败", Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Toast.makeText(context, "访问网络失败", Toast.LENGTH_LONG).show(); } } }); } public void back(View view) { finish(); } private TextView userInfo; private Cjlb cjlb; private EditText lcbds; private CheckBox ygddtz; private CheckBox dlxj; private CheckBox mz; private CheckBox szxz; private int flag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jyxm); lcbds = (EditText) findViewById(R.id.lcbds); ygddtz = (CheckBox) findViewById(R.id.ygddtz); dlxj = (CheckBox) findViewById(R.id.dlxj); mz = (CheckBox) findViewById(R.id.mz); szxz = (CheckBox) findViewById(R.id.szxz); cjlb = getIntent().getParcelableExtra("bean"); flag = getIntent().getIntExtra("flag", 0); userInfo = (TextView) findViewById(R.id.user_info); userInfo.setText(PreferencesUtils.getUserInfo(this)); Jyxm jyxm = new Jyxm(); jyxm.setDMSM1("--"); zdlyList = gson.fromJson(getIntent().getStringExtra("zdly"), type); zdlyList.add(jyxm); qzdzList = gson.fromJson(getIntent().getStringExtra("qzdz"), type); qzdzList.add(jyxm); syxzList = gson.fromJson(getIntent().getStringExtra("syxz"), type); syxzList.add(jyxm); zdly = (NiceSpinner) findViewById(R.id.zdly); zdly.setTextColor(Color.BLUE); zdly.attachDataSource(zdlyList); for (int i = 0; i < zdlyList.size(); i++) { if (zdlyList.get(i).getDMSM1().equals("液压制动")) { zdly.setSelectedIndex(i); break; } } qzdz = (NiceSpinner) findViewById(R.id.qzdz); qzdz.setTextColor(Color.BLUE); qzdz.attachDataSource(qzdzList); for (int i = 0; i < qzdzList.size(); i++) { if (qzdzList.get(i).getDMSM1().equals("二灯远近光")) { qzdz.setSelectedIndex(i); break; } } qzsl = (NiceSpinner) findViewById(R.id.qzsl); qzsl.setTextColor(Color.BLUE); qzsl.attachDataSource(qzslList); syxz = (NiceSpinner) findViewById(R.id.syxz); syxz.setTextColor(Color.BLUE); syxz.attachDataSource(syxzList); for (int i = 0; i < syxzList.size(); i++) { if (syxzList.get(i).getDMSM1().equals("非营运")) { syxz.setSelectedIndex(i); break; } } Wgjyxm info = gson.fromJson(getIntent().getStringExtra("info"), Wgjyxm.class); zzs1 = (ImageButton) findViewById(R.id.zzs1); zzs1.setOnClickListener(this); zzs2 = (ImageButton) findViewById(R.id.zzs2); zzs2.setOnClickListener(this); zzs3 = (ImageButton) findViewById(R.id.zzs3); zzs3.setOnClickListener(this); zzs4 = (ImageButton) findViewById(R.id.zzs4); zzs4.setOnClickListener(this); zzs5 = (ImageButton) findViewById(R.id.zzs5); zzs5.setOnClickListener(this); zzs6 = (ImageButton) findViewById(R.id.zzs6); zzs6.setOnClickListener(this); // qdxs1 = (ImageButton) findViewById(R.id.qdxs1); // qdxs1.setOnClickListener(this); // qdxs2 = (ImageButton) findViewById(R.id.qdxs2); // qdxs2.setOnClickListener(this); // qdxs3 = (ImageButton) findViewById(R.id.qdxs3); // qdxs3.setOnClickListener(this); // qdxs4 = (ImageButton) findViewById(R.id.qdxs4); // qdxs4.setOnClickListener(this); // qdxs5 = (ImageButton) findViewById(R.id.qdxs5); // qdxs5.setOnClickListener(this); mEt_qdxs = (EditText) findViewById(R.id.qdxs_et); mEt_qdxs.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!TextUtils.isEmpty(s.toString())) qdxs = Integer.parseInt(s.toString()); } @Override public void afterTextChanged(Editable s) { } }); zczs1 = (ImageButton) findViewById(R.id.zczs1); zczs1.setOnClickListener(this); zczs2 = (ImageButton) findViewById(R.id.zczs2); zczs2.setOnClickListener(this); zczs3 = (ImageButton) findViewById(R.id.zczs3); zczs3.setOnClickListener(this); zczs4 = (ImageButton) findViewById(R.id.zczs4); zczs4.setOnClickListener(this); zczs5 = (ImageButton) findViewById(R.id.zczs5); zczs5.setOnClickListener(this); zczs6 = (ImageButton) findViewById(R.id.zczs6); zczs6.setOnClickListener(this); // zczw1 = (ImageButton) findViewById(R.id.zczw1); // zczw1.setOnClickListener(this); // zczw2 = (ImageButton) findViewById(R.id.zczw2); // zczw2.setOnClickListener(this); // zczw3 = (ImageButton) findViewById(R.id.zczw3); // zczw3.setOnClickListener(this); // zczw4 = (ImageButton) findViewById(R.id.zczw4); // zczw4.setOnClickListener(this); // zczw5 = (ImageButton) findViewById(R.id.zczw5); // zczw5.setOnClickListener(this); mEt_zczw = (EditText) findViewById(R.id.zczw_et); mEt_zczw.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!TextUtils.isEmpty(s.toString())) zczw = Integer.parseInt(s.toString()); } @Override public void afterTextChanged(Editable s) { } }); if(info!=null){ lcbds.setText(info.getLcbds()); switch (info.getZzs()){ case "1" : zzs1.setImageResource(R.drawable.yi_p); zzs = 1; break; case "2": zzs2.setImageResource(R.drawable.er_p); zzs=2; break; case "3": zzs3.setImageResource(R.drawable.san_p); zzs=3; break; case "4": zzs4.setImageResource(R.drawable.si_p); zzs=4; break; case "5": zzs5.setImageResource(R.drawable.wu_p); zzs=5; break; case "6": zzs6.setImageResource(R.drawable.liu_p); zzs=6; break; } mEt_qdxs.setText(info.getQdxs()); switch (info.getZczs()){ case "1" : zczs1.setImageResource(R.drawable.yi_p); zczs = 1; break; case "2": zczs2.setImageResource(R.drawable.er_p); zczs = 2; break; case "3": zczs3.setImageResource(R.drawable.san_p); zczs=3; break; case "4": zczs4.setImageResource(R.drawable.si_p); zczs=4; break; case "5": zczs5.setImageResource(R.drawable.wu_p); zczs=5; break; case "6": zczs6.setImageResource(R.drawable.liu_p); zczs=6; break; } mEt_zczw.setText(info.getZczw()); if(!TextUtils.isEmpty(info.getZdly())){ try{ for (int i = 0; i < zdlyList.size(); i++) { if (zdlyList.get(i).getDMZ().equals(info.getZdly())) { zdly.setSelectedIndex(i); break; } } }catch (Exception e){ e.printStackTrace(); } } if(!TextUtils.isEmpty(info.getQzdz())){ try{ for (int i = 0; i < qzdzList.size(); i++) { if (qzdzList.get(i).getDMZ().equals(info.getQzdz())) { qzdz.setSelectedIndex(i); break; } } }catch (Exception e){ e.printStackTrace(); } } if(!TextUtils.isEmpty(info.getQzsl())){ try{ for (int i = 0; i < qzslList.size(); i++) { if (qzslList.get(i).equals(info.getQzsl())) { qzsl.setSelectedIndex(i); break; } } }catch (Exception e){ e.printStackTrace(); } } if(!TextUtils.isEmpty(info.getSyxz())){ try{ for (int i = 0; i < syxzList.size(); i++) { if (syxzList.get(i).getDMZ().equals(info.getSyxz())) { syxz.setSelectedIndex(i); break; } } }catch (Exception e){ e.printStackTrace(); } } if("1".equals(info.getYgddtz())){ ygddtz.setChecked(true); } if("1".equals(info.getDlxj())){ dlxj.setChecked(true); } if("1".equals(info.getMz())){ mz.setChecked(true); } if("1".equals(info.getSzxz())){ szxz.setChecked(true); } } } } <file_sep>/app/src/main/java/edu/qau/car/ClActivity.java package edu.qau.car; import java.text.SimpleDateFormat; import java.util.Date; import edu.qau.car.bean.Cjlb; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; public class ClActivity extends Activity implements OnClickListener { private SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat( "yyyy/MM/dd hh:mm:ss"); private ImageButton zzs1; private ImageButton zzs2; private ImageButton zzs3; private ImageButton zzs4; private EditText wlkc1, wlkc2, wlkc3, wlkk1, wlkk2, wlkk3, wlkg1, wlkg2, wlkg3, gcc1, gcc2, gcc3, gck1, gck2, gck3, gcg1, gcg2, gcg3; int zzs = 0; private void clear() { wlkc1.setText(""); wlkc2.setText(""); wlkc3.setText(""); wlkk1.setText(""); wlkk2.setText(""); wlkk3.setText(""); wlkg1.setText(""); wlkg2.setText(""); wlkg3.setText(""); gcc1.setText(""); gcc2.setText(""); gcc3.setText(""); gck1.setText(""); gck2.setText(""); gck3.setText(""); gcg1.setText(""); gcg2.setText(""); gcg3.setText(""); } public void scsj(View view) { new XmlAsyncTask().execute(new XmlCallback() { String foramt = "<?xml version='1.0' encoding='GBK' ?><root><vehispara><jylsh>%s</jylsh></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { String xml = String.format(foramt, cjlb.getJylsh()); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F05"; } @Override public void callback(String obj) { String code = XmlUtils.getValue(obj, "code"); String message = XmlUtils.getValue(obj, "message"); if ("1".equals(code)) { } else { } Toast.makeText(ClActivity.this, message, Toast.LENGTH_LONG) .show(); } @Override public String getPara() { return "WriteXmlDoc"; } }); } public void clear(ImageButton yi, ImageButton er, ImageButton san, ImageButton si) { si.setImageResource(R.drawable.si_n); san.setImageResource(R.drawable.san_n); er.setImageResource(R.drawable.er_n); yi.setImageResource(R.drawable.yi_n); } public void cz(View view) { new XmlAsyncTask().execute(new XmlCallback() { String foramt = "<?xml version='1.0' encoding='GBK' ?><root><vehispara><teststa>4</teststa></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { Log.w("car", foramt); return foramt; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F04"; } @Override public void callback(String obj) { String code = XmlUtils.getValue(obj, "code"); String message = XmlUtils.getValue(obj, "message"); if ("1".equals(code)) { clear(); } else { } Toast.makeText(ClActivity.this, message, Toast.LENGTH_LONG) .show(); } @Override public String getPara() { return "WriteXmlDoc"; } }); } public void cljg(View view) { new XmlAsyncTask().execute(new XmlCallback() { String foramt = "<?xml version='1.0' encoding='GBK' ?><root><vehispara><jylsh>%s</jylsh></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { String xml = String.format(foramt, cjlb.getJylsh()); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return null; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F02"; } @Override public void callback(String obj) { Log.w("cljg", obj); String code = XmlUtils.getValue(obj, "code"); String message = XmlUtils.getValue(obj, "message"); if ("1".equals(code)) { wlkc1.setText(XmlUtils.getValue(obj, "cwkc")); wlkk1.setText(XmlUtils.getValue(obj, "cwkk")); wlkg1.setText(XmlUtils.getValue(obj, "cwkg")); wlkc2.setText(XmlUtils.getValue(obj, "wkcbz")); wlkk2.setText(XmlUtils.getValue(obj, "wkkbz")); wlkg2.setText(XmlUtils.getValue(obj, "wkgbz")); wlkc3.setText(XmlUtils.getValue(obj, "wkcpd")); wlkk3.setText(XmlUtils.getValue(obj, "wkkpd")); wlkg3.setText(XmlUtils.getValue(obj, "wkgpd")); } else { } Toast.makeText(ClActivity.this, code + " " + message, Toast.LENGTH_LONG).show(); } @Override public String getPara() { return null; } }); } public void kscl(View view) { new XmlAsyncTask().execute(new XmlCallback() { String foramt = "<?xml version='1.0' encoding='GBK' ?><root><vehispara id='0'><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><clsbdh>%s</clsbdh></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { User user = PreferencesUtils.getUser(ClActivity.this); String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), cjlb.getClsbdh()); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F03"; } @Override public void callback(String obj) { String code = XmlUtils.getValue(obj, "code"); String message = XmlUtils.getValue(obj, "message"); if ("1".equals(code)) { } else { } Toast.makeText(ClActivity.this, message, Toast.LENGTH_LONG) .show(); } @Override public String getPara() { return "WriteXmlDoc"; } }); } public void jsxm(View view) { new XmlAsyncTask().execute(new XmlCallback() { String foramt = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><jcxdh>%s</jcxdh><jycs>%s</jycs><jyxm>%s</jyxm><hpzl>%s</hpzl><hphm>%s</hphm><clsbdh>%s</clsbdh><jssj>%s</jssj></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { String hpzl = cjlb.getHpzlNum() + ""; if (hpzl.length() == 1) { hpzl = "0" + hpzl; } User user = PreferencesUtils.getUser(ClActivity.this); String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), zzs, cjlb.getJycs(), "M1", hpzl, cjlb.getHphm(), cjlb.getClsbdh(), simpleDateFormat2.format(new Date())); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F58"; } @Override public void callback(String obj) { String code = XmlUtils.getValue(obj, "code"); String message = XmlUtils.getValue(obj, "message"); if ("1".equals(code)) { } else { } Toast.makeText(ClActivity.this, message, Toast.LENGTH_LONG) .show(); } @Override public String getPara() { return "WriteXmlDoc"; } }); } public void xmks(View view) { new XmlAsyncTask().execute(new XmlCallback() { String foramt = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><jcxdh>%s</jcxdh><jycs>%s</jycs><jyxm>%s</jyxm><hpzl>%s</hpzl><hphm>%s</hphm><clsbdh>%s</clsbdh><kssj>%s</kssj></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { String hpzl = cjlb.getHpzlNum() + ""; if (hpzl.length() == 1) { hpzl = "0" + hpzl; } User user = PreferencesUtils.getUser(ClActivity.this); String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), zzs, cjlb.getJycs(), "M1", hpzl, cjlb.getHphm(), cjlb.getClsbdh(), simpleDateFormat2.format(new Date())); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F55"; } @Override public void callback(String obj) { String code = XmlUtils.getValue(obj, "code"); String message = XmlUtils.getValue(obj, "message"); if ("1".equals(code)) { } else { } Toast.makeText(ClActivity.this, message, Toast.LENGTH_LONG) .show(); } @Override public String getPara() { return "WriteXmlDoc"; } }); } private Cjlb cjlb; public static void actionStart(final Context context, final Cjlb cjlb) { Intent intent = new Intent(context, ClActivity.class); intent.putExtra("bean", cjlb); context.startActivity(intent); } public void back(View view) { finish(); } public void next(View view) { Intent intent = new Intent(this, JyxxActivity.class); intent.putExtra("bean", cjlb); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cl); cjlb = getIntent().getParcelableExtra("bean"); zzs1 = (ImageButton) findViewById(R.id.zzs1); zzs1.setOnClickListener(this); zzs2 = (ImageButton) findViewById(R.id.zzs2); zzs2.setOnClickListener(this); zzs3 = (ImageButton) findViewById(R.id.zzs3); zzs3.setOnClickListener(this); zzs4 = (ImageButton) findViewById(R.id.zzs4); zzs4.setOnClickListener(this); wlkc1 = (EditText) findViewById(R.id.wkjc1); wlkc2 = (EditText) findViewById(R.id.wkjc2); wlkc3 = (EditText) findViewById(R.id.wkjc3); wlkk1 = (EditText) findViewById(R.id.wkjk1); wlkk2 = (EditText) findViewById(R.id.wkjk2); wlkk3 = (EditText) findViewById(R.id.wkjk3); wlkg1 = (EditText) findViewById(R.id.wkjg1); wlkg2 = (EditText) findViewById(R.id.wkjg2); wlkg3 = (EditText) findViewById(R.id.wkjg3); gcc1 = (EditText) findViewById(R.id.gcc1); gcc2 = (EditText) findViewById(R.id.gcc2); gcc3 = (EditText) findViewById(R.id.gcc3); gck1 = (EditText) findViewById(R.id.gck1); gck2 = (EditText) findViewById(R.id.gck2); gck3 = (EditText) findViewById(R.id.gck3); gcg1 = (EditText) findViewById(R.id.gcg1); gcg2 = (EditText) findViewById(R.id.gcg2); gcg3 = (EditText) findViewById(R.id.gcg3); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.zzs1: clear(zzs1, zzs2, zzs3, zzs4); zzs1.setImageResource(R.drawable.yi_p); zzs = 1; break; case R.id.zzs2: clear(zzs1, zzs2, zzs3, zzs4); zzs2.setImageResource(R.drawable.er_p); zzs = 2; break; case R.id.zzs3: clear(zzs1, zzs2, zzs3, zzs4); zzs3.setImageResource(R.drawable.san_p); zzs = 3; break; case R.id.zzs4: clear(zzs1, zzs2, zzs3, zzs4); zzs4.setImageResource(R.drawable.si_p); zzs = 4; break; } } } <file_sep>/app/src/main/java/edu/qau/car/SetUrlActivity.java package edu.qau.car; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.IdRes; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.Toast; /**************************************** * 功能说明: * * Author: Created by bayin on 2018/2/1. ****************************************/ public class SetUrlActivity extends Activity { private EditText mEtUrl; private RadioGroup radiogroup; private SharedPreferences sharedPreferences; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_url); findViewById(R.id.set_url_tv_back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); mEtUrl = (EditText) findViewById(R.id.seturl_et); mEtUrl.setText(AppURL.BASE_URL); radiogroup = (RadioGroup) findViewById(R.id.radiogroup); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SetUrlActivity.this); //初始化radiogroup String second = sharedPreferences.getString(AppURL.SECOND_URL_KEY, AppURL.SECOND_PATH_1); if (second.contains("ref")) { radiogroup.check(R.id.path_2); } else { radiogroup.check(R.id.path_1); } findViewById(R.id.set_url_bt_save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = mEtUrl.getText().toString(); if (TextUtils.isEmpty(url)) { Toast.makeText(SetUrlActivity.this, "地址不能为空", Toast.LENGTH_SHORT).show(); } else { AppURL.BASE_URL = url; sharedPreferences.edit().putString(AppURL.BASE_URL_KEY, url).apply(); Toast.makeText(SetUrlActivity.this, "设置成功!", Toast.LENGTH_SHORT).show(); finish(); } } }); radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { if (checkedId == R.id.path_1) { sharedPreferences.edit().putString(AppURL.SECOND_URL_KEY, AppURL.SECOND_PATH_1).apply(); AppURL.SECOND_URL = AppURL.SECOND_PATH_1; } else if (checkedId == R.id.path_2) { sharedPreferences.edit().putString(AppURL.SECOND_URL_KEY, AppURL.SECOND_PATH_2).apply(); AppURL.SECOND_URL = AppURL.SECOND_PATH_2; } Toast.makeText(SetUrlActivity.this, "设置成功!", Toast.LENGTH_SHORT).show(); } }); } } <file_sep>/app/src/main/java/edu/qau/car/User.java package edu.qau.car; public class User { private String XM; private String SFZMHM; private String RYLB; private String JCZBH; public String getXM() { return XM; } public void setXM(String xM) { XM = xM; } public String getSFZMHM() { return SFZMHM; } public void setSFZMHM(String sFZMHM) { SFZMHM = sFZMHM; } public String getRYLB() { return RYLB; } public void setRYLB(String rYLB) { RYLB = rYLB; } public String getJCZBH() { return JCZBH; } public void setJCZBH(String jCZBH) { JCZBH = jCZBH; } } <file_sep>/app/src/main/java/edu/qau/car/bean/Jyxm.java package edu.qau.car.bean; public class Jyxm { private String DMLB; private String DMZ; private String DMSM1; private String SXH; @Override public String toString() { return DMSM1; } public String getDMLB() { return DMLB; } public void setDMLB(String dMLB) { DMLB = dMLB; } public String getDMZ() { return DMZ; } public void setDMZ(String dMZ) { DMZ = dMZ; } public String getDMSM1() { return DMSM1; } public void setDMSM1(String dMSM1) { DMSM1 = dMSM1; } public String getSXH() { return SXH; } public void setSXH(String sXH) { SXH = sXH; } } <file_sep>/app/src/main/java/edu/qau/car/CjlbActivity.java package edu.qau.car; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import edu.qau.car.bean.Cjlb; public class CjlbActivity extends Activity { private boolean isLjy; private ListView cjlbList; private CjlbAdapter adapter; private List<Cjlb> list; private LayoutInflater inflater; private static SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat( "yyyy-MM-dd"); private SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat( "yyyy/MM/dd hh:mm:ss"); private static final HashMap<String, String> hpzl = new HashMap<String, String>(); static { hpzl.put("01", "大型汽车"); hpzl.put("02", "小型汽车"); hpzl.put("03", "使馆汽车"); hpzl.put("04", "领馆汽车"); hpzl.put("05", "境外汽车"); hpzl.put("06", "外籍汽车"); hpzl.put("07", "普通摩托车"); hpzl.put("08", "轻便摩托车"); hpzl.put("09", "使馆摩托车"); hpzl.put("10", "领馆摩托车"); hpzl.put("11", "境外摩托车"); hpzl.put("12", "外籍摩托车"); hpzl.put("13", "低速车"); hpzl.put("14", "拖拉机"); hpzl.put("15", "挂车"); hpzl.put("16", "教练汽车"); hpzl.put("17", "教练摩托车"); hpzl.put("18", "试验汽车"); hpzl.put("19", "试验摩托车"); hpzl.put("20", "临时入境汽车"); hpzl.put("21", "临时入境摩托车"); hpzl.put("22", "临时行驶车"); hpzl.put("23", "警用汽车"); hpzl.put("24", "警用摩托"); hpzl.put("25", "原农机号牌"); hpzl.put("26", "香港入出境车"); hpzl.put("27", "澳门入出境车"); hpzl.put("31", "武警号牌"); hpzl.put("32", "军队号牌"); hpzl.put("41", "无号牌"); hpzl.put("42", "假号牌"); hpzl.put("43", "挪用号牌"); hpzl.put("51", "大型新能源汽车"); hpzl.put("52", "小型新能源汽车"); hpzl.put("99", "其他号牌"); } public void back(View view) { finish(); } public static void actionStart(final Context context, final String search) { new WsAsyncTask().execute(new WsCallback() { String foramt = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jyjgbh>%s</jyjgbh><jyxm>%s</jyxm><hphm>%s</hphm></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { User user = PreferencesUtils.getUser(context); String xml = String.format(foramt, user.getJCZBH(), PreferencesUtils.getJyxm(context), search); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return null; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F25"; } @Override public void callback(JSONObject obj) { try { if (obj.getBoolean("ok")) { JSONArray array = obj.getJSONArray("Table"); Intent intent = new Intent(context, CjlbActivity.class); intent.putExtra("array", array.toString()); context.startActivity(intent); } else { Toast.makeText(context, "未查询到车辆信息", Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Toast.makeText(context, "网络访问失败", Toast.LENGTH_LONG).show(); } } }); } public static void actionStart(final Context context, final int jylx) { new WsAsyncTask().execute(new WsCallback() { String foramt = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jyjgbh>%s</jyjgbh><jyrq>%s</jyrq><jylx>%d</jylx><jyxm>%s</jyxm></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { User user = PreferencesUtils.getUser(context); String xml = String.format(foramt, user.getJCZBH(),simpleDateFormat1.format(new Date()), jylx, PreferencesUtils.getJyxm(context)); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return null; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F22"; } @Override public void callback(JSONObject obj) { try { if (obj.getBoolean("ok")) { JSONArray array = obj.getJSONArray("Table"); Intent intent = new Intent(context, CjlbActivity.class); intent.putExtra("array", array.toString()); context.startActivity(intent); } else { Toast.makeText(context, "未查询到车辆信息", Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Toast.makeText(context, "网络访问失败", Toast.LENGTH_LONG).show(); } } }); } private TextView userInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cjlb); userInfo = (TextView) findViewById(R.id.user_info); isLjy = PreferencesUtils.isLsy(this); // if(isLjy){ userInfo.setText(PreferencesUtils.getUserInfo(this)); // } // else{ // userInfo.setText(PreferencesUtils.getUserInfo(this)); // } String array = getIntent().getStringExtra("array"); Log.w("car", array); init(array); inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); adapter = new CjlbAdapter(); cjlbList = (ListView) findViewById(R.id.cjlb_list); cjlbList.setAdapter(adapter); adapter.notifyDataSetChanged(); cjlbList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = PreferencesUtils.getUser(CjlbActivity.this); if (user.getRYLB().equals("10")) { ClActivity.actionStart(CjlbActivity.this, list.get(position)); }else if(user.getRYLB().equals("15")){ Intent intent = new Intent(CjlbActivity.this, LsjyXmxzActivity.class); intent.putExtra("bean", list.get(position)); startActivity(intent); }else{ Intent intent = new Intent(CjlbActivity.this, JyxxActivity.class); intent.putExtra("bean", list.get(position)); startActivity(intent); } } }); } private void init(String array) { try { list = new ArrayList<Cjlb>(); JSONArray jsonArray = new JSONArray(array); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Cjlb bean = new Cjlb(); bean.setJylsh(jsonObject.getString("jylsh")); bean.setHphm(jsonObject.getString("hphm")); try { Date date = simpleDateFormat2.parse(jsonObject .getString("jyrq")); bean.setCcrq(simpleDateFormat1.format(date)); } catch (ParseException e) { e.printStackTrace(); } String hpzlTemp = jsonObject.getString("hpzl"); if (hpzlTemp.length() == 1) { hpzlTemp = "0" + hpzlTemp; } bean.setHpzl(hpzl.get(hpzlTemp)); bean.setHpzlNum(Integer.parseInt(jsonObject.getString("hpzl"))); bean.setSyr(""); bean.setZt(Integer.parseInt(jsonObject.getString("iswg"))); bean.setIsdpdt(Integer.parseInt(jsonObject.getString("isdpdt"))); bean.setIsdp(Integer.parseInt(jsonObject.getString("isdp"))); try{ bean.setIsls(Integer.parseInt(jsonObject.getString("isls"))); bean.setIspdzc(Integer.parseInt(jsonObject.getString("ispdzc"))); }catch (Exception e){ e.printStackTrace(); } String jycs = jsonObject.getString("jycs"); if (null == jycs || "".equals(jycs)) { bean.setJycs("0"); } else { bean.setJycs(jycs); } bean.setClsbdh(jsonObject.getString("clsbdh")); list.add(bean); } } catch (JSONException e) { e.printStackTrace(); } } private class CjlbAdapter extends BaseAdapter { @Override public int getCount() { return list.size(); } @Override public Object getItem(int arg0) { return list.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { ViewHolder holder; if (arg1 == null) { arg1 = inflater.inflate(R.layout.cjlb_item, arg2, false); holder = new ViewHolder(); holder.jylsh = (TextView) arg1.findViewById(R.id.jylsh); holder.hphm = (TextView) arg1.findViewById(R.id.hphm); holder.ccrq = (TextView) arg1.findViewById(R.id.ccrq); holder.hpzl = (TextView) arg1.findViewById(R.id.hpzl); holder.zt = (TextView) arg1.findViewById(R.id.zt); holder.syr = (TextView) arg1.findViewById(R.id.syr); holder.dpdt = (TextView) arg1.findViewById(R.id.dpdt); holder.dp = (TextView) arg1.findViewById(R.id.dp); holder.xczd = (TextView) arg1.findViewById(R.id.xczd); holder.pdzc = (TextView) arg1.findViewById(R.id.pdzc); holder.ll_dpdt_dp = (LinearLayout) arg1.findViewById(R.id.ll_dpdt_dp); holder.ll_xczd_pdzc = (LinearLayout) arg1.findViewById(R.id.ll_xczd_pdzc); arg1.setTag(holder); } else { holder = (ViewHolder) arg1.getTag(); } holder.ll_dpdt_dp.setVisibility(View.GONE); holder.ll_xczd_pdzc.setVisibility(View.GONE); holder.jylsh.setText(list.get(arg0).getJylsh()); holder.hphm.setText(list.get(arg0).getHphm()); holder.ccrq.setText(list.get(arg0).getCcrq()); holder.hpzl.setText(list.get(arg0).getHpzl()); holder.syr.setText(list.get(arg0).getSyr()); if (list.get(arg0).getZt() == 0) { holder.zt.setBackgroundResource(R.drawable.wgbjc); } else if (list.get(arg0).getZt() == 1) { holder.zt.setBackgroundResource(R.drawable.wgdjc); } else if (list.get(arg0).getZt() == 2) { holder.zt.setBackgroundResource(R.drawable.wgyjc); } else if (list.get(arg0).getZt() == 3) { holder.zt.setBackgroundResource(R.drawable.wgfj); } if (list.get(arg0).getIsdpdt() == 0) { holder.dpdt.setBackgroundResource(R.drawable.dpdtbjc); holder.ll_dpdt_dp.setVisibility(View.VISIBLE); } else if (list.get(arg0).getIsdpdt() == 1) { holder.dpdt.setBackgroundResource(R.drawable.dpdtdjc); holder.ll_dpdt_dp.setVisibility(View.VISIBLE); } else if (list.get(arg0).getIsdpdt() == 2) { holder.dpdt.setBackgroundResource(R.drawable.dpdtyjc); holder.ll_dpdt_dp.setVisibility(View.VISIBLE); } else if (list.get(arg0).getIsdpdt() == 3) { holder.dpdt.setBackgroundResource(R.drawable.dpdtfj); holder.ll_dpdt_dp.setVisibility(View.VISIBLE); } if(isLjy){ if (list.get(arg0).getIsdp() == 0) { holder.dp.setBackgroundResource(R.drawable.dpbjc); holder.ll_dpdt_dp.setVisibility(View.VISIBLE); } else if (list.get(arg0).getIsdp() == 1) { holder.ll_dpdt_dp.setVisibility(View.VISIBLE); holder.dp.setBackgroundResource(R.drawable.dpdjc); } else if (list.get(arg0).getIsdp() == 2) { holder.ll_dpdt_dp.setVisibility(View.VISIBLE); holder.dp.setBackgroundResource(R.drawable.dpyjc); } else if (list.get(arg0).getIsdp() == 3) { holder.ll_dpdt_dp.setVisibility(View.VISIBLE); holder.dp.setBackgroundResource(R.drawable.dpfj); } if (list.get(arg0).getIsls() == 0) { holder.xczd.setBackgroundResource(R.drawable.xczdbjc); holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); } else if (list.get(arg0).getIsls() == 1) { holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); holder.xczd.setBackgroundResource(R.drawable.xczddjc); holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); } else if (list.get(arg0).getIsls() == 2) { holder.xczd.setBackgroundResource(R.drawable.xczdyjc); holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); } else if (list.get(arg0).getIsls() == 3) { holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); holder.xczd.setBackgroundResource(R.drawable.xczdfj); } if (list.get(arg0).getIspdzc() == 0) { holder.pdzc.setBackgroundResource(R.drawable.pdzcbjc); holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); } else if (list.get(arg0).getIspdzc() == 1) { holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); holder.pdzc.setBackgroundResource(R.drawable.pdzcdjc); } else if (list.get(arg0).getIspdzc() == 2) { holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); holder.pdzc.setBackgroundResource(R.drawable.pdzcyjc); } else if (list.get(arg0).getIspdzc() == 3) { holder.ll_xczd_pdzc.setVisibility(View.VISIBLE); holder.pdzc.setBackgroundResource(R.drawable.pdzcfj); } }else{ if (list.get(arg0).getIsdp() == 0) { holder.dp.setBackgroundResource(R.drawable.dpbjc1); } else if (list.get(arg0).getIsdp() == 1) { holder.dp.setBackgroundResource(R.drawable.dpdjc1); } else if (list.get(arg0).getIsdp() == 2) { holder.dp.setBackgroundResource(R.drawable.dpyjc1); } else if (list.get(arg0).getIsdp() == 3) { holder.dp.setBackgroundResource(R.drawable.dpfj1); } holder.dp.getLayoutParams().height=(dp2px(CjlbActivity.this,42)); } return arg1; } } private class ViewHolder { TextView jylsh, hphm, ccrq, hpzl, zt, syr, dpdt, dp,xczd,pdzc; LinearLayout ll_dpdt_dp,ll_xczd_pdzc; } private int dp2px(Context context , float dpValue){ float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } } <file_sep>/app/src/main/java/edu/qau/car/TjjgActivity.java package edu.qau.car; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import edu.qau.car.bean.Cjlb; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class TjjgActivity extends Activity { private ImageButton qbhg; public static void actionStart(final Context context, final Cjlb cjlb) { new WsAsyncTask().execute(new WsCallback() { String foramt = "<?xml version='1.0' encoding='GBK'?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><xmlb>%s</xmlb></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { User user = PreferencesUtils.getUser(context); String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), PreferencesUtils.getUserJyxm(context)); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return null; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F23"; } @Override public void callback(JSONObject obj) { try { if (obj.getBoolean("ok")) { JSONArray array = obj.getJSONArray("Table"); Intent intent = new Intent(context, TjjgActivity.class); intent.putExtra("bean", cjlb); intent.putExtra("array", array.toString()); context.startActivity(intent); } else { Toast.makeText(context, "网络访问失败", Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Toast.makeText(context, "网络访问失败", Toast.LENGTH_LONG).show(); } } }); } public void back(View view) { finish(); } private class TjjgItem implements OnClickListener { private String dmz; private String jy; private String dmsm4; private TextView bt; private ImageButton wj; private ImageButton hg; private ImageButton bhg; public String getDmsm4() { return dmsm4; } public String getDmz() { return dmz; } public String getJy() { return jy; } public TjjgItem(LinearLayout layout, String bt, String dmz, String dmsm4) { this.dmz = dmz; this.dmsm4 = dmsm4; jy = "0"; View view = inflater.inflate(R.layout.tjjg_item, layout, false); this.bt = (TextView) view.findViewById(R.id.bt); this.bt.setText(bt); wj = (ImageButton) view.findViewById(R.id.wj); hg = (ImageButton) view.findViewById(R.id.hg); bhg = (ImageButton) view.findViewById(R.id.bhg); wj.setOnClickListener(this); hg.setOnClickListener(this); bhg.setOnClickListener(this); layout.addView(view); } @Override public void onClick(View v) { clear(wj, hg, bhg); if (v == wj) { this.jy = "0"; wj.setImageResource(R.drawable.wj_p); } else if (v == hg) { this.jy = "1"; hg.setImageResource(R.drawable.hg_p); } else if (v == bhg) { this.jy = "2"; bhg.setImageResource(R.drawable.bhg_p); } } public void hg() { clear(wj, hg, bhg); this.jy = "1"; hg.setImageResource(R.drawable.hg_p); } private void clear(ImageButton wj, ImageButton hg, ImageButton bhg) { this.jy = "0"; wj.setImageResource(R.drawable.wj_n); hg.setImageResource(R.drawable.hg_n); bhg.setImageResource(R.drawable.bhg_n); } } private LayoutInflater inflater; private LinearLayout layout; private ArrayList<TjjgItem> list = new ArrayList<TjjgItem>(); private TextView userInfo; private static final int CONFIRM = 1; public void tj(View view) { User user = PreferencesUtils.getUser(this); String foramt = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><jcxdh>%s</jcxdh><jycs>%s</jycs><jyxm>%s</jyxm><hpzl>%s</hpzl><hphm>%s</hphm><clsbdh>%s</clsbdh>%s%s</vehispara></root>"; String jyxm = null; String wj = ""; if ("10".equals(user.getRYLB())) { jyxm = "F1"; wj = "<wgjcjyy>" + user.getXM() + "</wgjcjyy><wgjcjyysfzh>" + user.getSFZMHM() + "</wgjcjyysfzh>"; } else if ("11".equals(user.getRYLB())) { jyxm = "DC"; wj = "<dpdtjyy>" + user.getXM() + "</dpdtjyy><dpdtjyysfzh>" + user.getSFZMHM() + "</dpdtjyysfzh>"; } else if ("12".equals(user.getRYLB())) { jyxm = "C1"; wj = "<dpjcjyy>" + user.getXM() + "</dpjcjyy><dpjyysfzh>" + user.getSFZMHM() + "</dpjyysfzh>"; } StringBuffer stringBuffer = new StringBuffer(); for (TjjgItem item : list) { stringBuffer.append("<").append(item.getDmsm4()).append(">") .append(item.getJy()).append("</").append(item.getDmsm4()) .append(">"); } String jycs = String.valueOf(Integer.parseInt(cjlb.getJycs())); String hpzl = cjlb.getHpzlNum() + ""; if (hpzl.length() == 1) { hpzl = "0" + hpzl; } final String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), cjlb.getXzcdh(), jycs, jyxm, hpzl, cjlb.getHphm(), cjlb.getClsbdh(), stringBuffer.toString(), wj); Log.w("car", xml); new XmlAsyncTask().execute(new XmlCallback() { @Override public String getXtlb() { return "17"; } @Override public String getXml() { return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F80"; } @Override public void callback(String obj) { Log.w("car", obj); String code = XmlUtils.getValue(obj, "code"); if ("1".equals(code)) { Toast.makeText(TjjgActivity.this, "数据保存成功", Toast.LENGTH_LONG).show(); qbhg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(TjjgActivity.this, ConfirmActivity.class); intent.putExtra("message", "是否结束本车辆的检验?"); startActivityForResult(intent, CONFIRM); } }); } else { String message = XmlUtils.getValue(obj, "message"); Toast.makeText(TjjgActivity.this, message, Toast.LENGTH_LONG).show(); } } @Override public String getPara() { return "WriteXmlDoc"; } }); } private Cjlb cjlb; private SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat( "yyyy/MM/dd hh:mm:ss"); @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CONFIRM) { if (resultCode == Activity.RESULT_OK) { new XmlAsyncTask().execute(new XmlCallback() { String format = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><jcxdh>%s</jcxdh><jycs>%s</jycs><jyxm>%s</jyxm><hpzl>%s</hpzl><hphm>%s</hphm><clsbdh>%s</clsbdh><jssj>%s</jssj></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { User user = PreferencesUtils.getUser(TjjgActivity.this); String jyxm = null; if ("10".equals(user.getRYLB())) { jyxm = "F1"; } else if ("11".equals(user.getRYLB())) { jyxm = "DC"; } else if ("12".equals(user.getRYLB())) { jyxm = "C1"; } String jycs = String.valueOf(Integer.parseInt(cjlb .getJycs())); String hpzl = cjlb.getHpzlNum() + ""; if (hpzl.length() == 1) { hpzl = "0" + hpzl; } String xml = String.format(format, cjlb.getJylsh(), user.getJCZBH(), cjlb.getXzcdh(), jycs, jyxm, hpzl, cjlb.getHphm(), cjlb.getClsbdh(), simpleDateFormat2.format(new Date())); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F58"; } @Override public void callback(String obj) { Log.w("car", obj); String code = XmlUtils.getValue(obj, "code"); if ("1".equals(code)) { Intent intent = new Intent(TjjgActivity.this, ZjmActivity.class); //intent.putExtra("bean", cjlb); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); //finish(); } else { String message = XmlUtils.getValue(obj, "message"); Toast.makeText(TjjgActivity.this, message, Toast.LENGTH_LONG).show(); } } @Override public String getPara() { return "WriteXmlDoc"; } }); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tjjg); userInfo = (TextView) findViewById(R.id.user_info); userInfo.setText(PreferencesUtils.getUserInfo(this)); cjlb = getIntent().getParcelableExtra("bean"); layout = (LinearLayout) findViewById(R.id.layout); inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); qbhg = (ImageButton) findViewById(R.id.qbhg); String array = getIntent().getStringExtra("array"); Log.w("car", array); try { JSONArray jsonArray = new JSONArray(array); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); TjjgItem item = new TjjgItem(layout, json.getString("dmsm1"), json.getString("dmz"), json.getString("dmsm4")); list.add(item); item.hg(); } } catch (JSONException e) { e.printStackTrace(); } } } <file_sep>/app/src/main/java/edu/qau/car/PzActivity.java package edu.qau.car; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.SystemClock; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import edu.qau.car.bean.Cjlb; public class PzActivity extends Activity { private File file; private Uri uri; private static final int TAKE_PHOTO = 1; private static final int CONFIRM = 2; private static final int MY_PERMISSIONS_REQUEST = 5; public static final int SNAP_VELOCITY = 200; private int screenWidth; private View content1; private View content2; private View content3; private LinearLayout.LayoutParams content1Params; private LinearLayout.LayoutParams content3Params; private int leftEdge; private int rightEdge = 0; private VelocityTracker mVelocityTracker; private float xDown; private float xMove; private boolean isContent2Visible = false; private float xUp; private static boolean isNextStep = true ; private static String zcpd; private LinearLayout bt1; private LinearLayout pz1; private LinearLayout bt2; private LinearLayout pz2; private LinearLayout bt3; private LinearLayout pz3; private LinearLayout bt4; private LinearLayout pz4; private PzItem item; private Cjlb cjlb; private ViewPager mViewpager; private ArrayList<View> mPageList; private ImageButton next; public void back(View view) { finish(); } public void next(View view) { /* * if (bundle.size() == list.size()) { Intent intent = new Intent(this, * ConfirmActivity.class); intent.putExtra("message", "拍照完成了吗?"); * startActivityForResult(intent, CONFIRM); } else { * Toast.makeText(this, "请长传全部图片", Toast.LENGTH_LONG).show(); } */ Intent intent = new Intent(this, ConfirmActivity.class); intent.putExtra("message", "拍照完成了吗?"); startActivityForResult(intent, CONFIRM); } private ArrayList<Holder> list = new ArrayList<Holder>(); private static HashMap<String, String> map = new HashMap<String, String>(); public static class Holder { int n; int p; String name; public Holder(String name, int n, int p) { this.n = n; this.p = p; this.name = name; } } public static ArrayList<Holder> xm = new ArrayList<PzActivity.Holder>(); static { xm.add(new Holder("0111", R.drawable.d0111_n, R.drawable.d0111_p)); xm.add(new Holder("0112", R.drawable.d0112_n, R.drawable.d0112_p)); xm.add(new Holder("0113", R.drawable.d0113_n, R.drawable.d0113_p)); xm.add(new Holder("0115", R.drawable.d0115_n, R.drawable.d0115_p)); xm.add(new Holder("0116", R.drawable.d0116_n, R.drawable.d0116_p)); xm.add(new Holder("0117", R.drawable.d0117_n, R.drawable.d0117_p)); xm.add(new Holder("0118", R.drawable.d0118_n, R.drawable.d0118_p)); xm.add(new Holder("0119", R.drawable.d0119_n, R.drawable.d0119_p)); xm.add(new Holder("0120", R.drawable.d0120_n, R.drawable.d0120_p)); xm.add(new Holder("0121", R.drawable.d0121_n, R.drawable.d0121_p)); xm.add(new Holder("0122", R.drawable.d0122_n, R.drawable.d0122_p)); xm.add(new Holder("0126", R.drawable.d0126_n, R.drawable.d0126_p)); xm.add(new Holder("0127", R.drawable.d0127_n, R.drawable.d0127_p)); xm.add(new Holder("0128", R.drawable.d0128_n, R.drawable.d0128_p)); xm.add(new Holder("0130", R.drawable.d0130_n, R.drawable.d0130_p)); xm.add(new Holder("0132", R.drawable.d0132_n, R.drawable.d0132_p)); xm.add(new Holder("0133", R.drawable.d0133_n, R.drawable.d0133_p)); xm.add(new Holder("0134", R.drawable.d0134_n, R.drawable.d0134_p)); xm.add(new Holder("0135", R.drawable.d0135_n, R.drawable.d0135_p)); xm.add(new Holder("0136", R.drawable.d0136_n, R.drawable.d0136_p)); xm.add(new Holder("0138", R.drawable.d0138_n, R.drawable.d0138_p)); xm.add(new Holder("0139", R.drawable.d0139_n, R.drawable.d0139_p)); xm.add(new Holder("0140", R.drawable.d0140_n, R.drawable.d0140_p)); xm.add(new Holder("0141", R.drawable.d0141_n, R.drawable.d0141_p)); xm.add(new Holder("0154", R.drawable.d0154_n, R.drawable.d0154_p)); xm.add(new Holder("0155", R.drawable.d0155_n, R.drawable.d0155_p)); xm.add(new Holder("0156", R.drawable.d0156_n, R.drawable.d0156_p)); xm.add(new Holder("0157", R.drawable.d0157_n, R.drawable.d0157_p)); xm.add(new Holder("0158", R.drawable.d0158_n, R.drawable.d0158_p)); xm.add(new Holder("0159", R.drawable.d0159_n, R.drawable.d0159_p)); xm.add(new Holder("0160", R.drawable.d0160_n, R.drawable.d0160_p)); xm.add(new Holder("0161", R.drawable.d0161_n, R.drawable.d0161_p)); xm.add(new Holder("0163", R.drawable.d0163_n, R.drawable.d0163_p)); xm.add(new Holder("0171", R.drawable.d0171_n, R.drawable.d0171_p)); xm.add(new Holder("0172", R.drawable.d0172_n, R.drawable.d0172_p)); xm.add(new Holder("0173", R.drawable.d0173_n, R.drawable.d0173_p)); xm.add(new Holder("0174", R.drawable.d0174_n, R.drawable.d0174_p)); xm.add(new Holder("0175", R.drawable.d0175_n, R.drawable.d0175_p)); xm.add(new Holder("0176", R.drawable.d0176_n, R.drawable.d0176_p)); xm.add(new Holder("0323", R.drawable.d0323_n, R.drawable.d0323_p)); xm.add(new Holder("0344", R.drawable.d0344_n, R.drawable.d0344_p)); xm.add(new Holder("0342", R.drawable.d0342_n, R.drawable.d0342_p)); xm.add(new Holder("0341", R.drawable.d0341_n, R.drawable.d0341_p)); xm.add(new Holder("0343", R.drawable.d0343_n, R.drawable.d0343_p)); xm.add(new Holder("0345", R.drawable.d0345_n, R.drawable.d0345_p)); } /** * 启动本页面 * * @param context * @param cjlb */ public static void actionStart(final Context context, final Cjlb cjlb ,final String pdzcZcpd ,boolean isNext) { final Intent intent = new Intent(context, PzActivity.class); intent.putExtra("bean", cjlb); final User user = PreferencesUtils.getUser(context); isNextStep = isNext; zcpd = pdzcZcpd; getPhoto(context,cjlb,pdzcZcpd,user,intent); } public static void getPhoto(final Context context, final Cjlb cjlb ,final String pdzcZcpd,final User user,final Intent intent){ final ArrayList<String> list = new ArrayList<String>(); new WsAsyncTask().execute(new WsCallback() { String foramt = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><zcpd>%s</zcpd><jycs>%s</jycs><jyxm>%s</jyxm></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { String jycs = String.valueOf(Integer.parseInt(cjlb.getJycs())); String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), pdzcZcpd, jycs, PreferencesUtils.getJyxm(context)); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return null; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F27"; } @Override public void callback(JSONObject obj) { Log.w("car", obj.toString()); try { if (obj.getBoolean("ok")) { map.clear(); JSONArray array = obj.getJSONArray("Table"); for (int i = 0; i < array.length(); i++) { JSONObject json = array.getJSONObject(i); list.add(json.getString("zpzl")); map.put(json.getString("zpzl"), json.getString("zplj")); } } if("R1".equals(PreferencesUtils.getUserLsjyType(context))){ if(!list.contains("0341")){ list.add("0341"); } if(!list.contains("0343")){ list.add("0343"); } } else{ if(!list.contains("0345")){ list.add("0345"); } } intent.putExtra("list", list); context.startActivity(intent); } catch (JSONException e) { Toast.makeText(context, "网络访问失败", Toast.LENGTH_LONG) .show(); } } }); } /** * 启动本页面 * * @param context * @param cjlb */ public static void actionStart(final Context context, final Cjlb cjlb) { final Intent intent = new Intent(context, PzActivity.class); intent.putExtra("bean", cjlb); User user = PreferencesUtils.getUser(context); final ArrayList<String> list = new ArrayList<String>(); if ("12".equals(user.getRYLB())) { list.add("0323"); intent.putExtra("list", list); context.startActivity(intent); } else if ("11".equals(user.getRYLB())) { list.add("0344"); list.add("0342"); intent.putExtra("list", list); context.startActivity(intent); } else if ("15".equals(user.getRYLB())) { if("R1".equals(PreferencesUtils.getUserLsjyType(context))){ list.add("0341"); list.add("0343"); } else{ list.add("0345"); } intent.putExtra("list", list); context.startActivity(intent); } else if ("10".equals(user.getRYLB())) { new WsAsyncTask().execute(new WsCallback() { String foramt = "<?xml version='1.0' encoding='GBK'?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><jycs>%s</jycs><xmlb>wgjyzp</xmlb></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { User user = PreferencesUtils.getUser(context); String jycs = String.valueOf(Integer.parseInt(cjlb .getJycs())); String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), jycs); Log.w("car", xml); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return null; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F23"; } @Override public void callback(JSONObject obj) { try { Log.w("car", obj.toString()); if (obj.getBoolean("ok")) { map.clear(); JSONArray array = obj.getJSONArray("Table"); Log.w("car", array.toString()); for (int i = 0; i < array.length(); i++) { JSONObject json = array.getJSONObject(i); list.add(json.getString("dmz")); map.put(json.getString("dmz"), json.getString("zplj")); } intent.putExtra("list", list); context.startActivity(intent); } else { Toast.makeText(context, "获取数据失败", Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Toast.makeText(context, "网络访问失败", Toast.LENGTH_LONG) .show(); } } }); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pz); cjlb = getIntent().getParcelableExtra("bean"); next = (ImageButton) findViewById(R.id.next); mViewpager = (ViewPager) findViewById(R.id.pz_viewpager); //page LayoutInflater inflater = LayoutInflater.from(this); View page1 = inflater.inflate(R.layout.item_pz_layout, null, false); View page2 = inflater.inflate(R.layout.item_pz_layout, null, false); View page3 = inflater.inflate(R.layout.item_pz_layout, null, false); View page4 = inflater.inflate(R.layout.item_pz_layout, null, false); mPageList = new ArrayList<>(); mPageList.add(page1); mPageList.add(page2); mPageList.add(page3); mPageList.add(page4); bt1 = (LinearLayout) page1.findViewById(R.id.bt); pz1 = (LinearLayout) page1.findViewById(R.id.pz); bt2 = (LinearLayout) page2.findViewById(R.id.bt); pz2 = (LinearLayout) page2.findViewById(R.id.pz); bt3 = (LinearLayout) page3.findViewById(R.id.bt); pz3 = (LinearLayout) page3.findViewById(R.id.pz); bt4 = (LinearLayout) page4.findViewById(R.id.bt); pz4 = (LinearLayout) page4.findViewById(R.id.pz); ArrayList<String> nums = getIntent().getStringArrayListExtra("list"); for (String string : nums) { for (Holder holder : xm) { if (string.equals(holder.name)) { list.add(holder); continue; } } } //第一页 for (int i = 0; i < 6 && i < list.size(); i++) { if (i != 5) { new PzItem(this, bt1, 2, pz1, list.get(i)); } else { new PzItem(this, bt1, 3, pz1, list.get(i)); } } for (int i = list.size(); i < 6; i++) { if (i != 5) { new BlankItem(this, bt1, 2, pz1); } else { new BlankItem(this, bt1, 3, pz1); } } //第二页 if (list.size() > 6) { for (int i = 6; i < 12 && i < list.size(); i++) { if (i != 11) { new PzItem(this, bt2, 2, pz2, list.get(i)); } else { new PzItem(this, bt2, 3, pz2, list.get(i)); } } for (int i = list.size(); i < 12; i++) { if (i != 11) { new BlankItem(this, bt2, 2, pz2); } else { new BlankItem(this, bt2, 3, pz2); } } } //第三页 if (list.size() > 12 ) { for (int i = 12; i < 18 && i < list.size(); i++) { if (i != 17) { new PzItem(this, bt3, 2, pz3, list.get(i)); } else { new PzItem(this, bt3, 3, pz3, list.get(i)); } } for (int i = list.size(); i < 18; i++) { if (i != 17) { new BlankItem(this, bt3, 2, pz3); } else { new BlankItem(this, bt3, 3, pz3); } } } //第四页 if (list.size() > 18 ) { for (int i = 18; i < 24 && i < list.size(); i++) { if (i != 23) { new PzItem(this, bt4, 2, pz4, list.get(i)); } else { new PzItem(this, bt4, 3, pz4, list.get(i)); } } for (int i = list.size(); i < 24; i++) { if (i != 23) { new BlankItem(this, bt4, 2, pz4); } else { new BlankItem(this, bt4, 3, pz4); } } } mViewpager.setAdapter(new MyAdapter()); /* * new PzItem(this, R.drawable.d0111_n, R.drawable.d0111_p, bt1, 2, pz1, * "zqf"); new PzItem(this, R.drawable.d0112_n, R.drawable.d0112_p, bt1, * 2, pz1, "yhf"); new PzItem(this, R.drawable.d0113_n, * R.drawable.d0113_p, bt1, 2, pz1, "clsb"); new PzItem(this, * R.drawable.d0119_n, R.drawable.d0119_p, bt1, 2, pz1, "fdjh"); new * PzItem(this, R.drawable.d0115_n, R.drawable.d0115_p, bt1, 2, pz1, * "cxnb"); new PzItem(this, R.drawable.d0158_n, R.drawable.d0158_p, * bt1, 3, pz1, "clzhf"); * * new PzItem(this, R.drawable.d0111_n, R.drawable.d0111_p, bt2, 2, pz2, * "mhq"); new BlankItem(this, bt2, 2, pz2); new BlankItem(this, bt2, 2, * pz2); new BlankItem(this, bt2, 2, pz2); new BlankItem(this, bt2, 2, * pz2); new BlankItem(this, bt2, 3, pz2); */ // initValues(); if(!isNextStep){ next.setVisibility(View.GONE); } } private class MyAdapter extends PagerAdapter { @Override public int getCount() { return 4; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mPageList.get(position)); return mPageList.get(position); } } private Bundle bundle = new Bundle(); public void ckzp(View view) { if (!bundle.isEmpty()) { Intent intent = new Intent(this, CkzpActivity.class); intent.putExtras(bundle); startActivity(intent); } } public void takephoto() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST); } else { createFile(); } } public void pic(PzItem item) { this.item = item; takephoto(); } public void createFile(){ File dcim = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File camera = new File(dcim, "camera"); if (!camera.exists()) { camera.mkdir(); } file = new File(camera, SystemClock.elapsedRealtime() + ".jpg"); if (file.exists()) { file.delete(); } try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); uri = Uri.fromFile(file); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, TAKE_PHOTO); } private SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat( "yyyy/MM/dd hh:mm:ss"); @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == MY_PERMISSIONS_REQUEST){ if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { createFile(); } else { Toast.makeText(PzActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == TAKE_PHOTO) { if (resultCode == Activity.RESULT_OK) { LoadingActivity.startAction(PzActivity.this); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Bitmap temp = ImageUtils.decodeSampledBitmap( file.getAbsolutePath(), 1024, 768); ImageUtils.compressBitmap(temp, baos); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); fileOutputStream.write(baos.toByteArray()); } catch (IOException e1) { e1.printStackTrace(); } finally { temp.recycle(); baos.reset(); try { baos.close(); } catch (IOException e) { e.printStackTrace(); } baos = null; if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } new XmlAsyncTask().execute(new XmlCallback() { String foramt = "<?xml version=\"1.0\" encoding=\"GBK\"?><root><vehispara><jylsh>%s</jylsh><jyjgbh>%s</jyjgbh><jcxdh>%s</jcxdh><jycs>%s</jycs><hphm>%s</hphm><hpzl>%s</hpzl><clsbdh>%s</clsbdh><zp>%s</zp><pssj>%s</pssj><jyxm>%s</jyxm><zpzl>%s</zpzl></vehispara></root>"; @Override public String getXtlb() { return "17"; } @Override public String getXml() { FileInputStream fis = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { fis = new FileInputStream(file); int a = -1; while ((a = fis.read()) != -1) { baos.write(a); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } String jycs = String.valueOf(Integer.parseInt(cjlb .getJycs())); String hpzl = cjlb.getHpzlNum() + ""; if (hpzl.length() == 1) { hpzl = "0" + hpzl; } User user = PreferencesUtils.getUser(PzActivity.this); String xml = String.format(foramt, cjlb.getJylsh(), user.getJCZBH(), cjlb.getXzcdh(), jycs, cjlb .getHphm(), hpzl, cjlb.getClsbdh(), Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT), simpleDateFormat2 .format(new Date()), PreferencesUtils.getJyxm(PzActivity.this), item.getName()); return xml; } @Override public String getUri() { return null; } @Override public String getNamespace() { return null; } @Override public String getMethodName() { return "writeObjectOut"; } @Override public String getJkxlh() { return "00000"; } @Override public String getJkid() { return "17F63"; } @Override public void callback(String obj) { Log.w("car", obj); LoadingActivity.endAction(); String code = XmlUtils.getValue(obj, "code"); if ("1".equals(code)) { String message = XmlUtils.getValue(obj, "message"); // url = url.replaceAll("\\", "/"); // Log.w("car", url); item.pzwc(AppURL.BASE_URL + message); } else { String message = XmlUtils.getValue(obj, "message"); Toast.makeText(PzActivity.this, message, Toast.LENGTH_LONG).show(); item.pzsb(); } } @Override public String getPara() { return "WriteXmlDoc"; } }); // item.pzwc(); } } else if (requestCode == CONFIRM) { if (resultCode == Activity.RESULT_OK) { if(PreferencesUtils.isLsy(PzActivity.this)){ if("R1".equals(PreferencesUtils.getUserLsjyType(PzActivity.this))){ Intent intent = new Intent(PzActivity.this,LsjyXczdActivity.class); intent.putExtra("bean", cjlb); startActivity (intent ); finish(); }else if("R2".equals(PreferencesUtils.getUserLsjyType(PzActivity.this))){ Intent intent = new Intent(PzActivity.this,LsjyPdzcActivity.class); intent.putExtra("bean", cjlb); intent.putExtra("zcpd", zcpd); startActivity (intent ); finish(); } }else{ TjjgActivity.actionStart(this, cjlb); } } } } public class BlankItem { private int pzWh; public BlankItem(Context context, LinearLayout btLayout, int weight, LinearLayout pzLayout) { pzWh = context.getResources() .getDimensionPixelOffset(R.dimen.pz_wh); TextView bt = new TextView(context); LinearLayout.LayoutParams btLayoutParams = new LinearLayout.LayoutParams( pzWh, pzWh); btLayout.addView(bt, btLayoutParams); TextView btTv = new TextView(context); LinearLayout.LayoutParams btTvLayoutParams = new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT, weight); btLayout.addView(btTv, btTvLayoutParams); TextView pz = new TextView(context); LinearLayout.LayoutParams pzLayoutParams = new LinearLayout.LayoutParams( pzWh, pzWh); pzLayout.addView(pz, pzLayoutParams); TextView pzTv = new TextView(context); LinearLayout.LayoutParams pzTvLayoutParams = new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT, weight); pzLayout.addView(pzTv, pzTvLayoutParams); } } public class PzItem implements View.OnClickListener { private ImageView bt; private TextView btTv; private int pzWh; private int pzF; private FrameLayout pzFrame; private ImageView pz; private ImageView sc; private TextView f; private TextView pzTv; private Context context; private int btSrc; private int btP; private String name; public String getName() { return name; } public PzItem(Context context, LinearLayout btLayout, int weight, LinearLayout pzLayout, Holder holder) { this(context, holder.n, holder.p, btLayout, weight, pzLayout, holder.name); } public PzItem(Context context, int btSrc, int btP, LinearLayout btLayout, int weight, LinearLayout pzLayout, String name) { this.name = name; this.btSrc = btSrc; this.btP = btP; this.context = context; pzWh = context.getResources() .getDimensionPixelOffset(R.dimen.pz_wh); pzF = context.getResources().getDimensionPixelOffset(R.dimen.pz_f); bt = new ImageView(context); LinearLayout.LayoutParams btLayoutParams = new LinearLayout.LayoutParams( pzWh, pzWh); bt.setScaleType(ScaleType.FIT_XY); bt.setImageResource(btSrc); btLayout.addView(bt, btLayoutParams); btTv = new TextView(context); LinearLayout.LayoutParams btTvLayoutParams = new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT, weight); btLayout.addView(btTv, btTvLayoutParams); pzFrame = new FrameLayout(context); LinearLayout.LayoutParams pzFrameLayoutParams = new LinearLayout.LayoutParams( pzWh, pzWh); pzLayout.addView(pzFrame, pzFrameLayoutParams); pz = new ImageView(context); FrameLayout.LayoutParams pzLayoutParams = new FrameLayout.LayoutParams( pzWh, pzWh); pz.setScaleType(ScaleType.FIT_XY); pz.setImageResource(R.drawable.wsc); pzFrame.addView(pz, pzLayoutParams); sc = new ImageView(context); FrameLayout.LayoutParams scLayoutParams = new FrameLayout.LayoutParams( pzWh, pzWh); sc.setScaleType(ScaleType.FIT_XY); sc.setImageResource(R.drawable.pzsc); sc.setVisibility(View.GONE); sc.setOnClickListener(this); pzFrame.addView(sc, scLayoutParams); f = new TextView(context); FrameLayout.LayoutParams fLayoutParams = new FrameLayout.LayoutParams( pzF, pzF); f.setVisibility(View.GONE); f.setOnClickListener(this); pzFrame.addView(f, fLayoutParams); pzTv = new TextView(context); LinearLayout.LayoutParams pzTvLayoutParams = new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT, weight); pzLayout.addView(pzTv, pzTvLayoutParams); pz.setOnClickListener(this); if (!map.isEmpty()) { String zplj = map.get(name); if (zplj!=null && zplj.length() > 20) { pzwc(AppURL.BASE_URL + zplj); } } } public void pzwc(String url) { Picasso.with(context).load(url).placeholder(R.drawable.wsc) .error(R.drawable.no_photo) .resizeDimen(R.dimen.pz_wh, R.dimen.pz_wh).centerCrop() .into(pz); add(url); } public void pzsb() { Picasso.with(context).load(R.drawable.scsb) .placeholder(R.drawable.scsb).error(R.drawable.scsb) .resizeDimen(R.dimen.pz_wh, R.dimen.pz_wh).centerCrop() .into(pz); } private void add(String url) { bt.setImageResource(btP); f.setVisibility(View.VISIBLE); sc.setVisibility(View.VISIBLE); pz.setOnClickListener(null); bundle.putString(name, url); } @Override public void onClick(View v) { if (pz == v) { pic(this); } else if (sc == v) { sc.setVisibility(View.GONE); f.setVisibility(View.GONE); Picasso.with(context).load(R.drawable.wsc) .placeholder(R.drawable.wsc).error(R.drawable.scsb) .resizeDimen(R.dimen.pz_wh, R.dimen.pz_wh).centerCrop() .into(pz); pz.setOnClickListener(this); bt.setImageResource(btSrc); bundle.remove(name); } else if (f == v) { Intent zqfIntent = new Intent(context, CkActivity.class); Log.w("car", name + " " + bundle.getString(name)); zqfIntent.putExtra("tp", bundle.getString(name)); startActivity(zqfIntent); } } } } <file_sep>/app/src/main/java/edu/qau/car/CarApplication.java package edu.qau.car; import okhttp3.OkHttpClient; import android.app.Application; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class CarApplication extends Application { public static OkHttpClient client; @Override public void onCreate() { super.onCreate(); client = new OkHttpClient(); //load url SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); AppURL.BASE_URL = sharedPreferences.getString(AppURL.BASE_URL_KEY, AppURL.BASE_URL); AppURL.SECOND_URL = sharedPreferences.getString(AppURL.SECOND_URL_KEY, AppURL.SECOND_PATH_1); } } <file_sep>/app/src/main/java/edu/qau/car/CkzpActivity.java package edu.qau.car; import java.util.ArrayList; import edu.qau.car.PzActivity.Holder; import ru.truba.touchgallery.GalleryWidget.FilePagerAdapter; import ru.truba.touchgallery.GalleryWidget.GalleryViewPager; import ru.truba.touchgallery.GalleryWidget.UrlPagerAdapter; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class CkzpActivity extends Activity { private GalleryViewPager mViewPager; private ArrayList<String> items; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ckzp); items = new ArrayList<String>(); Bundle bundle = getIntent().getExtras(); for (Holder holder : PzActivity.xm) { if (bundle.containsKey(holder.name)) { items.add(bundle.getString(holder.name)); } } UrlPagerAdapter pagerAdapter = new UrlPagerAdapter(this, items); mViewPager = (GalleryViewPager) findViewById(R.id.viewer); // mViewPager.setOffscreenPageLimit(3); mViewPager.setAdapter(pagerAdapter); } } <file_sep>/app/src/main/java/edu/qau/car/AppURL.java package edu.qau.car; public class AppURL { public static String BASE_URL_KEY = "base_url_key"; public static String SECOND_URL_KEY = "second_url_key"; public static String SECOND_PATH_1 = "/ThinkOutAccess.asmx"; public static String SECOND_PATH_2 = "/ref/ThinkOutAccess.asmx"; public static String BASE_URL = "http://172.16.17.32:90"; // public static String BASE_URL = "http://172.21.1.8:98"; public static String SECOND_URL = SECOND_PATH_1; } <file_sep>/app/src/main/java/edu/qau/car/ImageUtils.java package edu.qau.car; import java.io.ByteArrayOutputStream; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.util.Log; public class ImageUtils { public static Bitmap decodeSampledBitmap(String picPath, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(picPath, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(picPath, options); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { int height = options.outHeight; int width = options.outWidth; int inSampleSize = 1; if (height > width) { int temp = width; width = height; height = temp; } if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } public static void compressBitmap(Bitmap bmp, ByteArrayOutputStream baos) { int options = 30; CompressFormat format = Bitmap.CompressFormat.JPEG; bmp.compress(format, options, baos); } }
07c179dc5ef495704864491c80c85300fb104ae5
[ "Java", "INI", "Gradle" ]
17
Java
mlycookie/Car
738b6dbf7a9f03b31671cd42dfa72a14a770cfb6
04710e552e2b587db7bea9fc64a7a2928a35102d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cwiczenie8 { class Program { static void Main(string[] args) { /* int liczba1 = 0; //Console.WriteLine(liczba1 / 0); // Operacja niedozwolony nie mozna dzielic przez 0 int liczba2, liczba3; liczba2 = 30; //liczba3 = liczba2 / liczba1; // Po tej operacji aplikacja wyrzuci wyjatek try { liczba3 = liczba2 / liczba1; } catch(Exception e) { Console.WriteLine("Nie mozna dzielic przez 0!"); Console.WriteLine(e.Message); Console.WriteLine(e.Data); Console.WriteLine(e.HelpLink); Console.WriteLine(e.Source); } finally { Console.WriteLine("Finally !!!"); // Jezeli wynik bylby mozliwy do uzyskania odpalony zostalby tylko blok finally } int []table=new int[3]; try { table[25] = 2; } catch(IndexOutOfRangeException e) { Console.WriteLine(e.Message); } catch { Console.WriteLine("Po za zakresem tablicy"); } */ try { throw new IndexOutOfRangeException(); } catch(IndexOutOfRangeException e) { Console.WriteLine(e.Message); } //StackOverflowException - przepelniony stos /* * NullReferenceException - FileNotFoundException- AccessViolationException- IndexOutOfRangeException - */ NaszWyjatekException Wyjatek = new NaszWyjatekException("BLAD"); Console.WriteLine(Wyjatek.Message); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cwiczenie8 { class NaszWyjatekException:Exception { public const string ErrMessage = "ALE BLAD"; public NaszWyjatekException(string Message):base(Message) { } public NaszWyjatekException(string Message,Exception innerException):base(Message,innerException) { } } }
11ec9d43223449b2016b69f5db50d9f12e113f3d
[ "C#" ]
2
C#
polubis/Cwiczenia8
07fd6ef498e068605ea968164738ef8e555ab2e3
380733eefd3be5ff109a0b1de461c2dbb869b801
refs/heads/master
<file_sep>#Declared parameters #Note that h is obtained using Maple. We don't have to find it each # time we run the program, since the declared parameters # aren't going to change. #igcdexOfFG is also obtained using maple. It doesn't have to do # anything with any changes to ASCII Values q = 232092 f = 23 g = 241 h = 111011 r = 140 igcdexOfFG= 21 #Splits the whole string to individual characters and return them #into an array def msg2Split(Message): msg = [] msg.append(Message[:1]) Message = Message.replace(Message[:1], '', 1) while len(Message) > 0: msg.append(Message[:1]) Message = Message.replace(Message[:1], '', 1) return msg #Takes the elements of passed array, converts them to ASCII Values, and #return an array of ASCII elements def char2Ascii( str ): asciiArr =[] for i in str: asciiArr.append(ord(i)) return asciiArr #Encrypts any passed ASCII array and return encrypted array def encryption(asciiArr): E = [] for i in asciiArr: e = (r * h + i) % q E.append(e) return E #Decrypts any passed encrypted array and return decrypted array + #It calls method cipherSplitter def decryption(encArr): encArr = cipherSplitter(encArr) D = [] for i in encArr: a = (f * int(i)) % q b = (igcdexOfFG * a) % g D.append(b) return D #This method takes input from the user as a cipher text and creates an array #to put those splitted numbers in, each element is 6 digits. #It creates an array for the sake of *decryption()* method. def cipherSplitter(Cipher): msg = [] msg.append(Cipher[:6]) Cipher = Cipher.replace(Cipher[:6], '', 1) while len(Cipher) > 0: msg.append(Cipher[:6]) Cipher = Cipher.replace(Cipher[:6], '', 1) return msg <file_sep>import socket import threading import NTRU class Client: def __init__(self): self.create_connection() def create_connection(self): self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) while 1: try: host = input('Enter host name --> ') port = int(input('Enter port --> ')) self.s.connect((host,port)) break except: print("Couldn't connect to server") self.username = input('Enter username --> ') self.s.send(self.username.encode()) message_handler = threading.Thread(target=self.handle_messages,args=()) message_handler.start() input_handler = threading.Thread(target=self.input_handler,args=()) input_handler.start() def handle_messages(self): while 1: #print(self.s.recv(1204).decode()) #Use this method for unencrypted messages received! decmsg = self.s.recv(1204).decode() decryptedArr = NTRU.decryption(decmsg) decmsgz = ''.join(chr(i) for i in decryptedArr) print(decmsgz) def input_handler(self): while 1: #self.s.send((self.username+' - '+input()).encode()) #Use this method for unecrypted messages sent! Message = input() combinedMsg = (self.username+' - '+Message) msg = NTRU.msg2Split(combinedMsg) m2Ascii = NTRU.char2Ascii(msg) encryptedArr = NTRU.encryption(m2Ascii) encryptedArr = ''.join([str(n) for n in encryptedArr]) self.s.send(encryptedArr.encode()) client = Client() <file_sep>import NTRU if __name__ == "__main__": print('NTRU for Integers stand-alone simple application') menu = '\n1.To Encrypt a plain-text' menu += '\n' + '2.To Decrypt a cipher text' menu += '\n' + '0.Exit' menu += '\n' + '> ' ch = -1 while(ch != 0): print(menu, end='') ch = int(input()) if ch == 1: Message = input('Enter your plain-text to be encrypted: ') msg = NTRU.msg2Split(Message) m2Ascii = NTRU.char2Ascii(msg) encryptedArr = NTRU.encryption(m2Ascii) print('Cipher: ', end='') #print('Encrypted Array: ', encryptedArr) #Prints the encrypted elements of the array returned print(''.join([str(n) for n in encryptedArr])) elif ch == 2: Cipher = input('Enter your cipher text to be decrypted: ') decryptedArr = NTRU.decryption(Cipher) #print('Decrypted Array: ',decryptedArr) #Prints the decrypted elements of the array returned print('Decrypted Cipher text: ', end='') print(''.join(chr(i) for i in decryptedArr)) elif ch == 0: print('Exit....') break else: print('Wrong input!')
a0d55466c598c1d9b51eebe26f57a96b573a90ca
[ "Python" ]
3
Python
turjumann/CMSE491-NTRU-Encryption-Chat-System
61477efc71e1c9e7efb7d0625a22054310685046
99927165e6ac9be50efd24547a4e7050529b4f62
refs/heads/main
<repo_name>jay-sb/Streanime<file_sep>/Streanime/views.py from django.shortcuts import render from django.http import HttpResponse import requests from requests_html import HTMLSession import os import googleapiclient.discovery from django.shortcuts import render import urllib.request import json f = open('episodes.json',) eplist = json.load(f) n=1 def home(request): ep = eplist['episodesl1'][0]['0'] # url return render(request, "home.html", {'no': n, 'eplink': ep}) def search(request): if 'episode' in request.GET: n = request.GET['episode'] nu = int(n)-1 num = str(nu) ep = eplist['episodesl1'][0][num] return render(request, "episode.html", {'no': n, 'eplink': ep}) def nextep(request,no): nu = no-1 print(nu) num = str(nu) ep = eplist['episodesl1'][0][num] return render(request, "nextep.html", {'no': no, 'eplink': ep}) <file_sep>/README.md # Streanime Hunter x Hunter - Episodes ![Capture](https://user-images.githubusercontent.com/46050761/128337984-a43f6f72-672d-4ed2-b23e-c39c7dce15a6.PNG)
861b95410dbbf314d0c493eeb778098f9db50a43
[ "Markdown", "Python" ]
2
Python
jay-sb/Streanime
0f3c460eafc560b36fab0cc53de50b69086bcfb8
7c58b6b2127480368985e6845d8d5b0e816138c0
refs/heads/master
<repo_name>GDGNorthAmerica/chrome-extensions-codelab-gdg-oakdale<file_sep>/step-04/js/background.js function updateUser() { chrome.storage.local.get('githubToken', function(data) { if(data && data.githubToken) { GitHub.getMe(data.githubToken).then(function (me) { chrome.storage.local.set({ user: me }); }); } }); } function updateIssues() { chrome.storage.local.get('githubToken', function(data) { if(data && data.githubToken) { GitHub.getMyIssues(data.githubToken).then(function (issues) { chrome.storage.local.set({ issues: issues }); chrome.browserAction.setBadgeBackgroundColor({ color: '#F00' }); chrome.browserAction.setBadgeText({ text: '' + issues.length }); }); } }); } // // Grab issues every 5 minutes // setInterval(updateIssues, 5 * 60 * 1000); updateIssues(); // // Grab user info every 60 minutes // setInterval(updateUser, 60 * 60 * 1000); updateUser();<file_sep>/README.md ## Chrome Extensions Codelab - GDG Oakdale Getting started building Chrome extensions as seen at the January 2015 meetup at GDG Oakdale. For steps and guide, visit [https://justinribeiro.github.io/chrome-extensions-codelab-gdg-oakdale/](https://justinribeiro.github.io/chrome-extensions-codelab-gdg-oakdale/). <file_sep>/step-04/js/options.js var githubToken = document.getElementById('githubToken'); var saveButton = document.getElementById('save'); // save our Github token saveButton.addEventListener('click', function() { chrome.storage.local.set({ githubToken: githubToken.value }, function() { // force background page to reload data chrome.extension.getBackgroundPage().updateUser(); chrome.extension.getBackgroundPage().updateIssues(); }); }); // get our Github token chrome.storage.local.get('githubToken', function(data) { if(data && data.githubToken) { githubToken.value = data.githubToken; } });
df3ecb1bed607ddb551af147d93bb865b4947589
[ "JavaScript", "Markdown" ]
3
JavaScript
GDGNorthAmerica/chrome-extensions-codelab-gdg-oakdale
30977189f206fc749a1d46acea6a537440c10400
8331683129dc6a36c9891c66d974680308e0da47
refs/heads/master
<repo_name>viethungbk/NMCNPM<file_sep>/README.md # NMCNPM(Web bán điện thoại online) <file_sep>/PHONE/application/views/site/product/catalog.php <div class="box-center"><!-- The box-center product--> <div class="tittle-box-center"> <h2><?php echo $catalog->name ?> (<?php echo $total_rows ?> sản phẩm)</h2> </div> <div class="box-content-center product"><!-- The box-content-center --> <?php foreach ($list as $key): ?> <div class='product_item'> <h3> <a href="<?php echo base_url('product/view/'.$key->id) ?>" title="<?php echo $key->name ?>"> <?php echo $key->name ?> </a> </h3> <div class='product_img'> <a href="<?php echo base_url('product/view/'.$key->id) ?>" title="<?php echo $key->name ?>"> <img src="<?php echo base_url('upload/product/'.$key->image_link ) ?>" alt=''/> </a> </div> <p class='price'> <?php if($key->discount > 0): ?> <?php $price_new=$key->price - $key->discount; ?> <?php echo number_format($price_new); ?>đ <span class="price_old"><?php echo number_format($key->price); ?>đ</span> <?php else: ?> <?php echo number_format($key->price); ?>đ <?php endif; ?> </p> <center> <div class='raty' style='margin:10px 0px' id='9' data-score='4'></div> </center> <div class='action'> <p style='float:left;margin-left:10px'>Lượt xem: <b><?php echo $key->view ?></b></p> <a class='button' href="<?php echo base_url('product/view/'.$key->id) ?>" title='Chi tiết'>Chi tiết</a> <div class='clear'></div> </div> </div> <?php endforeach ?> <div class='clear'></div> </div><!-- End box-content-center --> <div class="pagination"> <?php echo $this->pagination->create_links(); ?> </div> </div> <!-- End box-center product--><file_sep>/PHONE/application/controllers/Home.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Home extends MY_Controller { public function __construct() { parent::__construct(); } public function index() { //Lấy danh sách sản phẩm mới $this->load->model('product_model'); $input=array(); $input['limit']=array(3,0); $product_newsest=$this->product_model->get_list($input); $this->data['product_newsest']=$product_newsest; //Lấy danh sách sản phẩm được mua nhiều $input['order']=array('buyed','DESC'); $product_buyest=$this->product_model->get_list($input); $this->data['product_buyest']=$product_buyest; //lay nội dung của biến message $message = $this->session->flashdata('message'); $this->data['message'] = $message; $this->data['temp']='site/home/index'; //biến temp là giao diện của phần nội dung chính sẽ được hiển thị đối với từng page $this->load->view('site/layout', $this->data);//lấy dữ liệu từ MY COntroller rồi lại chuyển từ layout sang left } } /* End of file Home.php */ /* Location: ./application/controllers/Home.php */<file_sep>/PHONE/application/views/site/footer.php <!-- The box-footer--> <!-- Font awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css"> <!-- GG font --> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> <div id="footer_face"> <!-- The footer_face --> <a title="trên facebook" target="_blank" href="https://www.facebook.com/groups/374949286661756/" rel="nofollow"> <img alt="trên facebook" src="<?php echo public_url() ?>site/images/facebook.png"> </a> <a title="trên twitter" target="_blank" href="https://twitter.com/" rel="nofollow"> <img alt="trên twitter" src="<?php echo public_url() ?>site/images/twitter.png"> </a> <a title="trên google" target="_blank" href="https://plus.google.com/" rel="nofollow"> <img alt="trên google" src="<?php echo public_url() ?>site/images/google.png"> </a> </div><!-- End footer_face --> <div class="clear"></div><!-- clear float --> <!-- End box-footer --> <!-- Contact area starts --> <section id="contact" class="contact-area section-big"> <div class="container"> <div class="row"> <div class="col-md-12 text-center"> <div class="section-title"> <h2>Contact Us</h2> </div> </div> </div> <div class="contact-address-box clearfix"> <div class="address"> <div class="address-box clearfix"> <i class="fa fa-home"></i> <p>Số 1 Đại Cồ Việt, Hai Bà Trưng, Hà Nội</p> </div> <div class="address-box clearfix"> <i class="fas fa-mobile-alt"></i> <p><a href="tel:033 999 999">033 999 999 (Mr. Hùng)</a> </div> <div class="address-box clearfix"> <i class="fa fa-envelope"></i> <p><a href="mailto:<EMAIL>"><EMAIL></a> </div> <div class="address-box clearfix"> <i class="fas fa-globe"></i> <p><a href="http://>www.bk.edu.vn">www.bk.edu.vn</a></p> </div> <div class="address-box clearfix"> <i class="fab fa-facebook-f"></i> <p><a href="https://www.facebook.com/">Like our fan page</a></p></p> </div> </div> <div class="contact-form clearfix"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d7449.419253995984!2d105.84151262483981!3d21.00427374404641!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3135ac768ffe1abd%3A0x22b136bcf1c08e2a!2zQsOhY2ggS2hvYSwgSGFpIELDoCBUcsawbmcsIEjDoCBO4buZaQ!5e0!3m2!1svi!2s!4v1545144516522" width="100%" height="100%" frameborder="0" style="border:0" allowfullscreen></iframe> </div> </div><!-- .row --> </div> </section> <!-- Contact area ends --><file_sep>/PHONE/application/controllers/admin/Transaction.php <?php Class Transaction extends MY_Controller { function __construct() { parent::__construct(); //load ra file model $this->load->model('transaction_model'); // Tai cac file thanh phan $this->load->helper('language'); $this->lang->load('admin/transaction'); $this->lang->load('admin/common'); } /* * Hien thi danh sach giao dịch */ function index() { //lay tong so luong ta ca cac giao dich trong websit $total_rows = $this->transaction_model->get_total(); $this->data['total_rows'] = $total_rows; //load ra thu vien phan trang $this->load->library('pagination'); $config = array(); $config['total_rows'] = $total_rows;//tong tat ca cac giao dich tren website $config['base_url'] = admin_url('transaction/index'); //link hien thi ra danh sach giao dich $config['per_page'] = 10;//so luong giao dich hien thi tren 1 trang $config['uri_segment'] = 4;//phan doan hien thi ra so trang tren url $config['next_link'] = 'Trang kế tiếp'; $config['prev_link'] = 'Trang trước'; //khoi tao cac cau hinh phan trang $this->pagination->initialize($config); $segment = $this->uri->segment(4); $segment = intval($segment); $input = array(); $input['limit'] = array($config['per_page'], $segment); //kiem tra co thuc hien loc du lieu hay khong $id = $this->input->get('id'); $id = intval($id); $where = array(); $input['where'] = array(); if($id > 0) { $input['where']['id'] = $id; } //lọc theo thành viên $user = $this->input->get('user'); if($user) { $where['user_id'] = $user; } //lọc theo cổng thanh toán $payment = $this->input->get('payment'); if($payment) { $where['payment'] = $payment; } //lọc theo thời gian $created_to = $this->input->get('created_to'); $created = $this->input->get('created'); if($created && $created_to) { //tiem kiem tu ngay A -> B $time = get_time_between_day($created,$created_to); //nếu dữ liệu trả về hợp lệ if(is_array($time)) { $where['created >='] = $time['start']; $where['created <='] = $time['end']; } } //gắn các điệu điện lọc $input['where'] = $where; //lay danh sach san pha $list = $this->transaction_model->get_list($input); $this->data['list'] = $list; $this->data['filter'] = $input['where']; $this->data['created_to'] = $created_to; $this->data['created'] = $created; //lay nội dung của biến message $message = $this->session->flashdata('message'); $this->data['message'] = $message; //load view $this->data['temp'] = 'admin/transaction/index'; $this->load->view('admin/main', $this->data); } /** * Xem chi tiet giao dich */ function view() { //lay id cua giao dịch ma ta muon xoa $id = $this->uri->rsegment('3'); //lay thong tin cua giao dịch $info = $this->transaction_model->get_info($id); if(!$info) { return false; } $info->_amount = number_format($info->amount); //lấy danh sách đơn hàng của giao dịch này $this->load->model('order_model'); $input = array(); $input['where'] = array('transaction_id' => $id); $orders = $this->order_model->get_list($input); if(!$orders) { return false; } //load model sản phẩm product_model $this->load->model('product_model'); foreach ($orders as $row) { //thông tin sản phẩm $product = $this->product_model->get_info($row->product_id); $product->image = base_url('upload/product/'.$product->image_link); $product->_url_view = site_url('product/view/'.$product->id); $row->_price = number_format($product->price); $row->_amount = number_format($row->amount); $row->product = $product; } $this->data['info'] = $info; $this->data['orders'] = $orders; // Tai file thanh phan $this->load->view('admin/transaction/view', $this->data); } /* * Xoa du lieu */ function del() { $id = $this->uri->rsegment(3); $this->_del($id); //tạo ra nội dung thông báo $this->session->set_flashdata('message', 'không tồn tại giao dịch này'); redirect(admin_url('transaction')); } /* * Xóa nhiều sản phẩm */ function delete_all() { $ids = $this->input->post('ids'); foreach ($ids as $id) { $this->_del($id); } } /* *Xoa san pham */ private function _del($id) { $transaction = $this->transaction_model->get_info($id); if(!$transaction) { //tạo ra nội dung thông báo $this->session->set_flashdata('message', 'không tồn tại giao dịch này'); redirect(admin_url('transaction')); } //thuc hien xoa san pham $this->transaction_model->delete($id); } } <file_sep>/PHONE/application/views/admin/admin/index.php <!-- hiển thị list danh sách admin --> <?php $this->load->view('admin/admin/head'); ?> <div class="line"></div> <div class="wrapper"> <?php $this->load->view('admin/message'); ?> <div class="widget"> <div class="title"> <h6>Danh sách Admin</h6> <div class="num f12">Tổng số: <b><?php echo $total ?></b></div> </div> <table cellpadding="0" cellspacing="0" width="100%" class="sTable mTable myTable withCheck" id="checkAll"> <thead> <tr> <td style="width:80px;">Mã số</td> <td>name</td> <td>username</td> <td style="width:100px;">Hành động</td> </tr> </thead> <tbody> <?php foreach ($list as $key ): ?> <!-- Filter --> <tr> <td class="textC"><?php echo $key->id ?></td> <td> <span class="tipS" original-title="<?php echo $key->name ?>"> <?php echo $key->name ?> </span> </td> <td> <span class="tipS" original-title="<?php echo $key->username ?>"> <?php echo $key->username ?> </span> </td> <td class="option"> <!-- Mỗi lần kick vào nút chỉnh sửa sẽ hiện ra một link phân biệt bởi id --> <a href="<?php echo admin_url('admin/edit/'.$key->id) ?>" class="tipS " original-title="Chỉnh sửa"> <img src="<?php echo public_url() ?>admin/images/icons/color/edit.png"> </a> <a href="<?php echo admin_url('admin/delete/'.$key->id) ?>" class="tipS verify_action" original-title="Xóa"> <img src="<?php echo public_url() ?>admin/images/icons/color/delete.png"> </a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> <div class="clear mt30"></div><file_sep>/PHONE/application/views/admin/message.php <!-- chuyên để hiển thị nội dung thông báo --> <!-- Kiếm tra nếu tồn tại biến $message và biến này có giá trị thì hiện ra dòng thông báo, còn không thì ko có thông báo --> <?php if(isset($message) && $message):?> <div class="nNote nInformation hideit"> <p><strong>THÔNG BÁO: </strong> <?php echo $message ?></p> </div> <?php endif; ?>
eb620e4f71fdaef1ace90a7cbb26b913c3d75626
[ "Markdown", "PHP" ]
7
Markdown
viethungbk/NMCNPM
232ebf2ddfa969c3c37ca3e3686ab78e042f97b4
6efaa6067d66ca451d4d02c83993a28d8d89c68c
refs/heads/master
<file_sep>from os.path import abspath, dirname, join with open(join(dirname(dirname(abspath(__file__))), "VERSION"), encoding='utf-8') as version_file: version = version_file.read().strip() master_doc = 'index' project = "DNS-Lexicon" release = version <file_sep>"""Module provider for IBM Cloud""" from __future__ import absolute_import import json import logging import requests from lexicon.providers.cloudflare import Provider as CloudflareProvider LOGGER = logging.getLogger(__name__) NAMESERVER_DOMAINS = ['cloud.ibm.com'] def provider_parser(subparser): """Return the parser for this provider""" subparser.add_argument( "--auth-token", help="IBM Cloud API key") subparser.add_argument( "--ibm-crn", help="IBM Cloud Internet Services CRN") class Provider(CloudflareProvider): """Provider class for IBM Cloud""" def __init__(self, config): super(Provider, self).__init__(config) self.domain_id = None self.api_endpoint = 'https://api.cis.cloud.ibm.com/v1/{}'.format( self._get_provider_option('ibm_crn').replace('/', '%2F') ) self.ibm_auth_token = self.ibm_get_iamtoken() def ibm_get_iamtoken(self): headers = { "content-type": "application/x-www-form-urlencoded", "accept": "application/json", } params = { "grant_type": "urn:ibm:params:oauth:grant-type:apikey", "apikey": self._get_provider_option('auth_token'), } url = "https://iam.cloud.ibm.com/identity/token" resp = requests.post(url, params, headers=headers, timeout=30) return resp.json()["access_token"] def _request(self, action='GET', url='/', data=None, query_params=None): if data is None: data = {} if query_params is None: query_params = {} default_headers = { 'accept': 'application/json', 'content-type': 'application/json', 'x-auth-user-token': 'Bearer {0}'.format(self.ibm_auth_token) } if not url.startswith(self.api_endpoint): url = self.api_endpoint + url # remove extra parameters data = {k: v for k, v in data.items() if v is not None} response = requests.request(action, url, params=query_params, data=json.dumps(data), headers=default_headers, timeout=30) # if the request fails for any reason, throw an error. response.raise_for_status() return response.json()
c3dc068ae6e233208fe91d7cb751bac38685dc2c
[ "Python" ]
2
Python
drjeep/lexicon
a18a4a325080c2da3e0a0fde4b64385c2de29716
d753ab92b44b2ad8db1d1697f80018b52919f6d3
refs/heads/master
<repo_name>bgyhnddr/vue-block<file_sep>/build/test.js var express = require('express') var config = require('../config') var opn = require('opn') var webpack = require('webpack') var webpackConfig = require('./webpack.test.conf.js') var rm = require('rimraf') var ora = require('ora') var fs = require('fs') // default port where dev server listens for incoming traffic var port = process.env.PORT || config.dev.port var app = express() require('../app/entry')(app) var tests = [] fs.readdirSync('app/module').forEach((f) => { if (fs.existsSync('app/module/' + f + '/test')) { fs.readdirSync('app/module/' + f + '/test').forEach((t) => { tests.push("require('../../app/module/restaurant/test/" + t + "')") }) } }) fs.writeFileSync("test/page/entry.js", tests.join('\n')) var spinner = ora('building for test...') spinner.start() rm('./test/page/dist', err => { if (err) throw err webpack(webpackConfig, function(err, stats) { spinner.stop() if (err) throw err app.use(express.static('./test/page')) app.listen(port, function(err) { if (err) { console.log(err) return } console.log('Listening at http://localhost:' + port + '\n') }) // var uri = 'http://localhost:' + port // opn(uri) // opn(uri + "/upload.html") }) }) <file_sep>/app/init_models.js let fs = require('fs') let models = [] let initModels = (mods) => { mods.forEach((m) => { fs.readdirSync("app/module/" + m + "/server/db/models").forEach((o) => { models.push('./module/' + m + "/server/db/models/" + o) }) }) } module.exports = (types) => { if (!types) { initModels(fs.readdirSync('app/module')) } else { initModels(types) } return Promise.resolve().then(() => { return Promise.all(models.map((o) => { return require(o).sync({ force: true }) })) }).then(function() { console.log("success") }).catch(function(e) { console.log(e) }) } <file_sep>/app/router/index.js import Vue from 'vue' import Router from 'vue-router' import routers from './router' Vue.use(Router) var router = new Router() routers.forEach((o)=>{ o(router) }) export default router <file_sep>/app/module/sys/server/service/public/attachment.js let fs = require('fs') let attachment = require('../../functions/attachment') exports.getAttachment = (req, res) => { return attachment.getAttachment(req.query.attachment_id).then((result) => { let localFile = fs.readFileSync("upload/files/" + result.file_hash, 'binary') res.setHeader('Content-disposition', 'inline; filename=' + encodeURIComponent(result.name)) res.setHeader('Content-Type', result.file.type) res.setHeader('Content-Length', result.file.size) res.write(localFile, 'binary') res.end() }) } exports.uploadFile = (req, res) => { return attachment.uploadFile(req).then((result) => { res.send(result) }) } <file_sep>/build/init_module.js var fs = require('fs') module.exports = () => { fs.readdirSync('app/module').forEach((f) => { if (fs.existsSync('app/module/' + f + '/init.js')) { require('../app/module/' + f + '/init.js')() } }) } <file_sep>/app/module/sys/server/functions/attachment.js let formidable = require('formidable') let util = require('util') let fs = require('fs') let dealFile = (fileInfo) => { var file = require('../db/models/file') var attachment = require('../db/models/attachment') return file.upsert({ hash: fileInfo.hash, size: fileInfo.size, path: "upload/files/" + fileInfo.hash, type: fileInfo.type }).then(() => { return attachment.create({ file_hash: fileInfo.hash, name: fileInfo.name }) }) } exports.getAttachment = (attachment_id) => { return Promise.resolve().then(() => { var id = attachment_id if (id) { var fs = require('fs') var file = require('../db/models/file') var attachment = require('../db/models/attachment') attachment.belongsTo(file) return attachment.findOne({ include: file, where: { id: id } }).then((result) => { if (result != null) { return result } else { return Promise.reject("no file record") } }) } else { return Promise.reject("attachment id not found") } }) } exports.uploadFile = (req) => { return new Promise(function(resolve, reject) { try { if (req.method.toLowerCase() == 'post') { var form = new formidable.IncomingForm(); form.uploadDir = "upload/temp"; form.maxFieldsSize = 2; //10G form.hash = "md5" if (!fs.existsSync("upload")) { fs.mkdirSync("upload") } if (!fs.existsSync("upload/files")) { fs.mkdirSync("upload/files") } if (!fs.existsSync("upload/temp")) { fs.mkdirSync("upload/temp") } form.on('file', function(name, file) { fs.rename(file.path, "upload/files/" + file.hash, function(result) { dealFile(file).then((result) => { resolve(result) }).catch((e)=>{ reject(e) }) }) }) form.on('error', function(err) { console.log('error' + err) reject(err) }) form.parse(req) } else { reject("please post") } } catch (e) { reject("file upload error:" + e.message) } }) } <file_sep>/test/page/entry.js require('../../app/module/restaurant/test/menu.js')<file_sep>/app/router/router.js import sys from '../module/sys/router' export default [sys]
c526be4079ca46a2b9ed33570d189b24f36eb3b0
[ "JavaScript" ]
8
JavaScript
bgyhnddr/vue-block
1074a64461b602bf423f3757401be03462c91f10
e5d51bed5dbdc7b19a50538ae1c0240d18b7c299
refs/heads/master
<file_sep>-- MySQL Script generated by MySQL Workbench -- 04/18/15 10:16:41 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering -- ----------------------------------------------------- -- Schema DELTAPLUS Creation -- ----------------------------------------------------- CREATE DATABASE deltaplus; CREATE USER 'nfcdelta'@'localhost' IDENTIFIED BY '<PASSWORD>'; GRANT ALL PRIVILEGES ON deltaplus.* TO 'deltaplus'@'localhost'; FLUSH PRIVILEGES; -- ----------------------------------------------------- -- Table DELTA_USER -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS DELTAPLUS_USER( USER_ID INT(11) NOT NULL AUTO_INCREMENT, EMAIL VARCHAR(100) DEFAULT NULL, LOGIN VARCHAR(100) DEFAULT NULL, PASSWORD VARCHAR(100) DEFAULT NULL, FIRST_NAME VARCHAR(30) DEFAULT NULL, LAST_NAME VARCHAR(30) DEFAULT NULL, COMPANY VARCHAR(100) DEFAULT NULL, USER_TYPE INT(1) DEFAULT NULL, CREATE_DATE DATE DEFAULT NULL, LAST_UPDATE_DATE DATE DEFAULT NULL, PRIMARY KEY (USER_ID), UNIQUE INDEX EMAIL_UNIQUE (EMAIL ASC), UNIQUE INDEX LOGIN_UNIQUE (LOGIN ASC)) ENGINE = InnoDB DEFAULT CHARSET = utf8; -- ----------------------------------------------------- -- Table mydb.DELTA_PRODUCT -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS DELTAPLUS_PRODUCT( ID INT(11) NOT NULL AUTO_INCREMENT, PRODUCT VARCHAR(10) DEFAULT NULL, SERIAL VARCHAR(12) DEFAULT NULL, USERNAME VARCHAR(15) DEFAULT NULL, PROD_DATE VARCHAR(10) DEFAULT NULL, START_DATE VARCHAR(10) DEFAULT NULL, SAV1 VARCHAR(10) DEFAULT NULL, SAV2 VARCHAR(10) DEFAULT NULL, SAV3 VARCHAR(10) DEFAULT NULL, SAV4 VARCHAR(10) DEFAULT NULL, SAV5 VARCHAR(10) DEFAULT NULL, IS_DELETED INT(1) DEFAULT NULL, CREATE_DATE DATE DEFAULT NULL, LAST_UPDATE_DATE DATE DEFAULT NULL, DELTA_USER_ID INT(11) NOT NULL, PRIMARY KEY (ID), INDEX FK_USER_IDX (DELTA_USER_ID ASC), CONSTRAINT FK_USER FOREIGN KEY (DELTA_USER_ID) REFERENCES DELTAPLUS_USER (USER_ID)) ENGINE = InnoDB DEFAULT CHARSET = utf8; <file_sep>//global setting $.mobile.defaultPageTransition = 'flip'; // AWS Server //var web_server = "http://172.16.31.10/nfc_deltaweb"; //var web_index = "http://172.16.31.10/nfc_deltaweb/mindex.php"; // Local Host //var web_server = "http://localhost/nfc_deltaweb"; // var web_index = "https://www.deltaplus.eu/en_US/annual-check-service"; // var web_index = "https://www.deltaplus.eu/en_US"; var web_index = "https://www.deltaplus.eu/verification-antichute"; // Development Environment //var web_server_delta = "http://172.17.17.140:8080/api/jsonws/deltaplus-deltaweb-annualCheck-portlet.annualcheckuseraccount"; //var web_server_delta = "https://www.deltaplus.eu/api/jsonws/deltaplus-deltaweb-annualCheck-portlet.annualcheckuseraccount"; //Production Environment var web_server_delta = "https://www.deltaplus.eu/api/jsonws/deltaplus-deltaweb-annualCheck-portlet.annualcheckuseraccount/"; var web_server_equipment = "https://www.deltaplus.eu/api/jsonws/deltaplus-deltaweb-annualCheck-portlet.equipment/"; var liferaywsUserAdmin = "annualcheckserviceadmin"; var liferaywsPasswordAdmin = "<PASSWORD>"; // app maintenance flag var version_maintenance = false; //global varity var ifTagFound = false, ifEmpytyTag = false, isRead = true, isNfcEnable = false, hasViewMyPro = true, ifRegisteError = false, nfcData = [ '', //product '', //serial '', //user '', //prod. '', //start '', //sav1 '', //sav2 '', //sav3 '', //sav4 '', //sav5 '0' //if first use 0:new ], message, timeoutId, tagId, myAlert = function (key, param, callback) { var fun = callback ? callback : function () { }, msg = window.i18n[window.localStorage['language']][key]; if (!msg) { msg = key; } if (param) { for (var i in param) { if (window.i18n[window.localStorage['language']][param[i]]) msg = msg.replace("{" + i + "}", window.i18n[window.localStorage['language']][param[i]]); else msg = msg.replace("{" + i + "}", param[i]); } } navigator.notification.alert(msg, fun, window.i18n[window.localStorage['language']]['alert'], window.i18n[window.localStorage['language']]['ok']); }, myConfirm = function (key, param, callback) { var fun = callback ? callback : function () { }, msg = window.i18n[window.localStorage['language']][key]; if (param) { for (var i in param) { msg = msg.replace("{" + i + "}", param[i]); } } navigator.notification.confirm(msg, fun, window.i18n[window.localStorage['language']]['confirmMsg'], [window.i18n[window.localStorage['language']]['ok'], window.i18n[window.localStorage['language']]['cancel']]); }, callBackGroup = { tagRead: { mimeCallBack: function (nfcEvent) { var tag = nfcEvent.tag, ndefMessage = tag.ndefMessage; tagId = nfc.bytesToHexString(tag.id); console.log(tagId); nfcData = nfc.bytesToString(ndefMessage[0].payload).split('~'); if (nfcData.length != 11) { nfcData = [ '', //product '', //serial '', //user '', //prod. '', //start '', //sav1 '', //sav2 '', //sav3 '', //sav4 '', //sav5 '0' //if first use 0:new ]; message = [ ndef.mimeMediaRecord('mime/com.softtek.delta', nfc.stringToBytes(nfcData.join("~"))), ndef.uriRecord("http://www.deltaplus.eu") ]; nfc.write(message, function () { }, function (error) { // todo there is some random error when saving data into card, eg. if you move card during writing process. myAlert('appError', error); }); myAlert('dataFomatNotRight', [nfc.bytesToHexString(tag.id)]); return; } clearTimeout(timeoutId); scan_next(1, 4); if (nfcData[1] === "" || nfcData[1] == null) { ifEmpytyTag = true; } else { ifEmpytyTag = false; } setTimeout(function () { $('.scan_step2 input[name="product"]').val(nfcData[0]); $('.scan_step2 input[name="serial"]').val(nfcData[1]); $('.scan_step2 input[name="user"]').val(getStringFromCharCode(nfcData[2])); $('.scan_step2 input[name="prod"]').val(nfcData[3]); $('.scan_step2 input[name="start"]').val(nfcData[4]); $('.scan_step2 input[name="sav1"]').val(nfcData[5]); $('.scan_step2 input[name="sav2"]').val(nfcData[6]); $('.scan_step2 input[name="sav3"]').val(nfcData[7]); $('.scan_step2 input[name="sav4"]').val(nfcData[8]); $('.scan_step2 input[name="sav5"]').val(nfcData[9]); $('.scan_step2 input[name="product"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="serial"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="user"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="prod"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="start"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav1"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav2"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav3"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav4"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav5"]').attr('disabled', 'disabled'); $(".scan_step2_btn").hide(); $(".scan_read_btn").show(); $.mobile.navigate('#scan_read'); $('#scan_read').attr("class", "basic container"); showClearReadInput(); }, 2000); mimeCallBack = function () { }; tagCallBack = function () { }; }, mimeSuccessCallBack: function () { }, tagCallBack: function (nfcEvent) { clearTimeout(timeoutId); var tag = nfcEvent.tag; tagId = nfc.bytesToHexString(tag.id); if (!tag.ndefMessage) { nfcData = ['', '', '', '', '', '', '', '', '', '', '0']; scan_next(1, 4); ifEmpytyTag = true; } ; setTimeout(function () { $('.scan_step2 input[name="product"]').val(nfcData[0]); $('.scan_step2 input[name="serial"]').val(nfcData[1]); $('.scan_step2 input[name="user"]').val(getStringFromCharCode(nfcData[2])); $('.scan_step2 input[name="prod"]').val(nfcData[3]); $('.scan_step2 input[name="start"]').val(nfcData[4]); $('.scan_step2 input[name="sav1"]').val(nfcData[5]); $('.scan_step2 input[name="sav2"]').val(nfcData[6]); $('.scan_step2 input[name="sav3"]').val(nfcData[7]); $('.scan_step2 input[name="sav4"]').val(nfcData[8]); $('.scan_step2 input[name="sav5"]').val(nfcData[9]); $('.scan_step2 input[name="product"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="serial"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="user"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="prod"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="start"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav1"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav2"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav3"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav4"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav5"]').attr('disabled', 'disabled'); $(".scan_step2_btn").hide(); $(".scan_read_btn").show(); $.mobile.navigate('#scan_read'); showClearReadInput(); }, 2000); mimeCallBack = function () { }; tagCallBack = function () { }; }, tagSuccessCallBack: function () { } }, tagWrite: { mimeCallBack: function (nfcEvent) { clearTimeout(timeoutId); var newTagId = nfc.bytesToHexString(nfcEvent.tag.id); if (tagId === newTagId) { nfc.write(message, function () { scan_next(3, 4); writeCardInforToDB(); hasViewMyPro = false; }, function (error) { myAlert('appError', [error]); $.mobile.navigate('#scan'); }); mimeCallBack = function () { }; tagCallBack = function () { }; } else { isNfcEnable = false; scan_next(3, 3); myAlert('useSameIdCard'); } }, mimeSuccessCallBack: function () { }, tagCallBack: function (nfcEvent) { clearTimeout(timeoutId); var newTagId = nfc.bytesToHexString(nfcEvent.tag.id); if (tagId === newTagId) { nfc.write(message, function () { scan_next(3, 4); writeCardInforToDB(); hasViewMyPro = false; }, function (error) { myAlert('appError', [error]); $.mobile.navigate('#scan'); }); mimeCallBack = function () { }; tagCallBack = function () { }; } else { isNfcEnable = false; scan_next(3, 3); myAlert('useSameIdCard'); } }, tagSuccessCallBack: function () { } } }, mimeCallBack = function (nfcEvent) { //alert("in mimeCallBack isNfcEnable = " + isNfcEnable + " isRead=" + isRead); if (isNfcEnable) { if (isRead) { callBackGroup.tagRead.mimeCallBack(nfcEvent); } else { callBackGroup.tagWrite.mimeCallBack(nfcEvent); } isNfcEnable = false; } }, mimeSuccessCallBack = function () { }, tagCallBack = function (nfcEvent) { if (isNfcEnable) { if (isRead) { callBackGroup.tagRead.tagCallBack(nfcEvent); } else { callBackGroup.tagWrite.tagCallBack(nfcEvent); } isNfcEnable = false; } }, tagSuccessCallBack = function () { }; //go to next step in scan phase function scan_next(stepId, subStepId) { 'use strict'; switch (stepId) { case 1: switch (subStepId) { case 1: $('.scan_step1_1').hide(); $('.scan_step1_2').fadeIn(); break; case 2: $('.scan_step1_2').hide(); $('.scan_step1_3').fadeIn(); break; case 3: $('.scan_step1_3').hide(); $('.scan_step1_2').fadeIn(); break; case 4: $('.scan_step1_2').hide(); $('.scan_step1_4').fadeIn(); break; } ; break; case 2: $('.scan_step1').hide(); $('.scan_step1_3').hide(); $('.scan_step1_4').hide(); $('.scan_step2').fadeIn(); break; case 3: switch (subStepId) { case 1: $(".scan_step2").hide(); $(".scan_step3").show(); $(".scan_step3_1").show(); break; case 2: $(".scan_step3_3").hide(); $(".scan_step3_2").fadeIn(); break; case 3: $(".scan_step3_2").hide(); $(".scan_step3_3").fadeIn(); break; case 4: $(".scan_step3_2").hide(); $(".scan_step3_4").fadeIn(); break; case 5: $(".scan_step3_1").hide(); $(".scan_step3_2").fadeIn(); break; } ; break; } } //click to show detail function showProductDetail(data) { $('.myproducts_detail_form input[name="product"]').val(data.product); $('.myproducts_detail_form input[name="serial"]').val(data.serial); $('.myproducts_detail_form input[name="user"]').val(data.user); $('.myproducts_detail_form input[name="prod"]').val(data.prod); $('.myproducts_detail_form input[name="start"]').val(data.start); $('.myproducts_detail_form input[name="sav1"]').val(data.sav1); $('.myproducts_detail_form input[name="sav2"]').val(data.sav2); $('.myproducts_detail_form input[name="sav3"]').val(data.sav3); $('.myproducts_detail_form input[name="sav4"]').val(data.sav4); $('.myproducts_detail_form input[name="sav5"]').val(data.sav5); $.mobile.navigate("#myproducts_detail"); } //refresh local data function refreshLocalData(cardInforList, ifShowUpdate) { var temp = [ '<tr>', '<th width="10%" style="{color}">{id}.</th>', '<td width="40%" class="productList_bac">{product}</td>', '<td width="40%" class="productList_bac">{serial}</td>', '<td width="10%" class="productList_view" id="{serial}"><span class="glyphicon glyphicon-search"></span></td>', '</tr>' ], content = ""; if (ifShowUpdate) { for (var i in cardInforList) { if (window.currentUpdatedRecordId === cardInforList[i].serial) { content = content + temp.join("").replace("{id}", parseInt(i) + 1).replace("{product}", cardInforList[i].product).replace(/{serial}/g, cardInforList[i].serial).replace("{color}", "color:red;"); } else { content = content + temp.join("").replace("{id}", parseInt(i) + 1).replace("{product}", cardInforList[i].product).replace(/{serial}/g, cardInforList[i].serial); } } } else { for (var i in cardInforList) { content = content + temp.join("").replace("{id}", parseInt(i) + 1).replace("{product}", cardInforList[i].product).replace(/{serial}/g, cardInforList[i].serial); } } $(".productList tbody").html(content); $('.productList .productList_view').on('touchend', function () { readCradInforWithId($(this).attr('id')); }); $.mobile.navigate('#myproducts'); } //registe mime type listener function registeMimeTypeListener(callback, success) { window.localStorage.clear(); navigator.globalization.getPreferredLanguage( function (language) { //navigator.notification.alert('language 1: ' + language.value + '\n'); var lang = language.value.split('-'); // navigator.notification.alert('language 2: ' + lang[0] + '\n'); if (lang != null && (lang[0] == 'en' || lang[0] == 'zh' || lang[0] == 'sp' || lang[0] == 'fr')) { window.localStorage['language'] = lang[0]; // navigator.notification.alert('language 3: ' + window.localStorage['language'] + '\n'); } var language = window.localStorage['language']; // navigator.notification.alert('language 4: ' + window.localStorage['language'] + '\n'); language = language ? language : 'en'; window.localStorage['language'] = language; //navigator.notification.alert('language 5: ' + window.localStorage['language'] + '\n'); updateLanguage(language); }, function () { window.localStorage['language'] = 'en'; updateLanguage(language); //navigator.notification.alert('Error getting language\n'); }); nfc.addMimeTypeListener('mime/com.softtek.delta', callback, success, function (error) { // error callback ifRegisteError = true; var msg = JSON.stringify(error); if (msg === '"NFC_DISABLED"') { myAlert('nfcDisabled'); } else { myAlert("initAppFailed", [JSON.stringify(error)]); } } ); } //registe tag listener function registeTagListener(callback, success) { if (!ifRegisteError) { nfc.addTagDiscoveredListener( callback, success, function (error) { // error callback // alert("Error adding TAG listener, reason: " + JSON.stringify(error)); myAlert("appError", [JSON.stringify(error)]); } ); } } //write database function writeCardInforToDB(ifAddIdOnly) { nfcData[0] = $('.scan_step2 input[name="product"]').val(); nfcData[1] = $('.scan_step2 input[name="serial"]').val(); nfcData[2] = $('.scan_step2 input[name="user"]').val(); nfcData[3] = $('.scan_step2 input[name="prod"]').val(); nfcData[4] = $('.scan_step2 input[name="start"]').val(); nfcData[5] = $('.scan_step2 input[name="sav1"]').val(); nfcData[6] = $('.scan_step2 input[name="sav2"]').val(); nfcData[7] = $('.scan_step2 input[name="sav3"]').val(); nfcData[8] = $('.scan_step2 input[name="sav4"]').val(); nfcData[9] = $('.scan_step2 input[name="sav5"]').val(); var db = openDatabase('deltaplus', '1.0', 'deltaplus', 5 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS cardInfor(product,serial,user,prod,start,sav1,sav2,sav3,sav4,sav5,ifFirst,ifDelete,equipmentId)'); tx.executeSql('SELECT * FROM cardInfor WHERE serial = ?', [nfcData[1]], function (tx, re) { if (re.rows.length == 0) { tx.executeSql('INSERT INTO cardInfor VALUES(?,?,?,?,?,?,?,?,?,?,?,"0",NULL)', nfcData); } else { tx.executeSql('UPDATE cardInfor SET product=?,user=?,prod=?,start=?,sav1=?,sav2=?,sav3=?,sav4=?,sav5=?,ifDelete="0" WHERE serial = ?', [nfcData[0], nfcData[2], nfcData[3], nfcData[4], nfcData[5], nfcData[6], nfcData[7], nfcData[8], nfcData[9], nfcData[1]]); } }); if (ifAddIdOnly) { myAlert('addIdToMyProduct', null, function () { readCardInforListFromDB(); }); } }); } //read database function readCardInforListFromDB(ifShowUpdate) { var db = openDatabase('deltaplus', '1.0', 'deltaplus', 5 * 1024 * 1024), result = []; db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS cardInfor(product,serial,user,prod,start,sav1,sav2,sav3,sav4,sav5,ifFirst,ifDelete,equipmentId)') tx.executeSql("SELECT * FROM cardInfor WHERE ifDelete ='0'", [], function (tx, re) { for (var i = 0; i < re.rows.length; i++) { result[i] = {}; result[i].product = re.rows.item(i).product; result[i].serial = re.rows.item(i).serial; } refreshLocalData(result, ifShowUpdate); }); }); } //delete record function deleteRecordFromDB(serial) { var db = openDatabase('deltaplus', '1.0', 'deltaplus', 5 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql('UPDATE cardInfor SET ifDelete = "1" WHERE serial = ?', [serial], function (tx, re) { readCardInforListFromDB(); //$.mobile.back(); }); }); } //read database with id function readCradInforWithId(id) { var db = openDatabase('deltaplus', '1.0', 'deltaplus', 5 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql('SELECT * FROM cardInfor WHERE serial = ?', [id], function (tx, re) { showProductDetail(re.rows.item(0)); }); }); } //update language function updateLanguage(language) { if (window.i18n && window.i18n[language]) { for (var key in window.i18n[language]) { $('.i_' + key).html(window.i18n[language][key]); } } } function isAlphanumeric(obj) { reg = /[A-Za-z0-9/._-]+$/; if (!reg.test(obj)) { return false; } return true; } function isChinese(obj) { //reg=/^[\u4E00-\u9FA5]+$/; // GBK reg = /^[\u3400-\u9FBF]+$/; //UTF-8 if (!reg.test(obj)) { return false; } return true; } //form validation function validateForm() { var product = $('.scan_step2 input[name="product"]').val().replace(/ $/g, '').replace(/^ /g, ''), serial = $('.scan_step2 input[name="serial"]').val().replace(/ $/g, '').replace(/^ /g, ''), user = $('.scan_step2 input[name="user"]').val().replace(/ $/g, '').replace(/^ /g, ''), start = $('.scan_step2 input[name="start"]').val(); $('.scan_step2 input[name="product"]').val(product); $('.scan_step2 input[name="serial"]').val(serial) $('.scan_step2 input[name="user"]').val(user) if (product === "") { myAlert('productFieldEmpty'); return false; } if (product.length > 10) { myAlert('productMaxLength'); $('.scan_step2 input[name="product"]').val(""); $('.scan_step2 input[name="product"]').focus(); return false; } else if (!isAlphanumeric(product)) { myAlert('invalidInput', ['Product']); $('.scan_step2 input[name="product"]').val(""); $('.scan_step2 input[name="product"]').focus(); return false; } if (serial === "") { myAlert('serialFieldEmpty'); return false; } if (serial.length > 12) { myAlert('serialMaxLength'); $('.scan_step2 input[name="serial"]').val(""); $('.scan_step2 input[name="serial"]').focus(); return false; } else if (!isAlphanumeric(serial)) { myAlert('invalidInput', ['ID']); $('.scan_step2 input[name="serial"]').val(""); $('.scan_step2 input[name="serial"]').focus(); return false; } if (user.length > 15) { myAlert('userMaxLength'); $('.scan_step2 input[name="user"]').val(""); $('.scan_step2 input[name="user"]').focus(); return false; } if (start == "" && user != "") { myAlert('beforeAddFirstUseDate'); return false; } if (!isAlphanumeric(user)) { if (!isChinese(user)) { myAlert('invalidInput', ['User']); $('.scan_step2 input[name="user"]').val(""); $('.scan_step2 input[name="user"]').focus(); return false; } else { if (user.length > 3) { myAlert('userMaxLength'); $('.scan_step2 input[name="user"]').val(""); $('.scan_step2 input[name="user"]').focus(); return false; } } } return true; } //for language function initLanguageSelection() { var language = window.localStorage['language']; console.log('current lang ' + language); language = language ? language : 'en'; if (language == 'en') { $('input[name="changeLang"]:eq(0)')[0].checked = true; } else if (language == 'zh') { $('input[name="changeLang"]:eq(1)')[0].checked = true; } else if (language == 'fr') { $('input[name="changeLang"]:eq(2)')[0].checked = true; } else if (language == 'sp') { $('input[name="changeLang"]:eq(3)')[0].checked = true; } $('input[name="changeLang"]').checkboxradio("refresh"); } function changeLanguage() { var index = $('input[name="changeLang"]').index($(this)), lang = ''; console.log('language index = ', index); if (index == 0) { lang = 'en'; } else if (index == 1) { lang = 'zh'; } else if (index == 2) { lang = 'fr'; } else if (index == 3) { lang = 'sp'; } window.localStorage['language'] = lang; updateLanguage(lang); } //for synchronize function make_base_auth(user, password) { var token = user + ":" + password; var hash = btoa(token); return "Basic " + hash; } function prepareSendingData() { var loader = showLoading('Loading'), db = openDatabase('deltaplus', '1.0', 'deltaplus', 5 * 1024 * 1024), result = []; var liferaywsUser = window.localStorage['username']; var liferaywsPassword = window.localStorage['password']; db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS cardInfor(product,serial,user,prod,start,sav1,sav2,sav3,sav4,sav5,ifFirst,ifDelete,equipmentId)'); tx.executeSql('SELECT * FROM cardInfor ', [], function (tx, re) { for (var i = 0; i < re.rows.length; i++) { result[i] = {}; result[i].reference = re.rows.item(i).product; result[i].lotnumber = re.rows.item(i).serial; result[i].username = re.rows.item(i).user; result[i].manufacturingdate = re.rows.item(i).prod; result[i].firstcommissioningdate = re.rows.item(i).start; result[i].controlDate1 = re.rows.item(i).sav1; result[i].controlDate2 = re.rows.item(i).sav2; result[i].controlDate3 = re.rows.item(i).sav3; result[i].controlDate4 = re.rows.item(i).sav4; result[i].controlDate5 = re.rows.item(i).sav5; result[i].ifDelete = re.rows.item(i).ifDelete; result[i].equipmentId = re.rows.item(i).equipmentId; console.log('equipmentId ' + result[i].equipmentId + ' serial id: ' + result[i].lotnumber) // myAlert('equipmentId ' + result[i].equipmentId + ' serial id: ' + result[i].lotnumber); } for (var j = 0; j < result.length; j++) { //if(true) { // myAlert('equipmentId ' + result[j].equipmentId + ' serial id: ' + result[j].lotnumber); if (result[j].equipmentId == null || result[j].equipmentId == '') { var manufactureDate = getDateFromStr(result[j].manufacturingdate); var firstcommissioningdate = getDateFromStr(result[j].firstcommissioningdate); var controlDate1 = getDateFromStr(result[j].controlDate1); var controlDate2 = getDateFromStr(result[j].controlDate2); var controlDate3 = getDateFromStr(result[j].controlDate3); var controlDate4 = getDateFromStr(result[j].controlDate4); var controlDate5 = getDateFromStr(result[j].controlDate5); var parameters = 'reference=' + result[j].reference + '&brand=' + 'DELTAPLUS' + '&designation=' + 'DeltaPlus' + '&description' + '&lotNumber=' + result[j].lotnumber + '&userName=' + result[j].username + '&retailerName=' + 'DELTAPLUS' + '&retailerParticulars=' + 'DELTAPLUS China' + '&observation' + '&manufacturingMonth=' + getMonth(manufactureDate) + '&manufacturingDay=' + getDate(manufactureDate) + '&manufacturingYear=' + getYear(manufactureDate) + '&firstUsageMonth=' + getMonth(firstcommissioningdate) + '&firstUsageDay=' + getDate(firstcommissioningdate) + '&firstUsageYear=' + getYear(firstcommissioningdate) + '&lastcontrolDateMonth=' + 0 + '&lastcontrolDateDay=' + 0 + '&lastcontrolDateYear=' + 0 + '&control1DateMonth=' + getMonth(controlDate1) + '&control1DateDay=' + getDate(controlDate1) + '&control1DateYear=' + getYear(controlDate1) + '&control2DateMonth=' + getMonth(controlDate2) + '&control2DateDay=' + getDate(controlDate2) + '&control2DateYear=' + getYear(controlDate2) + '&control3DateMonth=' + getMonth(controlDate3) + '&control3DateDay=' + getDate(controlDate3) + '&control3DateYear=' + getYear(controlDate3) + '&control4DateMonth=' + getMonth(controlDate4) + '&control4DateDay=' + getDate(controlDate4) + '&control4DateYear=' + getYear(controlDate4) + '&control5DateMonth=' + getMonth(controlDate5) + '&control5DateDay=' + getDate(controlDate5) + '&control5DateYear=' + getYear(controlDate5); $.ajax({ type: 'POST', url: web_server_equipment + "create-equipment", contentType: 'application/x-www-form-urlencoded;charset=UTF-8', dataType: 'json', data: parameters, beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", make_base_auth(liferaywsUser, liferaywsPassword)); }, success: function (data, status) { console.log('created one equipment successfully') if (typeof data.equipmentId !== 'undefined') { // TODO: Uncaught InvalidStateError: Failed to execute 'executeSql' on 'SQLTransaction': SQL execution is disallowed. /* tx.executeSql('UPDATE cardInfor SET equipmentId=? WHERE product=? AND serial=? ', [data.equipmentId, data.reference, data.lotnumber], transactionSuccess, errorHandler); */ // Workaround for above issue, to re-open db connection db.transaction(function (tx) { tx.executeSql('UPDATE cardInfor SET equipmentId=? WHERE product=? AND serial=? ', [data.equipmentId, data.reference, data.lotnumber], transactionSuccess, errorHandler); }); } else { // myAlert('No equipment id returned !!!'); //todo: handle failed equipment creation. } }, error: function (m1, m2, m3) { //myAlert("Error Web Services status " + m2 + " Exception " + m3); myAlert("appError", [m3]); } }); } else { var manufactureDate = getDateFromStr(result[j].manufacturingdate); var firstcommissioningdate = getDateFromStr(result[j].firstcommissioningdate); var controlDate1 = getDateFromStr(result[j].controlDate1); var controlDate2 = getDateFromStr(result[j].controlDate2); var controlDate3 = getDateFromStr(result[j].controlDate3); var controlDate4 = getDateFromStr(result[j].controlDate4); var controlDate5 = getDateFromStr(result[j].controlDate5); var deleteFlag = result[j].ifDelete == 1 ? true : false; var parameters = 'equipmentId=' + result[j].equipmentId + '&reference=' + result[j].reference + '&brand=' + 'DELTAPLUS' + '&designation=' + 'DeltaPlus' + '&description' + '&lotNumber=' + result[j].lotnumber + '&userName=' + result[j].username + '&retailerName=' + 'DELTAPLUS' + '&retailerParticulars=' + 'DELTAPLUS China' + '&observation' + '&manufacturingMonth=' + getMonth(manufactureDate) + '&manufacturingDay=' + getDate(manufactureDate) + '&manufacturingYear=' + getYear(manufactureDate) + '&firstUsageMonth=' + getMonth(firstcommissioningdate) + '&firstUsageDay=' + getDate(firstcommissioningdate) + '&firstUsageYear=' + getYear(firstcommissioningdate) + '&lastcontrolDateMonth=' + 0 + '&lastcontrolDateDay=' + 0 + '&lastcontrolDateYear=' + 0 + '&delete=' + deleteFlag.toString() + // '&delete=false' + '&control1DateMonth=' + getMonth(controlDate1) + '&control1DateDay=' + getDate(controlDate1) + '&control1DateYear=' + getYear(controlDate1) + '&control2DateMonth=' + getMonth(controlDate2) + '&control2DateDay=' + getDate(controlDate2) + '&control2DateYear=' + getYear(controlDate2) + '&control3DateMonth=' + getMonth(controlDate3) + '&control3DateDay=' + getDate(controlDate3) + '&control3DateYear=' + getYear(controlDate3) + '&control4DateMonth=' + getMonth(controlDate4) + '&control4DateDay=' + getDate(controlDate4) + '&control4DateYear=' + getYear(controlDate4) + '&control5DateMonth=' + getMonth(controlDate5) + '&control5DateDay=' + getDate(controlDate5) + '&control5DateYear=' + getYear(controlDate5); $.ajax({ type: 'POST', url: web_server_equipment + "/update-equipment", contentType: 'application/x-www-form-urlencoded;charset=UTF-8', dataType: 'json', data: parameters, beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", make_base_auth(liferaywsUser, liferaywsPassword)); }, success: function (data, status) { // myAlert(JSON.stringify(data) + ' status ' + status); if (typeof data.equipmentId !== 'undefined') { // myAlert('uploadSuccessfully'); } else { //todo: handle failed equipment creation. // myAlert('No success returns'); } }, error: function (m1, m2, m3) { myAlert("Error Web Services status " + m2 + " Exception " + m3); myAlert("appError", [m3]); } }); } } loader.hide(); myAlert('uploadSuccessfully'); }); /*remove the deleted records after sync from remote server*/ tx.executeSql('DELETE FROM cardInfor WHERE ifDelete = ?', ["1"], function (tx, re) { console.log("delete row count is ", re.rows.length); }); }); } function transactionSuccess(transaction, results) { //todo handle DB transaction success // myAlert("successful DB transaction: "); console.log('update successfully') } function errorHandler(transaction, error) { console.log('update failed') // myAlert("failure DB transaction: " + JSON.stringify(error)); // todo handler error message for DB transactions. if (error.code === 1) { // DB Table already exists // alert("Table already exists"); } else { // Error is a human-readable string. // alert('Oops. Error was '+error.message+' (Code '+ error.code +')'); } return false; } function updateReceivingData(data) { try { var db = openDatabase('deltaplus', '1.0', 'deltaplus', 5 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS cardInfor(product,serial,user,prod,start,sav1,sav2,sav3,sav4,sav5,ifFirst,ifDelete,equipmentId)'); for (var i in data) { console.log('equipmentId ' + data[i].equipmentId + ' serial id: ' + data[i].lotnumber); (function (item) { // var item = data[i]; tx.executeSql('SELECT * FROM cardInfor WHERE serial = ?', [item.lotnumber], function (tx, re) { if (re.rows.length == 0) { try { tx.executeSql('INSERT INTO cardInfor VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)', [item.reference, item.lotnumber, item.username, getFullDate(item.manufacturingdate), getFullDate(item.firstcommissioningdate), getFullDate(item.controlDate1), getFullDate(item.controlDate2), getFullDate(item.controlDate3), getFullDate(item.controlDate4), getFullDate(item.controlDate5), 1, "0", item.equipmentId ], transactionSuccess, errorHandler); } catch (err) { console.log(err); } } else { tx.executeSql('UPDATE cardInfor SET ifDelete="0", ' + ' product=?,user=?,prod=?,start=?,sav1=?,sav2=?,sav3=?,sav4=?,sav5=? ' + ' WHERE serial = ?', [item.reference, item.username, getFullDate(item.manufacturingdate), getFullDate(item.firstcommissioningdate), getFullDate(item.controlDate1), getFullDate(item.controlDate2), getFullDate(item.controlDate3), getFullDate(item.controlDate4), getFullDate(item.controlDate5), item.lotnumber ], transactionSuccess, errorHandler); } }); })(data[i]); } myAlert('importSuccessfully'); }); } catch (err) { console.log(err); return false; } return true; } /* get char code from string */ function getCharCodeFromString(str) { if (isChinese(str)) { var res = []; for (var i = 0; i < str.length; i++) { res.push(str.charCodeAt(i)); } ; return res.join('.'); } else { return str; } } function getStringFromCharCode(str) { var res = "", arr = str.split("."); for (var i = 0; i < arr.length; i++) { res = res + String.fromCharCode(arr[i]); } if (isChinese(res)) { return res; } else { return str; } } /* end */ function clearReadInput(e) { var obj = e.target; var element = $(obj).parent().find('input'); var answer; if (element.val() != "") { /* if (myConfirm('ifDelete')) { element.val(''); }*/ myConfirm('ifDelete', null, function (index) { //alert("comfirmation choose:" + index); if (index == 1) { element.val(''); } }); } } /** * show clear read input for scan_read */ function showClearReadInput() { var clearBtns = $(".scan_step2 form").find("span"); clearBtns.each(function () { var input = $(this).parent().find('input'); if (!input[0].disabled) { $(this).show(); } else { $(this).hide(); } }); } /** * for date picker */ function confirmToSelectDate() { var selectedMonth = parseInt($("select[name='month_tobe_selected']").val()), selectedYear = parseInt($("select[name='year_tobe_selected']").val()); // todo: have to append 15 as date, otherwise, the remote will give error. // var value = "15/" + selectedMonth + "/" + selectedYear; var value = selectedMonth + "/" + selectedYear; //alert("confirmToSelectDate" + value); if (window.currentDateName === "start") { var proDate = $('.scan_step2 input[name="prod"]').val().split("/"); if (selectedYear < parseInt(proDate[1]) || (selectedYear == parseInt(proDate[1]) && selectedMonth < parseInt(proDate[0]))) { myAlert('beforeProductDate'); return false; } if (myConfirm('addFirstUseDate')) { $(".scan_step2 input[name='" + window.currentDateName + "']").val(value); $("#date_picker").popup('close'); } ; } //alert("selected date = " + value); $(".scan_step2 input[name='" + window.currentDateName + "']").val(value); $("#date_picker").popup('close'); } /** * for date picker end */ $(".btn_confirmSelectDate").on('click', confirmToSelectDate); $(".glyphicon-remove").on('click', function (e) { clearReadInput(e); }); $('input[name="changeLang"]').change(changeLanguage); //initialize position var bodyHeight = $('body').height(), baseCount = bodyHeight / 640; $('body').css('font-size', 0.8 * baseCount * 100 + '%'); $('.productList').css('height', bodyHeight * 0.45); //myproducts height $('.scan_step1_2_instruction').css('height', bodyHeight * 0.25); $('.productList_table').css('height', bodyHeight * 0.55); $('.btn_back,.btn_home,.btn_set').css('font-size', bodyHeight * 0.08); $('.btn_webhome').css('height', bodyHeight * 0.1).css('margin-left', bodyHeight * 0.02) .css('margin-top', bodyHeight * 0.02); $('.form-control,.form-control[disabled]').css('height', bodyHeight * 0.04); $('.little,.little[disabled]').css('height', bodyHeight * 0.04); $('.user_login_form').css('height', bodyHeight * 0.2); $('.scan_step3_1,.scan_step3_2,.scan_step3_3,.scan_step3_4').css('top', bodyHeight * 0.25); //initialize date picker //$(".scan_step2 .dateInput").val('').mobiscroll().date({ // preset: 'date', // theme: 'android', // mode: 'clickpick', // display: 'modal', // lang: '', // dateOrder: 'mmy', // dateFormat: 'mm/yy', // onClose: function(val, type, inst) { // if (type === "cancel") { // return true; // } else { // if (this.name == "start") { // var proDate = $('.scan_step2 input[name="prod"]').val(); // if (proDate === "") { // navigator.notification.alert('Start Date cannot be selected if Production Date is empty', function() {}, window.i18n[window.localStorage['language']]['alert'],window.i18n[window.localStorage['language']]['ok']); // return false; // } // if (val < proDate) { // navigator.notification.alert(window.i18n[window.localStorage['language']]['beforeProductDate'], function() {}, window.i18n[window.localStorage['language']]['alert'],window.i18n[window.localStorage['language']]['ok']); // return false; // } // return confirm(window.i18n[window.localStorage['language']]['addFirstUseDate']); // } // if(this.name==="sav1"||this.name==="sav2"||this.name==="sav3"||this.name==="sav4"||this.name==="sav5"){ // if($('.scan_step2 input[name="prod"]').val()===""){ // navigator.notification.alert('Please fill production date first!', function() {}, window.i18n[window.localStorage['language']]['alert'],window.i18n[window.localStorage['language']]['ok']); // return false; // } // } // } // return true; // } // //}); $(".scan_step2 .dateInput").val("").on('touchend', function (e) { var t = e.currentTarget; if (!t.disabled) { window.currentDateName = t.name; if (t.name == "start") { var proDate = $('.scan_step2 input[name="prod"]').val(); if (proDate === "") { myAlert('startDateNotSelect'); return false; } } if (t.name === "sav1" || t.name === "sav2" || t.name === "sav3" || t.name === "sav4" || t.name === "sav5") { if ($('.scan_step2 input[name="prod"]').val() === "") { myAlert('fillProductionDate'); return false; } } $("#date_picker").popup('open'); } }); (function () {//initialize date picker year list var curYear = new Date().getFullYear(), options = [], curMonth = new Date().getMonth() + 1; for (var i = (curYear - 5); i <= (curYear + 5); i++) { options.push("<option value='" + i + "'>" + i + "</option>"); } $("select[name='year_tobe_selected']").html(options).val(curYear); $("select[name='month_tobe_selected']").val(curMonth); })(); //navigator $(window).on('navigate', function (e, data) { //alert("navigate - " + data.state.direction + " - " + data.state.hash); if (data.state.direction == null && data.state.hash === "#scan") { //when back to #scan page $(".scan_step1_1").show(20); $(".scan_step1_2").hide(20); $(".scan_step1_3").hide(20); $(".scan_step1_4").hide(20); clearTimeout(timeoutId); } if (data.state.direction == null && data.state.hash === "#scan_sync") { //when back to #scan_sync page $(".scan_step3_1").show(20); $(".scan_step3_2").hide(20); $(".scan_step3_3").hide(20); $(".scan_step3_4").hide(20); clearTimeout(timeoutId); } }); //initialize event $('.generic_btn').on('touchstart', function () { $(this).addClass('generic_btn_click'); }); $('.generic_btn').on('touchend', function () { $(this).removeClass('generic_btn_click'); }); $('.generic_btn_scan').on('touchstart', function () { $(this).addClass('generic_btn_scan_click'); }); $('.generic_btn_scan').on('touchend', function () { $(this).removeClass('generic_btn_scan_click'); }); $('.btn_home').on('touchstart', function () { $(this).css('color', 'yellow'); }); $('.btn_home').on('touchend', function () { $(this).css('color', 'white'); $.mobile.navigate("#home"); }); $('.btn_set').on('touchstart', function () { $(this).css('color', 'yellow'); }); $('.btn_set').on('touchend', function () { $(this).css('color', 'white'); $.mobile.navigate("#setting"); }); $('.btn_back').on('touchstart', function () { $(this).css('color', 'yellow'); }); $('.btn_back').on('touchend', function () { $(this).css('color', 'white'); if (window.location.hash == "#scan_read") { //alert("goto scan_read"); if (!$('.scan_step2 input[name="user"]')[0].disabled) { $('.scan_step2 input[name="product"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="serial"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="user"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="prod"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="start"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav1"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav2"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav3"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav4"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav5"]').attr('disabled', 'disabled'); $(".scan_step2_btn").hide(); $(".scan_read_btn").show(); showClearReadInput(); } else { $.mobile.navigate("#scan"); $('.scan_step1_1').show(); $('.scan_step1_2').hide(); $('.scan_step1_3').hide(); $('.scan_step1_4').hide(); } } else if (window.location.hash == "#myproducts") { if (hasViewMyPro) { $.mobile.back(); } else { $('.scan_step1_1').show(); $('.scan_step1_2').hide(); $('.scan_step1_3').hide(); $('.scan_step1_4').hide(); $.mobile.navigate('#scan'); hasViewMyPro = true; } } else if (window.location.hash === "#scan") { if ($(".scan_step1_1")[0].hidden) { $(".scan_step1_1").show(); $(".scan_step1_2").hide(); $(".scan_step1_3").hide(); $(".scan_step1_4").hide(); } else { $.mobile.back(); } } else if (window.location.hash === "#scan_sync") { $.mobile.back(); $(".scan_step2_btn").hide(); $(".scan_read_btn").show(); showClearReadInput(); } else { $.mobile.back(); } }); $('.btn_webhome').on('touchend', function () { window.open('http://www.deltaplus.eu', '_system', 'location=yes'); }); $('.website').on('touchend', function () { window.open('http://www.deltaplus.eu', '_system', 'location=yes'); }); $(".menu_scan").on('touchend', function () { $('.scan_step1_1').show(); $('.scan_step1_2').hide(); $('.scan_step1_3').hide(); $('.scan_step1_4').hide(); $.mobile.navigate('#scan'); //window.history.pushState({}, '', '#scan'); }); $(".menu_view").on('touchend', function () { readCardInforListFromDB(); $.mobile.navigate("#myproducts"); }); $(".menu_product").on('touchend', function () { //window.localStorage['userId'] = 11748068; //window.localStorage.clear(); if (window.localStorage['userId']) { $.mobile.navigate('#product_manager_center'); } else { $.mobile.navigate("#product_manager"); } }); $('.scan_step1_1_btn').on('touchstart', function () { $(this).toggleClass('scan_step1_1_btn_click'); }); $('.scan_step1_1_btn').on('touchend', function () { $(this).toggleClass('scan_step1_1_btn_click'); scan_next(1, 1); isRead = true; isNfcEnable = true; timeoutId = setTimeout(function () { if (!ifTagFound) { isNfcEnable = false; scan_next(1, 2); } else { ifTagFound = false; } }, 20000); }); $('.scan_step1_3_instruction').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.scan_step1_3_instruction').on('touchend', function () { $(this).toggleClass('general_btn_click'); scan_next(1, 1); $('.scan_step1_3').hide(); isRead = true; isNfcEnable = true; timeoutId = setTimeout(function () { if (!ifTagFound) { isNfcEnable = false; scan_next(1, 2); } else { ifTagFound = false; } }, 20000); }); $('.scan_step1_4_instruction').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.scan_step1_4_instruction').on('touchend', function () { $(this).toggleClass('general_btn_click'); $('.scan_step2 input[name="product"]').val(nfcData[0]); $('.scan_step2 input[name="serial"]').val(nfcData[1]); $('.scan_step2 input[name="user"]').val(getStringFromCharCode(nfcData[2])); $('.scan_step2 input[name="prod"]').val(nfcData[3]); $('.scan_step2 input[name="start"]').val(nfcData[4]); $('.scan_step2 input[name="sav1"]').val(nfcData[5]); $('.scan_step2 input[name="sav2"]').val(nfcData[6]); $('.scan_step2 input[name="sav3"]').val(nfcData[7]); $('.scan_step2 input[name="sav4"]').val(nfcData[8]); $('.scan_step2 input[name="sav5"]').val(nfcData[9]); $('.scan_step2 input[name="product"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="serial"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="user"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="prod"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="start"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav1"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav2"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav3"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav4"]').attr('disabled', 'disabled'); $('.scan_step2 input[name="sav5"]').attr('disabled', 'disabled'); $(".scan_step2_btn").hide(); $(".scan_read_btn").show(); $.mobile.navigate('#scan_read'); }); //new button for add id to my product only $(".scan_add_to_myproduct").on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $(".scan_add_to_myproduct").on('touchend', function () { console.log('scanned records serila is ', $('.scan_step2 input[name="serial"]').val()); if ($('.scan_step2 input[name="serial"]').val() === '') { myAlert('emptyCardFound'); return; } // validate data before add to my product. var db = openDatabase('deltaplus', '1.0', 'deltaplus', 5 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS cardInfor(product,serial,user,prod,start,sav1,sav2,sav3,sav4,sav5,ifFirst,ifDelete,equipmentId)'); tx.executeSql('SELECT serial FROM cardInfor WHERE serial = ?', [nfcData[1]], function (tx, re) { if (re.rows.length == 0) { writeCardInforToDB(true); } else { myAlert('productCantAdd', [nfcData[1]]); } }); }); }); $(".scan_step2_btn").on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $(".scan_step2_btn").on('touchend', function () { // validate data before save into card if (validateForm()) { $.mobile.navigate('#scan_sync'); $('.scan_step2 input[name="product"]').textinput('disable'); $('.scan_step2 input[name="serial"]').textinput('disable'); $('.scan_step2 input[name="user"]').textinput('disable'); $('.scan_step2 input[name="prod"]').textinput('disable'); $('.scan_step2 input[name="start"]').textinput('disable'); $('.scan_step2 input[name="sav1"]').textinput('disable'); $('.scan_step2 input[name="sav2"]').textinput('disable'); $('.scan_step2 input[name="sav3"]').textinput('disable'); $('.scan_step2 input[name="sav4"]').textinput('disable'); $('.scan_step2 input[name="sav5"]').textinput('disable'); showClearReadInput(); } // $(this).toggleClass('general_btn_click').html('EDIT DATA'); }); $(".scan_step2_btn2").on("touchend", function () { $(".scan_read_btn").hide(); $(".scan_step2_btn").show(); if (version_maintenance) { $('.scan_step2 input[name="product"]').textinput('disable'); $('.scan_step2 input[name="serial"]').textinput('disable'); $('.scan_step2 input[name="user"]').textinput('enable'); $('.scan_step2 input[name="prod"]').textinput('enable'); $('.scan_step2 input[name="start"]').textinput('enable'); $('.scan_step2 input[name="sav1"]').textinput('enable'); $('.scan_step2 input[name="sav2"]').textinput('enable'); $('.scan_step2 input[name="sav3"]').textinput('enable'); $('.scan_step2 input[name="sav4"]').textinput('enable'); $('.scan_step2 input[name="sav5"]').textinput('enable'); } else if (ifEmpytyTag) { $('.scan_step2 input[name="product"]').textinput('enable'); $('.scan_step2 input[name="serial"]').textinput('enable'); $('.scan_step2 input[name="user"]').textinput('enable'); $('.scan_step2 input[name="prod"]').textinput('enable'); $('.scan_step2 input[name="start"]').textinput('enable'); } else if (nfcData[10] == "0" || nfcData[10] == null) { $('.scan_step2 input[name="user"]').textinput('enable'); $('.scan_step2 input[name="start"]').textinput('enable'); nfcData[10] = '1'; } else { $('.scan_step2 input[name="user"]').textinput('enable'); } showClearReadInput(); $('.scan_step3_1').show(); $('.scan_step3_2').hide(); $('.scan_step3_3').hide(); $('.scan_step3_4').hide(); }); $(".scan_step3_1_btn").on('touchstart', function () { $(this).toggleClass('scan_step3_1_btn_click'); }); //register listener for syncronize functionality $(".scan_step3_1_btn").on('touchend', function () { $(this).toggleClass('scan_step3_1_btn_click'); nfcData[0] = $('.scan_step2 input[name="product"]').val(); nfcData[1] = $('.scan_step2 input[name="serial"]').val(); nfcData[2] = getCharCodeFromString($('.scan_step2 input[name="user"]').val()); nfcData[3] = $('.scan_step2 input[name="prod"]').val(); nfcData[4] = $('.scan_step2 input[name="start"]').val(); nfcData[5] = $('.scan_step2 input[name="sav1"]').val(); nfcData[6] = $('.scan_step2 input[name="sav2"]').val(); nfcData[7] = $('.scan_step2 input[name="sav3"]').val(); nfcData[8] = $('.scan_step2 input[name="sav4"]').val(); nfcData[9] = $('.scan_step2 input[name="sav5"]').val(); window.currentUpdatedRecordId = nfcData[1];//keep serial number for showing which one has been updated message = [ ndef.mimeMediaRecord('mime/com.softtek.delta', nfc.stringToBytes(nfcData.join("~"))), ndef.uriRecord("http://www.deltaplus.eu") ]; scan_next(3, 5); isRead = false; isNfcEnable = true; timeoutId = setTimeout(function () { if (!ifTagFound) { isNfcEnable = false; scan_next(3, 3); } else { ifTagFound = false; } }, 20000); }); $(".scan_step3_3_instruction").on('touchstart', function () { $(this).toggleClass('scan_step3_1_btn_click'); }); $(".scan_step3_3_instruction").on('touchend', function () { $(this).toggleClass('scan_step3_1_btn_click'); message = [ ndef.mimeMediaRecord('mime/com.softtek.delta', nfc.stringToBytes(nfcData.join("~"))), ndef.uriRecord("http://www.deltaplus.eu") ]; scan_next(3, 2); isRead = false; isNfcEnable = true; timeoutId = setTimeout(function () { if (!ifTagFound) { isNfcEnable = false; scan_next(3, 3); } else { ifTagFound = false; } }, 20000); }); $(".scan_step3_4_instruction").on('touchend', function () { readCardInforListFromDB(true);//set true if need to show which one has been updated }); $(".backToViewMyProducts").on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $(".backToViewMyProducts").on('touchend', function () { $(this).toggleClass('general_btn_click'); myConfirm('confirmToDeleteRecord', null, function (index) { if (index == 1) { deleteRecordFromDB($(".myproducts_detail_form input[name='serial']").val()); } }); }); //setting $('.menu_language').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.menu_language').on('touchend', function () { $(this).toggleClass('general_btn_click'); initLanguageSelection(); $("#language_setting").popup('open'); }); $('.menu_use').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.menu_use').on('touchend', function () { $(this).toggleClass('general_btn_click'); // window.open('http://www.deltaplus.eu', '_blank', 'location=yes'); window.open(web_index, '_system', 'location=yes'); }); $('.menu_update').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.menu_update').on('touchend', function () { $(this).toggleClass('general_btn_click'); if (window.localStorage['userId']) { $.mobile.navigate('#product_manager_center'); } else { $.mobile.navigate("#product_manager"); } }); $('.menu_about').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.menu_about').on('touchend', function () { $(this).toggleClass('general_btn_click'); myAlert('version', ['1.7.1']); }); //setting end //product manager $(".product_manager").on('touchend', function () { if (window.localStorage['userId']) { $.mobile.navigate('#product_manager_center'); } else { $.mobile.navigate("#product_manager"); } }); $('.access_my').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.access_my').on('touchend', function () { $(this).toggleClass('general_btn_click'); // window.open('http://www.deltaplus.eu', '_blank', 'location=yes'); window.open(web_index + "?userId=" + window.localStorage['userId'], '_system', 'location=yes'); }); $('.upload_my').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.upload_my').on('touchend', function () { $(this).toggleClass('general_btn_click'); prepareSendingData(); }); $('.backup_my').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.backup_my').on('touchend', function () { $(this).toggleClass('general_btn_click'); var login = window.localStorage['username']; var password = window.localStorage['password']; var loader = showLoading('Loading'); $.ajax({ type: 'POST', url: web_server_equipment + 'get-equipments', crossDomain: true, data: "start=0&end=100", dataType: 'json', beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", make_base_auth(login, password)); }, success: function (data, status) { loader.hide(); if (data) { updateReceivingData(data); } else { myAlert('noDataFound'); } }, error: function (jqXHR, status, throwerror) { loader.hide(); myAlert("appError", [throwerror]); } }); }); $('.status_my').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.status_my').on('touchend', function () { $(this).toggleClass('general_btn_click'); $.mobile.navigate('#ppe_status'); }); $('.signout').on('touchstart', function () { $(this).toggleClass('general_btn_click'); }); $('.signout').on('touchend', function () { $(this).toggleClass('general_btn_click'); window.localStorage['userId'] = ''; window.localStorage['username'] = ''; window.localStorage['password'] = ''; $.mobile.navigate('#home'); }); $("input[name='login']").change(function () { $(this).val($(this).val().toLowerCase()); }); //product manager end //user login and registion $(".validate_login").on('touchend', function () { if (!checkConnection()) { return; } var login = $("#product_manager input[name='login']").val(), password = $("#product_manager input[name='password']").val(); if (isNull(login)) { myAlert('invalidInput', ['user']); } else if (isNull(password)) { myAlert('invalidInput', ['password']); } else { var loader = showLoading('Loading'); $.ajax({ type: 'GET', url: web_server_delta + 'get-annual-check-account', crossDomain: true, data: { userId: -1 }, contentType: 'application/json;charset=UTF-8', dataType: 'json', beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", make_base_auth(login, password)); }, success: function (data, status) { loader.hide(); if (typeof data.userId !== 'undefined') { window.localStorage['userId'] = data.userId; window.localStorage['username'] = login; window.localStorage['password'] = <PASSWORD>; $("#product_manager input[name='login']").val(""); $("#product_manager input[name='password']").val(""); $.mobile.navigate('#product_manager_center'); } else { myAlert('loginfailed'); $("#product_manager input[name='password']").val(""); $("#product_manager input[name='password']").focus(); } }, error: function (jqXHR, status, throwerror) { loader.hide(); myAlert("appError", [throwerror]); } }); } }); $("#user_registion #email").change(function () { $(this).val($(this).val().toLowerCase()); }); $(".validate_registion").on('touchend', function () { var firstName = $("#user_registion #firstName").val(), lastName = $("#user_registion #lastName").val(), company = $("#user_registion #company").val(), phone = $("#user_registion #phone").val(), email = $("#user_registion #email").val(), password = $("#user_registion #password").val(), confirm = $("#user_registion #passwordConfirm").val(); var emailRegEx = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; //Delta Type for Maintenance version var deltaType = 0; if (firstName == "" || lastName == "" || company == "" || phone == "" || email == "" || password == "" || confirm == "") { myAlert('creationMsgMissing'); } else if (!emailRegEx.test(email.toLowerCase())) { myAlert('wrongEmail'); $("#user_registion #email").val(""); $("#user_registion #email").focus(); } else if (password != confirm) { myAlert('confPassword'); $("#user_registion #password").val(""); $("#user_registion #passwordConfirm").val(""); $("#user_registion #password").focus(); } else if (password.length < 6) { myAlert('passworminlength'); $("#user_registion #password").val(""); $("#user_registion #passwordConfirm").val(""); $("#user_registion #password").focus(); } else { var loader = showLoading('Loading...'); $.ajax({ type: "GET", url: web_server_delta + "create-annual-check-account", contentType: 'application/json;charset=UTF-8', dataType: 'json', data: { emailAddress: email, firstName: firstName, lastName: lastName, password: <PASSWORD>, jobTitle: null, company: company, street1: null, zip: null, city: null, country: null, phoneNumber: phone, phoneExtension: null, faxNumber: null, faxExtension: null, companyActivity: null, companyWorkforce: null, companyTurnover: null, comment: null, contactWish: 'Mail', languageCode: 'en' }, beforeSend: function (xhr, status) { //xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Authorization", make_base_auth(liferaywsUserAdmin, liferaywsPasswordAdmin)); }, success: function (data, status) { loader.hide(); // fix error of https://github.com/stkwx-phabricator/nfc_deltacard/issues/5 if (typeof data !== 'undefined' && typeof data.exception == 'undefined') { myAlert('accountCreated'); $("#user_registion #firstName").val(""); $("#user_registion #lastName").val(""); $("#user_registion #email").val(""); $("#user_registion #phone").val(""); $("#user_registion #company").val(""); $("#user_registion #password").val(""); $("#user_registion #passwordConfirm").val(""); $.mobile.navigate("#product_manager"); } else { loader.hide(); myAlert('noAccountCreate'); } }, error: function (jqXHR, status, throwerror) { loader.hide(); myAlert("appError", [throwerror]); } }); } }); /** * Remember password Function binding. */ /*$(".nav_lost_password").on('click', function () { $.mobile.navigate('#remember_password'); });*/ $('.nav_lost_password').on('touchend', function () { window.open(web_index, '_system', 'location=yes'); }); $(".nav_new_user_registration").on('click', function () { $.mobile.navigate('#user_registion'); }); $('.nav_about_product_manager').on('touchend', function () { window.open(web_index, '_system', 'location=yes'); }); $(".remember_password_step1_nextstep").on('click', function () { var login = $('#rp_step1_login').val(); if (isNull(login)) { myAlert('invalidInput', ['user']); $('#rp_step1_login').focus(); return; } else { if (!checkConnection()) { return; } var loader = showLoading('Loading...'); $.post(web_server + "/restm.php", { type: 'findAccount', email: login }, function (data) { loader.hide(); if (data && data.length != 0) { $('#rp_step2_email').val(data[0].email); $(".remember_password_step1").hide(); $(".remember_password_step2").show(); $('#rp_step1_login').val(''); } else { myAlert('invalidInput', ['user']); $('#rp_step1_login').focus(); } }, 'JSON').error(function () { loader.hide(); myAlert('noConnect'); }); } }); $(".remember_password_step2_nextstep").on('click', function () { var secCode = $('#rp_step2_secCode').val(); if (isNull(secCode)) { myAlert('invalidInput', ['secCode']); $('#rp_step2_secCode').focus(); return; } else { var loader = showLoading('Loading...'); $.post(web_server + "/restm.php", { type: 'validateSecCode', secCode: secCode }, function (data) { loader.hide(); //if (data && data.status == 'success') { if (window.localStorage['secCode'] == secCode) { $(".remember_password_step2").hide(); $(".remember_password_step3").show(); $('#rp_step2_secCode').val('') window.localStorage['secCode'] = ''; } else { myAlert('invalidInput', ['secCode']); $('#rp_step2_secCode').focus(); } }, 'JSON').error(function () { loader.hide(); myAlert('noConnect'); }); } }); $(".remember_password_step2_sendcode").on('click', function () { var email = $('#rp_step2_email').val(); var loader = showLoading('Loading...'); $.post(web_server + "/sendmail.php", { resource: 'mobile', email: email }, function (data) { loader.hide(); if (data) { if (!isNull(data.secCode)) { myAlert('emailSendSuccess', [email]); window.localStorage['secCode'] = data.secCode; } else { myAlert('emailsendFail', [email]); } } else { myAlert('noConnect'); $('#rp_step1_login').focus(); return; } }, 'JSON').error(function (error) { loader.hide(); myAlert('noConnect'); }); }); $(".remember_password_step3_save").on('click', function () { var login = $('#rp_step2_email').val(); var psw1 = $('#rp_step3_password1').val(); var psw2 = $('#rp_step3_password2').val(); if (!psw1 || !psw2 || psw1 == '' || psw2 == '') { myAlert('invalidInput', ['password']); return; } if (psw1 != psw2) { myAlert('confPassword'); return; } if (psw1.length < 6) { myAlert('passworminlength'); return; } var loader = showLoading('Loading...'); $.post(web_server + "/restm.php", { type: 'resetPassword', login: login, password: <PASSWORD> }, function (data) { loader.hide(); myAlert('rp_step3_succes'); $(".remember_password_step3").hide(); $(".remember_password_step1").show(); $.mobile.navigate('#product_manager'); window.localStorage['secCode'] = ''; $('#rp_step3_password1').val(''); $('#rp_step3_password2').val(''); }, 'JSON').error(function (error) { loader.hide(); myAlert('noConnect'); }); }); $(".remember_password_cancel").on('click', function () { $.mobile.navigate('#product_manager'); $('#rp_step1_login').val(''); return; }); // valudate form input function isNull(obj) { if (!obj || obj == '') { return true; } return false; } function showLoading(msg) { var uploadLoader = $.mobile.loading("show", { text: "foo", textVisible: true, theme: "z", html: '<span class="ui-bar ui-shadow ui-overlay-d ui-corner-all" style="background-color:white;"><span class="ui-icon-loading"></span><span style="font-size:2em;">' + msg + '</span></span>' }); uploadLoader.show(); return uploadLoader; } // check network available function checkConnection() { var networkState = navigator.connection.type; /* var states = {}; states[Connection.UNKNOWN] = 'Unknown connection'; states[Connection.ETHERNET] = 'Ethernet connection'; states[Connection.WIFI] = 'WiFi connection'; states[Connection.CELL_2G] = 'Cell 2G connection'; states[Connection.CELL_3G] = 'Cell 3G connection'; states[Connection.CELL_4G] = 'Cell 4G connection'; states[Connection.CELL] = 'Cell generic connection'; states[Connection.NONE] = 'No network connection'; navigator.notification.alert('Connection type: ' + states[networkState]);*/ var connected = networkState == Connection.NONE ? false : true; if (!connected) { myAlert('nonetwork'); } return connected; } /*function checkLanguage() { navigator.globalization.getPreferredLanguage( function (language) { navigator.notification.alert('language 1: ' + language.value + '\n'); var lang = language.value.split('-'); navigator.notification.alert('language 2: ' + lang[0] + '\n'); if(lang != null && (lang[0] == 'en' || lang[0] == 'zh' || lang[0] == 'sp' || lang[0] == 'fr') ) { window.localStorage['language'] = lang[0]; } }, function () { window.localStorage['language'] = 'en'; //navigator.notification.alert('Error getting language\n'); } ); }*/ //end //navigate var app = { // Application Constructor initialize: function () { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function () { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function () { // console.log(device.cordova); // console.log(device.model); // console.log(device.name); // console.log(device.platform); // console.log(device.uuid); // console.log(device.version); navigator.splashscreen.hide(); registeMimeTypeListener(mimeCallBack, mimeSuccessCallBack); registeTagListener(tagCallBack, tagSuccessCallBack); } }; <file_sep>INSERT INTO DELTAPLUS_USER_TEST VALUES (NULL, '<EMAIL>', 'gerardo', '123456', 'Gerardo', 'Garza', 'Softtek', 1, sysdate(), sysdate()); select * from DELTAPLUS_USER_TEST; SELECT * FROM DELTAPLUS_PRODUCT_TEST WHERE ID = 1 AND IS_DELETED = 0 LIMIT 20; SELECT COUNT(*) totalCount FROM DELTAPLUS_PRODUCT_TEST WHERE ID = '1' AND IS_DELETED = 0; SELECT P.ID, P.PRODUCT, P.SERIAL, P.USERNAME, P.PROD_DATE, P.START_DATE, P.SAV1, P.SAV2, P.SAV3, P.SAV4, P.SAV5, CONCAT(U.FIRST_NAME, ' ', U.LAST_NAME) USER_NAME FROM DELTAPLUS_PRODUCT_TEST P,DELTAPLUS_USER_TEST U WHERE P.DELTA_USER_ID = U.USER_ID AND P.IS_DELETED = 0 LIMIT 20; INSERT INTO DELTAPLUS_PRODUCT_TEST VALUES (NULL, 'Glooves', 'GL-45424', 'Gerardo', '2014-12-20', '2015-02-2', null, null, null, null, null, 0, sysdate(), sysdate(), 1); SELECT COUNT(*) totalCount FROM DELTAPLUS_PRODUCT_TEST WHERE IS_DELETED = 0; SELECT * FROM DELTAPLUS_USER_TEST LIMIT 20; INSERT INTO DELTAPLUS_USER_TEST(USER_ID, EMAIL, PASSWORD, FIRST_NAME, LAST_NAME, COMPANY, LOGIN, USER_TYPE) VALUES(NULL, '<EMAIL>', 'pacman', 'Manny', 'Pacquiao', 'Box', 'pacman', 0); SELECT USER_ID, CONCAT(FIRST_NAME, ' ', LAST_NAME) name, USER_TYPE FROM DELTAPLUS_USER_TEST WHERE LOGIN = 'GERARDO' AND PASSWORD = '<PASSWORD>' ORDER BY USER_ID DESC;<file_sep>## NFC data demo: ` product~serial~user~prod~start~sav1~sav2~sav3~sav4~sav5~newFlag ` ## Code Demo: ``` mimeCallBack: function (nfcEvent) { var tag = nfcEvent.tag, ndefMessage = tag.ndefMessage; tagId = nfc.bytesToHexString(tag.id); console.log(tagId); nfcData = nfc.bytesToString(ndefMessage[0].payload).split('~'); if (nfcData.length != 11) { nfcData = [ '', //product '', //serial '', //user '', //prod. '', //start '', //sav1 '', //sav2 '', //sav3 '', //sav4 '', //sav5 '0' //if first use 0:new ]; message = [ ndef.mimeMediaRecord('mime/com.softtek.delta', nfc.stringToBytes(nfcData.join("~"))), ndef.uriRecord("http://www.deltaplus.eu") ]; nfc.write(message, function () { }, function (error) { // todo there is some random error when saving data into card, eg. if you move card during writing process. myAlert('appError', error); }); myAlert('dataFomatNotRight', [nfc.bytesToHexString(tag.id)]); return; } ```<file_sep>window.i18n = {}; window.i18n.en = { scan_id_card: 'Scan ID CARD', scan_id_card_press: 'Push', view_my_products: 'View my Products', product: 'Product', serial: 'ID', product_manager: 'My PPE Manager', lost_password: '<PASSWORD>', new_user_registration: 'Register an account', about_product_manager: 'About Manager', password: '<PASSWORD>', email: 'email', first_name: '<NAME>', last_name: '<NAME>', phone: 'Phone', company: 'Company', language: 'Language', use_instruction: 'Operating Instructions', update_backup: 'Update', about: 'About', launch_scan: 'Tap to start', appro_to_card: 'Approach to ID CARD', wait_for_syn: 'Wait for Synchronization', user: 'User', dates: 'Dates', prod: 'Production', start: 'First use', sav1: 'Maintenance 1', sav2: 'Maintenance 2', sav3: 'Maintenance 3', sav4: 'Maintenance 4', sav5: 'Maintenance 5', edit_data: 'Edit Data', save_data: 'Save Data', syn_infor: '<div>To save data, information</div><div>must be synchronized</div><div>with product ID CARD</div>', validate: 'Login', select_lang: 'Please select your language', return: 'Confirm', products_manager: 'My PPE Manager', web_access: 'Web Access', scanning: 'Scanning', read_product_id_card: 'Read product ID Card', ifDelete: 'Are you sure you want to delete?', yes: 'Yes', no: 'No', addFirstUseDate: 'Are you sure to launch product first use date? It will no longer be editable!', beforeAddFirstUseDate: 'You cannot save user if first use date has not been validate.', notSameCard: 'The ID CARD you are synchronizing is not the same that you read.', saveInfo: 'To save data, you must synchronize the ID CARD', creationMsgMissing: 'All the fields are mandatory.Please fill out all fields correctly.', creationSuccessful: 'Your account has been created! Now you will be able to log in from ID CARD or from the http://www.deltaplus.eu website to access your PPE Manager space', login: 'Username (email)', confirmPassword: '<PASSWORD>', idCardNotFound: "ID CARD<br/>Not found", scanAgain: 'Try scanning again', idCardFound: 'ID CARD<br/>Found', ok: 'OK', version: 'Version {0}', addIdTo: 'Add Product', myProductList: 'My Products', editProduct: 'Edit Product', idCard: 'ID CARD', alert: 'Alert', updatingSuccess: 'Update successfully!', sycnIdCard: 'Sync.<br/>ID CARD', inforSycn: 'Information synchronized', databaseUpdate: 'Product DataBase Updated', delete: 'Delete', signin: 'S<small>ign in:</small>', contactInfor: 'C<small>ontact information:</small>', loginInfor: 'L<small>ogin Information:</small>', myPPEManager: 'My PPE Manager', importMyProductList: 'Download My Product List', myPPEStatus: 'My PPE status', register: 'Register', accountCreated: 'Your account has been created! Now you will be able to log in from ID CARD or from the http://www.deltaplus.eu website to access your PPE manager space', beforeProductDate: 'Start Date cannot be before Production Date', addIdToMyProduct: 'Add ID to My Products successfully', saveData: 'Save Data', uploadMyProductList: 'Upload My Product List', useSameIdCard:'Please use the same ID card!', productFieldEmpty:'Product field is empty!', //added on 1.31 2015 productMaxLength:'Product field exceed maximum length (10 chars)', serialFieldEmpty:'ID field is empty', serialMaxLength:'Serial field exceed maximum length (12 chars)', userMaxLength:'User field exceed maximum length name (15 chars)', //added on 2.2 2015 dataFomatNotRight:'Data format is not right. Initialization has been finished, please read again! tag id: {0}', nfcDisabled:'NFC has been disabled, please turn on in settings!', initAppFailed:"the application can't startup, the reason is {0}", uploadSuccessfully:"upload successfully!", importSuccessfully:'import data successfully!', startDateNotSelect:'Start Date cannot be selected if Production Date is empty', fillProductionDate:'Please fill production date first!', productCantAdd:'Product {0} is already in your Product List.', confirmToDeleteRecord:'Do you confirm to delete the record from phone?', confirmMsg:'Confirm', cancel:'Cancel', //added on 3/26/2015 message: 'Message', importMessage: 'Data was imported successfully!', loginfailed:'User or Password is wrong.', productsRegistered: 'PRODUCTS REGISTERED:', inUse: 'IN USE:', maintain: 'TO BE MAINTAIN:', now: 'NOW', lessMonth: 'IN LESS THAN 1 MONTH', lessThreeMonth: 'IN LESS THAN 3 MONTH', sameIDCard: 'Please use the same ID CARD', nfcDisable: 'NFC has been disabled, please turn on in Mobile Settings!', deleteProductConfirm: 'Do you confirm to delete the record from phone?', //added on 4/2/2015 appError: 'Application Error {0}', confPassword: '<PASSWORD> and Confirm Password are different.', // added on 5/29/2015 acctExists: 'Account already exist with same email.', noConnect: 'No Response from server.', nonetwork: 'Network is disabled, please open your network and try again.', invalidInput: 'Invalid input for {0}', /*Remember password*/ rp_step1_title: 'Step 1: Fill Account', rp_step_next: 'Next Step', rp_step_cancel: 'Cancel', rp_step2_title: 'Step 2: Validate Code', secCode: 'Code', rp_step2_note: 'Note: Please validate your account and email address and click send code.', rp_step2_sendcode: 'Send Code', rp_step3_title: 'Step 3: Reset Password', rp_step3_succes: 'password reset successfully. Please use your new password to login', passworminlength: 'Password must be 6 characters at least.', emailSendSuccess: 'Email has been sent to your email ({0}) successfully, please check your email.', emailSendFail: 'Failed to send email ({0}). please try again. If issue still present, please contact our IT support.', //added 8/29/2016 noAccountCreate: 'Account was not created. Please contact DeltaPlus Customer Service', wrongEmail: 'Email address is invalid.', remoteServerError: 'Remote server is unavailable now, please try later', noDataFound: 'No Data found.', emptyCardFound: 'Cannot add empty card into product list', signout: 'Sign Out' } window.i18n.zh = { scan_id_card: '扫描ID CARD', scan_id_card_press: '点击开始', view_my_products: '查看我的产品', product: '产品', serial: 'ID', product_manager: '我的个人防护用品管理器', lost_password: '<PASSWORD>', new_user_registration: '注册新账户', about_product_manager: '关于管理器', password: '密码', email: '邮箱', first_name: '名', last_name: '姓', phone: '电话', company: '公司', language: '语言设置', use_instruction: '使用说明', update_backup: '更新', about: '关于', launch_scan: '点击开始', appro_to_card: '近距离扫描ID卡', wait_for_syn: '等待同步', user: '用户', dates: '日期', prod: '制造', start: '第一次使用', sav1: '维护 1', sav2: '维护 2', sav3: '维护 3', sav4: '维护 4', sav5: '维护 5', edit_data: '编辑数据', save_data: '保存数据', syn_infor: '数据必须与NFC标签同步才能保存', validate: '登录', select_lang: '请选择语言', return: '确认', products_manager: '我的个人防护用品管理器', web_access: '进入官网', scanning: '扫描...', read_product_id_card: '读取ID卡信息', ifDelete: '确认删除?', yes: '是', no: '否', addFirstUseDate: '确认保存产品首次使用日期?保存后将无法再次编辑', beforeAddFirstUseDate: '你不能拯救给用户,如果尚未启动的第一次使用日期!', notSameCard: '您所同步的ID卡与开始同步的不是同一张,同步失败!', saveInfo: '若要保存数据,您必须同步 ID 卡', creationMsgMissing: '信息不完整,请正确填写所有信息!', creationSuccessful: '', login: '登录名(邮箱)', confirmPassword: '<PASSWORD>', idCardNotFound: "未发现ID卡", scanAgain: '请再次扫描', idCardFound: '发现ID卡', ok: '确认', version: '版本{0}', addIdTo: '添加产品', myProductList: '我的产品列表', editProduct: '编辑产品', idCard: 'ID卡', alert: '提示', updatingSuccess: '更新完成!', sycnIdCard: '点击同步ID卡', inforSycn: '信息已同步', databaseUpdate: '产品数据库已更新', delete: '删除', signin: '登录', contactInfor: '联系信息', loginInfor: '登录信息', myPPEManager: '我的个人防护用品管理器', importMyProductList: '下载我的产品列表', myPPEStatus: '我的个人防护用品状态', register: '注册', accountCreated: '账户已创建!您现在可以通过该应用程序或者http://www.deltaplus.eu网站进行登录来访问您的个人防护装备管理器空间', beforeProductDate: '第一次使用日期不能小于产品日期', addIdToMyProduct: '成功添加到我的产品列表', saveData: '保存数据', uploadMyProductList: '上传我的产品列表', useSameIdCard: '请使用相同的NFCID卡', productFieldEmpty: '产品不能为空!', //added on 1.31 2015 productMaxLength:'产品名字过长 (最多10个字符)', serialFieldEmpty:'序列号不能为空', serialMaxLength:'序列号过长(最多12个字符)', userMaxLength:'用户名过长(最多3个汉字或15个字符)', //added on 2.2 2015 dataFomatNotRight:'数据格式不正确,已初始化,请在此扫描!tag id : {0}', nfcDisabled:'NFC 功能被关闭,请在设置中打开。', initAppFailed:"初始化程序失败,原因: {0}", uploadSuccessfully:'上传成功', importSuccessfully:'导入数据成功', startDateNotSelect:'请先填入生产日期', fillProductionDate:'请先填入生产日期', productCantAdd:'产品已经存在,无法再次添加', confirmToDeleteRecord:'确定从手机中删除这条记录吗?', confirmMsg:'确认', cancel:'取消', //added 3/26/2015 message: '信息', importMessage: '数据导入成功!', loginfailed:'登录名或密码错误。', productsRegistered: '产品注册:', inUse: '在使用中的产品数量:', maintain: '需要维修的产品:', now: '维修数量', lessMonth: '使用时间少于一个月的', lessThreeMonth: '使用时间少于三个月的', sameIDCard: '请使用相同的ID CARD', nfcDisable: 'NFC已被禁用,请打开移动设置!', deleteProductConfirm: '你确认从手机中删除记录?', //added on 4/2/2015 appError: '应用程序错误 {0}', confPassword: '密码和确认密码是不同的。', acctExists: '用户已存在.不能使用相同用户名或邮箱重复注册.', noConnect: '服务器无法链接.' , nonetwork: '当前网络不可用,请开启后重试.', invalidInput: '无效的输入: {0}', /*Remember password*/ rp_step1_title: '第一步:查找用户名', rp_step_next: '下一步', rp_step_cancel: '取消', rp_step2_title: '第二步:验证', secCode: '验证码', rp_step2_note: '提示:请确认用户名和邮件地址是否正确,然后请按发送进行验证码检验。', rp_step2_sendcode: '发送', rp_step3_title: '第三步:重置密码', rp_step3_succes: '密码重置成功,请用新密码登陆。', passworminlength: '密码至少六位。', emailSendSuccess: '邮件成功发送到您的邮箱({0}),请查阅.', emailSendFail: '邮件未成功发送到您的邮箱({0}) ({0}).请重试。如果问题仍然存在请联系我们的客服人员。', //added 8/29/2016 noAccountCreate: '帐户创建失败,请重试。如果问题仍然存在请联系我们的客服人员。', wrongEmail: '邮件地址无效', remoteServerError: '服务器无响应,请稍后重试', noDataFound: '无数据', emptyCardFound: '无法保存内容为空的产品', signout: '退出' } window.i18n.sp = { scan_id_card: 'Escanear ID CARD', scan_id_card_press: 'Presione', view_my_products: 'Ver mis Productos', product: 'Producto', serial: 'ID', product_manager: 'Mi Gerente EPI', lost_password: '<PASSWORD>', new_user_registration: 'Registrar una Cuenta', about_product_manager: 'Sobre Manager', password: '<PASSWORD>', email: 'Correo electrónico', first_name: 'Nombre', last_name: 'Apellido', phone: 'Telefono', company: 'Empresa', language: 'Idiomas', use_instruction: 'Manual de instrucciones', update_backup: 'Actualización', about: 'Acerca de', launch_scan: 'Pulse para comenzar', appro_to_card: 'Acercar al ID CARD', wait_for_syn: 'Esperar para la sincronización', user: 'Usuario', dates: 'Fechas', prod: 'Producción', start: 'Primer Uso', sav1: 'Mantenimiento 1', sav2: 'Mantenimiento 2', sav3: 'Mantenimiento 3', sav4: 'Mantenimiento 4', sav5: 'Mantenimiento 5', edit_data: 'Editar datos', save_data: 'Guardar los datos', syn_infor: '<div>Para guardar los datos, la informacion</div><div>debe ser sincronizada</div><div>con el producto ID CARD</div>', validate: 'Validar', select_lang: 'Por favor seleccione su idioma', return: 'Confirmar', products_manager: 'Mi Gerente EPI', web_access: 'Acceso a la web', scanning: 'Escaneado', read_product_id_card: 'Leer ID CARD del producto', ifDelete: '¿Estás seguro que deseas eliminar?', yes: 'Sí', no: 'No', addFirstUseDate: '¿Está seguro lanzar fecha de primer uso del producto ? ¡Ya no será editable!', beforeAddFirstUseDate: 'No se puede guardar usuario si no ha sido validado la fecha de primer uso.', notSameCard: 'El ID CARD que estásincronizando no es lo mismo que el leido.', saveInfo: "Para guardar datos, debe sincronizar el ID CARD", creationMsgMissing: 'Todos los campos son obligatorios. Por favor llene correctamente.', creationSuccessful: '¡Tu cuenta ha sido creada! Ahora podrás iniciar sesión del mobil o del sitio web de http://www.deltaplus.eu acceder a su espacio Acceso Web ', login: 'Usuario (email)', confirmPassword: '<PASSWORD>', idCardNotFound: "ID CARD<br/>No encontrada", scanAgain: 'Intente escanear de nuevo', idCardFound: 'ID Card<br/>Encontrado', ok: 'OK', version: 'Versión{0}', addIdTo: 'Agregar Producto', myProductList: 'Mis Productos', editProduct: 'Editar Producto', idCard: 'ID CARD', alert: 'Alerta', updatingSuccess: 'Actualizacion Exitosa!', sycnIdCard: 'SYNC.<br/>ID CARD', inforSycn: 'Information sincronizada', databaseUpdate: 'Base de datos de producto actualizado', delete: 'Eliminar', signin: 'S<small>ign en</small>', contactInfor: 'C<small>ontacto información</small>', loginInfor: 'L<small>ogin información</small>', myPPEManager: 'Mi Gerente EPI', importMyProductList: 'Descargar mi lista de productos', myPPEStatus: 'Mi condición de PPE', register: 'Registrar', accountCreated: 'Su cuenta ha sido creada. Ahora usted podrá conectarse desde la aplicación ID CARD o desde el sitio web http://www.deltaplus.eu para acceder a su espacio de Gerente EPI', beforeProductDate: 'La fecha de inicio no puede ser menor que la fecha de Produccion.', addIdToMyProduct: 'ID añadido a mis productos con éxito', saveData: 'Guardar los datos', uploadMyProductList: 'Añadir a mi lista de productos', useSameIdCard:'Utilice la misma tarjeta!', productFieldEmpty:'¡Campo de producto está vacía!', //added on 1.31 2015 productMaxLength:'El campo Producto excede el maximo de caracteres para el nombre (10 chars)', serialFieldEmpty:'El campo Serial Number esta vacio', serialMaxLength:'El numero de serie exceder la longitud máxima(12 chars)', userMaxLength:'El nombre de usuario exceder la longitud máxima (15 chars)', //added on 2.2 2015 dataFomatNotRight:'Formato de datos no es correcto. ¡Inicialización ha sido terminada, lea otra vez! id Card: {0}', nfcDisabled:'NFC ha sido deshabilitado, por favor, activar en ajustes!', initAppFailed:"la aplicación no puede iniciar, la razón es {0}", uploadSuccessfully:"¡subido con éxito!", importSuccessfully:'¡importacion de datos con éxito!', startDateNotSelect:'Fecha de inicio no se puede seleccionar si la fecha de producción está vacía', fillProductionDate:'Llenar fecha de producción!', productCantAdd:'Producto {0} ya está en su lista de productos.', confirmToDeleteRecord:'¿Confirmar para eliminar del teléfono?', confirmMsg:'Confirmar', cancel:'Cancelar', //added 3/26/2015 message: 'Mensaje', importMessage: 'Informacion fue guardada exitosamenete!', loginfailed:'Usuario o Password es incorrecto.', productsRegistered: 'PRODUCTOS REGISTRADOS:', inUse: 'EN USO:', maintain: 'PARA DAR MANTENIMIENTO:', now: 'AHORA', lessMonth: 'EN MENOS DE 1 MES', lessThreeMonth: 'EN MENOS DE 3 MESES', sameIDCard: 'Use la misma ID CARD', nfcDisable: 'NFC esta desactivado, por favor encenderlo en la Configuracion del equipo!', deleteProductConfirm: 'Do you confirm to delete the record from phone?', //added on 4/2/2015 appError: 'Error de la aplicacion {0}', confPassword: 'Contraseña y Confirmar Contraseña son diferentes.', acctExists: 'El Correo electronico ya esta usado con otra cuenta', noConnect: 'El servidor no responde', nonetwork: 'La red está deshabilitada, por favor abra su red y vuelva a intentarlo.', invalidInput: 'Entrada no válida para {0}', /*Remember password*/ rp_step1_title: 'Paso 1: Llenar cuenta', rp_step_next: 'Siguiente paso', rp_step_cancel: 'Cancelar', rp_step2_title: 'Paso 2: Validar la contraseña', secCode: 'Contraseña', rp_step2_note: 'Nota: Por favor validar su cuenta y correo electrónico y haga clic en enviar la contraseña.', rp_step2_sendcode: 'Enviar contraseña', rp_step3_title: 'Paso 3: Restablecer contraseña', rp_step3_succes: 'Contraseña restablecida con éxito. Utilice la nueva contraseña para iniciar sesión', passworminlength: 'La contraseña debe tener al menos 6 caracteres.', emailSendSuccess: 'un correo electrónico ha sido enviado a su correo electrónico ({0}) con éxito, por favor revise su correo electrónico.', emailSendFail: 'Error al enviar correo electrónico ({0}). por favor, inténtelo de nuevo. Si el problema sigue, favor de contactar nuestro soporte.', //added 8/29/2016 Todo: need translate into Spanish noAccountCreate: 'No se creó la cuenta. Por favor, contacten con servicio al cliente de Deltaplus', wrongEmail: 'La dirección de correo electrónico no es válida.', remoteServerError: 'El servidor no está disponible ahora, inténtalo más tarde', noDataFound: 'Datos no encontrados.', emptyCardFound: "¿Confirmar para eliminar el producto del teléfono?", signout: 'Desconectar' } window.i18n.fr = { scan_id_card: 'Scanner ID CARD', scan_id_card_press: 'Presser', view_my_products: 'Voir mes Produits', product: 'Produit', serial: 'ID', product_manager: 'Mon Gestionnaire EPI', lost_password: '<PASSWORD>', new_user_registration: 'Créer un Compte', about_product_manager: 'A propos de Manager', password: '<PASSWORD>', email: 'Messagerie', first_name: 'Prénom', last_name: 'Nom de famille', phone: 'Téléphone', company: 'Compagnie', language: 'Langues', use_instruction: 'Mode d’emploi', update_backup: 'Mise à Jour', about: 'Information', launch_scan: 'Appuyer pour commencer', appro_to_card: "Approcher l'ID CARD", wait_for_syn: 'Attendez la synchronisation', user: 'Utilisateur', dates: 'DATES', prod: 'Production', start: 'Première Utilisation', sav1: 'Entretien 1', sav2: 'Entretien 2', sav3: 'Entretien 3', sav4: 'Entretien 4', sav5: 'Entretien 5', edit_data: 'Modifier données', save_data: 'Enregistrer les données', syn_infor: '<div>Pour enregistrer les données,</div><div> vous devez synchroniser</div><div>synchroniser ID CARD</div>', validate: 'Valider', select_lang: 'Veuillez sélectionner votre langue', return: 'confirmer', products_manager: 'Mon Gestionnaire EPI', web_access: 'Accès Web', scanning: 'En scan', read_product_id_card: "Lecture de l'ID CARD", ifDelete: 'Êtes-vous sûr de que vouloir supprimer ?', yes: 'Oui', no: 'Non', addFirstUseDate: 'Y êtes-vous sûr de lancer la date de mise en service du produit ? elle ne sera plus modifiable !', beforeAddFirstUseDate: 'Vous ne pouvez pas enregistrer d’utilisateur si la mise en service n’a pas ete entamée.', notSameCard: "L'ID CARD que vous synchronisez n'est pas le même.", saveInfo: "Pour enregistrer les données, vous devez synchroniser l'ID CARD", creationMsgMissing: 'Tous les champs sont obligatoires. Merci de remplir tous les champs correctement !', creationSuccessful: "Votre compte a été créé ! Maintenant, vous serez capables de vous connecter depuis cette application ou depuis le site Web de http://www.deltaplus.eu afin d'accéder à votre espace de gestionnaire EPI", login: 'Username (email)', confirmPassword: '<PASSWORD>', idCardNotFound: "ID CARD <br/> introuvable", scanAgain: 'Essayez de scanner de nouveau', idCardFound: 'ID CARD<br/>Trouvé', ok: 'OK', version: 'Version{0}', addIdTo: 'Ajouter Produit', myProductList: 'Mes Produits', editProduct: 'éditer Produit', idCard: 'ID CARD', alert: 'Alerte', updatingSuccess: 'Mise à jour réussie!', sycnIdCard: 'SYNC.<br/>ID CARD', inforSycn: 'Information syncronized', databaseUpdate: 'Base de données mise à jour', delete: 'Supprimer', signin: 'C<small>onnexion:</small>', contactInfor: 'C<small>ontactez information:</small>', loginInfor: 'L<small>ogin d’utilisateur:</small>', myPPEManager: 'Mon gestionnaire PPE', importMyProductList: 'Importer ma liste de produits', myPPEStatus: 'Situation de mes EPI', register: 'S’inscrire', accountCreated: "Votre compte a été créé ! Maintenant, vous serez capables de vous connecter depuis cette application ou depuis le site Web de 'www.deltaplus.eu' afin d'accéder à votre espace de gestionnaire EPI", beforeProductDate: 'Date de début ne peut pas être avant la Date de Production', addIdToMyProduct: 'ID ajoutés à mes produits avec succès', saveData: 'Enregistrer les données', uploadMyProductList: 'Exporter ma listes de produits', useSameIdCard:"S’il vous plaît utiliser la même carte!", productFieldEmpty:'Produit le champ est vide !', //added on 1.31 2015 productMaxLength:'Le champ Produit dépasse le nom de longueur maximum (10 chars)', serialFieldEmpty:'Le champ série est vide', serialMaxLength:'Le champ série dépasse le nom de longueur maximale (12 chars)', userMaxLength:'Le champ utilisateur dépasse le nom de longueur maximale (15 chars)', //added on 2.2 2015 dataFomatNotRight:'Format de données ne est pas juste. Initialisation a été fini, se il vous plaît lire à nouveau! tag id: {0}', nfcDisabled:"NFC a été désactivé, s'il vous plaît activer dans les paramètres!", initAppFailed:"Application ne peut pas démarrer, la raison en est {0}", uploadSuccessfully:"Télécharger correctement!", importSuccessfully:'Téléchargez les données avec succès!', startDateNotSelect:'La date de début ne peut pas être sélectionnée si la date de production est vide', fillProductionDate:'Veuillez remplir la date de production en premier!', productCantAdd: 'Le produit {0} est déjà dans votre liste de produits.', confirmToDeleteRecord:"Confirmez-vous de supprimer l'enregistrement du téléphone?", confirmMsg:'Confirmer', cancel:'Annuler', //added on 3/26/2015 message: 'Message', importMessage: 'Les données ont été importées avec succès!', loginfailed: 'Utilisateur ou mot de passe est erroné.', productsRegistered: 'PRODUCTOS REGISTRADOS:', inUse: 'EN USO:', maintain: 'PARA DAR MANTENIMIENTO:', now: 'AHORA', lessMonth: 'EN MENOS DE 1 MES', lessThreeMonth: 'EN MENOS DE 3 MESES', sameIDCard: 'Se il vous plaît utiliser le même ID CARD', nfcDisable: 'NFC a été désactivé, se il vous plaît activer dans les paramètres mobiles!', deleteProductConfirm: 'Confirmez-vous la suppression du produit du téléphone ?', //added on 4/2/2015 appError: 'Erreur application {0}', confPassword: '<PASSWORD> et Conf<PASSWORD> mot de passe sont différents.', acctExists: 'Cette email est déjà utilisée avec un autre compte', noConnect: 'Le serveur ne reponds pas', nonetwork: 'La connexion réseau est désactivé, veuillez ouvrir votre réseau et réessayez.', invalidInput:'Entrée non valide pour {0}', /*Remember password*/ rp_step1_title: 'Étape 1 : Remplir compte', rp_step_next: "Prochaine étape", rp_step_cancel: 'Annuler', rp_step2_title: 'Etape 2 : Valider le mot de passe', secCode: 'Mot de passe', rp_step2_note: 'Remarque : Veuillez valider votre compte et votre adresse email et cliquez sur envoyer le mot de passe.', rp_step2_sendcode: 'Envoyer le mot de passe', rp_step3_title: 'Étape 3 : Réinitialisation mot de passe', rp_step3_succes: 'mot de passe réinitialisé avec succès. Veuillez utiliser votre nouveau mot de passe pour vous connecter', passworminlength: 'Mot de passe doit contenir 6 caractères au moins.', emailSendSuccess: "un e-mail a été envoyé à votre adresse email ({0}) avec succès, s’il vous plaît consulter votre courrier électronique.", emailSendFail: "Impossible de valider l'e-mail ({0}). s’il vous plaît essayer de nouveau. Si problème persiste, contacter notre IT support.", //added 8/29/2016 Todo: need translate into France noAccountCreate: "Compte pas créé. Veuillez contacter le Service à la clientèle DeltaPlus", wrongEmail: "l'adresse de courriel electronique est invalide.", remoteServerError: "Le serveur n’est pas disponible maintenant, essayer plus tard", noDataFound: 'Aucune donnée trouvée.', emptyCardFound: "No se puede agregar una tarjeta vacía a la lista de productos", signout: 'Se déconnecter' }<file_sep> var date2 = new Date('1/21/2015'); console.log(date2.getFullYear()); console.log(date2.getMonth()+1); console.log(date2.getDate()); var x ; console.log(typeof x) var date = new Date(1482361200000); console.log(date.toDateString())<file_sep>## Changes on 2017-02-02 v1.7.1 - Change web access link to new URL and add new link for "About Manager" - Rename upload/ download my product list button label - Change the error message for text length limit when edit product details - re-format date field. Only display MONTH/ YEAR, remove DAY; but when upload to website, need give a default DAY as 15. - Fix the issue that when upload, always creating new records. ## Changes on 2017-01-07 v1.7.0 - force user email input to lower case when user login and register -- done - correction on the language translation (waiting Georges help) -- done - change label as "Web Access" from PPE Manager when opening website -- done - Use logout to replace “my PPE status" -- done - link to annual check page when click “Operation Structure” -- done - only username and all date fields are editable. -- done - ## Changes on 2016-12-26 - Change the way of opening URL, using system browser, instead of app inside - done - Hide the menu "My PPE Status" - done - Change the Links to annual check service page and label to "Web Access" instead of My PPE Manager - done - Language translation - done - Fix issue after choose french and spanish, if goto change lanugage again, it will move to English automatically. -- done. - Avoid insert empty NFC into production list -- done - Change date format to 'dd/mm/yyyy' -- done ## BUG SUMMARY ``` DONE(10H): new requirements DONE (8H) 2nd round of test Done (4 H ) New Feature: required by George and Michale DONE( 3H ) New Feature: force user input to lower case when user login and register DONE(4 H) Bug: After create a new equipement, the equipmentId isnot update successfully bug Done (2H) Forgot password and find it back DONE (3H) BUG: annual-check create equipment WS not save maintenance date DONE(6H) BUG: Mobile APP date only have mm/YYYY DONE(3H) BUG: data is not update when import data from remote WS into mobile bug DONE(1H): Setup a way to debug cordova APP by GapDebug help wanted invalid wontfix DONE(4H) : there is no deletion logic in current Webservice question DONE(4 H): Handle the Registion message correctly enhancement DONE (4h) : APP login failed bug DONE(6 H) Replace get method with POST enhancement DONE (18H): Upload product to remote Server by Call New API enhancement DONE (4h) : Download Delta products into mobile enhancement ```<file_sep> "use strict" /** * * @param str eg. '15/12/2016' * @returns {*} */ function getDateFromStr(strDate) { // Note: by default, user only choose month/year in front-end, so have to prefix 15 as day. if(strDate != null && strDate != "") { var str = strDate; if(strDate.length < 10) { str = '15/' + strDate; } console.log(str.substr(0, str.indexOf('/'))) console.log(str.substr(str.indexOf('/')+1, str.indexOf('/', str.indexOf('/')+1) - str.indexOf('/') - 1 )) console.log(str.substr(str.indexOf('/', str.indexOf('/')+1)+1, str.length +1)) var day = str.substr(0, str.indexOf('/')); var month = str.substr(str.indexOf('/')+1, str.indexOf('/', str.indexOf('/') + 1) - str.indexOf('/') - 1 ); var year = str.substr(str.indexOf('/', str.indexOf('/') + 1) + 1, str.length + 1); var date = month + '/' + day + '/' + year; return new Date(date) } return null; } function getEmptyValue(val) { if(val != null) { return val; } return "" } /** * * @param date * @returns {*} */ function getYear(date) { if(date != null) { return date.getFullYear(); } return 0; } function getMonth(date) { if(date != null) { return date.getMonth() + 1; } return 0; } function getDate(date) { if(date != null) { return date.getDate(); } return 0; } /** * * @param ms * @returns {*} */ function getFullDate(ms) { if(ms != null) { var date = new Date(ms); var month = date.getMonth() +1; var year = date.getFullYear(); var day = date.getDate(); // TODO: remove the day // return day + "/" + month + "/" + year; return month + "/" + year; } else { return "" } } var str = '21/12/2016' console.log(getDateFromStr(str)); console.log(str.indexOf('/')) console.log(str.indexOf('/', str.indexOf('/')+1)) console.log(str.substr(0, str.indexOf('/'))) console.log(str.substr(str.indexOf('/')+1, str.indexOf('/', str.indexOf('/')+1) - str.indexOf('/') - 1 )) console.log(str.substr(str.indexOf('/', str.indexOf('/')+1)+1, str.length +1)) // console.log(str.)<file_sep>## Built in Mac > cd /Users/kaishen/Documents/Confidential/github/nfc_deltacard/android_app cordova build --release jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ../docs/delta.keystore "/Users/kaishen/Documents/Confidential/github/nfc_deltacard/android_app/platforms/android/build/outputs/apk/android-release-unsigned.apk" delta password: <PASSWORD> cp /Users/kaishen/Documents/Confidential/github/nfc_deltacard/android_app/platforms/android/build/outputs/apk/android-release-unsigned.apk ../dist/delta_kaya_mac.apk ## Issue of Cannot open Android emulator when docker/ vbox is running **Solution: ** - Stop Docker, then use android studio to start android emulator again. Once Emulator is running, you can following following commands to test your applications. - If still not work, you have to restart your computer, once restart, stop the docker service again. - If emulator error "/dev/kvm not found", please refer to here for re-installation ## Test in MAC emulator for android > cordova build android cordova emulate android ## Debug by GapDebug > start GapDebug App, it will open the Emulator in chrome auto. ## To build maintenance version or user version > need change the www/js/index.js file following line: `var version_maintenance = true;` ## Test Account > User = <EMAIL> Password = <PASSWORD> User ID = 11748068 equipmentId = 51802 equipmentId = 53805 equipmentId = 55801 equipmentId = 55802 User = <EMAIL> Password = <PASSWORD> UserId = 11877150 User = <EMAIL> Password = <PASSWORD> UserId = 11877160 User = <EMAIL> Password = 88888888 UserId = 11940029 var liferaywsUserAdmin = "annualcheckserviceadmin"; var liferaywsPasswordAdmin = "<PASSWORD>"; ## Remote Server URLs > //Production Environment var web_server_delta = "https://www.deltaplus.eu/api/jsonws/deltaplus-deltaweb-annualCheck-portlet.annualcheckuseraccount/"; Jerry 12:01:37 var web_server_equipment = "https://www.deltaplus.eu/api/jsonws/deltaplus-deltaweb-annualCheck-portlet.equipment/"; ## This is the site you can check for new users > https://www.deltaplus.eu/en_US/annual-check-service **NOTE**: all these are Prod environment because for Dev we need VPN
27d256fde58fadc4a6774ffcb588fa7de85b1dce
[ "JavaScript", "SQL", "Markdown" ]
9
SQL
stkwx-phabricator/nfc_deltacard
c08cacb3e154be329bb5ebd2234f90500c494c00
7f6a4f16e169fcd8594939c860ca92e91c857301
refs/heads/master
<repo_name>zealprajapati/sudoku<file_sep>/CSP.cpp // // CSP.cpp // Sudoku // // Created by cpsfaculty on 02/10/18. // Copyright (c) 2018 ___<NAME>___. All rights reserved. // #include <stdio.h> #include "CSP.h" #include<cmath> /************************************** Below are the three functions you need to implement ***************************************/ /*Check whether current state satisfy the constraints*/ bool CSP::goalCheck(const State state) { int r, c = 0; int x, y = 0; for (int i = 0; i < 81; i++) { r = i / 9; c = i % 9; if (r == 0 || c == 0) { for (int j = 0; j < 9; j++) { if (state.values[j][c] == state.values[r][c] && j != r) { return false; } if (state.values[r][j] == state.values[r][c] && j != c) { return false; } if (state.values[r][j] == state.values[r][j-1] && j != c) { return false; } if (state.values[r][j] == state.values[r-1][j] && j != c) { return false; } } } if ((r == 0 || r == 3 || r == 6 ) &&(c == 0 || c == 3 || c == 6)) { x = r / 3 * 3; y = c / 3 * 3; for (int i = x; i < x + 3; i++) { for (int j = y; j < y + 3; j++) { if (state.values[i][j] == state.values[r][c] && i != r && j != c) { return false; } } } } return true; } } /*Update Domain for the forward checking*/ void CSP::updateDomain(const State state) { for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) { variables[i][j].domain.clear(); for (int z = 1; z < 10; z++) variables[i][j].domain.push_back(z); } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { //row for (int z = 0; z < 9; z++) { int p = variables[i][j].assignement; for (int k = 0; k < variables[i][z].domain.size(); k++) { if ((variables[i][z].domain[k] == p) && (variables[i][z].domain.size() > 0)) { variables[i][z].domain.erase(variables[i][z].domain.begin() + k); break; } } } //column for (int z = 0; z < 9; z++) { int p = variables[i][j].assignement; for (int k = 0; k < variables[z][j].domain.size(); k++) { if ((variables[z][j].domain[k] == p) && (variables[z][j].domain.size() > 0)) { variables[z][j].domain.erase(variables[z][j].domain.begin() + k); break; } } } //3*3 box int i3 = (i / 3) * 3; int j3 = (j / 3) * 3; int p = variables[i][j].assignement; for (int x = i3; x < (i3 + 3); x++) { for (int y = j3; y < (j3 + 3); y++) { for(int k=0;k<variables[x][y].domain.size();k++) if ((variables[x][y].domain[k] == p) && (variables[x][y].domain.size()>0)) { variables[x][y].domain.erase(variables[x][y].domain.begin() + k); break; } } } } } } /*Arc consistency use*/ void CSP::arcConsistency(const State state) { updateDomain(state); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (variables[i][j].assignement==0 && variables[i][j].domain.size() == 1) { int num = variables[i][j].domain[0]; //row for (int z = 0; z < 9; z++) { if (j==z) { continue; } else { for (int k = 0; k < variables[i][z].domain.size(); k++) { if (variables[i][z].domain[k] == num) { variables[i][z].domain.erase(variables[i][z].domain.begin() + k); break; } } } } //column for (int z = 0; z < 9; z++) { if (i==z) { continue; } else { for (int k = 0; k < variables[z][j].domain.size(); k++) { if ((variables[z][j].domain[k] == num)) { variables[z][j].domain.erase(variables[z][j].domain.begin() + k); break; } } } } ////3*3 box int i3 = (i / 3) * 3; int j3 = (j / 3) * 3; for (int x = i3; x < (i3 + 3); x++) { for (int y = j3; y < (j3 + 3); y++) { if (x == i && y == j) { continue; } else { for (int k = 0; k < variables[x][y].domain.size(); k++) if ((variables[x][y].domain[k] == num)) { variables[x][y].domain.erase(variables[x][y].domain.begin() + k); break; } } } } } } } } /************************************************ End of Assignment ***********************************************/ CSP::CSP() { /*Initially assign the domain, assignment for each variable and initialize the current state*/ for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { variables[y][x].assignement = 0; //Initialize the assignment /*Initialize the domain*/ for (int i = 1; i <= 9; i++) { variables[y][x].domain.push_back(i); } cur_state.values[y][x] = 0; //Initizlize the current state } } alg_opt = 1; //initially set it as back track srand(time(NULL)); random = 0; } CSP::~CSP() { } void CSP::setData(int *data) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { int idx = y * 9 + x; variables[y][x].assignement = data[idx]; //Initialize the assignment cur_state.values[y][x] = data[idx]; //Initizlize the current state } } } void CSP::clearData() { /*Initially assign the domain, assignment for each variable and initialize the current state*/ for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { variables[y][x].assignement = 0; //Initialize the assignment /*Initialize the domain*/ variables[y][x].domain.clear(); for (int i = 1; i <= 9; i++) { variables[y][x].domain.push_back(i); } cur_state.values[y][x] = 0; //Initizlize the current state } } /*Check whether a random domain is use*/ if (random == 1) reshuffleDomain(); repeating_list.clear(); while (!assigned_variables.empty()) { assigned_variables.pop(); repeating_list.clear(); } } void CSP::reshuffleDomain() { for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; std::random_shuffle(variables[y][x].domain.begin(), variables[y][x].domain.end()); } } void CSP::sortDomain() { for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; std::sort(variables[y][x].domain.begin(), variables[y][x].domain.end()); } } /*Cancel last assignment*/ int CSP::goBack(int *chosen_cell) { if (assigned_variables.size() > 0) { int cur_id = assigned_variables.top(); /*Remove last options*/ assigned_variables.pop(); //pop out last option int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; //assign the cell to zero cur_state.values[y][x] = 0; //update the assignment *chosen_cell = cur_id; // printf("(%d, %d)\n", y, x); if (alg_opt == 2) { updateDomain(cur_state); } else if (alg_opt == 3) { arcConsistency(cur_state); } } return goalCheck(cur_state); } bool CSP::arcCheckingOrder(int *chosen_cell) { arcConsistency(cur_state); /*First go through all the variables and do backtrack if there is no empty domain */ for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() == 0) { int available_assignemnt = 0; //an indicatior whether there are possible possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; cur_state.values[y][x] = 0; arcConsistency(cur_state); for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(temp_state); available_assignemnt = 1; *chosen_cell = cur_id; arcConsistency(cur_state); return false; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { variables[y][x].assignement = 0; cur_state.values[y][x] = 0; assigned_variables.pop(); } } } } /*If there is no variable that has empty domain, then assign variable here*/ /*First go through all the variables and do backtrack if there is no empty domain */ int count = 0; while (count < 81) { /*Find the index of minimum number of domain*/ int min_idx = 0; int min_num = 10; //because the maximum number of domain is 10 for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() > 0) { if (variables[y][x].domain.size() < min_num) { min_idx = i; min_num = variables[y][x].domain.size(); } } } int y = min_idx / 9; int x = min_idx % 9; /*If there is any varable has not been assigned yet, assign it and return it*/ if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() > 0) { /*Find the smalles number in domain to assign it. Here no update domain for bracktrack*/ int id_min = 0; cur_state.values[y][x] = variables[y][x].domain[id_min]; variables[y][x].assignement = variables[y][x].domain[id_min]; assigned_variables.push(min_idx); //push the variable into stack, which will be used for backtrack (or DFS) repeating_list.push_back(cur_state); //make this state into the repeat_list *chosen_cell = 9 * y + x; arcConsistency(cur_state); //Every time modify the assignment update the domain return false; } count++; } if (goalCheck(cur_state)) { printf("find the goal\n"); return true; } else { int available_assignemnt = 0; //an indicatior whether there are possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; cur_state.values[y][x] = 0; arcConsistency(cur_state); for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(cur_state); available_assignemnt = 1; *chosen_cell = cur_id; break; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { assigned_variables.pop(); } } return false; } return false; } /*arcChecking without ordering*/ bool CSP::arcChecking(int *chosen_cell) { arcConsistency(cur_state); /*First go through all the variables and do backtrack if there is no empty domain */ for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() == 0) { int available_assignemnt = 0; //an indicatior whether there are possible possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; cur_state.values[y][x] = 0; arcConsistency(cur_state); for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(temp_state); available_assignemnt = 1; *chosen_cell = cur_id; arcConsistency(cur_state); return false; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { variables[y][x].assignement = 0; cur_state.values[y][x] = 0; assigned_variables.pop(); } } } } /*If there is no variable that has empty domain, then assign variable here*/ for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; /*If there is any varable has not been assigned yet, assign it and return it*/ if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() > 0) { /*Find the smalles number in domain to assign it. Here no update domain for bracktrack*/ int id_min = 0; cur_state.values[y][x] = variables[y][x].domain[id_min]; variables[y][x].assignement = variables[y][x].domain[id_min]; assigned_variables.push(i); //push the variable into stack, which will be used for backtrack (or DFS) repeating_list.push_back(cur_state); //make this state into the repeat_list *chosen_cell = 9 * y + x; arcConsistency(cur_state); //Every time modify the assignment update the domain return false; } } if (goalCheck(cur_state)) { printf("find the goal\n"); return true; } else { int available_assignemnt = 0; //an indicatior whether there are possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; cur_state.values[y][x] = 0; arcConsistency(cur_state); for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(cur_state); available_assignemnt = 1; *chosen_cell = cur_id; break; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { assigned_variables.pop(); } } return false; } return false; } /*Forward Checking algorithm*/ bool CSP::forwardChecking(int *chosen_cell) { updateDomain(cur_state); //the first step is based on current setting to update the domain /*First go through all the variables and do backtrack whether there is an empty domain */ for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() == 0) { int available_assignemnt = 0; //an indicatior whether there are possible possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; cur_state.values[y][x] = 0; updateDomain(cur_state); for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(temp_state); available_assignemnt = 1; *chosen_cell = cur_id; updateDomain(cur_state); return false; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { variables[y][x].assignement = 0; cur_state.values[y][x] = 0; assigned_variables.pop(); } } } } /*If there is no variable that has empty domain, then assign variable here*/ for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; /*If there is any varable has not been assigned yet, assign it and return it*/ if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() > 0) { /*Find the smalles number in domain to assign it. Here no update domain for bracktrack*/ int id_min = 0; cur_state.values[y][x] = variables[y][x].domain[id_min]; variables[y][x].assignement = variables[y][x].domain[id_min]; assigned_variables.push(i); //push the variable into stack, which will be used for backtrack (or DFS) repeating_list.push_back(cur_state); //make this state into the repeat_list *chosen_cell = 9 * y + x; updateDomain(cur_state); //Every time modify the assignment update the domain return false; } } if (goalCheck(cur_state)) { printf("find the goal\n"); return true; } else { int available_assignemnt = 0; //an indicatior whether there are possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; cur_state.values[y][x] = 0; updateDomain(cur_state); for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(cur_state); available_assignemnt = 1; *chosen_cell = cur_id; break; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { assigned_variables.pop(); } } return false; } return false; } /*Forward Checking algorithm*/ bool CSP::forwardCheckingOrder(int *chosen_cell) { updateDomain(cur_state); //the first step is based on current setting to update the domain /*First go through all the variables and do backtrack whether there is an empty domain */ for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() == 0) { int available_assignemnt = 0; //an indicatior whether there are possible possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; cur_state.values[y][x] = 0; updateDomain(cur_state); for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(temp_state); available_assignemnt = 1; *chosen_cell = cur_id; updateDomain(cur_state); return false; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { variables[y][x].assignement = 0; cur_state.values[y][x] = 0; assigned_variables.pop(); } } } } int count = 0; while (count < 81) { /*Find the index of minimum number of domain*/ int min_idx = 0; int min_num = 10; //because the maximum number of domain is 10 for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() > 0) { if (variables[y][x].domain.size() < min_num) { min_idx = i; min_num = variables[y][x].domain.size(); } } } int y = min_idx / 9; int x = min_idx % 9; /*If there is any varable has not been assigned yet, assign it and return it*/ if (cur_state.values[y][x] == 0 && variables[y][x].domain.size() > 0) { /*Find the smalles number in domain to assign it. Here no update domain for bracktrack*/ int id_min = 0; cur_state.values[y][x] = variables[y][x].domain[id_min]; variables[y][x].assignement = variables[y][x].domain[id_min]; assigned_variables.push(min_idx); //push the variable into stack, which will be used for backtrack (or DFS) repeating_list.push_back(cur_state); //make this state into the repeat_list *chosen_cell = 9 * y + x; \ updateDomain(cur_state); //Every time modify the assignment update the domain return false; } count++; } if (goalCheck(cur_state)) { printf("find the goal\n"); return true; } else { int available_assignemnt = 0; //an indicatior whether there are possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; variables[y][x].assignement = 0; cur_state.values[y][x] = 0; updateDomain(cur_state); for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(cur_state); available_assignemnt = 1; *chosen_cell = cur_id; break; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { assigned_variables.pop(); } } return false; } return false; } /*Back Track to solve the proble*/ bool CSP::backTrack(int *chosen_cell) { for (int i = 0; i < 81; i++) { int y = i / 9; int x = i % 9; /*If there is any varable has not been assigned yet, assign it and break*/ if (cur_state.values[y][x] == 0) { /*Find the smalles number in domain to assign it. Here no update domain for bracktrack*/ int id_min = 0; cur_state.values[y][x] = variables[y][x].domain[id_min]; variables[y][x].assignement = variables[y][x].domain[id_min]; assigned_variables.push(i); //push the variable into stack, which will be used for backtrack (or DFS) repeating_list.push_back(cur_state); //make this state into the repeat_list *chosen_cell = 9 * y + x; return false; } } /*If all the the variable are assigned*/ { if (assigned_variables.size() == 0)//reset all the variables if there are no any varaibles assigned yet { for (int i = 0; i < 81; i++) { assigned_variables.push(i); } } if (goalCheck(cur_state)) { printf("find the goal\n"); return true; } else { int available_assignemnt = 0; //an indicatior whether there are possible varaibles to be re-assigned while (available_assignemnt == 0) { int cur_id = assigned_variables.top(); int y = cur_id / 9; int x = cur_id % 9; for (int i = 0; i < variables[y][x].domain.size(); i++) { State temp_state; temp_state = cur_state; temp_state.values[y][x] = variables[y][x].domain[i]; if (std::find(repeating_list.begin(), repeating_list.end(), temp_state) == repeating_list.end()) //if not in the repeating list { cur_state = temp_state; variables[y][x].assignement = variables[y][x].domain[i]; repeating_list.push_back(cur_state); available_assignemnt = 1; *chosen_cell = cur_id; break; //get out of the current varaible assignment } } if (available_assignemnt == 0) //if all the domain values have been tried for current variable { variables[y][x].assignement = 0; cur_state.values[y][x] = 0; assigned_variables.pop(); } } return false; } } }
fd75d1eb1dda4b2351e970b9a2be46c22c6fab63
[ "C++" ]
1
C++
zealprajapati/sudoku
59c13a3d351182084ca63346e9abbe35f55e3ec8
4132d4745f7f5ea015171b0c6ec6388d2fa44d78
refs/heads/master
<file_sep># post-form-google-forms-client Sometimes, the client wants to store data in google forms along with storage at their end.<br/> check the embedFormHandler.js ## Basic logic form has action defined with the default google-form-response url,<br/> if invalid, we ensure event.preventDefault() which prevents the form from being submitted<br/> if valid, form is automatically submitted to goole-form and also the client storage<br/> <file_sep>var nameInput = document.getElementById('nameInput'); var phoneInput = document.getElementById('phoneInput'); var emailInput = document.getElementById('emailInput'); var submit = document.getElementById('submit'); var TEST_URL = 'http://5901b0dd6fd058001126c269.mockapi.io/user'; //emulate client URL var submitted = false; submit.addEventListener('click', function (e) { embedFormSubmitHandler(e); }); function embedFormSubmitHandler(e) { // console.log('running submitHandler. . .'); var nameValue = nameInput.value; var phoneValue = phoneInput.value; var emailValue = emailInput.value; // invalid conditions if(nameValue !== 'user'){ console.log('name invalid, do not submit'); e.preventDefault(); return ; } if(phoneValue !== '123'){ console.log('phone invalid, do not submit'); e.preventDefault(); return ; } if(emailValue !== '<EMAIL>'){ console.log('email invalid, do not submit'); e.preventDefault(); return ; } // if valid else { if(!submitted){ submitted = true; console.log('inputs valid, proceed with submission'); handlePostToClient(nameValue, phoneValue, emailValue); } } } function handlePostToClient(nameValue, phoneValue, emailValue) { console.log('running handlePostToClient. . .'); axios.post(TEST_URL, { name: nameValue, phone: phoneValue, email: emailValue }) .then(function (response) { console.log('response: ', response); }) .catch(function (err) { console.log('error: ', err); }); }
4919462c182d0e894e209f76aed4ea9c0b7b75ae
[ "Markdown", "JavaScript" ]
2
Markdown
ThekhoN/post-form-google-forms-client
b04c40baa254ef3f107b16fb85ad87acfdea09ff
efe6e95c81716d3ec18883070ce449fca4344472
refs/heads/master
<file_sep>import requests while True: question = input("Quesion:") if question == "exit": break else: post_data = {"question":question} res = requests.post(url="http://127.0.0.1:5000/question",data=post_data) print(res.text)<file_sep>from flask import Flask, request import execjs import requests app = Flask(__name__) @app.route('/question', methods=["POST"]) def question(): if request.method == "POST": question = request.form['question'] js = execjs.compile(''' function encrypt(title){ var CryptoJS = require('./jm'); var key = '39383033327777772e313530732e636e'; key = CryptoJS.enc.Hex.parse(key); var enc = CryptoJS.AES.encrypt(title ,key); var enced = enc.ciphertext.toString(); return enced; }; ''') url = "https://www.150s.cn/topic/getSubject" headers = {"Content-Type":"application/x-www-form-urlencoded", "Accept-Language":"zh-CN,en-US;q=0.8,en;q=0.6,zh;q=0.4"} data = {"secret":js.call('encrypt', question), "title":question} cookies = dict(JSESSIONID='13C7A0FC413FF43A4E98715E4D9DF78F', UM_distinctid='17196b5b0502ae-081894d8c1190a-325e2766-59b90-17196b5b051203', CNZZDATA1278612510='642624008-1587371003-%7C1587371003', Hm_lvt_b656d8b02edc9a9cf671edf4ceeddbc3='1587371423', Hm_lpvt_b656d8b02edc9a9cf671edf4ceeddbc3='1587371423') resp = requests.post(url = url, headers = headers, data = data, cookies = cookies, timeout = 1) return resp.text from app import views<file_sep>import execjs import requests js = execjs.compile(''' function encrypt(title){ var CryptoJS = require('./myjs'); var key = '39383033327777772e313530732e636e'; key = CryptoJS.enc.Hex.parse(key); var enc = CryptoJS.AES.encrypt(title ,key); var enced = enc.ciphertext.toString(); return enced; }; ''') question = input("Question:") url = "https://www.150s.cn/topic/getSubject" headers = {"Content-Type":"application/x-www-form-urlencoded", "Accept-Language":"zh-CN,en-US;q=0.8,en;q=0.6,zh;q=0.4"} data = {"secret":js.call('encrypt', question), "title":question} cookies = dict(JSESSIONID='13C7A0FC413FF43A4E98715E4D9DF78F', UM_distinctid='17196b5b0502ae-081894d8c1190a-325e2766-59b90-17196b5b051203', CNZZDATA1278612510='642624008-1587371003-%7C1587371003', Hm_lvt_b656d8b02edc9a9cf671edf4ceeddbc3='1587371423', Hm_lpvt_b656d8b02edc9a9cf671edf4ceeddbc3='1587371423') #s = requests.Session() resp = requests.post(url = url, headers = headers, data = data, cookies = cookies, timeout = 1) #print(resp.text)
b375c73d94afcc28463b2b2bc995d156da9165e7
[ "Python" ]
3
Python
Yi-Yuanzhe/wk
db0469b479d9f7af35832191fbef6c35eb1255b8
3610fef7fe8003323583e211420d66c019b0533e
refs/heads/master
<repo_name>sandrt/greenery<file_sep>/greenery/website/Models/EmailFormModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace website.Models { public class EmailFormModel { [Required, Display(Name = "Naam")] public string FromName { get; set; } [Required, Display(Name = "E-mail"), EmailAddress] public string FromEmail { get; set; } [Required, Display(Name = "Onderwerp")] public string Subject { get; set; } [Required, Display(Name = "Bericht")] public string Message { get; set; } } }<file_sep>/greenery/admincp/Models/Recipe.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace admincp.Models { public class Recipe { public int id { get; set; } public string name { get; set; } public string ingredients { get; set; } public string preparation { get; set; } public string duration { get; set; } public string user { get; set; } public string date { get; set; } } }<file_sep>/greenery/website/Controllers/ProductsController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using website.Controllers; using website.Models; namespace website.Controllers { public class ProductsController : DatabaseController { private static List<int> cartItems = new List<int>(); private static int currentProductId; public ActionResult ProductOverview() { const string selectAllProducts = "select * from gr_products inner join gr_categories on gr_products.categories_id = gr_categories.id"; MySqlCommand cmd = new MySqlCommand(); List<Product> products = new List<Product>(); ActionResult result = new ViewResult(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectAllProducts; MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { Product product = new Product { id = dataReader.GetInt32("id"), categories_id = dataReader.GetInt32("categories_id"), name = dataReader.GetString("p_name"), stock = dataReader.GetInt32("stock"), price = dataReader.GetDouble("price"), discountPrice = dataReader.GetDouble("discountPrice"), description = dataReader.GetString("description"), imagePrimary = dataReader.GetString("imagePrimary"), isOnFrontpage = dataReader.GetBoolean("isOnFrontPage"), category = dataReader.GetString("c_name"), }; products.Add(product); } connection.Close(); //loading products succesfull, go to product page result = View(products); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } public ActionResult ProductDetail(int product_id) { const string selectProduct = "select * from gr_products where id = @id"; const string selectRecipes = "select * from gr_productRecipes inner join gr_recipes on gr_productRecipes.recipe_id = gr_recipes.id inner join gr_users on gr_recipes.user = gr_users.id where product_id = @id"; Product product = new Product() { id = -1 }; MySqlCommand cmd = new MySqlCommand(); ActionResult result = new ViewResult(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectProduct; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32) { Value = product_id }); cmd.Prepare(); MySqlDataReader datareader = cmd.ExecuteReader(); datareader.Read(); product.id = product_id; product.categories_id = datareader.GetInt32("categories_id"); product.name = datareader.GetString("p_name"); product.stock = datareader.GetInt32("stock"); product.price = datareader.GetDouble("price"); product.discountPrice = datareader.GetDouble("discountPrice"); product.description = datareader.GetString("description"); product.imagePrimary = datareader.GetString("imagePrimary"); product.imageSecondaryOne = datareader.GetString("imageSecondaryOne"); product.imageSecondaryTwo = datareader.GetString("imageSecondaryTwo"); product.imageSecondaryThree = datareader.GetString("imageSecondaryThree"); product.imageSecondaryFour = datareader.GetString("imageSecondaryFour"); product.isOnFrontpage = datareader.GetBoolean("isOnFrontPage"); datareader.Close(); cmd.CommandText = selectRecipes; datareader = cmd.ExecuteReader(); while (datareader.Read()) { Recipe recipe = new Recipe(); recipe.id = datareader.GetInt32("recipe_id"); recipe.name = datareader.GetString("name"); //recipe.image = datareader.GetString("image"); recipe.ingredients = datareader.GetString("ingredients"); recipe.preparation = datareader.GetString("preparation"); recipe.duration = datareader.GetString("duration"); recipe.user = datareader.GetString("username"); recipe.date = datareader.GetString("date"); product.recipes.Add(recipe); } datareader.Close(); connection.Close(); //loading product detail succesfull, go to product page result = View(product); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } currentProductId = product_id; return result; } [HttpPost] public ActionResult SubmitRecipe(Recipe recipe) { const string insertRecipe = "insert into gr_recipes (name, ingredients, preparation, duration, user, date) " + "values (@name, @ingredients, @preparation, @duration, @user, @date)"; const string selectRecipeId = "select last_insert_id() as id " + "from gr_recipes"; const string insertProductRecipe = "insert into gr_productRecipes (product_id, recipe_id) " + "values (@product_id, @recipe_id)"; MySqlTransaction trans = null; MySqlCommand cmd = new MySqlCommand(); ActionResult result = new ViewResult(); int recipeId; try { connection.Open(); cmd.Connection = connection; trans = connection.BeginTransaction(); cmd.CommandText = insertRecipe; cmd.Parameters.Add(new MySqlParameter("@name", MySqlDbType.String) { Value = recipe.name }); cmd.Parameters.Add(new MySqlParameter("@ingredients", MySqlDbType.String) { Value = recipe.ingredients }); cmd.Parameters.Add(new MySqlParameter("@preparation", MySqlDbType.String) { Value = recipe.preparation }); cmd.Parameters.Add(new MySqlParameter("@duration", MySqlDbType.String) { Value = recipe.duration }); cmd.Parameters.Add(new MySqlParameter("@user", MySqlDbType.Int32) { Value = (Session.Count == 1? Session[0]: 0)}); cmd.Parameters.Add(new MySqlParameter("@date", MySqlDbType.Date) { Value = DateTime.Now }); cmd.Prepare(); cmd.ExecuteNonQuery(); trans.Commit(); cmd.CommandText = selectRecipeId; MySqlDataReader datareader = cmd.ExecuteReader(); datareader.Read(); recipeId = datareader.GetInt32("id"); datareader.Close(); trans = connection.BeginTransaction(); cmd.CommandText = insertProductRecipe; cmd.Parameters.Clear(); cmd.Parameters.Add(new MySqlParameter("product_id", MySqlDbType.Int32) { Value = currentProductId }); cmd.Parameters.Add(new MySqlParameter("recipe_id", MySqlDbType.Int32) { Value = recipeId }); cmd.Prepare(); cmd.ExecuteNonQuery(); trans.Commit(); connection.Close(); //submitting recipe succesfull, go to product detail page result = RedirectToAction("ProductDetail", new { product_id = currentProductId }); } catch (Exception e) { trans.Rollback(); connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } public ActionResult Cart() { const string selectSingleProduct = "select * from gr_products " + "where id = @id"; MySqlCommand cmd = new MySqlCommand(); List<ProductInCart> products = new List<ProductInCart>(); ActionResult result = new ViewResult(); int n; try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectSingleProduct; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32)); for (int i=0; i<cartItems.Count; i++) { for (n=0; n<products.Count; n++) { if (products[n].id == cartItems[i]) { products[n].amountInCart++; products[n].priceTotal += products[n].price; break; } } if (n == products.Count) { cmd.Parameters[0].Value = cartItems[i]; cmd.Prepare(); MySqlDataReader dataReader = cmd.ExecuteReader(); dataReader.Read(); ProductInCart product = new ProductInCart { id = dataReader.GetInt32("id"), categories_id = dataReader.GetInt32("categories_id"), name = dataReader.GetString("p_name"), stock = dataReader.GetInt32("stock"), price = dataReader.GetDouble("price"), discountPrice = dataReader.GetDouble("discountPrice"), description = dataReader.GetString("description"), imagePrimary = dataReader.GetString("imagePrimary"), isOnFrontpage = dataReader.GetBoolean("isOnFrontPage"), amountInCart = 1, priceTotal = dataReader.GetDouble("price") }; products.Add(product); dataReader.Close(); } } connection.Close(); //loading cart succesfull, go to cart page result = View(products); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } [HttpPost] public ActionResult AddToCart(int productID) { cartItems.Add(productID); return RedirectToAction("ProductOverview"); } [HttpPost] public ActionResult AddToCartFromDetail(int productID) { cartItems.Add(productID); return RedirectToAction("ProductDetail", new { product_id = currentProductId }); } [HttpPost] public ActionResult RemoveFromCart(int productID) { int n = 0; do { if (cartItems[n] == productID) { cartItems.RemoveAt(n); } n++; } while (n < cartItems.Count); return RedirectToAction("Cart"); } public ActionResult Checkout() { const string selectUser = "select * from gr_users " + "where id = @id"; const string selectSingleProduct = "select * from gr_products " + "where id = @id"; MySqlCommand cmd = new MySqlCommand(); Checkout checkout = new Checkout(); checkout.user = new Profile(); checkout.products = new List<ProductInCart>(); ActionResult result = new ViewResult(); int n; try { connection.Open(); cmd.Connection = connection; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32)); if (Session.Count == 1) { cmd.CommandText = selectUser; cmd.Parameters[0].Value = Session[0]; cmd.Prepare(); MySqlDataReader datareader = cmd.ExecuteReader(); datareader.Read(); checkout.user.firstname = datareader.GetString("firstname"); checkout.user.lastname = datareader.GetString("lastname"); checkout.user.streetname = datareader.GetString("streetname"); checkout.user.adress = datareader.GetString("adress"); checkout.user.zipcode = datareader.GetString("zipcode"); checkout.user.city = datareader.GetString("city"); checkout.user.phonenumber = datareader.GetString("phonenumber"); checkout.user.mobilePhonenumber = datareader.GetString("mobilePhonenumber"); checkout.user.username = datareader.GetString("username"); checkout.user.email = datareader.GetString("email"); checkout.user.password = datareader.GetString("password"); datareader.Close(); } cmd.CommandText = selectSingleProduct; for (int i = 0; i < cartItems.Count; i++) { for (n = 0; n < checkout.products.Count; n++) { if (checkout.products[n].id == cartItems[i]) { checkout.products[n].amountInCart++; checkout.products[n].priceTotal += checkout.products[n].price; break; } } if (n == checkout.products.Count) { cmd.Parameters[0].Value = cartItems[i]; cmd.Prepare(); MySqlDataReader dataReader = cmd.ExecuteReader(); dataReader.Read(); ProductInCart product = new ProductInCart { id = dataReader.GetInt32("id"), categories_id = dataReader.GetInt32("categories_id"), name = dataReader.GetString("p_name"), stock = dataReader.GetInt32("stock"), price = dataReader.GetDouble("price"), discountPrice = dataReader.GetDouble("discountPrice"), description = dataReader.GetString("description"), imagePrimary = dataReader.GetString("imagePrimary"), isOnFrontpage = dataReader.GetBoolean("isOnFrontPage"), amountInCart = 1, priceTotal = dataReader.GetDouble("price") }; checkout.products.Add(product); dataReader.Close(); } } connection.Close(); //loading user data and cart succesfull, go to checkout page result = View(checkout); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } } }<file_sep>/greenery/admincp/Models/Login.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace admincp.Models { public class Login { protected const string fieldManditory = "Dit veld is verplicht"; public string message { get; set; } [Required(ErrorMessage = fieldManditory)] public string username { get; set; } [Required(ErrorMessage = fieldManditory)] public string password { get; set; } } }<file_sep>/greenery/website/Models/Profile.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace website.Models { public class Login { protected const string fieldManditory = "Dit veld is verplicht"; public string message { get; set; } [Required(ErrorMessage = fieldManditory)] public string username { get; set; } [Required(ErrorMessage = fieldManditory)] public string password { get; set; } } public class Profile : Login { [Required(ErrorMessage = fieldManditory)] public string firstname { get; set; } [Required(ErrorMessage = fieldManditory)] public string lastname { get; set; } [Required(ErrorMessage = fieldManditory)] public string streetname { get; set; } [Required(ErrorMessage = fieldManditory)] public string adress { get; set; } [Required(ErrorMessage = fieldManditory)] public string zipcode { get; set; } [Required(ErrorMessage = fieldManditory)] public string city { get; set; } public string phonenumber { get; set; } public string mobilePhonenumber { get; set; } [Required(ErrorMessage = fieldManditory)] public string email { get; set; } } }<file_sep>/greenery/website/Models/Product.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace website.Models { public class Product { public int id { get; set; } public int categories_id { get; set; } public string name { get; set; } public string category { get; set; } public int stock { get; set; } public double price { get; set; } public double discountPrice { get; set; } public string description { get; set; } public string imagePrimary { get; set; } public string imageSecondaryOne { get; set; } public string imageSecondaryTwo { get; set; } public string imageSecondaryThree { get; set; } public string imageSecondaryFour { get; set; } public string imageNotFound { get; } = "Afbeelding niet gevonden"; public bool isOnFrontpage { get; set; } public List<Recipe> recipes = new List<Recipe>(); } public class ProductInCart : Product { public int amountInCart { get; set; } public double priceTotal { get; set; } } }<file_sep>/greenery/website/Controllers/HomeController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using website.Controllers; using website.Models; namespace website.Controllers { public class HomeController : DatabaseController { // GET: Index public ActionResult Home() { List<Product> products = new List<Product>(); try { // note that the connection to the database is managed in the super class! connection.Open(); // get the products from the database //// TODO: we should try to keep this layer of the application clean by moving the sql/database specific code to another controller string selectQuery = "select * from gr_products"; MySqlCommand cmd = new MySqlCommand(selectQuery, connection); MySqlDataReader dataReader = cmd.ExecuteReader(); // data has been fetched, transform it into a clean model while (dataReader.Read()) { int id = dataReader.GetInt32("id"); bool isOnFrontPage = dataReader.GetBoolean("isOnFrontPage"); double price = dataReader.GetDouble("price"); double discountPrice = dataReader.GetDouble("discountPrice"); string imagePrimary = dataReader.GetString("imagePrimary"); Product product = new Product { id = id, isOnFrontpage = isOnFrontPage, price = price, discountPrice = discountPrice, imagePrimary = imagePrimary }; products.Add(product); } } catch (Exception e) { // redirect to our custom error view return View("Error", new Error { Message = "An error occurred fetching the products from the database.", Exception = e }); } finally { connection.Close(); } // return the list view return View(products); } } }<file_sep>/greenery/website/Models/Checkout.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace website.Models { public class Checkout { public Profile user { get; set; } public List<ProductInCart> products; } }<file_sep>/greenery/admincp/Models/Customers.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace admincp.Models { public class Customers { public int id { get; set; } public string message { get; set; } public string username { get; set; } public string password { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string streetname { get; set; } public string adress { get; set; } public string zipcode { get; set; } public string city { get; set; } public string phonenumber { get; set; } public string mobilePhonenumber { get; set; } public string email { get; set; } } }<file_sep>/greenery/admincp/Controllers/ProductsController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using admincp.Controllers; using admincp.Models; namespace admincp.Controllers { public class ProductsController : DatabaseController { // GET: Products public ActionResult Products() { const string selectAllProducts = "select * from gr_products inner join gr_categories on gr_products.categories_id = gr_categories.id"; MySqlCommand cmd = new MySqlCommand(); List<Product> products = new List<Product>(); ActionResult result = new ViewResult(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectAllProducts; MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { Product product = new Product { id = dataReader.GetInt32("id"), categories_id = dataReader.GetInt32("categories_id"), name = dataReader.GetString("p_name"), stock = dataReader.GetInt32("stock"), price = dataReader.GetDouble("price"), discountPrice = dataReader.GetDouble("discountPrice"), description = dataReader.GetString("description"), imagePrimary = dataReader.GetString("imagePrimary"), isOnFrontpage = dataReader.GetBoolean("isOnFrontPage"), category = dataReader.GetString("c_name"), }; products.Add(product); } connection.Close(); //loading products succesfull, go to product page result = View(products); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } [HttpPost] public ActionResult DeleteProduct(int product_id) { const string deleteProduct = "delete from gr_products where id = @id"; const string deleteProductRecipe = "delete from gr_productRecipes (product_id, recipe_id) " + "values (@product_id, @recipe_id)"; const string deleteRecipe = "delete from gr_recipes (id) " + "values (@id"; Customers customers = new Customers() { id = -1 }; MySqlCommand cmd = new MySqlCommand(); ActionResult result = new ViewResult(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = deleteProduct; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32) { Value = product_id }); cmd.Prepare(); cmd.ExecuteNonQuery(); connection.Close(); //deleting product succesfull, go to product admin page result = RedirectToAction("products"); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } } }<file_sep>/greenery/admincp/Controllers/RecipesController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Web.Mvc; using admincp.Models; namespace admincp.Controllers { public class RecipesController : DatabaseController { // GET: Recipes public ActionResult Recipes() { const string selectAllRecipes = "select * from gr_recipes"; MySqlCommand cmd = new MySqlCommand(); List<Recipe> recipes = new List<Recipe>(); ActionResult result = new ViewResult(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectAllRecipes; MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { Recipe recipe = new Recipe { id = dataReader.GetInt32("id"), name = dataReader.GetString("name"), ingredients = dataReader.GetString("ingredients"), preparation = dataReader.GetString("preparation"), duration = dataReader.GetString("duration"), date = dataReader.GetString("date"), }; recipes.Add(recipe); } connection.Close(); //loading products succesfull, go to product page result = View(recipes); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } } }<file_sep>/greenery/website/Controllers/ProfileController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using website.Controllers; using website.Models; namespace website.Controllers { public class ProfileController : DatabaseController { // GET: Profile public ActionResult profile(User userchange) { if (HttpContext.Request.HttpMethod == "POST") { MySqlTransaction trans = null; try { connection.Open(); trans = connection.BeginTransaction(); string insertString = @"update gr_users set name = '@name', lastname = '@lastname', zipcode = '@zipcode', streetname = '@streetname', housenumber = '@housenumber', phonenumber = '@phonenumber', mobilenumber = '@mobilenumber', username = '@username', password = <PASSWORD>', email = '@email' where username = 'test'"; MySqlCommand cmd = new MySqlCommand(insertString, connection); MySqlParameter nameParam = new MySqlParameter("@name", MySqlDbType.VarChar); MySqlParameter lastnameParam = new MySqlParameter("@lastname", MySqlDbType.VarChar); MySqlParameter zipcodeParam = new MySqlParameter("@zipcode", MySqlDbType.VarChar); MySqlParameter streetnameParam = new MySqlParameter("@streetname", MySqlDbType.VarChar); MySqlParameter housenumberParam = new MySqlParameter("@housenumber", MySqlDbType.VarChar); MySqlParameter phonenumberParam = new MySqlParameter("@phonenumber", MySqlDbType.VarChar); MySqlParameter mobilenumberParam = new MySqlParameter("@mobilenumber", MySqlDbType.VarChar); MySqlParameter usernameParam = new MySqlParameter("@username", MySqlDbType.VarChar); MySqlParameter passwordParam = new MySqlParameter("@password", MySqlDbType.VarChar); MySqlParameter emailParam = new MySqlParameter("@email", MySqlDbType.VarChar); nameParam.Value = userchange.Name; lastnameParam.Value = userchange.Lastname; zipcodeParam.Value = userchange.Zipcode; streetnameParam.Value = userchange.Streetname; housenumberParam.Value = userchange.Housenumber; phonenumberParam.Value = userchange.Phonenumber; mobilenumberParam.Value = userchange.Mobilenumber; usernameParam.Value = userchange.Username; passwordParam.Value = <PASSWORD>; emailParam.Value = userchange.Email; cmd.Parameters.Add(nameParam); cmd.Parameters.Add(lastnameParam); cmd.Parameters.Add(zipcodeParam); cmd.Parameters.Add(streetnameParam); cmd.Parameters.Add(housenumberParam); cmd.Parameters.Add(phonenumberParam); cmd.Parameters.Add(mobilenumberParam); cmd.Parameters.Add(usernameParam); cmd.Parameters.Add(passwordParam); cmd.Parameters.Add(emailParam); cmd.Prepare(); cmd.ExecuteNonQuery(); trans.Commit(); } catch (Exception e) { trans.Rollback(); return View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } finally { connection.Close(); } } List<User> users = new List<User>(); try { // note that the connection to the database is managed in the super class! connection.Open(); // get the students from the database //// TODO: we should try to keep this layer of the application clean by moving the sql/database specific code to another controller string selectQuery = "select * from gr_users where username = 'test'"; MySqlCommand cmd = new MySqlCommand(selectQuery, connection); MySqlDataReader dataReader = cmd.ExecuteReader(); // data has been fetched, transform it into a clean model while (dataReader.Read()) { int id = dataReader.GetInt32("id"); string name = dataReader.GetString("name"); string lastname = dataReader.GetString("lastname"); string zipcode = dataReader.GetString("zipcode"); string streetname = dataReader.GetString("streetname"); string housenumber = dataReader.GetString("housenumber"); string phonenumber = dataReader.GetString("phonenumber"); string mobilenumber = dataReader.GetString("mobilenumber"); string username = dataReader.GetString("username"); string password = dataReader.GetString("password"); string email = dataReader.GetString("email"); User user = new User { Id = id, Name = name, Lastname = lastname, Zipcode = zipcode, Streetname = streetname, Housenumber = housenumber, Phonenumber = phonenumber, Mobilenumber = mobilenumber, Username = username, Password = <PASSWORD>, Email = email }; users.Add(user); } } catch (Exception e) { // redirect to our custom error view return View("Error", new Error { Message = "An error occurred fetching the users from the database.", Exception = e }); } finally { connection.Close(); } // return the list view return View(users); } } }<file_sep>/greenery/admincp/Controllers/DatabaseController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MySql.Data.MySqlClient; namespace admincp.Controllers { public class DatabaseController : Controller { protected MySqlConnection connection { get; private set; } public DatabaseController() { connection = new MySqlConnection("Server=db4free.net;Database=the_greenery;Uid=the_greenery;Pwd=<PASSWORD>;"); } } }<file_sep>/greenery/website/Controllers/LoginController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using website.Controllers; using website.Models; namespace website.Controllers { public class LoginController : DatabaseController { List<User> users = new List<User>(); // GET: Login public ActionResult Login() { try { // note that the connection to the database is managed in the super class! connection.Open(); // get the users from the database //// TODO: we should try to keep this layer of the application clean by moving the sql/database specific code to another controller string selectQuery = "select * from gr_users"; MySqlCommand cmd = new MySqlCommand(selectQuery, connection); MySqlDataReader dataReader = cmd.ExecuteReader(); // data has been fetched, transform it into a clean model while (dataReader.Read()) { int id = dataReader.GetInt32("id"); String username = dataReader.GetString("username"); String password = dataReader.GetString("password"); User user = new User { id = id, username = username, password = <PASSWORD> }; users.Add(user); } } catch (Exception e) { // redirect to our custom error view return View("Error", new Error { Message = "An error occurred fetching the users from the database.", Exception = e }); } finally { connection.Close(); } // return the view return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult SubmitLogin(User u) { // this action is for handle post (login) if (ModelState.IsValid) // this is check validity { var v = users.Where(a => a.username.Equals(u.username) && a.password.Equals(u.password)).FirstOrDefault(); if (v != null) { Session["LogedUserID"] = v.id.ToString(); Session["LogedUserLastname"] = v.lastname.ToString(); return RedirectToAction("AfterLogin"); } } return View(u); } public ActionResult AfterLogin() { if (Session["LogedUserID"] != null) { return View(); } else { return RedirectToAction("Login"); } } } } <file_sep>/greenery/website/Controllers/ContactController.cs using System.Web.Mvc; using System.Net; using System.Net.Mail; using System.Threading.Tasks; using website.Models; namespace website.Controllers { public class ContactController : Controller { // GET: Contact public ActionResult Contact() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Contact(EmailFormModel model) { if (ModelState.IsValid) { var body = "<p>Naam:{0}</p><p>E-mail:({1})</p><p>Onderwerp:{2}</p><p>Bericht:{3}</p>"; var message = new MailMessage(); message.To.Add(new MailAddress("<EMAIL>")); message.From = new MailAddress("<EMAIL>"); message.Subject = "Bericht van website: " + model.Subject; message.Body = string.Format(body, model.FromName, model.FromEmail, model.Subject, model.Message); message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credential = new NetworkCredential { UserName = "<EMAIL>", Password = "<PASSWORD>" }; smtp.Credentials = credential; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; await smtp.SendMailAsync(message); return RedirectToAction("Sent"); } } return View(model); } public ActionResult Sent() { return View(); } } }<file_sep>/greenery/website/App_Start/RouteConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace website { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "AboutUs", url: "aboutus", defaults: new { controller = "AboutUs", action = "AboutUs"} ); routes.MapRoute( name: "Cart", url: "cart", defaults: new { controller = "Cart", action = "Cart" } ); routes.MapRoute( name: "Checkout", url: "checkout", defaults: new { controller = "Checkout", action = "Checkout" } ); routes.MapRoute( name: "Contact", url: "contact", defaults: new { controller = "Contact", action = "Contact" } ); routes.MapRoute( name: "Login", url: "login", defaults: new { controller = "Login", action = "Login" } ); routes.MapRoute( name: "ProductDetail", url: "productdetail", defaults: new { controller = "ProductDetail", action = "ProductDetail" } ); routes.MapRoute( name: "Products", url: "products", defaults: new { controller = "Products", action = "Products" } ); routes.MapRoute( name: "Profile", url: "profile", defaults: new { controller = "Profile", action = "Profile" } ); routes.MapRoute( name: "Register", url: "registreer", defaults: new { controller = "Register", action = "Register" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "Home", action = "Home" } ); } } } <file_sep>/greenery/admincp/Controllers/LoginController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using admincp.Controllers; using admincp.Models; namespace admincp.Controllers { public class LoginController : DatabaseController { public ActionResult Login() { return View(new Login() { message = "" }); } [HttpPost] public ActionResult SubmitLogin(Login user) { ActionResult result = new ViewResult(); if (ModelState.IsValid) { const string selectUser = "select id, password, username from gr_admin_users " + "where username = @username"; MySqlCommand cmd = new MySqlCommand(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectUser; cmd.Parameters.Add(new MySqlParameter("@username", MySqlDbType.VarChar) { Value = user.username }); cmd.Prepare(); MySqlDataReader datareader = cmd.ExecuteReader(); if (datareader.Read()) { if (datareader.GetString("password").Equals(user.password)) { Session.Add("user id", datareader.GetInt32("id")); //login succesfull, go to dashboard page result = RedirectToAction("Dashboard", "Dashboard"); } else { //password incorrect, reload login page to correct credentials result = View("Login", new Login { message = "Dit wachtwoord is onjuist" }); } } else { //username not found, reload login page to correct credentials result = View("Login", new Login { message = "Deze gebruikersnaam is niet bij ons bekend" }); } connection.Close(); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } } else { //validations incorrect, reload login page with validation messages user.message = "Niet alle velden zijn ingevuld"; result = View("Login", user); } return result; } public ActionResult Logout() { Session.Clear(); return RedirectToAction("Login", "Login"); } private ActionResult ViewWithProfile(Login user) { ActionResult result = new ViewResult(); const string selectUser = "select * from gr_admin_users " + "where id = @id"; MySqlCommand cmd = new MySqlCommand(); try { if (Session.Count == 1) { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectUser; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32) { Value = Session[0] }); cmd.Prepare(); MySqlDataReader datareader = cmd.ExecuteReader(); if (datareader.Read()) { user.username = datareader.GetString("username"); user.password = <PASSWORD>("<PASSWORD>"); //loading user data succesfull, go to update page with user data result = View("Update", user); } else { //id of currently logged in user not found, go to home page //should not occur, you would not have been able to log in result = RedirectToAction("Login", "Login"); } } else { //no user logged in, go to home page //should not occur, profile button would not be present result = RedirectToAction("Login", "Login"); } connection.Close(); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } } }<file_sep>/greenery/website/Controllers/UsersController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using website.Controllers; using website.Models; namespace website.Controllers { public class UsersController : DatabaseController { public ActionResult Registration() { return View(new Profile() { message = "" }); } [HttpPost] public ActionResult SubmitRegistration(Profile user) { ActionResult result = new ViewResult(); if (ModelState.IsValid) { const string insertUser = "insert into gr_users (firstname, lastname, streetname, adress, zipcode, city, phonenumber, mobilePhonenumber, username, email, password) " + "values (@firstname, @lastname, @streetname, @adress, @zipcode, @city, @phonenumber, @mobilePhonenumber, @username, @email, @password)"; const string checkUsername = "select count(*) as equalUsernames from gr_users " + "where username = @username"; MySqlTransaction trans = null; MySqlCommand cmd = new MySqlCommand(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = checkUsername; cmd.Parameters.Add(new MySqlParameter("@username", MySqlDbType.VarChar) { Value = user.username }); cmd.Prepare(); MySqlDataReader datareader = cmd.ExecuteReader(); datareader.Read(); if (datareader.GetInt32("equalUsernames") == 0) { datareader.Close(); cmd.Parameters.Clear(); trans = connection.BeginTransaction(); cmd.CommandText = insertUser; cmd.Parameters.Add(new MySqlParameter("@firstname", MySqlDbType.VarChar) { Value = user.firstname }); cmd.Parameters.Add(new MySqlParameter("@lastname", MySqlDbType.VarChar) { Value = user.lastname }); cmd.Parameters.Add(new MySqlParameter("@streetname", MySqlDbType.VarChar) { Value = user.streetname }); cmd.Parameters.Add(new MySqlParameter("@adress", MySqlDbType.VarChar) { Value = user.adress }); cmd.Parameters.Add(new MySqlParameter("@zipcode", MySqlDbType.VarChar) { Value = user.zipcode }); cmd.Parameters.Add(new MySqlParameter("@city", MySqlDbType.VarChar) { Value = user.city }); cmd.Parameters.Add(new MySqlParameter("@phonenumber", MySqlDbType.VarChar) { Value = user.phonenumber }); cmd.Parameters.Add(new MySqlParameter("@mobilePhonenumber", MySqlDbType.VarChar) { Value = user.mobilePhonenumber }); cmd.Parameters.Add(new MySqlParameter("@username", MySqlDbType.VarChar) { Value = user.username }); cmd.Parameters.Add(new MySqlParameter("@email", MySqlDbType.VarChar) { Value = user.email }); cmd.Parameters.Add(new MySqlParameter("@password", MySqlDbType.VarChar) { Value = user.password }); cmd.Prepare(); cmd.ExecuteNonQuery(); trans.Commit(); //registration succesfull, go to home page result = RedirectToAction("Home", "Home"); } else { //username already in use, reload registration page to correct credentials result = View("Registration", new Profile { message = "Deze gebruikersnaam is al in gebruik" }); } connection.Close(); } catch (Exception e) { if (trans != null) { trans.Rollback(); } connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } } else { //validation incorrect, reload registration page with validation messages user.message = "Niet alle velden zijn ingevuld"; result = View("Registration", user); } return result; } public ActionResult Update() { return ViewWithProfile(new Profile() { message = "" }); } [HttpPost] public ActionResult SubmitUpdate(Profile user) { ActionResult result = new ViewResult(); if (ModelState.IsValid) { const string updateUser = "update gr_users " + "set firstname = @firstname, lastname = @lastname, streetname = @streetname, adress = @adress, zipcode = @zipcode, city = @city, phonenumber = @phonenumber, mobilePhonenumber = @mobilePhonenumber, username = @username, email = @email, password = <PASSWORD> " + "where id = @id"; MySqlTransaction trans = null; MySqlCommand cmd = new MySqlCommand(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = updateUser; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32) { Value = Session[0] }); cmd.Parameters.Add(new MySqlParameter("@firstname", MySqlDbType.VarChar) { Value = user.firstname }); cmd.Parameters.Add(new MySqlParameter("@lastname", MySqlDbType.VarChar) { Value = user.lastname }); cmd.Parameters.Add(new MySqlParameter("@streetname", MySqlDbType.VarChar) { Value = user.streetname }); cmd.Parameters.Add(new MySqlParameter("@adress", MySqlDbType.VarChar) { Value = user.adress }); cmd.Parameters.Add(new MySqlParameter("@zipcode", MySqlDbType.VarChar) { Value = user.zipcode }); cmd.Parameters.Add(new MySqlParameter("@city", MySqlDbType.VarChar) { Value = user.city }); cmd.Parameters.Add(new MySqlParameter("@phonenumber", MySqlDbType.VarChar) { Value = user.phonenumber }); cmd.Parameters.Add(new MySqlParameter("@mobilePhonenumber", MySqlDbType.VarChar) { Value = user.mobilePhonenumber }); cmd.Parameters.Add(new MySqlParameter("@username", MySqlDbType.VarChar) { Value = user.username }); cmd.Parameters.Add(new MySqlParameter("@email", MySqlDbType.VarChar) { Value = user.email }); cmd.Parameters.Add(new MySqlParameter("@password", MySqlDbType.VarChar) { Value = user.password }); cmd.Prepare(); trans = connection.BeginTransaction(); cmd.ExecuteNonQuery(); trans.Commit(); connection.Close(); //update succesfull, reload update page to view new user data and make additional changes if desired result = ViewWithProfile(new Profile { message = "Uw profiel gegevens zijn bijgewerkt" }); } catch (Exception e) { trans.Rollback(); connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } } else { //validation incorrect, reload update page with validation messages user.message = "Niet alle velden zijn ingevuld"; result = View("Update", user); } return result; } public ActionResult Login() { return View(new Login() { message = "" }); } [HttpPost] public ActionResult SubmitLogin(Login user) { ActionResult result = new ViewResult(); if (ModelState.IsValid) { const string selectUser = "select id, password, username from gr_users " + "where username = @username"; MySqlCommand cmd = new MySqlCommand(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectUser; cmd.Parameters.Add(new MySqlParameter("@username", MySqlDbType.VarChar) { Value = user.username }); cmd.Prepare(); MySqlDataReader datareader = cmd.ExecuteReader(); if (datareader.Read()) { if (datareader.GetString("password").Equals(user.password)) { Session.Add("user id", datareader.GetInt32("id")); //login succesfull, go to home page result = RedirectToAction("Home", "Home"); } else { //password incorrect, reload login page to correct credentials result = View("Login", new Login { message = "Dit wachtwoord is onjuist" }); } } else { //username not found, reload login page to correct credentials result = View("Login", new Login { message = "Deze gebruikersnaam is niet bij ons bekend" }); } connection.Close(); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } } else { //validations incorrect, reload login page with validation messages user.message = "Niet alle velden zijn ingevuld"; result = View("Login", user); } return result; } public ActionResult Logout() { Session.Clear(); return RedirectToAction("Home", "Home"); } private ActionResult ViewWithProfile(Profile user) { const string selectUser = "select * from gr_users " + "where id = @id"; MySqlCommand cmd = new MySqlCommand(); ActionResult result = new ViewResult(); try { if (Session.Count == 1) { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectUser; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32) { Value = Session[0] }); cmd.Prepare(); MySqlDataReader datareader = cmd.ExecuteReader(); datareader.Read(); user.firstname = datareader.GetString("firstname"); user.lastname = datareader.GetString("lastname"); user.streetname = datareader.GetString("streetname"); user.adress = datareader.GetString("adress"); user.zipcode = datareader.GetString("zipcode"); user.city = datareader.GetString("city"); user.phonenumber = datareader.GetString("phonenumber"); user.mobilePhonenumber = datareader.GetString("mobilePhonenumber"); user.username = datareader.GetString("username"); user.email = datareader.GetString("email"); user.password = <PASSWORD>("<PASSWORD>"); datareader.Close(); //loading user data succesfull, go to update page with user data result = View("Update", user); } else { //no user logged in, go to home page //should not occur, profile button would not be present result = RedirectToAction("Home", "Home"); } connection.Close(); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } } }<file_sep>/greenery/website/Controllers/RegisterController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using website.Controllers; using website.Models; namespace website.Controllers { public class RegisterController : DatabaseController { // GET: Register public ActionResult Register(User user) { if (HttpContext.Request.HttpMethod == "POST") { MySqlTransaction trans = null; try { connection.Open(); trans = connection.BeginTransaction(); string insertString = @"insert into gr_users (name, lastname, zipcode, streetname, housenumber, phonenumber, mobilenumber, username, password, email) values (@name, @lastname, @zipcode, @streetname, @housenumber, @phonenumber, @mobilenumber, @username, @password, @email)"; MySqlCommand cmd = new MySqlCommand(insertString, connection); MySqlParameter nameParam = new MySqlParameter("@name", MySqlDbType.VarChar); MySqlParameter lastnameParam = new MySqlParameter("@lastname", MySqlDbType.VarChar); MySqlParameter zipcodeParam = new MySqlParameter("@zipcode", MySqlDbType.VarChar); MySqlParameter streetnameParam = new MySqlParameter("@streetname", MySqlDbType.VarChar); MySqlParameter housenumberParam = new MySqlParameter("@housenumber", MySqlDbType.VarChar); MySqlParameter phonenumberParam = new MySqlParameter("@phonenumber", MySqlDbType.VarChar); MySqlParameter mobilenumberParam = new MySqlParameter("@mobilenumber", MySqlDbType.VarChar); MySqlParameter usernameParam = new MySqlParameter("@username", MySqlDbType.VarChar); MySqlParameter passwordParam = new MySqlParameter("@password", MySqlDbType.VarChar); MySqlParameter emailParam = new MySqlParameter("@email", MySqlDbType.VarChar); nameParam.Value = user.Name; lastnameParam.Value = user.Lastname; zipcodeParam.Value = user.Zipcode; streetnameParam.Value = user.Streetname; housenumberParam.Value = user.Housenumber; phonenumberParam.Value = user.Phonenumber; mobilenumberParam.Value = user.Mobilenumber; usernameParam.Value = user.Username; passwordParam.Value = <PASSWORD>; emailParam.Value = user.Email; cmd.Parameters.Add(nameParam); cmd.Parameters.Add(lastnameParam); cmd.Parameters.Add(zipcodeParam); cmd.Parameters.Add(streetnameParam); cmd.Parameters.Add(housenumberParam); cmd.Parameters.Add(phonenumberParam); cmd.Parameters.Add(mobilenumberParam); cmd.Parameters.Add(usernameParam); cmd.Parameters.Add(passwordParam); cmd.Parameters.Add(emailParam); cmd.Prepare(); cmd.ExecuteNonQuery(); //ViewData["Mijn naam"] = "Test"; //ViewBag.MijnNaam = "Test"; trans.Commit(); } catch (Exception e) { trans.Rollback(); return View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } finally { connection.Close(); } } return View(); } } }<file_sep>/greenery/admincp/Controllers/CustomersController.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using admincp.Controllers; using admincp.Models; namespace admincp.Controllers { public class CustomersController : DatabaseController { private static int currentCustomersId; // GET: Customers public ActionResult Customers() { const string selectAllProducts = "select * from gr_users"; MySqlCommand cmd = new MySqlCommand(); List<Customers> customers = new List<Customers>(); ActionResult result = new ViewResult(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectAllProducts; MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { Customers product = new Customers { id = dataReader.GetInt32("id"), firstname = dataReader.GetString("firstname"), lastname = dataReader.GetString("lastname"), }; customers.Add(product); } connection.Close(); //loading products succesfull, go to product page result = View(customers); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } return result; } public ActionResult CustomersEdit(int customer_id, Customers customer) { const string selectCustomers = "select * from gr_users where id = @id"; Customers customers = new Customers() { id = -1 }; MySqlCommand cmd = new MySqlCommand(); ActionResult result = new ViewResult(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = selectCustomers; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32) { Value = customer_id }); cmd.Prepare(); MySqlDataReader datareader = cmd.ExecuteReader(); if (datareader.Read()) { customers.id = customer_id; customers.username = datareader.GetString("username"); customers.password = <PASSWORD>reader.GetString("password"); customers.firstname = datareader.GetString("firstname"); customers.lastname = datareader.GetString("lastname"); customers.streetname = datareader.GetString("streetname"); customers.adress = datareader.GetString("adress"); customers.zipcode = datareader.GetString("zipcode"); customers.city = datareader.GetString("city"); customers.phonenumber = datareader.GetString("phonenumber"); customers.mobilePhonenumber = datareader.GetString("mobilePhonenumber"); customers.email = datareader.GetString("email"); } datareader.Close(); connection.Close(); //loading product detail succesfull, go to product page result = View(customers); } catch (Exception e) { connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } currentCustomersId = customer_id; return result; } public ActionResult CustomersEditSubmit(Customers customer) { ActionResult result = new ViewResult(); if (ModelState.IsValid) { const string updateUser = "update gr_users " + "set firstname = @firstname, lastname = @lastname, streetname = @streetname, adress = @adress, zipcode = @zipcode, city = @city, phonenumber = @phonenumber, mobilePhonenumber = @mobilePhonenumber, username = @username, email = @email, password = <PASSWORD> " + "where id = @id"; MySqlTransaction trans = null; MySqlCommand cmd = new MySqlCommand(); try { connection.Open(); cmd.Connection = connection; trans = connection.BeginTransaction(); cmd.CommandText = updateUser; cmd.Parameters.Add(new MySqlParameter("@id", MySqlDbType.Int32) { Value = customer.id }); cmd.Parameters.Add(new MySqlParameter("@firstname", MySqlDbType.VarChar) { Value = customer.firstname }); cmd.Parameters.Add(new MySqlParameter("@lastname", MySqlDbType.VarChar) { Value = customer.lastname }); cmd.Parameters.Add(new MySqlParameter("@streetname", MySqlDbType.VarChar) { Value = customer.streetname }); cmd.Parameters.Add(new MySqlParameter("@adress", MySqlDbType.VarChar) { Value = customer.adress }); cmd.Parameters.Add(new MySqlParameter("@zipcode", MySqlDbType.VarChar) { Value = customer.zipcode }); cmd.Parameters.Add(new MySqlParameter("@city", MySqlDbType.VarChar) { Value = customer.city }); cmd.Parameters.Add(new MySqlParameter("@phonenumber", MySqlDbType.VarChar) { Value = customer.phonenumber }); cmd.Parameters.Add(new MySqlParameter("@mobilePhonenumber", MySqlDbType.VarChar) { Value = customer.mobilePhonenumber }); cmd.Parameters.Add(new MySqlParameter("@username", MySqlDbType.VarChar) { Value = customer.username }); cmd.Parameters.Add(new MySqlParameter("@email", MySqlDbType.VarChar) { Value = customer.email }); cmd.Parameters.Add(new MySqlParameter("@password", MySqlDbType.VarChar) { Value = customer.password }); cmd.Prepare(); cmd.ExecuteNonQuery(); trans.Commit(); connection.Close(); //update succesfull, reload update page to view new user data and make additional changes if desired result = RedirectToAction("CustomersEdit"); //View("CustomersEdit", new Customers { message = "Klant gegevens zijn bijgewerkt" }); } catch (Exception e) { trans.Rollback(); connection.Close(); //error, go to error page with error message result = View("Error", new Error { Message = "Er is iets fout gegaan", Exception = e }); } } else { //validation incorrect, reload update page with validation messages customer.message = "Niet alle velden zijn ingevuld"; result = View("Update", customer); } return result; } } }<file_sep>/greenery/admincp/App_Start/RouteConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace admincp { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Customers", url: "customers", defaults: new { controller = "Customers", action = "Customers" } ); routes.MapRoute( name: "CustomersEdit", url: "customersedit", defaults: new { controller = "CustomersEdit", action = "CustomersEdit" } ); routes.MapRoute( name: "Dashboard", url: "dashboard", defaults: new { controller = "Dashboard", action = "Dashboard" } ); routes.MapRoute( name: "Products", url: "products", defaults: new { controller = "Products", action = "Products" } ); routes.MapRoute( name: "ProductsEdit", url: "productsedit", defaults: new { controller = "ProductsEdit", action = "ProductsEdit" } ); routes.MapRoute( name: "Recipes", url: "recipes", defaults: new { controller = "Recipes", action = "Recipes" } ); routes.MapRoute( name: "RecipesEdit", url: "recipesedit", defaults: new { controller = "Recipesedit", action = "Recipesedit" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "Login", action = "Login" } ); } } }
b90e7f97863f649c52008b77035dac6775b1a0ae
[ "C#" ]
21
C#
sandrt/greenery
4547151bb5d7b7cbb1b53882fb13dc3ff830c168
d0e3e8ec5a622f7434488421e721632553b85c9a
refs/heads/master
<repo_name>Yaxin1996Z/BP_algorithm<file_sep>/netbp_mutihidden_v5.py # Layer类里自动更新权重 # 能定义隐层层数和每个隐层的单元个数 import numpy as np from load_mnist import load_train_images,load_train_labels import os import pickle # sigmoid激活函数 def sigmoid(net): y = 1/(1+np.exp(-net)) return y # 均方误差 def loss_mse(y_true: np.ndarray, y_pred: np.ndarray): return 0.5 *((y_true-y_pred)**2).sum() # sigmoid函数的导数 def deriv_sigmoid(x): fx = sigmoid(x) return fx*(1-fx) class Layer: # 初始化神经网络层 初始化参数:输入节点数,输出节点数,权重矩阵,偏置向量 def __init__(self,input_size=0,output_size=0): self.input_size = input_size self.output_size = output_size self.weights = np.random.normal(0, 1, (output_size,input_size)) self.bias = np.zeros((output_size)) def initWeights(self,input_size,output_size): self.weights = np.random.normal(0, 1, (output_size, input_size)) self.bias = np.zeros((output_size)) # 该层前向传播 得到总输出向量 def feedforward(self,inputs): net = np.dot(self.weights,inputs) + self.bias # inputs和weight一个行向量一个列向量 outputs = sigmoid(net) return outputs # input假设有d个单元 用i计数 该层输出是n个 用j计数 该层后面一层是c个 # 要更新的权矩阵为n*h 后面层w_next的权矩阵为c*n 后面层的delt有c个 每一行有c个 def update_weights_return_delt(self,inputs,delts,w_next, nets): num_in = np.size(inputs[0]) num_out = np.size(nets[0]) batch_size = np.size(nets[:,0]) delt_pre = np.dot(delts,w_next)*deriv_sigmoid(nets) for j in range(num_out): for i in range(num_in): for k in range(batch_size): self.weights[j][i] -= learning_rate*delt_pre[k][j]*inputs[k][i] return delt_pre class BPnn(): # 初始化网络,隐层和输出层权重、偏置 def __init__(self, d, num_hidden, hidden_cells, c): # 定义隐藏层和输出层,前向传播计算出预测输出 self.d = d self.num_hidden = num_hidden self.hidden_cells = hidden_cells self.c = c self.layer_hidden = [Layer()for i in range(num_hidden)] for i in range(self.num_hidden): if i==0: self.layer_hidden[i].initWeights(d,self.hidden_cells[i]) else: self.layer_hidden[i].initWeights(self.hidden_cells[i-1],self.hidden_cells[i]) self.layer_out = Layer(hidden_cells[-1], c) # 检测网络效果 def test(self, testin): inputs = np.array(testin) for i in range(self.num_hidden): h = self.layer_hidden[i].feedforward(inputs) inputs = h y_pred = self.layer_out.feedforward(h) predicted = np.argmax(y_pred) print("ouput : ", predicted) # 训练网络 def train(self, samples, samples_result, steps=100, learning_rate=0.1): dataset_size = np.shape(samples)[0] for step in range(steps): start = (step * batch_size) % dataset_size end = min(start + batch_size, dataset_size) mini_samples = samples[start:end] # bs*d mini_samples_result = samples_result[start:end] #bs*c net_h, h = [np.array([])for i in range(self.num_hidden)], [np.array([])for i in range(self.num_hidden)], for i in range(self.num_hidden): net_h[i]=np.zeros((batch_size,hidden_cells[i])) h[i]=np.zeros((batch_size,hidden_cells[i])) net_y, y_pred = np.zeros((batch_size,self.c)), np.zeros((batch_size,self.c)) delta_last = np.zeros((batch_size,self.c)) for t in range(batch_size): inputs = mini_samples[t] y_true = mini_samples_result[t] for k in range(self.num_hidden): if k==0: net_h[k][t] = np.dot(self.layer_hidden[k].weights, inputs) + self.layer_hidden[k].bias else: net_h[k][t] = np.dot(self.layer_hidden[k].weights, h[k-1][t]) + self.layer_hidden[k].bias h[k][t] = sigmoid(net_h[k][t]) net_y[t] = np.dot(self.layer_out.weights, h[k][t]) + self.layer_out.bias y_pred[t] = sigmoid(net_y[t]) delta_last = (y_pred - mini_samples_result) * deriv_sigmoid(net_y) for j in range(c): for i in range(self.hidden_cells[-1]): for k in range(batch_size): # weights2[k][j]-=learning_rate*(y_pred[k]-y_true[k])*deriv_sigmoid(net_y[k])*h[j] self.layer_out.weights[j][i] -= learning_rate * (delta_last[k][j]) * h[-1][k][i] # 更新输出层权重 delta = delta_last if self.num_hidden==1: delta = self.layer_hidden[0].update_weights_return_delt(mini_samples, delta, self.layer_out.weights, net_h[0]) else: pre_inputs = h[-2] for i in range(self.num_hidden): if self.num_hidden-i==1: delta = self.layer_hidden[0].update_weights_return_delt(mini_samples, delta, self.layer_hidden[1].weights, net_h[0]) elif i==0: delta = self.layer_hidden[-1].update_weights_return_delt(pre_inputs, delta, self.layer_out.weights, net_h[-1]) else: p = self.num_hidden-i-1 delta= self.layer_hidden[p].update_weights_return_delt(pre_inputs,delta,self.layer_hidden[p+1].weights,net_h[p] ) pre_inputs=h[p-1] # 更新隐层权重 # y_pred= if step % display_dteps == 0: print("steps:%d, loss:%f" % (step, loss_mse(mini_samples_result, y_pred))) def save(self, filename): with open(filename, "wb") as f: f.write(pickle.dumps(self)) @classmethod def load(cls, filename): with open(filename, "rb") as f: net = pickle.loads(f.read()) return net batch_size = 16 # 设定学习率 learning_rate = 0.01 # 设定训练轮数 steps = 1000 dataset_size = 60000 display_dteps = 50 if __name__ == '__main__': # samples = [[-2, -1], [25, 6], [17, -4], [-15, 4]] # samples_result = np.array([[0,0],[1,1],[1,0],[0,1]]) d,c = 28*28, 10 num_hidden = 2 hidden_cells = [15,20] # samples = [[-2, -1], [25, 6], [17, 4], [-15, -6]] # samples_result = np.array([[1], [0], [0], [1]]) # d, n_H, c = 2, 3, 1 # 加载MNIST数据集 if os.path.exists(os.path.abspath("mnist.pkl")): pkl_file = open('mnist.pkl','rb') samples = pickle.load(pkl_file) samples_result = pickle.load(pkl_file) pkl_file.close() else: samples = load_train_images() samples.resize((dataset_size, 28*28)) labels = load_train_labels() samples_result = np.apply_along_axis(f, 1, labels[:, np.newaxis]) # 将解析出来的数据集存储 pickle_output = open('mnist.pkl','wb') pickle.dump(samples,pickle_output) pickle.dump(samples_result, pickle_output) pickle_output.close() # bp = BPnn(d, num_hidden, hidden_cells, c) if os.path.exists(os.path.abspath("net.pkl")): bp = BPnn.load("net.pkl") else: bp = BPnn(d, num_hidden, hidden_cells, c) bp.train(samples, samples_result, steps, learning_rate) bp.save('net.pkl') # testsamples = samples[3] # bp.test(testsamples) # 输出应该是1,0 # 测试样本 # testsamples = [[-7, -3], [20, 2]] # bp.test(testsamples) # 输出应该是1,0<file_sep>/netbp_multisamples_v3.py # 解决了MNIST数据集的问题 # mini-batch训练 # import numpy as np from load_mnist import load_train_images,load_train_labels import os import pickle # sigmoid激活函数 def sigmoid(net): y = 1/(1+np.exp(-net)) return y # sigmoid函数的导数 def deriv_sigmoid(x): fx = sigmoid(x) return fx*(1-fx) # tanh激活函数 def abtanh(net,a=1.716,b=2/3): y = a*((1-np.exp(-b*net))/(1+np.exp(-b*net))) return y # 均方误差 def loss_mse(y_true: np.ndarray, y_pred: np.ndarray): return 0.5 *((y_true-y_pred)**2).sum() class Neuron: # 神经元初始化 权重 偏置 def __init__(self,weights,bias): self.weights = weights self.bias = bias # 前向传播 def feedforward(self,inputs): net = np.dot(inputs,self.weights)+self.bias #inputs和weight一个行向量一个列向量 outputs = sigmoid(net) return outputs class Layer: # 初始化神经网络层 初始化参数:输入节点数,输出节点数,权重矩阵,偏置向量 def __init__(self,input_size,output_size,weights,bias): self.input_size = input_size self.output_size = output_size self.ns = ([]) for i in range(output_size): self.ns = np.hstack((self.ns,Neuron(weights[i],bias[i]))) # 初始化该层神经节点 # 该层前向传播 得到总输出向量 def feedforward(self,inputs): outputs = ([]) for i in range(self.output_size): outputs = np.hstack((outputs, self.ns[i].feedforward(inputs))) return outputs class BPnn(): # 初始化网络,隐层和输出层权重、偏置 def __init__(self, d, n_H, c): self.weights1 = np.random.normal(0, 1, (n_H, d)) self.bias1 = np.zeros((n_H)) self.weights2 = np.random.normal(0, 1, (c, n_H)) self.bias2 = np.zeros((c)) # 定义隐藏层和输出层,前向传播计算出预测输出 self.layer1 = Layer(d, n_H, self.weights1, self.bias1) self.layer2 = Layer(n_H, c, self.weights2, self.bias2) # 检测网络效果 def test(self, testin): for sample in testin: inputs = np.array(sample) h = self.layer1.feedforward(inputs) y_pred = self.layer2.feedforward(h) print("ouput : ", y_pred) # # 计算损失 # def calLoss(self, samples, samples_result): # loss = 0.0 # for sample in samples: # inputs = np.array(sample[0]) # y_true = np.array(sample[1]) # h = self.layer1.feedforward(inputs) # y_pred = self.layer2.feedforward(h) # loss += loss_mse(y_true, y_pred) # return loss # 训练网络 def train(self, samples, samples_result, steps=100, learning_rate=0.1): dataset_size = np.shape(samples)[0] for step in range(steps): start = (step * batch_size) % dataset_size end = min(start + batch_size, dataset_size) mini_samples = samples[start:end] mini_samples_result = samples_result[start:end] for t in range(batch_size): inputs = mini_samples[t] y_true = mini_samples_result[t] net_h, h, net_y, y = np.array([]), np.array([]), np.array([]), np.array([]) net_h = np.dot(self.weights1, inputs) + self.bias1 h = sigmoid(net_h) net_y = np.dot(self.weights2, h) + self.bias2 y_pred = sigmoid(net_y) # 更新输出层权重 for k in range(c): delta_k = (y_pred - y_true) * deriv_sigmoid(net_y) for j in range(n_H): # weights2[k][j]-=learning_rate*(y_pred[k]-y_true[k])*deriv_sigmoid(net_y[k])*h[j] self.weights2[k][j] -= learning_rate * (delta_k[k]) * h[j] # 更新隐层权重 for j in range(n_H): delta_j = np.dot(delta_k, self.weights2[:, j]) * deriv_sigmoid(net_h[j]) # print(delta_j) for i in range(d): self.weights1[j][i] -= learning_rate * delta_j * inputs[i] if step % display_dteps == 0: print("steps:%d, loss:%f" % (step, loss_mse(y_true, y_pred))) def f(y): act = np.zeros((10)) act[int(y[0])] = 1 return act # 定义训练数据的batch大小 batch_size = 1 # 设定学习率 learning_rate = 0.5 # 设定训练轮数 steps = 1000 dataset_size = 4 display_dteps = 10 # 输入层中间层输出层 d, n_H, c = 4, 10, 1 # d, n_H, c = 28*28, 15, 10 if __name__ == '__main__': # 训练样本 简单训练 # samples = [[-2, -1], [25, 6], [17, 4], [-15, -6]] # samples_result = np.array([[1],[0],[0],[1]]) samples = [[5.1,3.5,1.4,0.2], [4.9,3.0,1.4,0.2], [4.7,3.2,1.3,0.2], [4.6,3.1,1.5,0.2], [5.0,3.6,1.4,0.2], [5.4,3.9,1.7,0.4], [4.6,3.4,1.4,0.3], [5.0,3.4,1.5,0.2], [4.4,2.9,1.4,0.2], [4.9,3.1,1.5,0.1], [5.4,3.7,1.5,0.2], [4.8,3.4,1.6,0.2], [4.8,3.0,1.4,0.1], [4.3,3.0,1.1,0.1], [7.0,3.2,4.7,1.4], [6.4,3.2,4.5,1.5], [6.9,3.1,4.9,1.5], [5.5,2.3,4.0,1.3], [6.5,2.8,4.6,1.5], [5.7,2.8,4.5,1.3], [6.3,3.3,4.7,1.6], [4.9,2.4,3.3,1.0]] samples_result = np.array([[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[1],[1],[1],[1],[1],[1],[1],[1]]) # 加载MNIST数据集 # if os.path.exists(os.path.abspath("mnist.pkl")): # pkl_file = open('mnist.pkl','rb') # samples = pickle.load(pkl_file) # samples_result = pickle.load(pkl_file) # pkl_file.close() # else: # samples = load_train_images() # samples.resize((dataset_size, 28*28)) # labels = load_train_labels() # samples_result = np.apply_along_axis(f, 1, labels[:, np.newaxis]) # # 将解析出来的数据集存储 # pickle_output = open('mnist.pkl','wb') # pickle.dump(samples,pickle_output) # pickle.dump(samples_result, pickle_output) # pickle_output.close() bp = BPnn(d, n_H, c) bp.train(samples, samples_result, steps, learning_rate) # 测试样本 # testsamples = [[-7, -3], [20, 2]] testsamples = [[4.7,3.2,1.3,0.2], [4.9, 2.4, 3.3, 1.0]] bp.test(testsamples) # 输出应该是1,0<file_sep>/netbp_v2.py import numpy as np # sigmoid激活函数 def sigmoid(net): y = 1/(1+np.exp(-net)) return y # sigmoid函数的导数 def deriv_sigmoid(x): fx = sigmoid(x) return fx*(1-fx) # tanh激活函数 def abtanh(net,a=1.716,b=2/3): y = a*((1-np.exp(-b*net))/(1+np.exp(-b*net))) return y # 均方误差 def loss_mse(y_true: np.ndarray, y_pred: np.ndarray): return 0.5 *((y_true-y_pred)**2).sum() class Neuron: # 神经元初始化 权重 偏置 def __init__(self,weights,bias): self.weights = weights self.bias = bias # 前向传播 def feedforward(self,inputs): net = np.dot(inputs,self.weights)+self.bias #inputs和weight一个行向量一个列向量 outputs = sigmoid(net) return outputs class Layer: # 初始化神经网络层 初始化参数:输入节点数,输出节点数,权重矩阵,偏置向量 def __init__(self,input_size,output_size,weights,bias): self.input_size = input_size self.output_size = output_size self.ns = ([]) for i in range(output_size): self.ns = np.hstack((self.ns,Neuron(weights[i],bias[i]))) # 初始化该层神经节点 # 该层前向传播 得到总输出向量 def feedforward(self,inputs): outputs = ([]) for i in range(self.output_size): outputs = np.hstack((outputs, self.ns[i].feedforward(inputs))) return outputs if __name__ == '__main__': # 1.初始化网络,权重、偏置、输入、实际输出 weights1 = np.array([[0.1, 0.8], [0.4, 0.6]]) weights2 = np.array([[0.3, 0.9]]) bias1 = np.array([0., 0.]) bias2 = np.array([0.]) inputs = np.array([0.35, 0.9]) y_true = np.array([0.5]) d, n_H, c = 2, 2, 1 learning_rate = 1 # 定义隐藏层和输出层,前向传播计算出预测输出 layer1 = Layer(d,n_H,weights1,bias1) layer2 = Layer(n_H,c,weights2,bias2) h=layer1.feedforward(inputs) y_pred = layer2.feedforward(h) # 初始损失 loss = loss_mse(y_true, y_pred) # 训练100epoch for epoch in range(100): net_h, h, net_y, y = np.array([]), np.array([]), np.array([]), np.array([]) net_h = np.dot(weights1, inputs) + bias1 h = sigmoid(net_h) net_y = np.dot(weights2, h) + bias2 y_pred = sigmoid(net_y) # 更新输出层权重 for k in range(c): delta_k = (y_pred - y_true) * deriv_sigmoid(net_y) for j in range(n_H): # weights2[k][j]-=learning_rate*(y_pred[k]-y_true[k])*deriv_sigmoid(net_y[k])*h[j] weights2[k][j] -= learning_rate * (delta_k[k]) * h[j] # 更新隐层权重 for j in range(n_H): delta_j = np.dot(delta_k, weights2[:, j]) * deriv_sigmoid(net_h[j]) #print(delta_j) for i in range(d): weights1[j][i] -= learning_rate * delta_j * inputs[i] h = layer1.feedforward(inputs) y_pred = layer2.feedforward(h) loss = loss_mse(y_true, y_pred) print("y_pred:%f, loss:%f" % (y_pred,loss))<file_sep>/net_v1.py import numpy as np # sigmoid激活函数 def sigmoid(net): y = 1/(1+np.exp(-net)) return y # tanh激活函数 def abtanh(net,a=1.716,b=2/3): y = a*((1-np.exp(-b*net))/(1+np.exp(-b*net))) return y # 均方误差的定义 def loss_mse(y_true: np.ndarray, y_pred: np.ndarray): return ((y_true-y_pred)**2).mean() class Neuron: # 神经元初始化 权重 偏置 def __init__(self,weights,bias): self.weights = weights self.bias = bias # 前向传播 def feedforward(self,inputs): net = np.dot(inputs,self.weights)+self.bias #inputs和weight一个行向量一个列向量 outputs = sigmoid(net) return outputs class Layer: # 初始化神经网络层 初始化参数:输入节点数,输出节点数,权重矩阵,偏置向量 def __init__(self,input_size,output_size,weights,bias): self.input_size = input_size self.output_size = output_size self.ns = ([]) for i in range(output_size): self.ns = np.hstack((self.ns,Neuron(weights[i],bias[i]))) # 初始化该层神经节点 # 该层前向传播 得到总输出向量 def feedforward(self,inputs): outputs = ([]) for i in range(self.output_size): outputs = np.hstack((outputs, self.ns[i].feedforward(inputs))) return outputs if __name__ == '__main__': weights1 = np.array([[0.,1.],[0.,1.]]) bias1 = np.array([0.,0.]) weights2 = np.array([[0.,1.]]) bias2 = np.array([0.]) layer1 = Layer(2,2,weights1,bias1) layer2 = Layer(2,1,weights2,bias2) h=layer1.feedforward(np.array([2,3])) y = layer2.feedforward(h) print(type(y))
aa53aafd122b8981ebbd41925ceec0d539d2abf6
[ "Python" ]
4
Python
Yaxin1996Z/BP_algorithm
84a337c8f23289c6f120c492d1a1e0f47760dd05
2ef020dbf91263e1edbd9433b0f6cfd5b5134a87
refs/heads/main
<repo_name>vipul2511/Swapp-Function<file_sep>/src/Containers/OnBoarding/Styles.js import {StyleSheet,Dimensions,Platform} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP as wp } from 'react-native-responsive-screen'; let width=Dimensions.get('window').width; let height=Dimensions.get('window').height const styles = StyleSheet.create({ appBar: { backgroundColor: 'transparent', color: '#fff', }, headerText: { fontFamily: Platform.OS=="android"?'Roboto':'Gill Sans', fontSize: 20, fontStyle: 'normal', fontWeight: '400', lineHeight: 36, letterSpacing: 0, textAlign: 'center', color: '#FFFFFF', marginLeft: 16, marginTop: 12, }, backAction: { color: '#fff', }, mainContainer: { backgroundColor: '#2e2d39', color: '#fff', flex: 1, }, mainImageView:{ marginVertical:hp('6%'), marginHorizontal:wp('18%') }, scrollContainer: { marginLeft: 30, marginRight: 30, }, mainImageContainer: { width:wp('100%'), height:hp('90%'), color:'#86888F' }, personaldata:{ color:'#5E6272', fontSize:wp('4%'), fontWeight:'bold' }, getitView:{ width:wp('100%'), position:'absolute', top:hp('46%'), left:wp('8%') }, getitText:{ fontSize:wp('9%'), fontFamily:'Poppins-SemiBold', color:'#FFFFFF', lineHeight: wp('10%'), }, personaldataView: {position:'absolute',top:hp('40%'),left:wp('8%')}, textContainer: { marginBottom: 20, alignItems: 'center', textAlign: 'center', }, textTitle: { fontFamily: Platform.OS=="android"?'Roboto':'Gill Sans', fontSize: 18, fontStyle: 'normal', fontWeight: '400', lineHeight: 21, letterSpacing: 0, textAlign: 'center', color: '#FFFFFF', marginBottom: 10, }, textDetail: { fontFamily: Platform.OS=="android"?'Roboto':'Gill Sans', fontSize: 14, fontStyle: 'normal', fontWeight: '400', lineHeight: 22, letterSpacing: 0, textAlign: 'center', color: '#FFFFFF', opacity: 0.55, alignItems: 'center', }, dotStyle: { backgroundColor: '#65646D', width: 10, // position:'absolute', // top:0 }, activeDotStyle: { backgroundColor: '#246BFD', // top:0, // position:'absolute', width: 10, }, bottomContainer: { flex: 1, justifyContent: 'flex-end', marginBottom: 100, }, btnContainer: { paddingLeft: 80, paddingRight: 80, }, createSwapp:{width:wp('85%'), height:hp('7.3%') }, }); export default styles; <file_sep>/src/Components/CreatingAccount/Button/styles.js import {StyleSheet,Dimensions} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP as wp } from 'react-native-responsive-screen'; let width=Dimensions.get('window').width; let height=Dimensions.get('window').height export default StyleSheet.create({ buttonContainer: { width:wp('100%'), height:hp('8%'), // backgroundColor:'red', marginTop: 'auto', marginBottom: hp('1.8%') }, button: { width:wp('90%'), alignSelf:'center', height:hp('7.6%'), borderRadius: hp('2%'), display: 'flex', justifyContent:'center', alignItems: 'center' }, buttonText: { color:'white', fontSize: wp('4.2%'), fontFamily:'Inter-Bold' }, }) <file_sep>/src/Containers/CreateNewPassword/styles.js import {StyleSheet} from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; const styles = StyleSheet.create({ container: { flex:1, backgroundColor: '#181A20' }, createbtn:{ width: wp('85%'), height: hp('7.3%'), backgroundColor: '#246BFD', borderColor: '#246BFD', justifyContent:'center', alignItems:'center', marginTop:'auto' }, activeborder: { borderBottomColor: '#FF0B80', shadowColor: '#FF0B80', shadowOpacity: 0.5, shadowRadius: 2, shadowOffset: { height: 1, width: 1, }, elevation: 10, borderBottomWidth: 1.5, }, disableborder: { borderBottomColor: '#5E6272', borderBottomWidth: 1.5, }, disable: { color: '#5E6272', }, active: { color: '#FF0B80', }, }); export default styles; <file_sep>/src/Saga/wording.saga.js import {call, put, takeEvery, takeLatest} from '@redux-saga/core/effects'; import * as wording from '../Services/wording.service'; import {setWordingError,setWordingSuccess,sendSecretLoader,setUsernameLoader,sendSecretSuccess,sendSecretError,setUsernameSuccess,setUsernameError,setWordingLoaderTrue} from "../Actions/wording.actions"; function* sendwording(action) { try { yield put(setWordingLoaderTrue()); console.log('------------------------'); console.log(action.data); console.log('------------------------'); let {data} = yield call(wording.sendwording, action.data); console.log('data from server2'); console.log(data); yield put(setWordingSuccess(action.data.msg)); } catch (error) { console.log('error',error); yield put(setWordingError(error.response.msg)) } } function* addusername(action){ try{ yield put(setUsernameLoader()); let {data}=yield call(wording.addusername,action.data); console.log('data of username',data); yield put(setUsernameSuccess(data.data)); }catch(error){ console.log('username error',error); yield put(setUsernameError(error.response.data)); } } function* sendSecretHash(action) { try { console.log('send secret saga') yield put(sendSecretLoader()); let {data} = yield call(wording.sendSecretHash, action.data); console.log(data) yield put(sendSecretSuccess(data.data)); console.log('send secret hash success') } catch (error) { console.log('error send secret saga') yield put(sendSecretError(error)); console.log(error) } } export default function* watchwording() { yield takeLatest('SET_WORDING', sendwording); yield takeLatest("ADD_USERNAME", addusername); yield takeLatest("SEND_SECRET", sendSecretHash); } <file_sep>/src/Components/Button/index.js import React from 'react'; import {TouchableOpacity, Text, Image, View} from 'react-native'; import { Spinner } from 'native-base' import Style from './styles'; import {widthPercentageToDP} from 'react-native-responsive-screen'; const Button = props => { const { style, textStyle, onPress, title, disabled, loading, selected, children, } = props; let textStyleNode = selected ? {...Style.text, ...textStyle, ...Style.selectedText} : {...Style.text, ...textStyle}; let buttonStyleNode = selected ? {...Style.button, ...style, ...Style.selectedButton} : {...Style.button, ...style}; let textNode = <Text style={textStyleNode}>{title}</Text>; textNode = title ? textNode : []; return ( <View style={{width: '85%'}}> <Image source={require('../../Assets/Images/buttonlogo.png')} style={{ width: 25, height: 25, position: 'absolute', top: widthPercentageToDP('4%'), zIndex: 1, left: '19%', }} /> <TouchableOpacity disabled={disabled} style={buttonStyleNode} onPress={onPress}> {!loading ? children : []} {/* {loading ? (<Spinner color={'#fff'} />) : textNode} */} {textNode} </TouchableOpacity> </View> ); }; export default Button; Button.defaultProps = { disabled: false, loading: false, selected: false, children: [], }; <file_sep>/src/Containers/Home/DataPoints.js import React from 'react'; import {View, Text, Image, TouchableOpacity} from 'react-native'; import { heightPercentageToDP, widthPercentageToDP, } from 'react-native-responsive-screen'; import resp from 'rn-responsive-font'; import * as Progress from 'react-native-progress'; import {Finance, Ticks, Youtube} from '../../Assets/Images'; import {useNavigation} from '@react-navigation/native'; const DataPoints = () => { const navigation = useNavigation(); const DataPoints = [ { Image1: Youtube, Image2: Ticks, Title: 'Entertaiment', Subtitle: 'No sources added', progress: 1, Point: '24/24', progresscolor: '#A5F59C', }, { Image1: Finance, // Image2: Ticks, Title: 'Financial', Subtitle: '150 Points added', progress: 0.8, Point: '150/200', progresscolor: '#246BFD', }, ]; return ( <View style={{marginTop: heightPercentageToDP('1')}}> <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginHorizontal: widthPercentageToDP('5.5'), }}> <Text style={{color: 'white', fontSize: resp(20),fontFamily:'Poppins-SemiBold'}}>Data Points</Text> <TouchableOpacity onPress={()=>navigation.navigate('Setting')}> <View style={{ width: widthPercentageToDP('20'), borderColor: '#246BFD', borderWidth: 1.5, borderRadius: 20, paddingVertical: 5, marginBottom: 10, }}> <Text style={{ textAlign: 'center', fontWeight: 'bold', color: '#246BFD', fontFamily:'Inter-Medium' }}> Show all </Text> </View> </TouchableOpacity> </View> <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginHorizontal: widthPercentageToDP('5'), marginTop: heightPercentageToDP('1'), }}> {DataPoints.map((item, index) => { return ( <View style={{ backgroundColor: '#1F222A', height: heightPercentageToDP('23'), width: widthPercentageToDP('43'), borderRadius: 12, }}> <View style={{ flexDirection: 'row', justifyContent: 'space-around', marginTop: heightPercentageToDP('2'), }}> <View style={{ height: heightPercentageToDP('6'), width: widthPercentageToDP('24'), marginLeft:widthPercentageToDP('-1%') }}> <Image source={item.Image1} style={{ height: '100%', width: '50%', resizeMode: 'contain', }} /> </View> <View style={{ height: heightPercentageToDP('5'), width: widthPercentageToDP('6'), // backgroundColor:'red', marginTop: heightPercentageToDP('-1'), }}> <Image source={item.Image2} style={{ height: '100%', width: '100%', resizeMode: 'contain', }} /> </View> </View> <View style={{ marginLeft: widthPercentageToDP('4'), marginTop: heightPercentageToDP('2'), }}> <Text style={{color: 'white', fontSize: resp(17),fontFamily:'Inter-Regular'}}> {item.Title} </Text> <Text style={{color: '#5E6272', lineHeight: 30,fontFamily:'Inter-Regular'}}> {item.Subtitle} </Text> </View> <View style={{ // marginLeft: widthPercentageToDP('5'), marginTop: heightPercentageToDP('1'), marginHorizontal: heightPercentageToDP('2.5'), justifyContent: 'space-between', flexDirection: 'row', }}> <View style={{marginTop: heightPercentageToDP('0.5'),justifyContent:'center',alignItems:'center'}}> <Progress.Bar progress={item.progress} width={widthPercentageToDP('18')} height={heightPercentageToDP('0.6')} borderColor={'transparent'} unfilledColor={'rgba(255,255,255,0.1)'} color={item.progresscolor} /> </View> <Text style={{color: 'white', fontSize: resp(12),fontFamily:'Inter-Regular'}}> {item.Point} </Text> </View> </View> ); })} </View> </View> ); }; export default DataPoints; <file_sep>/src/Reducers/wording.reducer.js const initialState = { wording: null, loader: false, wordingError:null, usernameError:null, username:null, usernameLoader:false, secretSuccess:null, secretError:null }; export default function(state = initialState, action) { switch (action.type) { case 'SET_WORDING_LOADER_TRUE': return { ...state, loader: true }; case 'SET_WORDING_SUCCESS': return{ ...state, wordingError:null, wording:action.msg, loader: false }; case 'SET_WORDING_ERROR': return{ ...state, loader: false, wordingError:action.msg }; case 'ADD_USERNAME_LOADER': return { ...state, usernameLoader: true }; case 'ADD_USERNAME_SUCCESS': return{ ...state, usernameError:null, username:action.data, usernameLoader: false }; case 'ADD_USERNAME_ERROR': return{ ...state, usernameLoader: false, usernameError:action.data.msg }; case 'ERASE_USERNAME_ERROR': return { ...state, usernameError: null, username:null }; case 'SEND_SECRET_LOADER': console.log('send secret') return{ ...state, loader: true } case 'SEND_SECRET_SUCCESS': console.log('send secret success',action); return { ...state, secretError: null, secretSuccess: action.data, loader: false }; case 'SEND_SECRET_ERROR': console.log('reducer token error',action) return { ...state, secretError: action.data.msg, loader: false }; default: return state; } }<file_sep>/src/Components/FloatingTextInput/index.js import React, { Component } from 'react'; import { View, StatusBar, TextInput, Text, } from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; class FloatingLabelInput extends Component { state = { isFocused: false, }; handleFocus = () => this.setState({ isFocused: true }); handleBlur = () => this.setState({ isFocused: false }); render() { const {inputStyle, titleStyle,label, ...props } = this.props; const { isFocused } = this.state; const labelStyle = { position: 'absolute', left: 0, top: !isFocused ? 18 : 0, fontSize: !isFocused ? wp('4.0%') : wp('4.0%'), color: !isFocused ? '#aaa' : '#fff', }; return ( <View style={{ paddingTop: 18 }}> <Text style={[labelStyle,{fontFamily:'Poppins-SemiBold',fontWeight:'bold'}]}> {label} </Text> <TextInput {...props} style={inputStyle} onFocus={this.handleFocus} onBlur={this.handleBlur} blurOnSubmit /> </View> ); } } export default FloatingLabelInput; <file_sep>/src/Containers/NameScreen/index.js import React, { useState } from 'react'; import { View, Text, Image, StatusBar, SafeAreaView, TextInput, TouchableOpacity, ScrollView, } from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import CustomInput from '../../Components/CustomInput'; import TransparentButton from '../../Components/TransparentButton'; // import {ArrowLeft} from '../../Assets/Images/ArrowLeft.svg'; import ValidationPopup from '../../Components/ValidationPopup'; import Button from '../../Components/CreatingAccount/Button'; import BackArrow from '../../Components/CreatingAccount/BackArrow'; const NameScreen = ({ navigation }) => { const [showText, setShowText] = useState(''); const [firstName, setFirstName] = useState(''); const [secondName, setSecondName] = useState(''); const [showValidation, setShowValidation] = useState(false); const InputValueHandler = e => { setFirstName(e); }; const sendName = () => { if (firstName != '') { if (secondName != '') { navigation.navigate('AcceptTerm') } else { setShowValidation(true) setShowText('Please enter your last name'); } } else { setShowValidation(true) setShowText('Please enter your first name'); } } const updateshow = () => { setShowValidation(false) } return ( <SafeAreaView style={{ flex: 1, backgroundColor: '#181A20' }}> <BackArrow /> <ScrollView> <View style={{ marginLeft: wp('5%') }}> <View style={{ marginTop: hp('2%'), }}> <Text style={{ color: 'white', fontSize: wp('7%'), fontFamily: 'Poppins-SemiBold', }}> Add your full name </Text> </View> <View style={{ marginTop: hp('2%') }}> <Text style={{ fontSize: wp('4%'), color: '#5E6272', fontFamily: 'Inter-Regular', letterSpacing: 0.4, }}> Enter your full name </Text> </View> <View style={{ width: wp('90%') }}> <CustomInput onchange={InputValueHandler} headertextstyle={{ marginTop: hp('4%') }} value={firstName} header={'<NAME>'} /> <CustomInput headertextstyle={{ marginTop: hp('4%') }} onchange={text => { setSecondName(text); }} value={secondName} header={'<NAME>'} /> </View> <View style={{ marginTop: wp('10%') }} /> </View> </ScrollView> <Button handleFunction={sendName} btnText={'Next'} /> {showValidation == true && ( <ValidationPopup title={showText} Show={true} showback={updateshow} /> )} </SafeAreaView> ); }; export default NameScreen; <file_sep>/src/Components/ValidationPopup/index.js import React, {useState} from 'react'; import { Alert, Modal, StyleSheet, Text, Pressable, View, TouchableOpacity, } from 'react-native'; import TransparentButton from '../../Components/TransparentButton'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; const App = ({onPress, Show, showback,title}) => { // console.log(Show + ) const [modalVisible, setModalVisible] = useState(Show); const updateModalstate = () => { setModalVisible(!modalVisible); showback(!modalVisible); }; return ( <View> <Modal animationType="slide" transparent={true} visible={modalVisible} onRequestClose={() => { // Alert.alert('Modal has been closed.'); setModalVisible(!modalVisible); }}> <View style={{ backgroundColor: '#262A34', borderTopEndRadius: 25, borderTopLeftRadius: 25, marginTop: hp('80%'), paddingBottom: hp('8%'), }}> <View style={{marginTop: hp('2%')}}> <Text style={{ color: '#5E6272', fontSize: wp('4%'), textAlign: 'center', // marginTop: hp('3%'), // backgroundColor:'yellowzfs' fontFamily:'Inter-Regular' }}> {title} </Text> </View> <View style={{ marginTop: hp('3%'), alignItems: 'center', }}> <TransparentButton title="Got it" onPress={updateModalstate} style={{ width: wp('85%'), height: hp('7.3%'), backgroundColor: '#246BFD', borderColor: '#246BFD', // marginTop:20padding // paddingBottom:5 // marginLeft:wp('5%') }} textStyle={{fontFamily:'Inter-Bold', fontSize: wp('4.5%')}} /> </View> </View> </Modal> </View> ); }; export default App; <file_sep>/src/Navigator/styles.js import { StyleSheet, Dimensions } from 'react-native' let width=Dimensions.get('window').width; let height=Dimensions.get('window').height; import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen'; export default StyleSheet.create({ container: { flex:1, backgroundColor: '#181A20' }, navIcon:{ width:wp('6%'), resizeMode: 'contain' }, tabBar: { backgroundColor:'#1F2129', borderTopRightRadius:wp('6%'), borderTopLeftRadius:wp('6%'), height:hp('10%') }, tabBarText: { fontSize:wp('3%'), fontFamily:'Inter-Medium', marginBottom:'5%' } }) <file_sep>/src/Containers/Home/ReferEarn.js import React from 'react'; import {View, Text, Image,TouchableOpacity} from 'react-native'; // import { TouchableOpacity } from 'react-native-gesture-handler'; import { heightPercentageToDP as hp, widthPercentageToDP as wp, } from 'react-native-responsive-screen'; import resp from 'rn-responsive-font'; import {Piggy} from '../../Assets/Images'; const ReferEarn = () => { return ( <View style={{marginTop: hp('3')}}> <TouchableOpacity style={{ backgroundColor: '#1F222A', marginHorizontal: wp('5'), borderRadius: 12, }}> <View style={{marginLeft: wp('5'), paddingVertical: hp('3')}}> <Text style={{ color: 'white', marginBottom: 10, fontSize: resp(24), fontFamily: 'Poppins-SemiBold', }}> {'Refer & Earn'} </Text> <Text style={{ marginRight: wp('36'), color: '#5E6272', lineHeight: 23, fontFamily: 'Inter-Medium', }}> Invite your friends with a $5 gift and get 50 Swapps on your wallet account </Text> </View> <View style={{ height: hp('21'), width: wp('58'), position: 'absolute', right: wp('2'), }}> <Image source={Piggy} style={{height: '100%', width: '100%',resizeMode:'contain'}} /> </View> </TouchableOpacity> </View> ); }; export default ReferEarn; <file_sep>/src/Containers/Splash/Styles.js import { StyleSheet, Dimensions } from 'react-native' let width=Dimensions.get('window').width; let height=Dimensions.get('window').height; import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen'; export default StyleSheet.create({ Container: { flex:1, backgroundColor:'#2C303A' }, image:{ width:wp('100%'), height:hp('100%'), justifyContent:'center', alignItems:'center' }, logo:{ width:wp('40%'), height:hp('22%'), } }) <file_sep>/src/Components/CreatingAccount/BackArrow/index.js import React from 'react'; import {Image, Text, TouchableOpacity, View} from "react-native"; import { heightPercentageToDP, widthPercentageToDP } from 'react-native-responsive-screen'; import styles from './styles'; import {useNavigation} from '@react-navigation/native'; const BackArrow = (props) => { const navigation = useNavigation(); const { isText } = props; const handlePress = () => { navigation.goBack(); if(props.func) { props.func(); } } return ( <View style={styles.container} > <TouchableOpacity onPress={()=>handlePress()} style={styles.imgContainer}> <Image style={styles.img} source={require('../../../Assets/Images/arrow.png')} /> </TouchableOpacity> { isText && <View style={styles.textContainer}> <Text style={styles.text}>{isText}</Text> </View> } </View> ) } export default BackArrow; <file_sep>/src/Containers/CreatingAccount/InitialScreen/index.js import React from 'react'; import {Image, SafeAreaView, StatusBar, StyleSheet, Text,TouchableOpacity, View} from "react-native"; import styles from './Styles'; import BackArrow from "../../../Components/CreatingAccount/BackArrow"; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; const OptionBlock = (props) => { const { img, title, text,onPress } = props; return ( <TouchableOpacity style={styles.optionBlock} onPress={onPress}> <Image style={styles.optionIcon} source={img} /> <View> <Text style={styles.optionTitle}>{title}</Text> <Text style={styles.optionText}>{text}</Text> </View> <Image style={styles.nextIcon} source={require('../../../Assets/Images/arrowRight.png')} /> </TouchableOpacity> ) } const InitialScreen = ({navigation}) => { return ( <SafeAreaView style={styles.container}> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow /> <View style={styles.body}> <Text style={styles.title}>Create your Swapp</Text> <Image style={styles.bodyImage} source={require('../../../Assets/Images/createAccountInitial.png')} /> </View> <View style={styles.footer}> <Text style={styles.text}>Please select option to send link</Text> <OptionBlock onPress={()=>navigation.navigate('EnterEmailPhoneScreen', {isPhone: false})} img= {require('../../../Assets/Images/message.png')} title={'Register via email'} text={'If you have email linked to account'} /> <OptionBlock onPress={()=>navigation.navigate('EnterEmailPhoneScreen', {isPhone: true})} img={require('../../../Assets/Images/phone.png')} title={'Register via SMS'} text={'If you have email linked to account'} /> </View> </SafeAreaView> ) } export default InitialScreen; <file_sep>/src/Containers/CreatingAccount/ConfirmBackupPhaseScreen/Styles.js import {StyleSheet, Dimensions} from 'react-native'; let width = Dimensions.get('window').width; let height = Dimensions.get('window').height; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; export default StyleSheet.create({ container: { flex:1, backgroundColor: '#181A20' }, closeIcon: { width:wp('6%'), height:wp('6%'), resizeMode: 'contain' }, wordBoard: { marginTop:hp('2%'), width: wp('90%'), alignSelf:'center', height: hp('27%'), backgroundColor: '#262A34', borderWidth: 1, borderRadius: wp('2.6%'), display:'flex', flexDirection: 'row', flexWrap: 'wrap', paddingVertical:hp('0.6%'), paddingHorizontal:wp('1.4%'), }, wordBtnContainer: { marginVertical:hp('0.6%'), width:'30%', height:hp('4.8%'), /*marginHorizontal:wp('1.2%'), marginVertical:hp('0.4%'),*/ paddingHorizontal:wp('2.4%'), paddingVertical:wp('0.6%'), display:'flex', flexDirection:'row', alignItems: 'center', justifyContent:'center', borderWidth: 1, borderRadius: wp('1.4%'), }, wordBtnText: { fontSize:wp('3.6%'), fontFamily:'Inter-Medium' }, attachedWordContainer: { height:'20%', paddingHorizontal:'1%', marginHorizontal:'1%', marginVertical:'1%', display:'flex', flexDirection:'row', borderColor: '#5E6272', borderWidth: 1, borderRadius: wp('1.2%'), alignItems:'center' }, titleContainer: { width: wp('90%'), alignSelf:'center', height: hp('18%'), }, title: { color: '#FFFFFF', fontSize:hp('3.7%'), fontFamily:'Poppins-SemiBold' }, text: { color: '#5E6272', fontSize:hp('2.3%'), fontFamily:'Inter-Regular' }, attachedWordText: { color:'#FFFFFF', fontSize:wp('4.0%'), paddingHorizontal:wp('1.8%'), fontFamily:'Inter-Medium' }, wordBtnBlock: { height:hp('24%'), marginTop:'auto', width:wp('90%'), alignSelf:'center', display:'flex', flexDirection:'row', flexWrap: 'wrap', justifyContent:'space-between' }, cell: { width: hp('6.4%'), height: hp('7.2%'), borderWidth: 2, borderColor: '#5E6272', textAlign: 'center', backgroundColor: '#262A34', borderRadius: 8, display: 'flex', justifyContent: 'center', }, inputBlock: { marginTop: hp('6%'), width: wp('90%'), alignSelf: 'center', height: hp('15%'), display: 'flex', justifyContent: 'space-between', }, input: { width: wp('100%'), height: hp('6%'), borderBottomColor: '#246BFD', borderBottomWidth: 3, color: 'white', fontSize: 18, }, email: { marginTop: hp('0.5%'), color: 'white', fontSize: wp('3.8%'), width: '90%', alignSelf: 'center', paddingVertical: hp('1%'), }, codeFieldRoot: { marginTop: hp('1%'), width: wp('70%'), alignSelf: 'center', }, focusCell: { borderColor: '#246BFD', shadowColor: '#246BFD', shadowOffset: {width: 0, height: 0}, shadowOpacity: 0.3, shadowRadius: 14, }, digit: { color: 'white', fontSize: 20, textAlign: 'center', }, additionalPostscript: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: hp('3%'), }, additionalPostscriptTitle: { color: '#5E6272', fontSize: wp('3.8%'), }, additionalPostscriptBtnText: { color: '#246BFD', fontSize: wp('3.8%'), textShadowColor: '#246BFD', textShadowOffset: {width: -1, height: 0}, textShadowRadius: 30, }, }); <file_sep>/src/Navigator/TabNav.js import * as React from 'react'; import {View} from 'react-native'; import {createBottomTabNavigator} from '@react-navigation/bottom-tabs'; import WalletScreen from "../Containers/Wallet/WalletScreen"; import {Image} from "react-native"; import styles from './styles'; import Home from '../Containers/Home'; import Settings from '../Containers/Settings'; const Tab = createBottomTabNavigator(); const TabNav = () => { return ( <Tab.Navigator screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { let icon; switch (route.name) { case 'Home': icon = focused ? require('../Assets/Images/HomeIconActive.png') : require('../Assets/Images/HomeIcon.png'); break; case 'Data points': icon = focused ? require('../Assets/Images/DataPointsIconActive.png') : require('../Assets/Images/DataPointsIcon.png'); break; case 'Dapps': icon = focused ? require('../Assets/Images/DappsIconActive.png') : require('../Assets/Images/DappsIcon.png'); break; case 'NFT (soon)': icon = focused ? require('../Assets/Images/NFTIconActive.png') : require('../Assets/Images/NFTIcon.png'); break; case 'Settings': icon = focused ? require('../Assets/Images/SettingsIconActive.png') : require('../Assets/Images/SettingIcon.png'); break; } return <Image style={styles.navIcon} source={icon} /> }, tabBarStyle: styles.tabBar, tabBarLabelStyle: styles.tabBarText, tabBarActiveTintColor: '#FFFFFF', tabBarInactiveTintColor: '#5E6272', })} > <Tab.Screen name="Home" component={Home} options={{headerShown: false}}/> <Tab.Screen name="Data points" component={WalletScreen} options={{headerShown: false}}/> <Tab.Screen name="Dapps" component={WalletScreen} options={{headerShown: false}}/> <Tab.Screen name="NFT (soon)" component={WalletScreen} options={{headerShown: false}}/> <Tab.Screen name="Settings" component={WalletScreen} options={{headerShown: false}}/> </Tab.Navigator> ); }; export default TabNav; <file_sep>/src/Containers/Settings/Styles.js import { StyleSheet, Dimensions } from 'react-native' let width=Dimensions.get('window').width; let height=Dimensions.get('window').height; import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen'; export default StyleSheet.create({ container:{ flex:1, },indicatorstyle:{ backgroundColor: '#131313',borderRadius:20, }, tabNavigator:{ width:'95%', justifyContent:'center',alignSelf:'center', marginTop:'4%' }, label:{ textTransform: 'none', fontSize: wp('3.7%'), fontFamily:'Inter-Bold', }, primary:{ color:'#5E6272', textTransform:'uppercase', fontFamily:'Inter-Bold', fontSize:wp('3.2%') }, viewprimary:{ marginTop:hp('5%'), marginLeft:wp('5%'), }, line:{ width:wp('90%'), borderWidth:0.6, borderColor:'#5E6272', alignSelf:'center', marginTop:hp('2%') }, EmailContainer:{ marginTop:hp('3%'), width:wp('95%'), justifyContent:'center', alignSelf:'center', alignItems:'flex-start', backgroundColor:'#262A34', paddingLeft:'5%', borderRadius:wp('3%'), height:hp('7%') }, emailText:{ fontFamily:'Inter-SemiBold', color:'#fff' }, absolute: { position: "absolute", top: 0, left: 0, bottom: 0, right: 0 } });<file_sep>/src/Components/CreatingAccount/BackArrow/styles.js import {StyleSheet,Dimensions} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP, widthPercentageToDP as wp } from 'react-native-responsive-screen'; let width=Dimensions.get('window').width; let height=Dimensions.get('window').height export default StyleSheet.create({ container: { height: hp('8%'), display:'flex', flexDirection:'row', alignItems:'center' }, imgContainer: { height:'100%', marginLeft:wp('4%'), width:wp('8%'), zIndex:9999 }, img: { position:'absolute', width:wp('8%'), height:'100%', resizeMode: 'contain' }, textContainer: { position:'absolute', width:'100%', display: 'flex', justifyContent:'center' }, text: { color:'white', fontSize:widthPercentageToDP('5.2%'), fontFamily:'Poppins-SemiBold', textAlign:'center' } }) <file_sep>/src/Containers/CreatingAccount/RecoveryPhaseScreen/index.js import React, {useEffect, useState} from 'react'; import { Image, KeyboardAvoidingView, SafeAreaView, StatusBar, Text, TextInput, TouchableOpacity, View, Clipboard, ActivityIndicator, Share } from "react-native"; import styles from './Styles'; import { CodeField, useBlurOnFulfill, useClearByFocusCell, } from 'react-native-confirmation-code-field'; import Button from "../../../Components/CreatingAccount/Button"; import BackArrow from "../../../Components/CreatingAccount/BackArrow"; import {connect} from "react-redux"; import bip39 from 'react-native-bip39' import { ethers } from "ethers"; import ValidationPopup from "../../../Components/ValidationPopup"; const Word = (props) => { const { text, n } = props; return ( <View style={styles.wordContainer}> <Text style={styles.number}>{n}</Text> <Text style={styles.word}>{text}</Text> </View> ) } const RecoveryPhaseScreen = (props) => { const [ words, setWords ] = useState([]); const [ hash, setHash ] = useState(); const [ walletAddress, setWalletAddress ] = useState(''); const [ showValidpop, setShowValidpop ] = useState(true); const generateMnemonic = async () => { try { console.log('-----------') let mnemonic = await bip39.generateMnemonic(128) // default to 128 console.log(typeof mnemonic) /*walletMnemonic = ethers.Wallet.fromMnemonic(mnemonic) console.log('wallet address') console.log(walletMnemonic.address) setWalletAddress(walletMnemonic.address)*/ setWords(mnemonic.split(' ')) let h = bip39.mnemonicToEntropy(mnemonic) setHash(h); console.log(h) //const mnemonic2 = bip39.entropyToMnemonic(h) //console.log(mnemonic2) } catch(e) { console.log(e) return false } } useEffect(() => { generateMnemonic() }, []) const onShare = async () => { try { const result = await Share.share({ message: words.join(' '), }); if (result.action === Share.sharedAction) { if (result.activityType) { // shared with activity type of result.activityType } else { // shared } } else if (result.action === Share.dismissedAction) { // dismissed } } catch (error) { alert(error.message); } }; return ( <SafeAreaView style={styles.container}> {!words[0] ? <ActivityIndicator style={{flex: 1}} size="large" color="#246BFD"/> : <> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow /> <View> <Image style={styles.img} source={require('../../../Assets/Images/lock.png')} /> </View> <Text style={styles.title}>Write down your Secret Recovery Phase</Text> <Text style={styles.text}>Below is your secret back-up phrase. Please, write it down and save it. On the next screen you will be asked to re-enter it in order.</Text> <View style={styles.wordsBlock}> { words[0] && words.map((word, i) => <Word text={word} n={i+1}/>) } </View> <View style={styles.btnContainer}> <View style={styles.insideBtnContainer}> <TouchableOpacity onPress={() => Clipboard.setString(words.join(' '))} style={styles.miniBtn}> <Text style={styles.textMiniBtn}>Copy</Text> <Image style={styles.btnIcon} source={require('../../../Assets/Images/Copy.png')} /> </TouchableOpacity> <TouchableOpacity onPress={() => onShare()} style={styles.miniBtn}> <Text style={styles.textMiniBtn}>Share</Text> <Image style={styles.btnIcon} source={require('../../../Assets/Images/Upload.png')} /> </TouchableOpacity> </View> </View> <Button handleFunction={()=>props.navigation.navigate('ConfirmBackupPhaseScreen', {words, hash, walletAddress})} btnText={'Next'}/> </>} </SafeAreaView> ) } const mapStateToProps = (state) => ({ auth: state.auth }); const mapDispatchToProps = (dispatch) => ({ sendEmail: (data) => {dispatch({type: "SEND_EMAIL", data})}, eraseEmailError: () => {dispatch({type: "ERASE_EMAIL_ERROR"})}, }); export default connect( mapStateToProps, mapDispatchToProps )(RecoveryPhaseScreen); <file_sep>/src/Containers/Home/Token.js import React, { useEffect,useState } from 'react'; import {View, Text, Image, ImageBackground, TouchableOpacity, Platform} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP as wp, } from 'react-native-responsive-screen'; import resp from 'rn-responsive-font'; import {mining} from '../../Assets/Images'; import { VibrancyView } from "react-native-blur"; import BlurOverlay,{closeOverlay,openOverlay} from 'react-native-blur-overlay'; import {useNavigation} from '@react-navigation/native'; const Token = () => { const navigation = useNavigation(); const [swappPoint,setSwappPoint]=useState(50) useEffect(()=>{ openOverlay(); },[]) return ( <View style={{marginTop: hp('3')}}> <View style={{ backgroundColor: '#1F222A', marginHorizontal: wp('5'), borderRadius: 12, // height: hp(''),er overflow: 'hidden', // opacity:4 }}> <View style={{marginLeft: wp('5'), paddingVertical: hp('3')}}> <Text style={{ color: 'white', fontSize: resp(24), // fontWeight: 'bold', // marginBottom: hp('2'), marginRight: wp('40%'), // lineHeight: 30, zIndex: 100, fontFamily:'Poppins-SemiBold' }}> {'Get a free Swapp token!'} </Text> <View style={{height: wp('12'), width: wp('21'),position:'absolute'}}> <Image source={require('../../Assets/Images/swappToken.png')} style={{ height: '100%', width: '100%', resizeMode: 'contain', top:Platform.OS=="ios"?hp('6%'):hp('7%'), // backgroundColor:'red', marginLeft: wp('-1%'), }} /> </View> <View style={{ borderColor: '#94F0F0', borderWidth: 1, width: wp('20'), borderRadius: 8, // position:'absolute' marginTop: hp('2'), }}> <Text style={{ textAlign: 'center', padding: 5, color: '#94F0F0', fontSize: resp(12), fontFamily:'Inter-Medium' }}> {swappPoint} Swapps </Text> </View> </View> <View style={{ height: hp('30%'), width: wp('65%'), position: 'absolute', right:wp('-10%'), top:Platform.OS=="android"?hp('2%'):hp('0%'), }}> <Image source={mining} style={{height: '100%', width: '100%'}}/> </View> <ImageBackground source={require('../../Assets/Images/blurImg.png')} style={{ // backgroundColor: 'rgba(0,0,0,0.3)', flexDirection: 'row', }}> <View style={{padding: 4, paddingVertical: 10}}> <Text style={{fontSize:resp(13),marginRight: wp('30'),marginLeft:wp('5'), lineHeight: 28, color: '#5E6272',fontFamily:'Inter-Medium'}}> Store digital assets and euros together. Set your account.now </Text> <TouchableOpacity onPress={()=>navigation.navigate('ChangePassword')} style={{ backgroundColor: 'white', // height: hp('5'), width: wp('17'), position: 'absolute', right: 10, top: wp('5'), borderRadius: 4, paddingVertical: 2, }}> <Text style={{textAlign: 'center',fontSize:wp('3%') ,padding: 5,fontFamily:'Inter-Medium'}}>Open</Text> </TouchableOpacity> </View> </ImageBackground> {/* </VibrancyView> */} </View> </View> ); }; export default Token; <file_sep>/src/Containers/CreatingAccount/ConfirmBackupPhaseScreen/index.js import React, {useEffect, useState} from 'react'; import { Image, KeyboardAvoidingView, SafeAreaView, StatusBar, Text, TouchableOpacity, View, } from "react-native"; import styles from './Styles'; import Button from "../../../Components/CreatingAccount/Button"; import BackArrow from "../../../Components/CreatingAccount/BackArrow"; import PopupModal from '../../../Components/PopupModal'; import {connect} from "react-redux"; import EncryptedStorage from 'react-native-encrypted-storage'; const WordButton = (props) => { const { wordItem, handleAddWord } = props; const { word, isSelected, id } = wordItem; return ( <TouchableOpacity onPress={() => handleAddWord(id)} style={[styles.wordBtnContainer, {borderColor: isSelected ? '#303136' : '#5E6272'}]}> <Text style={[styles.wordBtnText, {color: isSelected ? '#303136' : '#FFFFFF'}]}>{word}</Text> </TouchableOpacity> ) } const AttachedWord = (props) => { const { wordItem, handleDeleteWord } = props; const { word, id } = wordItem; return ( <TouchableOpacity onPress={() => handleDeleteWord(id)} style={styles.attachedWordContainer}> <Text style={styles.attachedWordText}>{word}</Text> <View> <Image style={styles.closeIcon} source={require('../../../Assets/Images/CloseSquare.png')} /> </View> </TouchableOpacity> ) } const ConfirmBackupPhaseScreen = (props) => { const getWords = () => { let wordsArray = props.route.params.words.map((el, i) => ({id:i+1, word:el, isSelected: false})); return wordsArray.sort(() => Math.random() - 0.5); } const [ words, setWords ] = useState(getWords()); const [ popModal, setPopModal ] = useState(false); const [ checkedWords, setCheckedWords ] = useState([]); const [ isWrongPhrase, setIsWrongPhrase ] = useState('pending'); const [id,setId]=useState(''); const handleAddWord = (id) => { setWords(words.map(el => el.id === id ? { ...el, isSelected: true} : el)); let checkedWord = words.find(el => el.id == id) checkedWord.isSelected == false && setCheckedWords([...checkedWords, checkedWord]) setIsWrongPhrase('pending') } useEffect(()=>{ EncryptedStorage.getItem('@user_id').then(id=>{ if(id){ setId(JSON.parse(id)); } }) },[]); const handleDeleteWord = (id) => { setWords(words.map(el => el.id === id ? { ...el, isSelected: false} : el)); setCheckedWords(checkedWords.filter(el => el.id !== id)) setIsWrongPhrase('pending') } useEffect(() => { if(isWrongPhrase === 'correct') { props.eraseUserNameError(); props.sendSecretHash({ id: id, secret: props.route.params.hash }); setPopModal(true); // AsyncStorage.setItem('@token',JSON.stringify()) // props.navigation.navigate('ThreeThingsScreen') } if(isWrongPhrase === 'wrong') { console.log(isWrongPhrase) } }, [isWrongPhrase]) const handleConfirm = () => { if(checkedWords.length !== 12) { setIsWrongPhrase('wrong') } else { let flag = false; checkedWords.forEach((el, i) => { if(el.id != i+1) { console.log(el.id + ' ' + i+1) flag = true; setIsWrongPhrase('wrong') } }) if(!flag) { setIsWrongPhrase('correct') } } // props.navigation.navigate('NameScreen') } const setTokenToAsyncStorage = async () => { const value = await EncryptedStorage.getItem('token'); console.log('async') console.log(value) await EncryptedStorage.setItem( 'token', props.auth.isAuth.token ); } useEffect(()=>{ EncryptedStorage.getItem('@user_id').then(id=>{ if(id){ setId(JSON.parse(id)); } }) },[]) useEffect(() => { if(props.auth.isAuth) { console.log('success. Must to navigate to next screens') //props.sendWalletAddress({wallet: props.route.params.walletAddress}) } }, [props.auth]) return ( <SafeAreaView style={styles.container}> <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={{flex:1}}> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow navigate={props.navigate}/> <View style={styles.titleContainer}> <Text style={styles.title}>Confirm your Secret Backup Phase</Text> <Text style={styles.text}>Pleace select each phase in order to make sure it is correct.</Text> </View> <View style={[styles.wordBoard, {borderColor: isWrongPhrase === 'wrong' ? '#FF0B80' : isWrongPhrase === 'correct' ? '#A5F59C' : '#5E6272'}]}> { checkedWords.map(wordItem => <AttachedWord handleDeleteWord={handleDeleteWord} wordItem={wordItem}/>) } </View> <View style={styles.wordBtnBlock}> { words.map(wordItem => ( <WordButton wordItem={wordItem} handleAddWord={handleAddWord}/> )) } </View> <Button inActive={checkedWords.length !== 12} disabled={props.auth.loader || checkedWords.length !== 12} loading={props.auth.loader} handleFunction={handleConfirm} btnText={'Confirm'}/> </KeyboardAvoidingView> { popModal && <PopupModal visible={popModal} children={"You have registered your Swap account. Have a good use of the app."} height={'55%'} onPress={() => { setPopModal(false) props.navigation.navigate('ThreeThingsScreen') } } /> } </SafeAreaView> ) } const mapStateToProps = (state) => ({ auth: state.auth, wording:state.wording }); const mapDispatchToProps = (dispatch) => ({ sendWalletAddress: (data) => {dispatch({type: "SEND_WALLET_ADDRESS", data})}, eraseEmailError: () => {dispatch({type: "ERASE_EMAIL_ERROR"})}, sendSecretHash: (data) => {dispatch({type: "SEND_SECRET", data})}, eraseUserNameError: () => {dispatch({type: "ERASE_USERNAME_ERROR"})}, }); export default connect( mapStateToProps, mapDispatchToProps )(ConfirmBackupPhaseScreen); <file_sep>/src/Services/wording.service.js import axios from 'axios'; import DeviceInfo from 'react-native-device-info'; const URL = 'https://data-stage.hubioid.com'; export function sendwording(data) { return axios.request({ method: 'post', url: `${URL}/api/v1/mobile/user/wording/set`, headers: { Authorization: 'Bearer ' + data.token }, data: data.data }); } export function addusername(data) { console.log('set username', data); return axios.request({ method: 'post', headers: { Authorization: `Bearer ${DeviceInfo.getUniqueId()}`, 'Content-Type': 'application/json' }, url: `${URL}/api/v1/mobile/user/name/set`, data }); } export function sendSecretHash(data) { console.log('scert', data); return axios.request({ method: 'post', url: `${URL}/api/v1/mobile/user/secret/set`, headers: { Authorization: `Bearer ${DeviceInfo.getUniqueId()}`, 'Content-Type': 'application/json' }, data }); } <file_sep>/src/Assets/Images/Navigationimage/index.js const SettingActive = require("./setting_active_icon.png"); const SettingInactive = require("./setting_inactive_icon.png"); const WebImage = require("./cart_bag.png"); export {SettingActive,SettingInactive,WebImage} // {require('../../assets/Images/logo_cart_paddle.png')<file_sep>/src/Containers/ChangePassword/ChangePasscode/index.js import React, { useState } from 'react'; import {View, Text, TouchableOpacity, Image, ImageBackground} from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import BackArrow from '../../../Components/CreatingAccount/BackArrow'; import Pinkeyboard from '../../../Components/ChangePasscodeKeyboard'; import Button from '../../../Components/CreatingAccount/Button'; import {useRoute} from '@react-navigation/native'; import ValidationPopup from '../../../Components/ValidationPopup'; import EncryptedStorage from 'react-native-encrypted-storage'; import Header from '../../../Components/Header'; const ChangePassCode = ({navigation}) => { const [ isModal, setIsModal ] = useState(false); const [NewPasscode,setNewPasscode]=useState(['', '', '', '', '', '']); const [showValidation, setShowValidation] = useState(false); const [message,setmessage]=useState("Enter your old PIN code"); const [save,setSave]=useState(false); const route = useRoute(); function onSucess(password) { let tempCode = password; console.log('temp code',tempCode); setNewPasscode([...tempCode]); if(message=='Enter your old PIN code') setmessage('Create new PIN code') if(message=='Create new PIN code') setmessage('Repeat the new PIN code'); if(message=='Repeat the new PIN code'){ setmessage('Your parrot has been updated!') setSave(true) } } const HandleNext=()=>{ if(NewPasscode[5]!=''){ EncryptedStorage.setItem('@NewPasscode',JSON.stringify(NewPasscode)).then(suc=>{ navigation.navigate('ConfirmPassCode', { InitalScreen: route?.params?.InitalScreen, isRegistration: route.params.isRegistration }); }); }else{ setShowValidation(true) } } const updateshow = () => { setShowValidation(false) } return ( <View style={{backgroundColor: '#181A20', flex: 1}}> <Header navigation={navigation} hide onSave={()=>{navigation.navigate('Home')}} setting save={save}/> <View style={{marginHorizontal: wp('5%'), marginBottom: hp('5%'),marginTop: hp('3%')}}> <Text style={{ color: 'white', fontSize: wp('6%'), fontWeight: '600', // marginTop: hp('4%'), fontFamily: 'Poppins-SemiBold', }}> Change passcode </Text> {message=="Enter your old PIN code"?<View style={{height:hp('8%')}}> <Text style={{color:'#fff',fontFamily:'Inter-Regular',lineHeight:25}}>For the changes to take effect, you need to update the passcode</Text> </View>:<View style={{height:hp('8%')}}></View>} </View> <View style={{marginTop:hp('5%')}}> <Pinkeyboard navigation={navigation} textPin={message} confirm={false} onSucess={onSucess} /> </View> {/* <View> <Button handleFunction={HandleNext} btnText={'Next'} // style={{marginTop:20}} /> </View> <TouchableOpacity onPress={() => { }}> <Text style={{color: '#5E6272', textAlign: 'center'}}>Skip</Text> </TouchableOpacity> */} {showValidation == true && ( <ValidationPopup title={"Please enter a 5 digit passcode"} Show={true} showback={updateshow} /> )} </View> ); }; export default ChangePassCode; <file_sep>/src/Actions/auth.actions.js export const setEmailSuccess = (email) => ({type: 'SET_EMAIL_SUCCESS', email}); export const setEmailError = (data) => ({type: 'SET_EMAIL_ERROR', data}); export const setCodeError = (data) => ({type: 'SET_CODE_ERROR', data}); export const setTokenError = (data) => ({type: 'SET_TOKEN_ERROR', data}); export const setTokenSuccess= (data) => ({type: 'SET_TOKEN_SUCCESS', data}); export const setEmailLoaderTrue=()=>({type: 'SET_EMAIL_LOADER'}); export const setLoginLoaderTrue=()=>({type: 'SET_LOGIN_LOADER'}); export const setAuthVerificationLoader=()=>({type:'SET_AUTH_VERIFICATION_LOADER'}) export const setAuthVerificationError = (data) => ({type: 'SET_AUTH_VERIFICATION_ERROR', data}); export const setAuthVerificationSuccess= (data) => ({type: 'SET_AUTH_VERIFICATION_SUCCESS', data}); export const setCodeSuccess = (data) => { console.log('action ') console.log(data) return ({type: 'SET_CODE_SUCCESS', data}) } export const setLoaderTrue = () => ({type: 'SET_LOADER_TRUE'}); <file_sep>/src/Containers/ChangePassword/ChangePassword/Condition.js import React, {useState} from 'react'; import {View, Text, Image} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP as wp, } from 'react-native-responsive-screen'; const Condition = ({pattern, Title}) => { const [check, setcheck] = useState(null); React.useEffect(() => { setcheck(pattern); // console.log('dd') }, [pattern]); return ( <View style={{flexDirection: 'row', marginVertical: hp('0.8')}}> {check ? <View style={[ { width: wp('5'), height: wp('5'), borderRadius: 30, overflow:'hidden' }, // check ? {backgroundColor: 'pink'} : {backgroundColor: 'red'}, ]} > <Image source={require('../../../Assets/Images/Check2.png') } style={{height:'100%',width:'100%'}}/> </View> : <View style={[ { width: wp('5'), height: wp('5'), borderRadius: 30, overflow:'hidden', borderColor:'gray', borderWidth:1 }, // check ? {backgroundColor: 'pink'} : {backgroundColor: 'red'}, ]} />} <Text style={{marginLeft: wp('4'), color: '#5E6272'}}>{Title}</Text> </View> ); }; export default Condition; <file_sep>/src/Components/TransparentButton/index.js import React from 'react'; import {TouchableOpacity,Text,Platform,View} from 'react-native'; // import { Spinner } from 'native-base' import Style from './style'; import AntDesgin from 'react-native-vector-icons/AntDesign'; const TransparentButton=(props)=>{ const { style, textStyle, onPress, title, disabled, loading, selected, children}=props; let textStyleNode = selected ? { ...Style.text, ...textStyle, ...Style.selectedText} : { ...Style.text, ...textStyle}; let buttonStyleNode = selected ? { ...Style.button, ...style, ...Style.selectedButton } : { ...Style.button, ...style }; let textNode = ( <Text style={textStyleNode}>{title}</Text>); textNode = title ? textNode : []; return( <View style={{width:'85%'}}> <TouchableOpacity disabled={disabled} style={buttonStyleNode} onPress={onPress}> {!loading ? children : []} {textNode} </TouchableOpacity> </View> ) } export default TransparentButton; TransparentButton.defaultProps = { disabled: false, loading: false, selected: false, children: [] };<file_sep>/src/Navigator/index.js import * as React from 'react'; import {NavigationContainer} from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import {createStackNavigator} from '@react-navigation/stack'; import SplashScreen from '../Containers/Splash'; import OnBoarding from '../Containers/OnBoarding'; import InitialScreen from '../Containers/CreatingAccount/InitialScreen'; import EnterEmailPhoneScreen from '../Containers/CreatingAccount/EnterEmailPhoneScreen'; import Verification from '../Containers/CreatingAccount/Verification'; import ThreeThingsScreen from '../Containers/CreatingAccount/ThreeThingsScreen'; import RecoveryPhaseScreen from '../Containers/CreatingAccount/RecoveryPhaseScreen'; import ConfirmBackupPhaseScreen from '../Containers/CreatingAccount/ConfirmBackupPhaseScreen'; import PinCodeScreen from '../Containers/PinScreen'; import NameScreen from '../Containers/NameScreen'; import AcceptTerm from '../Containers/AcceptTerm'; import CreateNewPasscode from '../Containers/CreateNewPassCode'; import CreateNewPassword from '../Containers/CreateNewPassword'; import EnterPassword from '../Containers/EnterPassword'; import ConfirmPassCode from '../Containers/ConfirmPasscode'; import TypeWordPhrase from "../Containers/ImportAccount/TypeWordPhrase"; import CreatePasscode from "../Containers/ImportAccount/CreatePasscode"; import AddUsername from "../Containers/AddUsername"; import WalletScreen from "../Containers/Wallet/WalletScreen"; import SendScreen from "../Containers/Wallet/SendScreen"; import TabNav from "./TabNav"; import Home from "../Containers/Home"; import Settings from '../Containers/Settings'; import ChangePassword from '../Containers/ChangePassword/ChangePassword' import ChangePassCode from '../Containers/ChangePassword/ChangePasscode'; const Stack = createStackNavigator(); const Tab = createBottomTabNavigator(); function AppStack() { return ( <NavigationContainer theme={{colors: {background: '#181A20'}}}> <Stack.Navigator initialRouteName="SplashScreen"> <Stack.Screen name="SplashScreen" component={SplashScreen} options={{headerShown: false}} /> <Stack.Screen name="OnBoarding" component={OnBoarding} options={{headerShown: false}} /> <Stack.Screen name="Home" component={Home} options={{headerShown: false}} /> <Stack.Screen name="InitialScreen" component={InitialScreen} options={{headerShown: false}} /> <Stack.Screen name="EnterEmailPhoneScreen" component={EnterEmailPhoneScreen} options={{headerShown: false}} /> <Stack.Screen name="Verification" component={Verification} options={{headerShown: false}} /> <Stack.Screen name="ThreeThingsScreen" component={ThreeThingsScreen} options={{headerShown: false}} /> <Stack.Screen name="RecoveryPhaseScreen" component={RecoveryPhaseScreen} options={{headerShown: false}} /> <Stack.Screen name="ConfirmBackupPhaseScreen" component={ConfirmBackupPhaseScreen} options={{headerShown: false}} /> <Stack.Screen name="PinScreen" component={PinCodeScreen} options={{headerShown: false}} /> <Stack.Screen name="NameScreen" component={NameScreen} options={{headerShown: false}} /> <Stack.Screen name="AddUsername" component={AddUsername} options={{headerShown: false}} /> <Stack.Screen name="AcceptTerm" component={AcceptTerm} options={{headerShown: false}} /> <Stack.Screen name="CreateNewPasscode" component={CreateNewPasscode} options={{headerShown: false}} /> <Stack.Screen name="CreateNewPassword" component={CreateNewPassword} options={{headerShown: false}} /> <Stack.Screen name="EnterPassword" component={EnterPassword} options={{headerShown: false}} /> <Stack.Screen name="WalletScreen" component={WalletScreen} options={{headerShown: false}} /> <Stack.Screen name="ConfirmPassCode" component={ConfirmPassCode} options={{headerShown: false}} /> <Stack.Screen name="CreatePasscode" component={CreatePasscode} options={{headerShown: false}} /> <Stack.Screen name="SendScreen" component={SendScreen} options={{headerShown: false}} /> <Stack.Screen name="TabNav" component={TabNav} options={{headerShown: false}} /> <Stack.Screen name="Setting" component={Settings} options={{headerShown: false}} /> <Stack.Screen name="ChangePassword" component={ChangePassword} options={{headerShown: false}} /> <Stack.Screen name="ChangePassCode" component={ChangePassCode} options={{headerShown: false}} /> <Stack.Screen name="TypeWordPhrase" component={TypeWordPhrase} options={{headerShown:false}} /> </Stack.Navigator> </NavigationContainer> ); } export default AppStack; <file_sep>/src/Containers/Wallet/SendScreen/index.js import React, {useEffect, useRef, useState} from 'react'; import { Image, KeyboardAvoidingView, SafeAreaView, StatusBar, Text, TextInput, TouchableOpacity, TouchableWithoutFeedback, View, ScrollView } from "react-native"; import styles from './Styles'; import Button from "../../../Components/CreatingAccount/Button"; import BackArrow from "../../../Components/CreatingAccount/BackArrow"; import uuid from 'react-native-uuid'; import {useRoute} from '@react-navigation/native'; import {connect} from "react-redux"; const SendScreen = (props) => { return ( <SafeAreaView style={styles.container}> <KeyboardAvoidingView keyboardVerticalOffset={StatusBar.currentHeight} behavior={Platform.OS === "ios" ? "padding" : "height"} style={styles.contentContainer}> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow isText={'Send by wallet'} navigation={props.navigation}/> <View style={styles.senderContainer}> <View style={styles.senderHeader}> <Text style={styles.senderHeaderText}>From</Text> <Text style={styles.senderHeaderText}>15 coins</Text> </View> <View style={styles.senderInfoContainer}> <View style={styles.senderCurrencyContainer}> <Image style={styles.currencyImg} source={require('../../../Assets/Images/ETH.png')} /> <View style={styles.currencyValueContainer}> <Text style={styles.senderValue}>51.05 ETC</Text> <Text style={styles.senderConvertedValue}>$155.500,00</Text> </View> </View> <TouchableOpacity> <Image style={styles.btnIcon} source={require('../../../Assets/Images/arrowDown.png')} /> </TouchableOpacity> </View> </View> <View style={styles.senderContainer}> <View style={styles.senderHeader}> <Text style={styles.senderHeaderText}>To</Text> </View> <View style={styles.senderInfoContainer}> <View style={styles.senderCurrencyContainer}> <Text style={styles.senderConvertedValue}>Wallet address</Text> </View> <TouchableOpacity> <Image style={styles.btnIcon} source={require('../../../Assets/Images/QrIcon.png')} /> </TouchableOpacity> </View> </View> <View style={[styles.senderContainer, {height: '24%'}]}> <View style={styles.resultHeader}> <Text style={styles.senderHeaderText}>To</Text> </View> <View style={styles.senderInfoContainer}> <TouchableOpacity> <Image style={styles.btnIcon} source={require('../../../Assets/Images/QrIcon.png')} /> </TouchableOpacity> </View> </View> </KeyboardAvoidingView> </SafeAreaView> ) } const mapStateToProps = (state) => ({ auth: state.auth }); const mapDispatchToProps = (dispatch) => ({ getToken: (data) => {dispatch({type: "GET_TOKEN", data})}, eraseEmailError: () => {dispatch({type: "ERASE_EMAIL_ERROR"})}, sendSecretHash: (data) => {dispatch({type: "SEND_SECRET", data})}, }); export default connect( mapStateToProps, mapDispatchToProps )(SendScreen); <file_sep>/src/Containers/Settings/index.js import React, {useState, useEffect} from 'react'; import { View, Text, TouchableOpacity, Image, TextInput, KeyboardAvoidingView, Platform, SafeAreaView, } from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import Header from '../../Components/Header'; import {createMaterialTopTabNavigator} from '@react-navigation/material-top-tabs'; import style from './Styles'; import Emails from './emails'; import Phone from './phonenumber'; const Tab = createMaterialTopTabNavigator(); const Settings=({navigation})=>{ return( <SafeAreaView style={style.container}> <Header setting hide navigation={navigation} onSave={()=>{}} save={true} /> <Tab.Navigator tabBarOptions={{ activeTintColor: '#fff', inactiveTintColor: '#fff', indicatorStyle: {backgroundColor: '#246BFD',height: '100%',borderRadius:20}, indicatorContainerStyle: style.indicatorstyle, labelStyle: style.label, style:style.tabNavigator }}> <Tab.Screen name="Emails" component={Emails} /> <Tab.Screen name="Phone Numbers" component={Phone} /> </Tab.Navigator> </SafeAreaView> ) } export default Settings;<file_sep>/src/Containers/AddUsername/Styles.js import { StyleSheet, Dimensions } from 'react-native' let width=Dimensions.get('window').width; let height=Dimensions.get('window').height; import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen'; export default StyleSheet.create({ container: { flex:1, backgroundColor: '#181A20' }, image:{ width:wp('100%'), height:hp('100%'), justifyContent:'center', alignItems:'center' }, inputTitle: { color:'white', fontSize:wp('3.0%'), marginBottom:hp('2%'), fontFamily:'Inter-Bold' }, inputBlock: { marginTop:hp('4%'), width:wp('90%'), alignSelf:'center', height: hp('8%'), display: 'flex', justifyContent:'space-between' }, input: { width:wp('90%'), height:hp('6%'), borderBottomColor: '#246BFD', borderBottomWidth:2, color:'white', fontSize:wp('4.5%'), fontFamily:'Inter-SemiBold' }, }) <file_sep>/src/Components/CreatingAccount/Button/index.js import React from 'react'; import {Text, TouchableOpacity, View,ActivityIndicator} from "react-native"; import { heightPercentageToDP, widthPercentageToDP } from 'react-native-responsive-screen'; import styles from './styles'; const Button = (props) => { const { btnText, inActive, isTransparent,style,btnconstyle,disabled, handleFunction,loading,roundBtn } = props; const getTextColor = () => { if(style) { return '#3A3D46' } else if(inActive) { return '#3A3D46' } else { return 'white' } } const getBackgroundColor = () => { if(style) { return '#262A34' } else if(inActive) { return '#262A34' } else { return '#246BFD' } } return ( <View style={[btnconstyle,styles.buttonContainer]}> <TouchableOpacity disabled={disabled} style={[styles.button, isTransparent ? { backgroundColor: '#ffffff00', borderWidth: 1, borderColor: roundBtn?'#246BFD':'#5E6272', borderRadius:roundBtn?heightPercentageToDP('10%'):heightPercentageToDP('2%') } : {backgroundColor: getBackgroundColor()}]} onPress={() => {handleFunction()}} > {loading?(<ActivityIndicator color={"#fff"} size={widthPercentageToDP('10%')} />):(<Text style={[styles.buttonText,{color: getTextColor(),fontFamily:roundBtn?'Inter-Medium':'Inter-Bold',fontSize:roundBtn?widthPercentageToDP('3.8%'):widthPercentageToDP('4.2%')}]}>{btnText}</Text>)} </TouchableOpacity> </View> ) } export default Button; <file_sep>/src/Components/SelectionBtn/index.js import React from 'react'; import {View, Text, TouchableOpacity} from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import Styles from './styles'; import Icon from 'react-native-vector-icons/AntDesign'; const SelectionBtn = ({selection, GetSelected}) => { const [select, setselect] = React.useState(selection); console.log(select); const Selectedvalue = item => { setselect(item); GetSelected(item); }; const emoji = [' 😎', ' 💸', ' 👍']; return ( <View> {selection.map((item, index) => { return ( <View style={{paddingVertical: hp('1%')}} key={index}> <TouchableOpacity onPress={() => Selectedvalue(item)} style={ select === item ? Styles.activebutton : Styles.disablebutton }> <View style={ select === item ? Styles.activecheck : Styles.disablecheck }> {select === item ? ( <Icon size={15} color="white" name="check" /> ) : null} </View> <View> <Text style={ select === item ? Styles.btntext : Styles.btntextdisable }> {item} {emoji[index]} </Text> </View> </TouchableOpacity> </View> ); })} </View> ); }; export default SelectionBtn; <file_sep>/src/Containers/Wallet/WalletScreen/index.js import React, {useEffect, useRef, useState} from 'react'; import { Image, KeyboardAvoidingView, SafeAreaView, StatusBar, Text, TextInput, TouchableOpacity, TouchableWithoutFeedback, View, ScrollView } from "react-native"; import styles from './Styles'; import Button from "../../../Components/CreatingAccount/Button"; import BackArrow from "../../../Components/CreatingAccount/BackArrow"; import uuid from 'react-native-uuid'; import {useRoute} from '@react-navigation/native'; import {connect} from "react-redux"; import bip39 from 'react-native-bip39' import { ethers } from "ethers"; const NFT = (props) => { const {id, name, img, version, number, total} = props.el; return ( <View style={styles.nftContainer}> <Image style={styles.nftImg} source={img} /> <Text style={styles.nftName}>{name}</Text> <View style={styles.nftInfoContainer}> <Text style={styles.nftText}>{number} of {total}</Text> <Text style={styles.nftText}>{version}</Text> </View> </View> ) } const Token = (props) => { const { icon, name, percent, value, convertValue } = props.token; return ( <View style={styles.tokenContainer}> <View style={styles.tokensInfoContainer}> <Image style={styles.tokenIcon} source={icon} /> <View style={styles.tokenInfo}> <Text style={styles.tokenName}>{name}</Text> <Text style={styles.tokenPercent}>{percent}</Text> </View> </View> <View style={styles.priceContainer}> <Text style={styles.price}>{value} <Text style={{ fontFamily:'Inter-Medium' }}>{name}</Text></Text> <Text style={styles.convertedPrice}>{convertValue}</Text> </View> </View> ) } const HeaderButton = (props) => { const { img, text } = props; return ( <TouchableOpacity onPress={() => props.navigation.navigate('SendScreen')} style={styles.btnContainer}> <Image style={styles.btnIcon} source={img} /> <Text style={styles.btnName}>{text}</Text> </TouchableOpacity> ) } const WalletScreen = (props) => { const [ isTokens, setIsTokens ] = useState(true); const [ tokens, setTokens ] = useState([ {id:1, icon: require('../../../Assets/Images/ETH.png'), value:'256', name:'ETH', convertValue:'$ 240 004,44', percent:'-0.85%'}, {id:2, icon: require('../../../Assets/Images/BNB.png'), value:'256', name:'BNB', convertValue:'$ 240 004,44', percent:'-0.85%'}, {id:3, icon: require('../../../Assets/Images/USDT.png'), value:'256', name:'USDT', convertValue:'$ 240 004,44', percent:'-0.85%'}, {id:4, icon: require('../../../Assets/Images/ZEK.png'), value:'256', name:'ZEK', convertValue:'$ 240 004,44', percent:'-0.85%'}, {id:5, icon: require('../../../Assets/Images/BTX.png'), value:'256', name:'BTX', convertValue:'$ 240 004,44', percent:'-0.85%'} ]); const [ nft, setNft ] = useState([ {id:1, name:'Amazing digital art', img:require('../../../Assets/Images/NFT1.png'), version:3, number:2, total:10}, {id:1, name:'Amazing digital art', img:require('../../../Assets/Images/NFT1.png'), version:3, number:2, total:10}, {id:1, name:'Amazing digital art', img:require('../../../Assets/Images/NFT1.png'), version:3, number:2, total:10}, {id:1, name:'Amazing digital art', img:require('../../../Assets/Images/NFT1.png'), version:3, number:2, total:10}, {id:1, name:'<NAME>', img:require('../../../Assets/Images/NFT1.png'), version:3, number:2, total:10}, ]); /*const generateMnemonic = async () => { try { console.log('------------------------------') console.log('Generate mnemonic phrase') let mnemonic = await bip39.generateMnemonic(128) // default to 128 console.log(mnemonic) let walletMnemonic = ethers.Wallet.fromMnemonic(mnemonic) console.log('wallet address') console.log(walletMnemonic.address) let network = ethers.providers.getNetwork("homestead") console.log('network') console.log(network) let defProvider = ethers.getDefaultProvider( network ) console.log('defProvider') console.log(defProvider) let wallet = walletMnemonic.connect(defProvider) console.log('balace') let b = await wallet.getBalance(); console.log(b.toString()) console.log('!!!!!!!!!!!!!!!!!!!!!!!') let signer = new ethers.VoidSigner('0x8ba1f109551bD432803012645Ac136ddd64DBA72', defProvider) let abi = [ "function balanceOf(address) view returns (uint)", "function transfer(address, uint) returns (bool)" ] let contract = new ethers.Contract("0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", abi, defProvider) console.log('contract') console.log(contract.address) let tokens = await contract.balanceOf(signer.getAddress()) console.log('tokens') console.log(ethers.utils.formatEther(tokens)) const balance2 = await contract.balanceOf('0xAd8924167B16d57E0dAE50856D57Dc7E727adc5f'); console.log(balance2) console.log(ethers.utils.formatEther(balance2)) } catch(e) { console.log(e) return false } }*/ useEffect(() => { //generateMnemonic() }, []) return ( <SafeAreaView style={styles.container}> <KeyboardAvoidingView keyboardVerticalOffset={StatusBar.currentHeight} behavior={Platform.OS === "ios" ? "padding" : "height"} style={{flex:1}}> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow isText={'Wallet'} navigation={props.navigation}/> <View style={styles.headerContainer}> <View style={styles.profileContainer}> <Image style={styles.icon} source={require('../../../Assets/Images/defaultAvatar.png')} /> <View style={styles.infoContainer}> <Text style={styles.walletName}>My Swapp wallet</Text> <View style={styles.balance}> <Text style={styles.balanceText}>Total balance:</Text> <Text style={styles.balanceValue}>$ 514.25</Text> </View> </View> </View> <TouchableOpacity style={styles.walletAddressContainer}> <Text style={styles.walletAddress}>Bella_Adams.swapp.eth</Text> <Image style={styles.copyImg} source={require('../../../Assets/Images/Copy.png')} /> </TouchableOpacity> <View style={styles.buttonsContainer}> <HeaderButton navigation={props.navigation} img={require('../../../Assets/Images/sendBtn.png')} text={'Send'} /> <HeaderButton img={require('../../../Assets/Images/shareBtn.png')} text={'Share'} /> <HeaderButton img={require('../../../Assets/Images/soonBtn.png')} text={'Soon'} /> <HeaderButton img={require('../../../Assets/Images/historyBtn.png')} text={'History'} /> </View> </View> <View style={styles.switchButtonsContainer}> <TouchableOpacity onPress={() => setIsTokens(!isTokens)} style={[styles.switchBtn, {backgroundColor: isTokens ? '#246BFD' : '#131313'}]} > <Image style={styles.switchBtnImg} source={require('../../../Assets/Images/Work.png')} /> <Text style={styles.switchBtnText}>Tokens</Text> </TouchableOpacity> <TouchableOpacity onPress={() => setIsTokens(!isTokens)} style={[styles.switchBtn, {backgroundColor: !isTokens ? '#246BFD' : '#131313'}]} > <Image style={styles.switchBtnImg} source={require('../../../Assets/Images/NFT.png')} /> <Text style={styles.switchBtnText}>NFT</Text> </TouchableOpacity> </View> <ScrollView showsVerticalScrollIndicator={false} style={{width:'90%', flex:1, alignSelf:'center', marginTop:'4%'}}> { isTokens ? tokens.map(token => ( <Token token={token}/> )) : <View style={{display:'flex', flexDirection:'row', flexWrap:'wrap'}}> { nft.map(el => ( <NFT el={el}/> )) } </View> } </ScrollView> </KeyboardAvoidingView> </SafeAreaView> ) } const mapStateToProps = (state) => ({ auth: state.auth }); const mapDispatchToProps = (dispatch) => ({ getToken: (data) => {dispatch({type: "GET_TOKEN", data})}, eraseEmailError: () => {dispatch({type: "ERASE_EMAIL_ERROR"})}, sendSecretHash: (data) => {dispatch({type: "SEND_SECRET", data})}, }); export default connect( mapStateToProps, mapDispatchToProps )(WalletScreen); <file_sep>/src/Components/Header/index.js import React from 'react'; import {View, Text, Image, TouchableOpacity} from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; const Header = ({navigation,hide,setting,changePassword,save,onSave}) => { return ( <View style={{flexDirection: 'row', marginTop: hp('2%'),justifyContent:'space-between'}}> <View> <TouchableOpacity style={{marginLeft: wp('5%')}} onPress={() => navigation.goBack()}> <Image source={require('../../Assets/Images/arrow.png')} style={{width:hp('5%'),height:hp('5%')}} /> {/* <ArrowLeft height={15} width={15} /> */} </TouchableOpacity> </View> {!hide?<View style={{alignItems: 'center', justifyContent: 'center', flex: 1}}> <Text style={{ marginRight: wp('14%'), fontSize: wp('5.5%'), fontWeight: '600', color: 'white', fontFamily:'Poppins-SemiBold' }}> Registration </Text> </View>:null} {changePassword?<View style={{alignItems: 'center', justifyContent: 'center', flex: 1}}> <Text style={{ marginRight: wp('14%'), fontSize: wp('5.5%'), fontWeight: '600', color: 'white', fontFamily:'Poppins-SemiBold' }}> Change Password </Text> </View>:null} {setting? <> <View style={{alignItems: 'center', justifyContent: 'center',}}> <Text style={{ // marginRight: wp('14%'), fontSize: wp('5.5%'), fontWeight: '600', color: 'white', fontFamily:'Poppins-SemiBold' }}> Settings </Text> </View> <TouchableOpacity style={{alignItems: 'center', justifyContent: 'center',marginRight:wp('3%')}} onPress={onSave}> {save?<Text style={{ color: '#246BFD', fontSize: wp('4.5%'), fontFamily: 'Inter-Bold', textShadowColor: '#246BFD', textShadowOffset: {width: -1, height: 0}, textShadowRadius: 30, }}> {' '} Save </Text>:null} </TouchableOpacity> </> :null} </View> ); }; export default Header; <file_sep>/src/Actions/wording.actions.js export const setWordingError = (data) => ({type: 'SET_WORDING_ERROR', data}); export const setWordingSuccess = () => ({type: 'SET_WORDING_SUCCESS'}); export const setWordingLoaderTrue = () => ({type: 'SET_WORDING_LOADER_TRUE'}); export const setUsernameLoader=()=>({type: 'ADD_USERNAME_LOADER'}); export const setUsernameError = (data) => ({type: 'ADD_USERNAME_ERROR', data}); export const setUsernameSuccess= (data) => ({type: 'ADD_USERNAME_SUCCESS', data}); export const sendSecretSuccess= (data) => ({type: 'SEND_SECRET_SUCCESS', data}); export const sendSecretLoader= () => ({type: 'SEND_SECRET_LOADER'}); export const sendSecretError= (data) => ({type: 'SEND_SECRET_ERROR', data});<file_sep>/src/Containers/EnterPassword/index.js import React, {useState, useEffect} from 'react'; import { View, Text, TouchableOpacity, Image, TextInput, KeyboardAvoidingView, Platform, SafeAreaView, } from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import CustomInput from '../../Components/CustomInput'; import TransparentButton from '../../Components/TransparentButton'; import Button from '../../Components/CreatingAccount/Button'; import Styles from './Styles'; import BackArrow from '../../Components/CreatingAccount/BackArrow'; import { connect } from 'react-redux'; import EncryptedStorage from 'react-native-encrypted-storage'; const EnterPassword = (props) => { const [isshow, setIsShow] = useState(false); const [warning, Setwarning] = useState(false); const [Password, setPassword] = useState(''); const [perviousPass,setperviousPass]=useState(''); const [focus, setFocus] = useState(false); const [obj,setobj]=useState(''); const Inputhandler = e => { setPassword(e); if(Password.length > 8){ Setwarning(false); } console.log(Password.length) }; const updatefocus = () => { setFocus(false); setFocus(!focus); }; const Setdata = () => { if (Password.length < 8) { setFocus(false); Setwarning(true); } else { if(perviousPass!=''){ if(Password===perviousPass){ props.eraseEmailData(); props.eraseCodeData(); // props.navigation.navigate('Verification',{isPhone:obj?.phone,phoneTrue:obj?.phone,emailphonenumber:obj?.emailPhone,fromLogin:true}); props.navigation.navigate('TabNav'); }else{ setFocus(true); Setwarning(true); } }else{ } } }; useEffect(()=>{ EncryptedStorage.getItem('@Password').then(succ=>{ if(succ){ setperviousPass(JSON.parse(succ)); } }); EncryptedStorage.getItem('@emailPhone').then(succ=>{ if(succ){ console.log(JSON.parse(succ),'suucID') setobj(JSON.parse(succ)); } }) },[]) return ( <SafeAreaView style={{backgroundColor: '#181A20', flex: 1}}> <KeyboardAvoidingView style={{backgroundColor: '#181A20', flex: 1}} behavior={Platform.OS == 'ios' ? 'padding' : 'height'}> {/* <BackArrow /> */} <View style={{marginHorizontal: wp('8%')}}> <View style={{marginVertical: hp('3%')}}> <Text style={{ fontSize: wp('5.5%'), fontWeight: '600', fontFamily: 'Poppins-SemiBold', color: 'white', }}> Enter your password </Text> </View> <CustomInput header={'PASSWORD (MIN 8 CHARS)'} placeholder={''} eye eyeStyle={{ height: 20, width: 20, overflow: 'hidden', position: 'absolute', right: wp('1%'), top: hp('5%'), zIndex: 100, }} securetext onchange={Inputhandler} value={Password} warning={warning} noBorder style={{ color: warning ? '#FF0B80' : '#fff', fontFamily: 'Inter-Bold', }} /> {/* <View style={focus?Styles.focusborder:warning?Styles.activeborder:Styles.disableborder} /> */} {warning ? ( <Text style={[ Styles.active, { fontSize: 15, fontFamily: 'Inter-Regular', marginTop: hp('1.5%'), }, ]}> Wrong password </Text> ) : null} {/* <View style={{flexDirection: 'row', justifyContent: 'flex-end'}}> <TouchableOpacity style={{ borderColor: '#5E6272', borderWidth: 1.5, // fontFamily:'Inter-Regular', borderRadius: 20, padding: 5, marginTop: hp('2%'), paddingHorizontal: wp('3%'), }}> <Text style={{ textAlign: 'center', color: '#5E6272', letterSpacing: 0.5, fontSize: 16, fontFamily: 'Inter-Regular', }}> Forgot your password? </Text> </TouchableOpacity> */} {/* </View> */} {/* <TextInput placeholder={'dffd'}/> */} </View> {!warning ? ( <Button handleFunction={text => Setdata(text)} btnText={'Log in'} /> ) : ( // <TransparentButton // title="log in" // onPress={() => { // // setShowModal(true); // }} // style={{ // width: wp('85%'), // height: hp('7.3%'), // backgroundColor: '#262A34', // borderColor: '#262A34', // marginTop: 'auto', // }} // textStyle={{color: '#3A3D46'}} // /> <Button style={true} handleFunction={text => Setdata(text)} btnText={'Log in'} /> )} </KeyboardAvoidingView> </SafeAreaView> ); }; const mapStateToProps = (state) => ({ auth: state.auth }); const mapDispatchToProps = (dispatch) => ({ eraseEmailData: () => {dispatch({type: "ERASE_EMAIL_DATA"})}, eraseCodeData: () => {dispatch({type: "ERASE_CODE_DATA"})}, }); export default connect( mapStateToProps, mapDispatchToProps )(EnterPassword); <file_sep>/src/Components/TransparentButton/style.js import { StyleSheet,Platform } from 'react-native' import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen'; // import { Colors,Metrics, Helpers, Fonts, ApplicationStyles } from 'App/Theme' export default StyleSheet.create({ button: { backgroundColor: 'transparent', borderColor: '#5E6272', borderWidth: 1, overflow: 'visible', borderRadius: 10, alignItems: 'center', flexDirection: 'row', paddingLeft: 15, paddingRight: 15, justifyContent: 'space-around', paddingBottom: 10, paddingTop: 10 }, text: { color: '#fff', fontSize: wp('4.2%'), textAlign: 'center', fontFamily:'Inter-Bold', marginRight:Platform.OS=="ios"?wp('5%'):wp('5%') }, }) <file_sep>/src/Components/PopupModal/index.js import React, {useState} from 'react'; import { Alert, Modal, StyleSheet, Image, Text, Pressable, View, } from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import TransparentButton from '../../Components/TransparentButton'; const PopupModal = ({ visible, onPress, children, height, btntext, img, btncon, }) => { const [modalVisible, setModalVisible] = useState(visible); return ( <View style={styles.centeredView}> <Modal animationType="slide" transparent={true} visible={modalVisible}> <View style={[styles.centeredView]}> <View style={[styles.modalView, {height: hp(height)}]}> {img ? ( img ) : ( <View style={{ height: hp('23%'), width: wp('100%'), justifyContent: 'center', alignItems: 'center', }}> <Image source={require('../../Assets/Images/ModalImage.png')} style={{ height: hp('20%'), width: wp('45%'), justifyContent: 'center', alignItems: 'center', }} /> </View> )} <View style={{marginVertical: hp('1%')}}> <Text style={styles.modalText}>Congratulations!</Text> <View style={{width: wp('85%')}}> <Text style={styles.modalText2}>{children}</Text> </View> <View style={[{marginVertical: hp('5%')}, btncon]}> <TransparentButton title={btntext ? btntext : 'Next'} onPress={onPress} style={{ width: wp('85%'), height: hp('7.3%'), backgroundColor: '#246BFD', borderColor: '#246BFD', }} textStyle={{ fontWeight: 'bold', fontFamily: 'Poppins-SemiBold', }} /> {/* <TransparentButton title="Get start!" onPress={onPress} style={{width:wp('85%'),height:hp('7.3%'),backgroundColor:'#246BFD',borderColor: null}} textStyle={{fontWeight:'bold'}}/> */} </View> </View> </View> </View> </Modal> {/* <Pressable style={[stylesd.button, styles.buttonOpen]} onPress={() => setModalVisible(true)} > <Text style={stylesd.textStyle}>Show Modal</Text> </Pressable> */} </View> ); }; const styles = StyleSheet.create({ centeredView: { flex: 1, justifyContent: 'center', alignItems: 'center', // marginTop: 22, backgroundColor: 'rgba( 0, 0, 0, 0.9 )', }, modalText2: { color: '#5E6272', fontSize: wp('4%'), lineHeight: hp('4%'), textAlign: 'center', fontFamily: 'Inter-Medium', }, modalView: { // margin: 10, width: wp('90%'), backgroundColor: '#262A34', borderColor: '#3A3D46', borderRadius: 20, // padding: 35, alignItems: 'center', }, button: { borderRadius: 20, padding: 10, elevation: 2, }, buttonOpen: { backgroundColor: '#F194FF', }, buttonClose: { backgroundColor: '#2196F3', }, textStyle: { color: 'white', fontWeight: 'bold', textAlign: 'center', }, modalText: { marginBottom: hp('3.5%'), textAlign: 'center', fontSize: wp('6%'), fontWeight: '600', color: '#fff', fontFamily: 'Poppins-SemiBold', }, }); export default PopupModal; <file_sep>/src/Containers/Home/index.js import React, { useState, useEffect } from 'react'; import { View, Text, TouchableOpacity, Image, TextInput, KeyboardAvoidingView, Platform, SafeAreaView, BackHandler, FlatList, ScrollView, Dimensions, Animated, PanResponder, } from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import DataPoint from './DataPoints'; import Stories from './Stories'; import { useIsFocused } from '@react-navigation/native'; import styles from './Styles'; import Header from './Header'; import ReferEarn from './ReferEarn'; import Token from './Token'; import NewData from './NewData'; import resp from 'rn-responsive-font'; import {resolvePlugin} from '@babel/core'; const SCREEN_HEIGHT = Dimensions.get('window').height; const SCREEN_WIDTH = Dimensions.get('window').width; const Home = ({navigation}) => { const isFocused=useIsFocused() const [currentIndex, setcurrentIndex] = useState(0); const [cardData, setcardData] = useState([ { id: 1, backgroundColor: '#8CC676', totalBalance: 514.25, changeToday: 15.5, walletId: 'Bella_Adams.swapp.ID', }, { id: 2, backgroundColor: '#E87B48', totalBalance: 514.25, changeToday: 13.5, walletId: 'Bella_Adams.swapp.ID', }, { id: 3, backgroundColor: '#246BFD', totalBalance: 514.9, changeToday: 13.5, walletId: 'Bella_Adams.swapp.ID', }, ]); useEffect(() => { BackHandler.addEventListener('hardwareBackPress', backButtonHandler); return () => { BackHandler.removeEventListener('hardwareBackPress', backButtonHandler); }; }, [backButtonHandler]); function backButtonHandler() { if (isFocused) { BackHandler.exitApp(); return true; } } const renderFoods = () => { const position = new Animated.ValueXY(); let PanRes = PanResponder.create({ onStartShouldSetPanResponder: (evt, gestureState) => true, onPanResponderMove: (evt, gestureState) => { position.setValue({x: gestureState.dx, y: gestureState.dy}); }, onPanResponderRelease: (evt, gestureState) => {}, }); return cardData.map((item, i) => { if (i < currentIndex) { return null; } else { return ( <Animated.View key={i} // {...PanRes.panHandlers} style={[ {transform: position.getTranslateTransform()}, { height: hp('26%'), width: wp('88%'), padding: hp('2'), backgroundColor: item.backgroundColor, margin:5, // marginTop:hp('-5'), // zIndex:100, borderRadius: wp('3%'), }, ]}> <View style={{flexDirection: 'row', justifyContent: 'space-between'}}> <View > <Text style={{ color: 'white', fontSize: resp(13), opacity: 0.5, fontFamily: 'Inter-Regular', }}> Total balance </Text> <View style={{flexDirection: 'row'}}> <View style={{ height: wp('3.5'), width: wp('3.5'), overflow: 'hidden', marginTop: hp('0.8'), marginRight: 5, }}> <Image source={require('../../Assets/Swaap/Story/Union.png')} style={{ height: '100%', width: '100%', resizeMode: 'contain', }} /> </View> <Text style={{ color: 'white', fontSize: resp(24), // fontWeight: 'bold', fontFamily: 'Poppins-SemiBold', }}> {item.totalBalance} </Text> </View> </View> <View> <Text style={{ color: 'white', fontSize: resp(13), opacity: 0.5, textAlign:'right', fontFamily: 'Inter-Regular', }}> Change today </Text> <Text style={{ color: 'white', fontSize: resp(24), // fontWeight: 'bold', fontFamily: 'Poppins-SemiBold', }}> {item.totalBalance}% </Text> </View> </View> <View style={{position:'absolute',bottom:hp('1%'),marginLeft:wp('3%')}}> <Text style={{ fontSize: resp(13), color: 'white', opacity: 0.5, letterSpacing: 0.5, fontFamily: 'Inter-Regular', // lineHeight:30 }}> WalletID </Text> <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }}> <Text style={{ color: 'white', fontSize: resp(16), fontWeight: 'bold', fontFamily: 'Inter-Regular', }}> {item.walletId} </Text> <View style={{ height: wp('12'), width: wp('75%'), overflow: 'hidden', marginTop: hp('0.8'), // marginRight: wp('1%'), marginTop: hp('-2'), }}> <Image source={require('../../Assets/Swaap/Story/Fox_image.png')} style={{ height: '100%', width: '100%', resizeMode: 'contain', position:'absolute', right:wp('6%'), bottom:wp('1%') }} /> </View> </View> </View> </Animated.View> ); } }); }; return ( <SafeAreaView style={{flex:1}}> <Header /> <ScrollView> <View style={{flex: 1, backgroundColor: '#181A20', paddingBottom: 44}}> <View style={{flexDirection: 'row',margin:5}}> <ScrollView showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} horizontal={true}>{renderFoods()}</ScrollView> </View> <Stories /> <DataPoint /> <ReferEarn /> <Token /> <NewData /> </View> </ScrollView> </SafeAreaView> ); }; export default Home; <file_sep>/src/Components/ChangePasscodeKeyboard/index.js import React, {useState, useEffect} from 'react'; import {View, Text, TouchableOpacity, Image} from 'react-native'; import styles from './styles'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import FingerprintScanner from 'react-native-fingerprint-scanner'; const index = ({navigation,onSucess,textPin}) => { const [password, setPassword] = useState(['', '', '', '', '', '']); const [inital, setinital] = useState(['', '', '', '', '', '']); const [confirm,setConfirm]=useState(false) const [biometryType, setbiometryType] = useState(null); let Numbers = [ {id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}, {id: 7}, {id: 8}, {id: 9}, {id: 0}, ]; const OnPressNumber = num => { let tempCode = password; for (var i = 0; i < tempCode.length; i++) { if (tempCode[i] == '') { tempCode[i] = num; break; } else { continue; } } setPassword([...tempCode]); if(tempCode[5]!=''){ onSucess(password); if(textPin!="Repeat the new PIN code") setPassword([...inital]) if(textPin=="Repeat the new PIN code") setConfirm(true) } }; const OnpressCancel = () => { let tempCode = password; for (var i = tempCode.length - 1; i >= 0; i--) { if (tempCode[i] !== '') { tempCode[i] = ''; break; } else { continue; } } onSucess(tempCode); setPassword([...tempCode]); }; useEffect(() => { FingerprintScanner.isSensorAvailable() .then(bioType => { setbiometryType(bioType); // if(bioType=="Biometrics"){ // showAuthenticationDialog(); // } // if(bioType=="TouchID"){ // showAuthenticationDialog(); // } // if(bioType=="Face ID"){ // showAuthenticationDialog(); // } }) .catch(error => console.log('isSensorAvailable error => ', error)); }, [navigation]); const Getmessage = () => { // console.log() const bioType = biometryType; if (bioType === 'Face ID') { return 'Scan your Face on the device to continue'; } else { return 'Scan your Fingerprint on the device scanner to continue'; } }; const showAuthenticationDialog = () => { const bioType = biometryType; if (bioType !== null && bioType !== undefined) { FingerprintScanner.authenticate({ description: Getmessage(), }) .then(() => { onSucess(); }) .catch(error => { console.log('Authentication error is => ', error); }); } else { console.log('biometric authentication is not available'); } }; // useEffect(() => { // FingerprintScanner.isSensorAvailable() return ( <> <View style={{justifyContent: 'center', alignItems: 'center'}}> <Text style={{color: 'white',fontFamily:'Inter-Bold',fontSize:wp('4.2%')}}>{textPin}</Text> </View> <View style={styles.CodeCon}> {password.map((p, index) => { let style = p !== '' ? [styles.Code2,{backgroundColor:confirm?'#A5F59C':'#246BFD'},{shadowColor:confirm?'#A5F59C':'#246BFD'}]: styles.Code1; return <View style={style} key={index} />; })} </View> <View style={styles.NumberCon}> {/* <Text>{biometryType}</Text> */} {Numbers.map(({id, index}) => { return ( <View key={index}> <TouchableOpacity style={styles.Number} onPress={() => OnPressNumber(id)}> <Text style={styles.NumberText}>{id}</Text> </TouchableOpacity> </View> ); })} <View style={{position: 'absolute', bottom: hp('2%'), left: wp('15%')}}> <TouchableOpacity onPress={() => showAuthenticationDialog()}> <View style={{height:50,width:50,overflow:'hidden'}}> <Image source={require('../../Assets/Images/TouchId.png')} style={{height:'100%',width:'100%',resizeMode:'contain'}} /> </View> </TouchableOpacity> </View> <View style={{position: 'absolute', bottom: hp('3%'), right: wp('15%')}}> <TouchableOpacity onPress={OnpressCancel}> {/* <Image source={require('../../Assets/Images/BackText.png')} /> */} <View style={{height:35,width:35,overflow:'hidden'}}> <Image source={require('../../Assets/Images/BackText.png')} style={{height:'100%',width:'100%',resizeMode:'contain'}} /> </View> </TouchableOpacity> </View> {/* -------------- */} {/* --------------------- */} </View> </> ); }; export default index; <file_sep>/src/Containers/CreatingAccount/ThreeThingsScreen/index.js import React, {useEffect, useState} from 'react'; import { Alert, Image, KeyboardAvoidingView, Modal, Pressable, SafeAreaView, StatusBar, Text, View } from "react-native"; import styles from './Styles'; import Button from "../../../Components/CreatingAccount/Button"; import BackArrow from "../../../Components/CreatingAccount/BackArrow"; import TermsOfUse from "../TermsOfUse"; import { BlurView, VibrancyView } from "react-native-blur"; const PointBlock = (props) => { const { text } = props; return ( <View style={styles.pointContainer}> <Image style={styles.pointImg} source={require('../../../Assets/Images/Check.png')} /> <Text style={styles.pointText}>{text}</Text> </View> ) } const ThreeThingsScreen = (props) => { const [modalVisible, setModalVisible] = useState(false); useEffect(() => { console.log('Three things screen there') }, []) const navigation=(text)=>{ console.log(text); if(text==true){ setModalVisible(false) props.navigation.navigate('AcceptTerm') } } return ( <SafeAreaView style={styles.container}> <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={{flex:1}}> { modalVisible && <View style={styles.blurContainer}></View> } <Modal animationType="slide" transparent={true} visible={modalVisible} > <TermsOfUse navigation={props.navigation} handle={(text)=>{navigation(text)}} setModalVisible={setModalVisible}/> </Modal> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow isText={'Registration'}/> <View style={styles.titleContainer}> <Text style={styles.title}>Three things you should know</Text> </View> <View style={styles.pointsBlock}> <PointBlock text={'No one can see the data you import, only you hold the key!'}/> <PointBlock text={'Your data is not held by us, you decide where it lives'}/> <PointBlock text={'Your data can only be shared with your explicit consent'}/> </View> <View style={styles.signatureContainer}> <Image style={styles.signatureImg} source={require('../../../Assets/Images/signature.png')} /> </View> <Button handleFunction={() => setModalVisible(true)} btnText={'Read the terms of use'}/> </KeyboardAvoidingView> </SafeAreaView> ) } export default ThreeThingsScreen; <file_sep>/src/Containers/ImportAccount/TypeWordPhrase/index.js import React, {useEffect, useRef, useState} from 'react'; import { Image, KeyboardAvoidingView, SafeAreaView, StatusBar, Text, TextInput, TouchableOpacity, TouchableWithoutFeedback, View,Clipboard } from "react-native"; import styles from './Styles'; import Button from "../../../Components/CreatingAccount/Button"; import BackArrow from "../../../Components/CreatingAccount/BackArrow"; import uuid from 'react-native-uuid'; import {useRoute} from '@react-navigation/native'; import {connect} from "react-redux"; import bip39 from 'react-native-bip39' import EncryptedStorage from 'react-native-encrypted-storage'; const AttachedWord = (props) => { const { wordItem, handleDeleteWord } = props; const { word, id } = wordItem; return ( <View style={styles.attachedWordContainer}> <Text style={styles.attachedWordText}>{word}</Text> <TouchableOpacity onPress={() => handleDeleteWord(id)}> <Image style={styles.closeIcon} source={require('../../../Assets/Images/closeIcon.png')} /> </TouchableOpacity> </View> ) } const TypeWordPhrase = (props) => { const [ word, setWord ] = useState(''); const [ isError, setIsError ] = useState(false); const route = useRoute(); const [ words, setWords ] = useState([]); const [ buffer, setBuffer ] = useState(''); const refInput = useRef(); const getStringFromBuffer = async () => { const copiedContent = await Clipboard.getString(); setBuffer(copiedContent) } useEffect(() => { getStringFromBuffer(); }, []) const handleAddWord = () => { if(!word) return setWords([...words, {id: uuid.v4(), word: word}]); setWord('') } const setTokenToAsyncStorage = async () => { const value = await EncryptedStorage.getItem('token'); await EncryptedStorage.setItem( 'token', props.auth.isAuth.token ); } const handleChange = async (e) => { if(buffer === e && buffer != '') { setWords([...words, ...e.split(' ').map(word => ({id: uuid.v4(), word}))]); } else { setWord(e) } } useEffect(() => { if(props.auth.tokenError) { setIsError(true) } if(props.auth.isAuth) { setTokenToAsyncStorage(); console.log('success, must to navigate') //success. here navigation to the next screen props.navigation.navigate('CreateNewPassword', {isRegistration: false}) } }, [props.auth]) const handleDeleteWord = (id) => { setWords(words.filter(el => el.id !== id)); } const sendWords = () => { let phrase = ''; words.forEach((el, i) => { if(i == 11) { phrase = phrase + el.word } else { phrase = phrase + el.word + ' ' } }) //phrase = 'abuse kick symbol tornado lend neither decorate hero first describe gown bless'; try { let h = bip39.mnemonicToEntropy(phrase) props.getToken({ secret: h }) } catch(error) { setIsError(true) } } const touchWordBlock = () => { refInput.current.focus(); setIsError(false) } return ( <SafeAreaView style={styles.container}> <KeyboardAvoidingView keyboardVerticalOffset={StatusBar.currentHeight} behavior={Platform.OS === "ios" ? "padding" : "height"} style={{flex:1}}> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow isText={'Import account'} navigation={props.navigation}/> <View style={styles.titleContainer}> <Text style={styles.title}>Type your 12-Word Phase</Text> <Text style={styles.text}>Enter the words below to make sure you’ve stored your recovery phrase correctly</Text> </View> <TouchableWithoutFeedback onPress={touchWordBlock}> <View style={[styles.wordBoard, {borderColor: isError ? '#FF0B80' : '#5E6272'}]}> { words.map(wordItem => <AttachedWord handleDeleteWord={handleDeleteWord} wordItem={wordItem}/>) } <TextInput ref={refInput} value={word} onSubmitEditing={handleAddWord} onChangeText={(e) => { handleChange(e) }} style={styles.inputWord} ></TextInput> </View> </TouchableWithoutFeedback> { isError && <Text style={styles.errorMessage}>Invaid Secret Recovery Phase</Text> } <Button disabled={isError} handleFunction={sendWords} btnText={'Confirm'}/> </KeyboardAvoidingView> </SafeAreaView> ) } const mapStateToProps = (state) => ({ auth: state.auth }); const mapDispatchToProps = (dispatch) => ({ getToken: (data) => {dispatch({type: "GET_TOKEN", data})}, eraseEmailError: () => {dispatch({type: "ERASE_EMAIL_ERROR"})}, sendSecretHash: (data) => {dispatch({type: "SEND_SECRET", data})}, }); export default connect( mapStateToProps, mapDispatchToProps )(TypeWordPhrase); <file_sep>/src/Containers/OnBoarding/index.js import React, {useEffect} from 'react'; import { ImageBackground, View, Text, Image, BackHandler, TouchableOpacity, } from 'react-native'; import AppIntroSlider from '../../Components/app-intro-slider'; import styles from './Styles'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, heightPercentageToDP, } from 'react-native-responsive-screen'; import Button from '../../Components/Button'; import TransparentButton from '../../Components/TransparentButton'; import {useIsFocused} from '@react-navigation/native'; const slides = [ { key: 1, title: 'Your personal data', text1: 'Get it.', text2: 'Use it.', text3: 'Monetize it!', image: require('../../Assets/Images/group5.png'), backgroundColor: '#2e2d39', }, { key: 2, title: '', text1: 'Lets you to', text2: 'share digital', text3: 'business', image: require('../../Assets/Images/group6.png'), backgroundColor: '#2e2d39', }, { key: 3, title: '', text1: 'Control', text2: 'your personal', text3: 'data', image: require('../../Assets/Images/group7.png'), backgroundColor: '#2e2d39', }, { key: 4, text1: 'Make money', text2: 'on personal', text3: 'data', image: require('../../Assets/Images/group8.png'), backgroundColor: '#2e2d39', }, ]; const OnBoarding = ({navigation}) => { const isFocused = useIsFocused(); useEffect(() => { BackHandler.addEventListener('hardwareBackPress', backButtonHandler); return () => { BackHandler.removeEventListener('hardwareBackPress', backButtonHandler); }; }, [backButtonHandler]); function backButtonHandler() { if (isFocused) { BackHandler.exitApp(); return true; } } const _renderItem = ({item, index}) => { return ( <View style={{flex: 1}}> <View style={styles.mainImageView}> <Image source={item.image} style={{width: wp('69%'), height: hp('35%')}} /> </View> <View style={styles.personaldataView}> <Text style={styles.personaldata}>{item.title}</Text> </View> <View style={styles.getitView}> <Text style={styles.getitText}>{item.text1}</Text> <Text style={styles.getitText}>{item.text2}</Text> <ImageBackground source={require('../../Assets/Images/Ellipse.png')} style={{width: wp('38%')}}> <View style={{width: wp('60%')}}> <Text style={styles.getitText}>{item.text3}</Text> </View> </ImageBackground> </View> </View> ); }; const _onDone = () => { // navigation.navigate('Auth'); // navigation.navigate('AddDevice'); }; return ( <> <View style={{ width: wp('100%'), height: hp('68%'), backgroundColor: '#181A20', }}> <AppIntroSlider dotGradientColors={['#65646D', '#65646D']} activeDotGradientColors={['#246BFD', '#246BFD', '#246BFD', '#246BFD']} dotStyle={styles.dotStyle} activeDotStyle={styles.activeDotStyle} bottomButton={false} renderItem={_renderItem} data={slides} onDone={_onDone} /> </View> <View style={{ width: wp('100%'), height: hp('50%'), backgroundColor: '#181A20', }}> <View style={{ justifyContent: 'center', alignItems: 'center', marginTop: wp('2%'), }}> <Button title="Create your Swapp" style={styles.createSwapp} onPress={() => { navigation.navigate('InitialScreen') //navigation.navigate('TabNav') //props.navigation.navigate('TabNav'); } } /> <View style={{marginTop: hp('3%')}}> <TransparentButton title="Import account" style={styles.createSwapp} onPress={() => navigation.navigate('TypeWordPhrase', { InitalScreen: 'Import Account', }) } /> </View> </View> <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: hp('3%'), }}> <Text style={{ color: '#5E6272', fontSize: wp('3.8%'), fontFamily: 'Inter-Regular', }}> Already have an account ? </Text> <TouchableOpacity onPress={() => navigation.navigate('Home')}> <Text style={{ color: '#246BFD', fontSize: wp('3.8%'), fontFamily: 'Inter-Bold', textShadowColor: '#246BFD', textShadowOffset: {width: -1, height: 0}, textShadowRadius: 30, }}> {' '} Sign In </Text> </TouchableOpacity> </View> </View> </> ); }; export default OnBoarding; <file_sep>/src/Containers/CreatingAccount/EnterEmailPhoneScreen/index.js import React, {useEffect, useState} from 'react'; import { ActivityIndicator, KeyboardAvoidingView, SafeAreaView, StatusBar, Text, TextInput, View } from "react-native"; import styles from './Styles'; import BackArrow from "../../../Components/CreatingAccount/BackArrow"; import Title from "../../../Components/CreatingAccount/Title"; import Button from "../../../Components/CreatingAccount/Button"; import {connect} from "react-redux"; import bip39 from 'react-native-bip39' import {useIsFocused, useRoute} from '@react-navigation/native'; import CustomInput from '../../../Components/CustomInput'; import ValidationPopup from '../../../Components/ValidationPopup'; const EnterEmailPhoneScreen = (props) => { const [ value, setValue ] = useState(''); const [showText, setShowText] = useState(''); const [showValidation,setshowValidation]=useState(''); const isFocused = useIsFocused(); const handleSendEmail = () => { if(value!=''){ console.log('no null') if(props.route.params.isPhone) { console.log(value.length); props.sendEmailPhone({ phone: value.trim()}) }else{ props.sendEmailPhone({ email: value.trim() }) } }else{ if(props.route.params.isPhone){ setshowValidation(true); setShowText('Please enter your phone number'); }else{ setshowValidation(true); setShowText('Please enter your email id') ; } } } function handleTextChange(text){ setValue(text); } const updateshow = () => { props.eraseEmailError(); setshowValidation(false) } useEffect(() => { console.log('erase data') return () => { props.eraseEmailError() } }, []) useEffect(() => { if(!isFocused) return if(props.auth.email) { props.navigation.navigate('Verification',{isPhone:props.route.params.isPhone}) } if(props.auth.phone){ props.navigation.navigate('Verification',{isPhone:props.route.params.isPhone}) } if(props.auth.emailError){ setShowText(props.auth.emailError); setshowValidation(true) } if(props.auth.phone){ props.navigation.navigate('Verification') } },[props.auth, isFocused]) return ( <SafeAreaView style={styles.container}> <KeyboardAvoidingView keyboardVerticalOffset={StatusBar.currentHeight} behavior={Platform.OS === "ios" ? "padding" : "height"} style={{flex:1}}> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow /> <Title title={props.route?.params?.addNew?props.route.params.addNew:'Create your Swapp'} text={props.route.params.isPhone ? 'We will send verification code on your Phone number' : 'We will send verification code on your email ID.'}/> <View style={styles.inputBlock}> <CustomInput onchange={handleTextChange} value={value} keyBoard={props.route.params.isPhone} header={props.route.params.isPhone ? 'ENTER YOUR PHONE NUMBER' : 'ENTER YOUR EMAIL'} /> </View> <Button inActive={!value} disabled={props.auth.emailLoader || !value} loading={props.auth.emailLoader} handleFunction={handleSendEmail} btnText={'Send Verification Code'}/> </KeyboardAvoidingView> {showValidation == true && ( <ValidationPopup title={showText} Show={true} showback={updateshow} /> )} </SafeAreaView> ) } const mapStateToProps = (state) => ({ auth: state.auth }); const mapDispatchToProps = (dispatch) => ({ sendEmailPhone: (data) => {dispatch({type: "SEND_EMAIL", data})}, eraseEmailError: () => {dispatch({type: "ERASE_EMAIL_ERROR"})}, eraseEmailData: () => {dispatch({type: "ERASE_EMAIL_DATA"})}, }); export default connect( mapStateToProps, mapDispatchToProps )(EnterEmailPhoneScreen); <file_sep>/src/Containers/CreatingAccount/Verification/Styles.js import { StyleSheet, Dimensions } from 'react-native' let width=Dimensions.get('window').width; let height=Dimensions.get('window').height; import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen'; export default StyleSheet.create({ container: { flex:1, backgroundColor: '#181A20' }, cell: { width: '20%', height: wp('13.2%'), borderWidth: 2, borderColor: '#5E6272', textAlign: 'center', backgroundColor:'#262A34', borderRadius:8, display:'flex', justifyContent:'center' }, inputBlock: { marginTop:hp('6%'), width:wp('90%'), alignSelf:'center', height: hp('15%'), display: 'flex', justifyContent:'space-between' }, input: { width:wp('100%'), height:hp('6%'), borderBottomColor: '#246BFD', borderBottomWidth:3, color:'white', fontSize:18 }, email: { marginTop:hp('0.5%'), color:'white', fontSize:wp('3.8%'), width:'90%', fontFamily:'Inter-SemiBold', alignSelf:'center', paddingVertical:hp('1%'), }, codeFieldRoot: { marginTop:hp('1%'), width:wp('60%'), alignSelf: 'center' }, focusCell: { borderColor: '#246BFD', shadowColor: '#246BFD', shadowOffset: {width: 0, height: 0}, elevation: 18, shadowOpacity: 0.3, shadowRadius: 14, }, digit: { color:'white', fontSize: 20, textAlign: 'center', }, additionalPostscript: { flexDirection:'row', justifyContent:'center', alignItems:'center', marginTop:hp('3%') }, additionalPostscriptTitle: { color:'#5E6272', fontSize:wp('3.8%'), fontFamily:'Inter-Regular' }, additionalPostscriptBtnText: { color:'#246BFD',fontSize:wp('3.8%'),textShadowColor: '#246BFD', textShadowOffset: {width: -1, height: 0}, textShadowRadius: 30, fontFamily:'Inter-Bold' } }) <file_sep>/src/Containers/CreatingAccount/RecoveryPhaseScreen/Styles.js import { StyleSheet, Dimensions } from 'react-native' let width=Dimensions.get('window').width; let height=Dimensions.get('window').height; import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen'; export default StyleSheet.create({ container: { flex:1, backgroundColor: '#181A20' }, img: { alignSelf:'center', height: hp('16%'), width: hp('16%'), resizeMode: 'contain' }, wordsBlock: { justifyContent:'center', display:'flex', flexDirection: 'row', width:'100%', alignSelf:'center', flexWrap: 'wrap', marginTop:hp('1%'), }, wordContainer: { width:'35%', marginHorizontal:wp('1.4%'), marginVertical:hp('0.6%'), paddingHorizontal:wp('2.4%'), paddingVertical:wp('0.8%'), display:'flex', flexDirection:'row', borderColor: '#5E6272', borderWidth: 1, borderRadius: wp('1.4%'), justifyContent:'center', alignItems:'center' }, word: { paddingLeft:wp('1.4%'), fontSize:wp('3.8%'), color:'white', fontFamily:'Inter-Medium' }, number: { fontSize:wp('4%'), color:'#5E6272' }, dangerIcon: { width: wp('10%'), resizeMode: 'contain' }, warning: { width: wp('90%'), alignSelf:'center', backgroundColor:'#3C1C35', height: hp('10%'), borderColor:'#FF0B80', borderWidth:1, borderRadius:wp('3.8%'), shadowColor: '#FF0B80', shadowOffset: {width: 0, height: 0}, elevation: 6, shadowOpacity: 0.3, shadowRadius: 8, display:'flex', flexDirection:'row', marginTop:hp('2.6%'), }, warningText: { color:'#FF0B80', fontSize:wp('3.8%'), width:wp('60%'), fontFamily:'Inter-Medium' }, warningIconContainer: { width:'20%', display:'flex', alignItems:'center', justifyContent:'center' }, warningTextContainer: { width:'80%', display:'flex', alignItems: 'center', justifyContent:'center' }, title: { width: wp('90%'), alignSelf:'center', fontSize: wp('5.5%'), color:'white', textAlign:'center', fontFamily:'Poppins-SemiBold' }, text: { marginTop:hp('1%'), width: wp('90%'), alignSelf:'center', color:'#5E6272', textAlign:'center', fontSize: wp('4%'), lineHeight: hp('3%'), fontFamily:'Inter-Regular' }, btnContainer: { width:wp('100%'), marginTop: 'auto', marginBottom: hp('1%') }, insideBtnContainer: { width:wp('90%'), alignSelf:'center', display:'flex', flexDirection:'row', marginBottom: hp('1%'), justifyContent:'space-between' }, miniBtn: { borderColor: '#5E6272', borderWidth: 1, width:'48%', alignSelf:'center', height:hp('7.6%'), borderRadius: hp('2%'), display: 'flex', flexDirection:'row', justifyContent:'center', alignItems: 'center' }, textMiniBtn: { color:'white', fontSize: wp('4.2%'), fontFamily:'Inter-Bold' }, btnIcon: { width: '16%', marginLeft:'6%', resizeMode: 'contain' }, cell: { width: hp('6.4%'), height: hp('7.2%'), borderWidth: 2, borderColor: '#5E6272', textAlign: 'center', backgroundColor:'#262A34', borderRadius:8, display:'flex', justifyContent:'center' }, inputBlock: { marginTop:hp('6%'), width:wp('90%'), alignSelf:'center', height: hp('15%'), display: 'flex', justifyContent:'space-between' }, input: { width:wp('100%'), height:hp('6%'), borderBottomColor: '#246BFD', borderBottomWidth:3, color:'white', fontSize:18 }, email: { marginTop:hp('0.5%'), color:'white', fontSize:wp('3.8%'), width:'90%', alignSelf:'center', paddingVertical:hp('1%'), }, codeFieldRoot: { marginTop:hp('1%'), width:wp('70%'), alignSelf: 'center' }, focusCell: { borderColor: '#246BFD', shadowColor: '#246BFD', shadowOffset: {width: 0, height: 0}, shadowOpacity: 0.3, shadowRadius: 14, }, digit: { color:'white', fontSize: 20, textAlign: 'center', }, additionalPostscript: { flexDirection:'row', justifyContent:'center', alignItems:'center', marginTop:hp('3%') }, additionalPostscriptTitle: { color:'#5E6272', fontSize:wp('3.8%') }, additionalPostscriptBtnText: { color:'#246BFD',fontSize:wp('3.8%'),textShadowColor: '#246BFD', textShadowOffset: {width: -1, height: 0}, textShadowRadius: 30 } }) <file_sep>/src/Containers/PinScreen/Styles.js import {StyleSheet, Dimensions} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP as wp, } from 'react-native-responsive-screen'; let width = Dimensions.get('window').width; let height = Dimensions.get('window').height; const styles = StyleSheet.create({ MainCon: {backgroundColor: '#181A20', flex: 1}, ImageCon: { height:220,width:220,overflow:'hidden', // marginLeft:wp('24%'), marginTop:hp('10%'), marginBottom:hp('3%') }, CodeCon: { justifyContent: 'space-between', alignItems: 'center', flexDirection: 'row', marginHorizontal: wp('35%'), marginTop: hp('2%'), }, Code1: {height: 10, width: 10, borderRadius: 20, backgroundColor: '#262A34'}, Code2: { height: 10, width: 10, borderRadius: 20, backgroundColor: '#246BFD', shadowColor: '#246BFD', // overflow: "hidden", shadowOffset: { width: 1, height: 1, }, shadowOpacity: 0.6, shadowRadius: 5, elevation:5, }, NumberCon: { marginTop: hp('7%'), flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'center', }, Number: { width: wp('30%'), height: hp('10%'), justifyContent: 'center', alignItems: 'center', }, NumberText: {color: 'white', fontWeight: 'bold', fontSize: 32}, }); export default styles; <file_sep>/src/Containers/Home/NewData.js import React from 'react'; import {View, Text, Image,TouchableOpacity} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP as wp, } from 'react-native-responsive-screen'; import resp from 'rn-responsive-font'; import {Piggy, Scan, AddUser, Paperplus} from '../../Assets/Images'; const Data = [ { Img: Scan, Content: 'Verify your account', }, { Img: Paperplus, Content: 'Connect all data points', }, { Img: AddUser, Content: 'Invite more friends', }, ]; const NewData = () => { return ( <View style={{marginTop: hp('3')}}> <View style={{ backgroundColor: '#1F222A', marginHorizontal: wp('5'), borderRadius: 12, }}> <View style={{marginLeft: wp('5'), paddingVertical: hp('3')}}> <Text style={{ color: 'white', fontSize: resp(20), marginBottom: 3, fontSize: resp(24), // fontWeight: 'bold', fontFamily: 'Poppins-SemiBold', }}> {'Your data earnings'} </Text> <Text style={{color: '#5E6272', fontFamily: 'Inter-Medium', lineHeight: 23}}> Fast doesn’t mean expensive.{'\n'}send money internationally at best rates </Text> </View> <View style={{flexDirection: 'row', marginLeft: wp('3')}}> {Data.map((item, index) => { return ( <View key={index} style={{paddingHorizontal: wp('1.5'), paddingBottom: hp('3')}}> <TouchableOpacity style={{ height: hp('17'), backgroundColor: '#262A34', borderColor: '#3A3D46', borderWidth: 1, width: wp('25'), borderRadius: 7, alignItems: 'center', justifyContent: 'center', }}> <View style={{ height: hp('10'), width: wp('12'), // backgroundColor: 'red', overflow: 'hidden', marginTop: hp('-3'), }}> <Image source={item.Img} style={{ height: '100%', width: '100%', resizeMode: 'contain', }} /> </View> <Text style={{ textAlign: 'center', color: 'white', // fontWeight: '800', fontSize:wp('3.2%'), marginTop: hp('-1'), fontFamily: 'Inter-Medium', }}> {item.Content} </Text> </TouchableOpacity> </View> ); })} </View> </View> </View> ); }; export default NewData; <file_sep>/src/Containers/AcceptTerm/index.js import React, {useState} from 'react'; import { View, Text, Image, TouchableOpacity, StatusBar, ImageBackground, } from 'react-native'; import Header from '../../Components/Header'; import SelectionBtn from '../../Components/SelectionBtn'; import Icon from 'react-native-vector-icons/FontAwesome'; import {connect} from 'react-redux'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import TransparentButton from '../../Components/TransparentButton'; import ValidationPopup from '../../Components/ValidationPopup'; import PopupModal from '../../Components/PopupModal'; import Styles from './styles'; import Button from '../../Components/CreatingAccount/Button'; import BackArrow from '../../Components/CreatingAccount/BackArrow'; import EncryptedStorage from 'react-native-encrypted-storage'; const AcceptTerm = (props) => { const [showValidpop, setshowValidpop] = React.useState(false); const [Selectedvalue, setselectedvalue] = React.useState(''); // const [showModal,setshowModal]= React.useState(false); const [PopModal, setPopModal] = useState(false); const selection = ['Privacy', 'Monetize', 'Both']; const GetSelected = value => { setselectedvalue(value); }; const updateshow = async() => { if (Selectedvalue === '') { setshowValidpop(!showValidpop); } else { let obj; if(Selectedvalue=="Privacy") obj={Privacy:true} if(Selectedvalue=="Monetize") obj={Monetize:true} if(Selectedvalue=="Both") obj={Both:true} props.sendwording({data:obj,token:props.wording.secretSuccess.token}); setPopModal(true) await EncryptedStorage.setItem('@processCompleted',JSON.stringify(true)); } }; return ( <View style={{flex: 1, backgroundColor: '#181A20'}}> <BackArrow isText={'Registration'} /> <View style={{ height: hp('22%'), width: wp('22%'), overflow: 'hidden', marginLeft: wp('5%'), }}> <Image source={require('../../Assets/Images/groupd4.png')} style={{resizeMode: 'contain', height: '100%', width: '100%'}} /> </View> <View style={Styles.FontHeadCon}> <Text style={Styles.headfont}>Choose the type of use of </Text> <Text style={Styles.headfont}>your personal data</Text> </View> <SelectionBtn selection={selection} GetSelected={GetSelected} /> {!showValidpop ? ( // <TransparentButton // onPress={updateshow} // title="Got it" // style={{ // width: wp('85%'), // height: hp('7.3%'), // backgroundColor: '#246BFD', // borderColor: '#246BFD', // // marginLeft: , // marginLeft: wp('7%'), // marginTop: hp('5%'), // }} // textStyle={{fontWeight: 'bold', fontSize: 14}} // /> <Button disabled={props.wording.loader} loading={props.wording.loader} handleFunction={updateshow} btnText={'Got it'} /> ) : null} {/* {PopModal && ( <PopupModal visible={true} children={ 'You have registered your Swap account. Have a good use of the app.' } height={'55%'} onPress={() => navigation.navigate('OnBoarding')} /> )} */} {PopModal && ( <PopupModal btncon={{marginVertical: hp('3%')}} visible={true} btntext={'Get started!'} children={ 'You have successfully protected your Swapp! Please keep you back-up phrase safe and sound.' } height={'57%'} onPress={() => { setPopModal(false) props.navigation.navigate('TabNav')}} img={ <View style={{ height: hp('23%'), width: wp('100%'), justifyContent: 'center', alignItems: 'center', }}> <ImageBackground resizeMode="contain" source={require('../../Assets/Images/checkcircle.png')} style={{ height: hp('20%'), width: wp('35%'), justifyContent: 'center', alignItems: 'center', }}> <Icon name="check" // backgroundColor="white" color="white" size={50} // onPress={this.loginWithFacebook} /> </ImageBackground> </View> } /> )} {showValidpop == true && ( <ValidationPopup title={"You can choose 1 option"} Show={true} showback={updateshow} /> )} </View> ); }; const mapStateToProps = (state) => ({ wording: state.wording, auth: state.auth }); const mapDispatchToProps = (dispatch) => ({ sendwording: (data) => {dispatch({type: "SET_WORDING", data})}, earseEmailData: () => {dispatch({type: "ERASE_EMAIL_DATA"})}, }); export default connect(mapStateToProps,mapDispatchToProps)(AcceptTerm); <file_sep>/src/App.js import React from 'react' // import { Provider } from 'react-redux' // import { PersistGate } from 'redux-persist/lib/integration/react' // import { ReduxNetworkProvider } from 'react-native-offline' import AppStack from './Navigator' import {Provider} from "react-redux"; import {store} from "./Store"; // import createStore from './Store/CreateStore'; // const { store, persistor } = createStore() const App = () => ( <> {/* // <Provider store={store} > // <ReduxNetworkProvider store={store}> // <PersistGate loading={null} persistor={persistor}> */} <Provider store={store} > <AppStack /> </Provider> {/* </PersistGate> </ReduxNetworkProvider> </Provider> */} </> ) export default App <file_sep>/src/Containers/AddUsername/index.js import React, {useEffect, useState} from 'react'; import { KeyboardAvoidingView, SafeAreaView, StatusBar, Text, TextInput, View, BackHandler } from 'react-native'; import styles from './Styles'; import BackArrow from '../../Components/CreatingAccount/BackArrow'; import Title from '../../Components/CreatingAccount/Title'; import Button from '../../Components/CreatingAccount/Button'; import {connect} from 'react-redux'; import bip39 from 'react-native-bip39'; import CustomInput from '../../Components/CustomInput'; import EncryptedStorage from 'react-native-encrypted-storage'; import ValidationPopup from '../../Components/ValidationPopup'; import {useIsFocused} from '@react-navigation/native'; const AddUsername = (props) => { const isFocused = useIsFocused(); const [cont, setCont] = useState(''); const [email, setEmail] = useState(''); const [id,setId]=useState(''); const [showText,setShowText]=useState(''); const [showValidation, setShowValidation] = useState(false); const [callAPI,setcallAPI]=useState(false); // const handleFunction=()=> { // if(cont!=''){ // console.log('id',id); // }else{ // setShowText('Please enter a username'); // setShowValidation(true); // } // } useEffect(() => { BackHandler.addEventListener('hardwareBackPress', backButtonHandler); return () => { BackHandler.removeEventListener('hardwareBackPress', backButtonHandler); }; }, [backButtonHandler]); function backButtonHandler() { if(isFocused){ props.eraseUserNameError(); props.eraseCodeData(); props.navigation.goBack() return true; } } const backButton=()=>{ props.eraseUserNameError(); props.eraseCodeData(); } const sendUsername=()=>{ if(cont!=''){ // setcallAPI(true) props.addusername({ id:id, user_name:cont }); }else{ setShowText('Please enter a username'); setShowValidation(true); } } useEffect(()=>{ EncryptedStorage.getItem('@user_id').then(id=>{ if(id){ setId(JSON.parse(id)); } }) },[]); useEffect(() => { // console.log('props username',props.auth); if(props.wording.username) { // setcallAPI(false) EncryptedStorage.setItem('@user_id',JSON.stringify(props.wording.username.id)); props.navigation.navigate('CreateNewPassword', {isRegistration: true}) } if(props.wording.usernameError) { setShowText(props.wording.usernameError); setShowValidation(true); } }, [props.wording]) useEffect(()=>{ props.eraseUserNameError(); },[]) const updateshow = () => { props.eraseUserNameError(); setShowValidation(false) } const handleTextChange=(text) =>{ setCont(text); } // const generateMnemonic = async () => { // try { // console.log('-----------'); // let mnemonic = await bip39.generateMnemonic(256); // default to 128 // console.log(mnemonic); // let h = bip39.mnemonicToEntropy(mnemonic); // console.log(h); // // props.getToken({ secret: h }); // const mnemonic2 = bip39.entropyToMnemonic(h); // console.log(mnemonic2); // } catch (e) { // console.log(e); // return false; // } // }; return ( <SafeAreaView style={styles.container}> <KeyboardAvoidingView keyboardVerticalOffset={StatusBar.currentHeight} behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={{flex: 1}}> <StatusBar backgroundColor="#181A20" barStyle="light-content" /> <BackArrow func={() => backButton()} /> <Title title={'Create your Username'} text={'Your username will be used to generate the Swap ID and screen name'} /> <View style={styles.inputBlock}> <CustomInput onchange={handleTextChange} value={cont} header={'USERNAME'} /> </View> </KeyboardAvoidingView> <Button disabled={props.wording.usernameLoader} loading={props.wording.usernameLoader} handleFunction={sendUsername} btnText={'Create'} /> {showValidation == true && ( <ValidationPopup title={showText} Show={true} showback={updateshow} /> )} </SafeAreaView> ); }; const mapStateToProps = (state) => ({ auth: state.auth, wording:state.wording, }); const mapDispatchToProps = (dispatch) => ({ getToken: (data) => {dispatch({type: "GET_TOKEN", data})}, addusername: (data) => {dispatch({type: "ADD_USERNAME", data})}, eraseUserNameError: () => {dispatch({type: "ERASE_USERNAME_ERROR"})}, eraseCodeData: () => {dispatch({type: "ERASE_CODE_DATA"})}, // ERASE_CODE_DATA }); export default connect(mapStateToProps,mapDispatchToProps)(AddUsername); <file_sep>/src/Containers/ChangePassword/ChangePassword/index.js import {continueStatement} from '@babel/types'; import React, {useState} from 'react'; import {View, Text, TouchableOpacity, Image, SafeAreaView,ScrollView} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP as wp, } from 'react-native-responsive-screen'; import Button from '../../../Components/CreatingAccount/Button'; import CustomInput from '../../../Components/CustomInput'; import Header from '../../../Components/Header'; // import Header from '../../../components/Swapp-com/Header'; import TransparentButton from '../../../Components/TransparentButton'; import Condition from './Condition'; const ChangePassword = ({navigation}) => { const [oldpassword, setoldpassword] = useState(''); const [newpassword, setnewpassword] = useState(''); const [confirmpassword, setconfirmpassword] = useState(''); const [checkcondition, setcheckcondition] = useState(false); const [uppercase, setuppercase] = useState(false); const [lowercase, setlowercase] = useState(false); const [onesymbol, setonesymbol] = useState(false); const [onenum, setonenum] = useState(false); const [confirmvalid, setconfirmvalid] = useState(false); const [isValid, setisValid] = useState(null); const [disable, setdisable] = useState(false); const [error,setError]=useState(''); React.useEffect(() => { // console.log(confirmpassword.length) // let pattern = new RegExp('^(?=.*[a-z])'); var pattern1 = new RegExp('^(?=.*[a-z])'); if (pattern1.test(newpassword)) { setlowercase(true); // console.log('d' + pattern1); } else { setlowercase(false); } var pattern2 = new RegExp('^(?=.*[A-Z])'); if (pattern2.test(newpassword)) { setuppercase(true); // console.log('d' + pattern1); } else { setuppercase(false); } var pattern4 = new RegExp('^(?=.*\\d)'); if (pattern4.test(newpassword)) { setonenum(true); // console.log('d' + pattern1); } else { setonenum(false); } }, [newpassword]); const Btnhandler = () => { if (newpassword.length >= 8&&confirmpassword.length >= 8) { if(newpassword==confirmpassword){ setdisable(true); navigation.navigate('ChangePassCode') }else{ setError('Password should match') setdisable(false); } } else { console.log('FAIL'); setError('Must be a least 8 characters') setdisable(false); } }; return ( <SafeAreaView style={{flex: 1, backgroundColor: '#181A20'}}> <Header changePassword hide navigation={navigation} /> <ScrollView > <View style={{marginHorizontal: wp('6'),marginTop:hp('6%')}}> <View> <CustomInput header={'ENTER YOUR OLD PASSWORD'} placeholder={''} eye eyeStyle={{ height: 20, width: 20, overflow: 'hidden', position: 'absolute', right: wp('1%'), top: hp('4%'), zIndex: 100, }} securetext onchange={e => setoldpassword(e)} value={oldpassword} // warning={warning} noBorder // style={{ // color: warning ? '#FF0B80' : '#fff', // fontFamily: 'Inter-Bold', // }} /> </View> <View style={{marginTop: hp('2')}}> <CustomInput header={'NEW PASSWORD (MIN 8 CHARS)'} placeholder={''} eye eyeStyle={{ height: 20, width: 20, overflow: 'hidden', position: 'absolute', right: wp('1%'), top: hp('4%'), zIndex: 100, }} securetext onchange={text => { setnewpassword(text); }} value={newpassword} // warning={warning} noBorder // style={{ // color: warning ? '#FF0B80' : '#fff', // fontFamily: 'Inter-Bold', // }} /> </View> <Condition pattern={uppercase} Title={'one uppercase character'} /> <Condition pattern={lowercase} Title={'one lowercase character'} /> <Condition pattern={onenum} Title={'one number'} /> <View style={{marginTop: hp('2'),marginBottom:hp('3')}}> <CustomInput header={'CONFIRM PASSWORD'} placeholder={''} eye eyeStyle={{ height: 20, width: 20, overflow: 'hidden', position: 'absolute', right: wp('1%'), top: hp('4%'), zIndex: 100, }} securetext onchange={e => setconfirmpassword(e)} value={confirmpassword} // warning={warning} noBorder // style={{ // color: warning ? '#FF0B80' : '#fff', // fontFamily: 'Inter-Bold', // }} /> {!disable ? ( <Text style={{marginTop: hp('1'), color: '#5E6272'}}> {error} </Text> ) : null} </View> {/* <View style={{justifyContent: 'center', alignItems: 'center'}}> {!disable ? ( <TransparentButton Btnsize={{width: '95%'}} title={'Next changes'} style={{ borderColor: 'trasparent', borderWidth: 0, // width:44, height: hp('7'), marginTop: hp('25'), backgroundColor: 'gray', // padding:44, elevation: 4, }} // disabled={disable} onPress={Btnhandler} // selected={false} /> ) : ( <TransparentButton Btnsize={{width: '95%'}} title={'Next changes'} style={{ borderColor: 'trasparent', borderWidth: 0, // width:44, height: hp('7'), marginTop: hp('25'), backgroundColor: '#246BFD', // padding:44, elevation: 4, }} // disabled={disable} onPress={Btnhandler} // selected={false} /> )} </View> */} </View> </ScrollView > <Button inActive={!confirmpassword} handleFunction={Btnhandler} btnText={'Next changes'}/> </SafeAreaView> ); }; export default ChangePassword; <file_sep>/ios/Empty.swift // // Empty.swift // Swapp // // Created by <NAME> on 22/09/21. // Copyright © 2021 Hubio. All rights reserved. // import Foundation <file_sep>/src/Components/CreatingAccount/Title/index.js import React from 'react'; import {Text, TouchableOpacity, View} from "react-native"; import styles from './styles'; const Title = (props) => { const { title, text } = props; return ( <View style={styles.container}> <Text style={styles.title}>{title}</Text> <View> <Text style={styles.text}>{text}</Text> </View> </View> ) } export default Title; <file_sep>/src/Containers/Settings/phonenumber.js import React from 'react'; import { View, Text, TouchableOpacity, Image, TextInput, KeyboardAvoidingView, Platform, SafeAreaView, } from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import style from './Styles'; import Button from '../../Components/CreatingAccount/Button'; import {useNavigation} from '@react-navigation/native'; import RBSheet from "react-native-raw-bottom-sheet"; import AntDesign from 'react-native-vector-icons/AntDesign'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons'; const Phone=()=>{ const navigation = useNavigation(); const refRBSheet = React.useRef(); const openBottomSheet = () => { if (refRBSheet && refRBSheet.current) { refRBSheet.current.open(); } }; const closeSheet=()=>{ if (refRBSheet && refRBSheet.current) { refRBSheet.current.close(); } }; return( <SafeAreaView style={{flex:1}}> <View style={style.viewprimary}> <Text style={style.primary}>Primary Phone Number</Text> </View> <View style={style.line}></View> <View style={style.EmailContainer}> <Text style={style.emailText}>+1 (941) 888 - 88 - 88</Text> </View> <View style={[style.viewprimary,{marginTop:hp('3%')}]}> <Text style={style.primary}>Other Phone Numbers</Text> </View> <View style={style.line}></View> <View style={[style.EmailContainer,{flexDirection:'row'}]}> <View style={{width:'80%',alignSelf:'center'}}> <Text style={style.emailText}>+1 (941) 888 - 88 - 88</Text> </View> <TouchableOpacity onPress={openBottomSheet} style={{width:'20%',justifyContent:'center',alignSelf:'center',alignItems:'center',flexDirection:'row'}}> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,}}></View> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,marginLeft:5}}></View> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,marginLeft:5}}></View> </TouchableOpacity> </View> <View style={[style.EmailContainer,{flexDirection:'row'}]}> <View style={{width:'80%',alignSelf:'center'}}> <Text style={style.emailText}>+1 (941) 888 - 88 - 88</Text> </View> <TouchableOpacity onPress={openBottomSheet} style={{width:'20%',justifyContent:'center',alignSelf:'center',alignItems:'center',flexDirection:'row'}}> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,}}></View> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,marginLeft:5}}></View> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,marginLeft:5}}></View> </TouchableOpacity> </View> <View style={[style.EmailContainer,{flexDirection:'row'}]}> <View style={{width:'80%',alignSelf:'center'}}> <Text style={style.emailText}>+1 (941) 888 - 88 - 88</Text> </View> <TouchableOpacity onPress={openBottomSheet} style={{width:'20%',justifyContent:'center',alignSelf:'center',alignItems:'center',flexDirection:'row'}}> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,}}></View> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,marginLeft:5}}></View> <View style={{width:5,height:5,backgroundColor:'#246BFD',borderRadius:20,marginLeft:5}}></View> </TouchableOpacity> </View> <RBSheet ref={refRBSheet} height={350} closeOnDragDown={true} closeOnPressMask={true} openDuration={250} customStyles={{ container: { borderTopRightRadius: 30, borderTopLeftRadius: 30, backgroundColor:'#262A34' }, wrapper: { backgroundColor: 'rgba(0,0,0,0.8)', }, draggableIcon: { backgroundColor: '#ccc', }, }} > <View style={{flex:1,}}> <View style={{flexDirection:'row'}}> <View style={{width:wp('80%'),marginLeft:wp('7%'),justifyContent:'center'}}> <Text style={{color:'#fff',fontFamily:'Inter-Medium'}}>+1 (941) 888 - 88 - 88</Text> </View> <TouchableOpacity onPress={closeSheet} style={{width:wp('10%'),alignContent:'flex-end',marginRight:'2%'}}> <AntDesign name="closecircle" size={30} color={"white"}/> </TouchableOpacity> </View> <View style={[style.line,{width:'100%'}]}></View> <View style={{marginTop:hp('3%'),marginLeft:wp('6%'),flexDirection:'row'}}> <View style={{width:wp('10%')}}> <AntDesign name="staro" color={'#fff'} size={30} /> </View> <View style={{justifyContent:'center',marginLeft:wp('3%')}}> <Text style={{fontFamily:'Inter-Medium',color:'#fff',fontSize:wp('4%'),fontWeight:'500'}}>Make it the Primary email</Text> </View> </View> <View style={[style.line,{width:'100%'}]}></View> <View style={{marginTop:hp('3%'),marginLeft:wp('6%'),flexDirection:'row'}}> <View style={{width:wp('10%')}}> <FontAwesome name="bell-slash-o" color={'#fff'} size={25} /> </View> <View style={{justifyContent:'center',marginLeft:wp('3%')}}> <Text style={{fontFamily:'Inter-Medium',color:'#fff',fontSize:wp('4%'),fontWeight:'500'}}>Unsubscribe</Text> </View> </View> <View style={[style.line,{width:'100%'}]}></View> <View style={{marginTop:hp('3%'),marginLeft:wp('6%'),flexDirection:'row'}}> <View style={{width:wp('10%')}}> <SimpleLineIcons name="pencil" color={'#fff'} size={25} /> </View> <View style={{justifyContent:'center',marginLeft:wp('3%')}}> <Text style={{fontFamily:'Inter-Medium',color:'#fff',fontSize:wp('4%'),fontWeight:'500'}}>Edit</Text> </View> </View> <View style={[style.line,{width:'100%'}]}></View> <View style={{marginTop:hp('3%'),marginLeft:wp('6%'),flexDirection:'row'}}> <View style={{width:wp('10%')}}> <AntDesign name="delete" color={'#fff'} size={25} /> </View> <View style={{justifyContent:'center',marginLeft:wp('3%')}}> <Text style={{fontFamily:'Inter-Medium',color:'#fff',fontSize:wp('4%'),fontWeight:'500'}}>Disable Email</Text> </View> </View> </View> </RBSheet> <Button roundBtn isTransparent handleFunction={() => navigation.navigate('EnterEmailPhoneScreen', {isPhone: true,addNew:'Add new phone number'})} btnText={'Add new phone number'} /> </SafeAreaView> ) } export default Phone;<file_sep>/src/Containers/CreateNewPassCode/index.js import React, { useState } from 'react'; import {View, Text, TouchableOpacity, Image, ImageBackground} from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import BackArrow from '../../Components/CreatingAccount/BackArrow'; import Pinkeyboard from '../../Components/Pinkeyboard'; import Button from '../../Components/CreatingAccount/Button'; import {useRoute} from '@react-navigation/native'; import ValidationPopup from '../../Components/ValidationPopup'; import EncryptedStorage from 'react-native-encrypted-storage'; import PopupModal from "../../Components/PopupModal"; import Icon from "react-native-vector-icons/FontAwesome"; const CreateNewPasscode = ({navigation}) => { const [ isModal, setIsModal ] = useState(false); const [NewPasscode,setNewPasscode]=useState(['', '', '', '', '', '']); const [showValidation, setShowValidation] = useState(false); const route = useRoute(); function onSucess(password) { let tempCode = password; console.log('temp code',tempCode); setNewPasscode([...tempCode]); } const HandleNext=()=>{ if(NewPasscode[5]!=''){ EncryptedStorage.setItem('@NewPasscode',JSON.stringify(NewPasscode)).then(suc=>{ navigation.navigate('ConfirmPassCode', { InitalScreen: route?.params?.InitalScreen, isRegistration: route.params.isRegistration }); }); }else{ setShowValidation(true) } } const updateshow = () => { setShowValidation(false) } return ( <View style={{backgroundColor: '#181A20', flex: 1}}> <BackArrow /> {isModal && ( <PopupModal btncon={{marginVertical: hp('3%')}} visible={true} btntext={'Get start!'} children={ 'You have successfully exported your Swapp account. Have a good use of the app.' } height={'57%'} onPress={() => { setIsModal(false) navigation.navigate('Home') // navigation.navigate('TabNav') } } img={ <View style={{ height: hp('23%'), width: wp('100%'), justifyContent: 'center', alignItems: 'center', }}> <ImageBackground resizeMode="contain" source={require('../../Assets/Images/ModalImage.png')} style={{ height: hp('20%'), width: wp('55%'), justifyContent: 'center', alignItems: 'center', }}> </ImageBackground> </View> } /> )} <View style={{marginHorizontal: wp('5%'), marginBottom: hp('5%'),marginTop: hp('2.4%')}}> <Text style={{ color: 'white', fontSize: wp('6.8%'), fontWeight: '600', // marginTop: hp('4%'), fontFamily: 'Poppins-SemiBold', textAlign: 'center', }}> Create new passcode </Text> </View> <Pinkeyboard navigation={navigation} confirm={false} onSucess={onSucess} /> <View> <Button handleFunction={HandleNext} btnText={'Next'} // style={{marginTop:20}} /> </View> <TouchableOpacity onPress={() => { route.params.isRegistration ? navigation.navigate('RecoveryPhaseScreen') : setIsModal(true) }}> <Text style={{color: '#5E6272', textAlign: 'center'}}>Skip</Text> </TouchableOpacity> {showValidation == true && ( <ValidationPopup title={"Please enter a 5 digit passcode"} Show={true} showback={updateshow} /> )} </View> ); }; export default CreateNewPasscode; <file_sep>/src/Containers/ImportAccount/TypeWordPhrase/Styles.js import { StyleSheet, Dimensions } from 'react-native' let width=Dimensions.get('window').width; let height=Dimensions.get('window').height; import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen'; export default StyleSheet.create({ container: { flex:1, backgroundColor: '#181A20' }, closeIcon: { width:wp('6%'), height:wp('6%'), resizeMode: 'contain' }, errorMessage: { color:'#FF0B80', width:wp('90%'), alignSelf:'center', marginTop:hp('1%'), fontSize:wp('4.4%'), }, wordBoard: { marginTop:hp('2%'), width: wp('90%'), alignSelf:'center', height: hp('24%'), backgroundColor: '#262A34', borderWidth: 1, borderRadius: wp('2.6%'), display:'flex', flexDirection: 'row', flexWrap: 'wrap', paddingVertical:hp('0.6%'), paddingHorizontal:wp('1.4%'), }, wordBtnContainer: { marginVertical:hp('0.6%'), width:'30%', height:hp('4.8%'), /*marginHorizontal:wp('1.2%'), marginVertical:hp('0.4%'),*/ paddingHorizontal:wp('2.4%'), paddingVertical:wp('0.6%'), display:'flex', flexDirection:'row', alignItems: 'center', justifyContent:'center', borderWidth: 1, borderRadius: wp('1.4%'), }, wordBtnText: { fontSize:wp('3.6%'), }, attachedWordContainer: { height:'20%', paddingHorizontal:'1%', marginHorizontal:'1%', marginVertical:'1%', display:'flex', flexDirection:'row', borderRadius: wp('1.2%'), backgroundColor: '#30333d', alignItems:'center' }, titleContainer: { marginTop:hp('2%'), width: wp('90%'), alignSelf:'center', height: hp('12%'), }, title: { color: '#FFFFFF', fontWeight:'600', fontSize:hp('3.5%'), }, text: { paddingTop:hp('1.2%'), color: '#5E6272', fontSize:hp('2.0%'), }, attachedWordText: { color:'#FFFFFF', fontSize:wp('3.8%'), paddingHorizontal:wp('1%'), }, inputWord: { width:'auto', marginLeft:0, marginRight:0, height:'20%', color:'#FFFFFF', fontSize:wp('3.8%'), // marginVertical:'1%', }, wordBtnBlock: { height:hp('24%'), marginTop:hp('2%'), width:wp('90%'), alignSelf:'center', display:'flex', flexDirection:'row', flexWrap: 'wrap', justifyContent:'space-between' }, cell: { width: hp('6.4%'), height: hp('7.2%'), borderWidth: 2, borderColor: '#5E6272', textAlign: 'center', backgroundColor:'#262A34', borderRadius:8, display:'flex', justifyContent:'center' }, inputBlock: { marginTop:hp('6%'), width:wp('90%'), alignSelf:'center', height: hp('15%'), display: 'flex', justifyContent:'space-between' }, input: { width:wp('100%'), height:hp('6%'), borderBottomColor: '#246BFD', borderBottomWidth:3, color:'white', fontSize:18 }, email: { marginTop:hp('0.5%'), color:'white', fontSize:wp('3.8%'), width:'90%', alignSelf:'center', paddingVertical:hp('1%'), }, codeFieldRoot: { marginTop:hp('1%'), width:wp('70%'), alignSelf: 'center' }, focusCell: { borderColor: '#246BFD', shadowColor: '#246BFD', shadowOffset: {width: 0, height: 0}, shadowOpacity: 0.3, shadowRadius: 14, }, digit: { color:'white', fontSize: 20, textAlign: 'center', }, additionalPostscript: { flexDirection:'row', justifyContent:'center', alignItems:'center', marginTop:hp('3%') }, additionalPostscriptTitle: { color:'#5E6272', fontSize:wp('3.8%') }, additionalPostscriptBtnText: { color:'#246BFD',fontSize:wp('3.8%'),textShadowColor: '#246BFD', textShadowOffset: {width: -1, height: 0}, textShadowRadius: 30 } }) <file_sep>/src/Store/CreateStore.js import {createNetworkMiddleware} from 'react-native-offline'; import {applyMiddleware, compose, createStore} from 'redux'; import {createLogger} from 'redux-logger'; import {createTransform, persistReducer, persistStore} from 'redux-persist'; import createSensitiveStorage from 'redux-persist-sensitive-storage'; import createSagaMiddleware from 'redux-saga'; const sensitiveStorage = createSensitiveStorage({ keychainService: 'myKeychain', sharedPreferencesName: 'mySharedPrefs', }); const persistConfig = { key: 'root', version: 0, storage: sensitiveStorage, debug: true, //migrate: createMigrate(migrations, { debug: true }), /** * Blacklist state that we do not need/want to persist */ }; export default (rootReducer, rootSaga) => { const middleware = []; const enhancers = []; // Connect the sagas to the redux store const sagaMiddleware = createSagaMiddleware(); const networkMiddleware = createNetworkMiddleware({ queueReleaseThrottle: 200, }); middleware.push(networkMiddleware); middleware.push(sagaMiddleware); enhancers.push(applyMiddleware(...middleware, createLogger())); // Redux persist const persistedReducer = persistReducer(persistConfig, rootReducer); const store = createStore(persistedReducer, compose(...enhancers)); const persistor = persistStore(store); // Kick off the root saga sagaMiddleware.run(rootSaga); return {store, persistor}; }; <file_sep>/src/Containers/AcceptTerm/styles.js import {StyleSheet} from 'react-native'; import { heightPercentageToDP as hp, widthPercentageToDP as wp, } from 'react-native-responsive-screen'; const Styles = StyleSheet.create({ Container: {flex: 1, backgroundColor: '#2C303A'}, Imgcon: { height: hp('22%'), width: wp('22%'), overflow: 'hidden', marginLeft: wp('5%'), }, headfont: { fontSize: wp('6.5%'), color: 'white', fontFamily: 'Poppins-SemiBold', // fontWeight: 'bold', lineHeight:hp('6%') }, Transpbtn: { width: wp('85%'), height: hp('7.3%'), backgroundColor: '#246BFD', borderColor: '#246BFD', marginLeft: wp('7%'), marginTop: hp('5%'), }, FontHeadCon: { marginLeft: wp('5%'), marginBottom: wp('5%'), marginTop: wp('-2%'), }, }); export default Styles;<file_sep>/src/Containers/PinScreen/index.js import React, { useState, useEffect } from 'react'; import { View, Text, Image, StatusBar, TouchableOpacity, Pressable, StyleSheet, Modal, Alert, } from 'react-native'; import styles from './Styles'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import FingerprintScanner from 'react-native-fingerprint-scanner'; import PopupModal from '../../Components/PopupModal'; import _ from 'lodash'; import ValidationPopup from '../../Components/ValidationPopup'; import EncryptedStorage from 'react-native-encrypted-storage'; const PinCodeScreen = ({ navigation }) => { const [password, setPassword] = useState(['', '', '', '', '', '']); const [biometryType, setbiometryType] = useState(''); const [showModal, setShowModal] = useState(false); const [EnteredPasscode, setEnteredPasscode] = useState(''); const [showValidpop, setshowValidpop] = useState(false); let Numbers = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }, { id: 8 }, { id: 9 }, { id: 0 }, ]; const OnPressNumber = num => { let tempCode = password; for (var i = 0; i < tempCode.length; i++) { if (tempCode[i] == '') { tempCode[i] = num; break; } else { continue; } } if (tempCode[5] != '') { if (!EnteredPasscode) navigation.navigate('EnterPassword') if (_.isEqual(password, EnteredPasscode)) { //navigation.navigate('Home') navigation.navigate('TabNav') } else { setshowValidpop(true) } } setPassword(prePassword => [...tempCode]); }; const OnpressCancel = () => { let tempCode = password; if (password != ['', '', '', '', '', '']) { for (var i = tempCode.length - 1; i >= 0; i--) { if (tempCode[i] !== '') { tempCode[i] = ''; break; } else { continue; } } setPassword(prePassword => [...tempCode]); } }; useEffect(() => { EncryptedStorage.getItem('@PasscodeValue').then(suc => { if (suc) { console.log('suc', JSON.parse(suc)); setEnteredPasscode(JSON.parse(suc)); } }) FingerprintScanner.isSensorAvailable() .then(bioType => { setbiometryType(bioType); // if (bioType == 'Biometrics') { // showAuthenticationDialog(); // } // if (bioType == 'TouchID') { // showAuthenticationDialog(); // } // if (bioType == 'Face ID') { // showAuthenticationDialog(); // } }) .catch(error => console.log('isSensorAvailable error => ', error)); }, []); const Getmessage = () => { // console.log() const bioType = biometryType; if (bioType === 'Face ID') { return 'Scan your Face on the device to continue'; } else { return 'Scan your Fingerprint on the device scanner to continue'; } }; const showAuthenticationDialog = () => { const bioType = biometryType; if (bioType !== null && bioType !== undefined) { FingerprintScanner.authenticate({ description: Getmessage(), }) .then(() => { //navigation.navigate('Home') navigation.navigate('TabNav') }) .catch(error => { console.log('Authentication error is => ', error); }); } else { console.log('biometric authentication is not available'); } }; const updateshow = () => { setshowValidpop(false) } return ( <> <View style={styles.MainCon}> <View style={{ justifyContent: 'center', alignItems: 'center' }}> <View style={styles.ImageCon}> <Image source={require('../../Assets/Images/Group46300.png')} style={{ width: '100%', height: '100%', resizeMode: 'contain' }} /> </View> </View> <View style={{ justifyContent: 'center', alignItems: 'center' }}> <Text style={{ color: '#5E6272', fontFamily: 'Inter-Regular' }}> Enter PIN code </Text> </View> <View style={styles.CodeCon}> {password.map((p, index) => { let style = p !== '' ? styles.Code2 : styles.Code1; return <View style={style} key={index} />; })} </View> <View style={styles.NumberCon}> {/* <Text>{biometryType}</Text> */} {Numbers.map(({ id, index }) => { return ( <TouchableOpacity style={styles.Number} key={index} onPress={() => OnPressNumber(id)}> <Text style={styles.NumberText}>{id}</Text> </TouchableOpacity> ); })} <View style={{ position: 'absolute', bottom: hp('2%'), left: wp('15%') }}> <TouchableOpacity onPress={showAuthenticationDialog}> <View style={{ height: 50, width: 50, overflow: 'hidden' }}> <Image source={require('../../Assets/Images/TouchId.png')} style={{ height: '100%', width: '100%', resizeMode: 'contain' }} /> </View> </TouchableOpacity> </View> <View style={{ position: 'absolute', bottom: hp('3%'), right: wp('15%') }}> <TouchableOpacity onPress={OnpressCancel}> <View style={{ height: 35, width: 35, overflow: 'hidden' }}> <Image source={require('../../Assets/Images/BackText.png')} style={{ height: '100%', width: '100%', resizeMode: 'contain' }} /> {/* <Image source={require('../../Assets/Images/BackText.png')} /> */} </View> </TouchableOpacity> </View> {showModal && ( <PopupModal visible={true} onPress={() => navigation.navigate('CreateNewPassword')} /> )} {/* -------------- */} {/* --------------------- */} </View> </View> {showValidpop == true && ( <ValidationPopup title={"Password is incorrect"} Show={true} showback={updateshow} /> )} </> ); }; export default PinCodeScreen; <file_sep>/src/Containers/Home/Stories.js /* eslint-disable react-native/no-inline-styles */ import React from 'react'; import {View, Text, Image, FlatList, Dimensions} from 'react-native'; import { heightPercentageToDP, widthPercentageToDP, } from 'react-native-responsive-screen'; let width=Dimensions.get('window').width; let height=Dimensions.get('window').height; const StoryData = [ { Img: require('../../Assets/Swaap/Story/Story1.png'), Content: 'The Rise of “DeFi”', }, { Img: require('../../Assets/Swaap/Story/Story2.png'), Content: 'DeFi Hits Record $13.6B', }, { Img: require('../../Assets/Swaap/Story/Story3.png'), Content: 'Updated privacy policy', }, { Img: require('../../Assets/Swaap/Story/Story4.png'), Content: '$1B Ether Staked on ETH 2.0', }, ]; const StoryRender = ({item}) => { return ( <View style={{ alignItems: 'center', padding:9, marginVertical: heightPercentageToDP('2%'), }}> <View style={{ height: widthPercentageToDP('18%'), width: widthPercentageToDP('18%'), backgroundColor: '#181A20', borderRadius: 200, borderWidth: 1.5, borderColor: '#246BFD', overflow: 'hidden', justifyContent: 'center', alignItems: 'center', shadowColor: '#000', shadowOffset: { width: 0, height: 5, }, shadowOpacity: 0.36, shadowRadius: 6.68, elevation: 11, }}> <View style={{ height: widthPercentageToDP('14.8%'), width: widthPercentageToDP('14.8%'), borderRadius: 200, }}> <Image source={item.Img} style={{height: '100%', width: '100%'}} /> </View> </View> <View style={{ width: widthPercentageToDP('20'), height:'auto', marginVertical: heightPercentageToDP('1'), }}> <Text style={{ color: '#FFFFFF', opacity: 0.5, textAlign: 'center', fontSize: 10, fontFamily: 'Inter-Regular', }}> {item.Content} </Text> </View> </View> ); }; const Stories = () => { return ( <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }}> <FlatList horizontal scrollEnabled={false} showsHorizontalScrollIndicator={false} data={StoryData} renderItem={StoryRender} /> </View> ); }; export default Stories; <file_sep>/src/Assets/Images/ModalImage/index.js const modal1 = require('./ProductImage.png'); const modal2 = require('./ProductImage2.png'); const modal3 = require('./productImage4.png'); const modal4 = require('./productImage5.png'); const modal5 = require('./productImage6.png'); const modal6 = require('./ProductImages3.png'); const m1 = require('./new/m1.jpg'); const m2 = require('./new/m2.jpg'); const m3 = require('./new/m3.jpg'); const m4 = require('./new/m4.jpg'); export {modal1, modal2, modal3, modal4, modal5, modal6, m1, m2, m3, m4}; // {require('../../assets/Images/logo_cart_paddle.png') <file_sep>/src/Components/Button/styles.js import { StyleSheet } from 'react-native' import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen'; export default StyleSheet.create({ button: { backgroundColor: '#246BFD', borderColor: 0, borderWidth: 0, overflow: 'visible', borderRadius: 10, alignItems: 'center', flexDirection: 'row', paddingLeft: 15, paddingRight: 15, justifyContent: 'space-around', flexDirection: 'row', paddingBottom: 10, paddingTop: 10 }, text: { color: '#fff', fontSize: wp('4.2%'), textAlign: 'center', fontFamily:'Inter-Bold' }, })<file_sep>/src/Store/index.js import {applyMiddleware, combineReducers, createStore} from "redux"; import rootSaga from '../Saga'; import authReducer from '../Reducers/auth.reducer'; import createSagaMiddleware from "redux-saga"; import wordingReducer from '../Reducers/wording.reducer'; const sagaMiddleware = createSagaMiddleware(); export const rootReducer = combineReducers({ auth: authReducer, wording:wordingReducer, }); export const store = createStore(rootReducer, applyMiddleware(sagaMiddleware)); sagaMiddleware.run(rootSaga);
8762fc148335bf74b11d06444338c5a54578cc99
[ "JavaScript", "Swift" ]
66
JavaScript
vipul2511/Swapp-Function
6c74590c035e3ce1242c23aac035d62ac14a4200
5d9fd2c51e9a09744d1000d0f2a8d21bd85e4ca0
refs/heads/master
<file_sep># android-reactor <file_sep>package com.example.androidreactor; import ioio.lib.api.AnalogInput; import ioio.lib.api.DigitalOutput; import ioio.lib.api.IOIO; import ioio.lib.api.PwmOutput; import ioio.lib.api.exception.ConnectionLostException; import ioio.lib.util.BaseIOIOLooper; import ioio.lib.util.IOIOLooper; import ioio.lib.util.android.IOIOActivity; import android.os.Bundle; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; /** * This class was renamed to Main for simplicity and understandability. * * Make sure you have the IOIO board wiring as follows: * - Distance Sensors x2: * - Red: 3.3v * - Black: Ground * - Yellow: Pins 39 (L), 40 (R). * - Servo motors x 2: * - Red: 5v * - Black: Ground * - Yellow: Pins 11 (L), 12 (R). * Then, BE SURE TO USE A RELATIVELY NEW BATTERY OR YOU WILL HAVE PROBLEMS!!!! * (Trust me on this one -- I banged my head against the wall for 45 minutes solving it). */ public class Main extends IOIOActivity { private TextView leftSensorTextView; private TextView rightSensorTextView; private ProgressBar leftProgressBar; private ProgressBar rightProgressBar; private TextView resultTextView; /** * Called when the main view is created. * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); leftSensorTextView = (TextView) findViewById(R.id.left_textview); rightSensorTextView = (TextView) findViewById(R.id.right_textview); leftProgressBar = (ProgressBar) findViewById(R.id.left_progressbar); rightProgressBar = (ProgressBar) findViewById(R.id.right_progressbar); resultTextView = (TextView) findViewById(R.id.result_textview); } /** * Class for looping while the IOIO board is connected. */ class Looper extends BaseIOIOLooper { private AnalogInput leftAnalogInput; private AnalogInput rightAnalogInput; private PwmOutput leftPwmOutput; private PwmOutput rightPwmOutput; private DigitalOutput led; /** * Called when the IOIO board is connected * @throws ConnectionLostException */ @Override public void setup() throws ConnectionLostException { led = ioio_.openDigitalOutput(IOIO.LED_PIN, true); leftAnalogInput = ioio_.openAnalogInput(39); rightAnalogInput = ioio_.openAnalogInput(40); leftPwmOutput = ioio_.openPwmOutput(11, 100); rightPwmOutput = ioio_.openPwmOutput(12, 100); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText( Main.this, "Connected to IOIO board!", Toast.LENGTH_SHORT ).show(); } }); } /** * Loops while the IOIO board is connected. This is where all the action happens. * @throws ConnectionLostException * @throws InterruptedException */ @Override public void loop() throws ConnectionLostException, InterruptedException { // Read the sensors only once per loop for increased performance float leftAnalogReading = leftAnalogInput.read(); float rightAnalogReading = rightAnalogInput.read(); displayNumber(leftAnalogReading, "L"); displayNumber(rightAnalogReading, "R"); // Rather than converting from float to int a million times, // let's just do it once here int leftAnalog = (int) (leftAnalogReading * 1000); int rightAnalog = (int) (rightAnalogReading * 1000); leftProgressBar.setProgress(leftAnalog); rightProgressBar.setProgress(rightAnalog); leftPwmOutput.setPulseWidth(500 + (leftAnalog * 2)); rightPwmOutput.setPulseWidth(500 + (rightAnalog * 2)); if ((leftAnalog > (rightAnalog - 75)) && (leftAnalog < rightAnalog + 75)) { led.write(false); // turn on status LED (counterintuitive) runOnUiThread(new Runnable() { @Override public void run() { resultTextView.setText("yes!"); } }); } else { led.write(true); runOnUiThread(new Runnable() { @Override public void run() { resultTextView.setText(""); } }); } Thread.sleep(10); } @Override public void disconnected() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText( Main.this, "Disconnected from IOIO board!", Toast.LENGTH_SHORT ).show(); } }); } } @Override protected IOIOLooper createIOIOLooper() { return new Looper(); } /** * Displays a number on a given side of the screen. * * @param f The number to display * @param side The side of the screen on which to display the number. * Must be "L", "l", "R", or "r" or else the function will do nothing. */ private void displayNumber(float f, String side) { final String numberString = String.format("%.2f", f); if (side.equals("l") || side.equals("L")) { runOnUiThread(new Runnable() { @Override public void run() { leftSensorTextView.setText(numberString); } }); return; } if (side.equals("r") || side.equals("R")) { runOnUiThread(new Runnable() { @Override public void run() { rightSensorTextView.setText(numberString); } }); } } }
b596c9518b60a24c668575c6fc2d611a65fce212
[ "Markdown", "Java" ]
2
Markdown
bt-uci-17/reactor
e79c8ccf848bcfe3abd049000a04a8f26b8e8596
f5134511239b9bb7fee27fc97d25b5832623a5dc
refs/heads/master
<repo_name>MarlonMunozWebDev/PAGINACION-PHP<file_sep>/conexion.php <?php /*DEFINIMOS LOS VALORES DE LA CONEXION MYSQL Y EL NOMBRE DE LA BD*/ $link = 'mysql:host=localhost;dbname=glosario'; /*DEFINIMOS NUESTRO USUARIO Y CONTRASEÑA DEL SERVIDOR*/ $usuario = 'root'; $pass = ''; //CONEXION Y VERIFICANDO LOS DATOS try { $pdo = new PDO($link,$usuario,$pass); //echo 'Conectado Exitosamente <br>'; /*SI OCURRE UN ERROR AL COMPOROBAR LOS DATOS*/ }catch (PDOException $e) { print "!Error de Conexion!: " . $e->getMessage() . "<br/>"; die(); } ?> <file_sep>/index.php <?php include_once 'conexion.php'; $sql = 'SELECT * FROM conceptos'; $sentencia = $pdo->prepare($sql); $sentencia->execute(); $resultado = $sentencia->fetchAll(); //var_dump($resultado); //DEFINIENDO EL NUMERO DE PAGINACION Y CUANTOS ELEMENTOS POR CADA SECCION $conceptos_x_pagina = 3; //CONTAMOS CUANTOS FILAS TIENE NUESTRA TABLA $total_conceptos_db = $sentencia->rowCount(); //echo $total_conceptos_db; //ESTABLECIENDO EL NUMERO DE PAGINAS SEGUN LAS FILAS OBTENIDAS $paginas = $total_conceptos_db/3; $paginas = ceil($paginas); echo $paginas; ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>PAGINACION</title> </head> <body class="bg-light"> <div class="container my-5"> <h1 class="mb-5">PRODUCTOS</h1> <?php //RECORREMOS EL ARRAY Y MOSTRAMOS UN ALERT POR CADA ELEMENTO ?> <?php foreach($resultado as $articulo): ?> <div class="alert alert-primary" role="alert"> <?php echo$articulo['concepto']?> </div> <?php endforeach ?> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item <?php echo $_GET['pagina']<=1 ? 'disabled' : '' ?>"> <?php //CHECA QUE PAGINA ESTA Y RESTALE UNO Y REDIRECCIONAME A EL RESULTADO ?> <a class="page-link" href="index.php?pagina=<?php echo $_GET['pagina']-1 ?>"> Anterior</a></li> <?php for($i=0;$i<$paginas;$i++): ?> <?php //SI GET-PAGINA = i COLOCALE LA CLASE ACTIVE Y SI NO SOLO ?> <li class="page-item <?php echo $_GET['pagina']==$i+1 ? 'active' : '' ?>"> <?php //GET - INDEX.PHP VA A COLOCAR UNA VARIABLE PAGINA SEGUN LA PAGINA EN LA QUE SE ENCUENTRE ?> <a class="page-link" href="index.php?pagina=<?php echo$i+1 ?> "> <?php echo$i+1 ?></a> </li> <?php endfor ?> <li class="page-item <?php // SI LA PAGINA ES MAYOR O IGUAL AL NUMERO DE PAGINAS PINTA DESABILTADO SI NO NADA ?> <?php echo $_GET['pagina']>=$paginas ? 'disabled' : '' ?>"> <a class="page-link" href="index.php?pagina=<?php echo $_GET['pagina']+1 ?>"> Siguiente</a> </li> </ul> </nav> </div> </body> </html>
934c6b64e3f6acf5b95a89836b5825508ec62c83
[ "PHP" ]
2
PHP
MarlonMunozWebDev/PAGINACION-PHP
2de8bae3d6874ad9fb722d4354480eea18c10b76
3eee050c58f0f98e5069838cb7d59bada6ece79c
refs/heads/master
<file_sep># Unit Test for the TestCombinationalCircuits class import unittest # import unittesting from MIPSPhase1 import BoolArray from MIPSphase2 import CombinationalCircuits # import your stage two class from stage3outline import RegisterFile,Memory class TestUnitClass3(unittest.TestCase): def setUp(self): self.regs = RegisterFile() self.mem = Memory() def testRFinit(self): for i in range(32): r = self.regs.getReg(i) self.assertEqual(type(r),type(BoolArray("0"))) self.assertEqual(len(r),32) if i != 29: self.assertEqual(int(r),0) else: self.assertEqual(int(r),int("3e0",16)) def testRFreadCyc(self): rs,rt,rd = 5,29,8 a,b = self.regs.readCycle(rs,rt,rd) self.assertEqual(int(a),0) self.assertEqual(int(b),int("3e0",16)) def testRFwriteCycTrue(self): rs,rt,rd = 5,29,8 a,b = self.regs.readCycle(rs,rt,rd) self.regs.writeCycle(True,BoolArray("BADDAD",32)) x = self.regs.getReg(8) self.assertEqual(int(x),int("BADDAD",16)) def testRFwriteCycFalse(self): rs,rt,rd = 5,29,8 a,b = self.regs.readCycle(rs,rt,rd) self.regs.writeCycle(False,BoolArray("BADDAD",32)) x = self.regs.getReg(8) print("reg8",int(x)) self.assertEqual(int(x),0) def testMMinitlimit1(self): self.assertEqual(int(self.mem.instrCycle(BoolArray("3FC",32))),0) def testMMinitlimit2(self): with self.assertRaises(KeyError): self.mem.instrCycle(BoolArray("400",32)) def testLoad(self): self.mem.loadProgram("addtwo.txt") self.assertEqual(int(self.mem.instrCycle(BoolArray("0",32))), int("200607a5",16)) self.assertEqual(int(self.mem.instrCycle(BoolArray("4",32))), int("2007FFFF",16)) self.assertEqual(int(self.mem.instrCycle(BoolArray("8",32))), int("00C74020",16)) self.assertEqual(int(self.mem.instrCycle(BoolArray("C",32))), int("FC000000",16)) self.assertEqual(int(self.mem.instrCycle(BoolArray("10",32))), int("0",16)) def testDataCycle(self): addr = BoolArray("000000C4",32) #196 data = BoolArray("00ADDFAD",32) other = BoolArray("000000DD",32) readval = self.mem.dataCycle(addr,data,True,False) self.assertEqual(int(readval),int("0",32)) readval = self.mem.dataCycle(addr,data,False,True) readval = self.mem.dataCycle(addr,other,True,False) self.assertEqual(int(readval),int("ADDFAD",16)) if __name__ == "__main__": unittest.main() <file_sep>#Stage One Outline #<NAME>, <NAME> & <NAME> from math import ceil class BoolArray: # a BoolArray object has as its main instance variable a # variable length array of boolean constants def __init__(self,hexstr,n=32): """ # convert the hextstring to a length n list of booleans # be careful of the order of indexing. # e.g., BoolArray("5C",8) should produce: # should accept either upper or lower case digits # [False, False, True,True,True,False,True,False] # i: 0 1 2 3 4 5 6 7 """ binary=bin(int(hexstr,16))[2:] binary=list(reversed(binary)) self.boolVals=[] self.n=n for i in range(len(binary)): if binary[i]=="1": self.boolVals.append(True) else: self.boolVals.append(False) while len(self.boolVals)<n: self.boolVals.append(False) def __str__(self): """ # __str__ is called when you 'print' a BoolArray object # it should return a string of 0's and 1's or T's and F's # in reverse order. the example in the init returns: # either 01011000 or FTFTTFFF """ t=self.boolVals[:] t.reverse() bitstring="" for i in range(len(t)): if t[i]: bitstring +="1" else: bitstring +="0" return bitstring def __len__(self): """ # __len__ is called when you use the the built in len() # it should return the numbr of bits from the __init__ """ return len(self.boolVals) def toHex(self): """ # return a string representing the current value in base 16 # eg a string whose current barray is [True,False,False,True,False] # should return "09" # the number of hex digits should be len//4 rounded up """ t=self.boolVals[:] t.reverse() string=str(self) string=hex(int(string,2)) string=string[2:] d=ceil(self.n/4)-len(string) string=d*"0"+string return string def __int__(self): """ # converts the array to an integer # the example "5C" should return 92 """ return int(str(self),2) def subArray(self,left,rightplus): """ # extracts a subarray of bits from indices left through rightplus # including left and upto but not including rightplus # e.g. getBits(7,10) a BoolArray object with bits equal to # bits 7 through 9 inclusive """ lst=self.boolVals[:] sm="" for i in range(len(lst)): if lst[i]: sm+="1" else: sm+="0" newlst=sm[left:rightplus] newlst=newlst[::-1] final=hex(int(newlst,2)) final=final[2:] return BoolArray(final,rightplus-left) def setBit(self,i,boolval): """ # sets the ith bit of the array to the value boolval """ self.boolVals[i]=boolval def getBit(self,i): """ # returns the ith bit of the array """ return self.boolVals[i] def catHigh(self,barrayobj): """ # returns a new BoolArray Object whose bits are those # of self with bits of barray concatenated on the high end. #partly courtsey of Wu & Nick """ n=len(barrayobj)+len(self) ans=BoolArray("0",n) for i in range(len(self)): ans.setBit(i,self.getBit(i)) for i in range(len(barrayobj)): k=len(self)+i ans.setBit(k,barrayobj.getBit(i)) return ans if __name__=="__main__": # students MAY NOT alter the code below without permission # until after stage one has been approved. # exception: you MAY add print statements for debugging purposes h1 = BoolArray("5C",8) h2 = BoolArray("3456ABCD",32) h3 = BoolArray("1F",5) # test __str__ assert str(h1) in ["01011100","FTFTTTFF"] assert str(h2) in ["00110100010101101010101111001101", "FFTTFTFFFTFTFTTFTFTFTFTTTTFFTTFT"] assert str(h3) in ["11111","TTTTT"] # test __len__ assert len(h1)==8 assert len(h2)==32 assert len(h3)==5 # test toHex assert h1.toHex() in ["5C","5c"] assert h2.toHex() in ["3456ABCD","3456abcd"] assert h3.toHex() in ["1F","1f"] # test __int__ assert int(h1) == int("5C",16) assert int(h2) == int("3456ABCD",16) assert int(h3) == int("1F",16) # test setBit() h1.setBit(1,True) assert h1.toHex() in ["5E","5e"] # test subArray h4 = h2.subArray(8,16) assert h4.toHex() in ["AB","ab"] # test getBit assert h3.getBit(1) assert not h1.getBit(7) # test catHigh() h5 = h3.catHigh(h1) assert len(h5) == 13 assert h5.toHex() in ["0BDF","0bdf"] print("These tests passed!") <file_sep># phase 3 control unit #<NAME>,<NAME>, <NAME> from MIPSPhase1 import BoolArray class RegisterFile: def __init__(self): # The register file is a list of 32 32-bit registers (BoolArray) # register 29 is initialized to "000003E0" the rest to "00000000" # an instance vaariable for writeReg is initialized to 0 self.regFile=[] for i in range(0,32): if i==29: self.regFile.append(BoolArray("000003E0",32)) else: self.regFile.append(BoolArray("00000000",32)) self. writeReg=0 def readCycle(self,readReg1,readReg2,writeReg): # readReg1, readReg2, and writeReg are integers 0..31 # writeReg is 'remembered' in the instance variable # copies of the two read registers are returned (BoolArrays) self.writeReg=writeReg read1,read2=self.regFile[readReg1],self.regFile[readReg2] return read1,read2 def writeCycle(self,RegWrite,data): # RegWrite is a boolean indicating that a write should occur # data is a BoolArray to be written if RegWrite is true # if the RegWrite control is True, # the value of data is copied into the writeReg register # where writeReg is the value most remembered from the most # recent read cycle # if RegWrite is false, no values change # NOTE: if writeReg is 0, nothing happens since $zero is constant if RegWrite==True: self.regFile[self.writeReg]=data else: return def getReg(self,i): # returns a copy of the BoolArray in register i return self.regFile[i] def showRegisters(self): # prints the index and hex contents of all non-zero registers # printing all registers is ok too but wastes screen real estate h=self.regFile(self) for i in range(len(regFile)): h=self.regFile(self) if h !=0: print(str(h)) else: return class Memory: # lets use 2K memory and map # 3FC,3Fd,3FE,3FF for inbuff,inflag,outbuff,outflag # sp is 3E0 and grows down def __init__(self): # creates a dictionary of BoolArrays whose # keys are 0, 4, 8, ... , 1020 and # values are all BoolArray("0",32) self.dicti={} for i in range(0,1021): self.dicti[i]=BoolArray("0",32) def showMemory(self): # print a nicely formatted table of non-zero memory print(" RegLocation", " ", "Data") print("+---------------------------------------------------------------+") for i in range(0,1021): if int(self.dicti[i]) !=0: print("| ",i," | ",self.dicti[i].toHex(), " |") else: return -1 print("+---------------------------------------------------------------+") def loadProgram(self,fname): # fname is the name of a text file that contains # one 8-digit hexidecimal string per line # they are cnverted to BoolArray and # read sequentially into memory in # locations 0, 4, 8, 12, ... f=open(fname,"r") temp=f.read() boolVals=[BoolArray(x[:8],32) for x in temp.split()] for i in range(0,len(boolVals)*4,4): self.dicti[i]=boolVals[i//4] f.close() def instrCycle(self,PC): # PC is a BoolArray # returns a copy of the memory address int(PC) p=PC return self.dicti[int(p)] def dataCycle(self,Address,WriteData,ReadMem,WriteMem): # Address and Write Data are BoolArrays # ReadMem and WriteMem are booleans (not both True) # if ReadMem True: # return a copy of the BoolArray at mem[int(address)] # if WriteMem is True: # a copy of WriteData is placed at mem[int(address)] # a BoolArray("00000000",32) is returned if ReadMem: p= self.dicti[int(Address)] return p elif WriteMem: k=WriteData self.dicti[int(Address)]=k return BoolArray("00000000",32) else: return BoolArray("0",32) if __name__=="__main__": d=Memory() d.showMemory() <file_sep># Unit Test for the TestCombinationalCircuits class import unittest # import unittesting from MIPSPhase1 import BoolArray # import your stage one class from MIPSphase2 import CombinationalCircuits # import your stage two class class TestUnitClass2(unittest.TestCase): def setUp(self): self.A = BoolArray("01234567",32) self.B = BoolArray("3FFEDCBA",32) self.C = BoolArray("01230ABC",32) self.D = BoolArray("00E00E00",32) def testMultiplexor(self): '''Testing MUX method''' A0 = BoolArray("BAD00DAD",32) A1 = BoolArray("F00D4DAD",32) self.assertEqual(int(CombinationalCircuits.Mux(A0,A1,False)), int(A0)) self.assertEqual(int(CombinationalCircuits.Mux(A0,A1,True)), int(A1)) def test_SignExtention(self): '''Testing Sign Extender (sign extend a 16-bit int to a 32 bit int)''' E = BoolArray("00BA",16) F = BoolArray("FF73",16) E1=CombinationalCircuits.Sign_extend(E).toHex() F1=CombinationalCircuits.Sign_extend(F).toHex() self.assertTrue(E1 in ["000000BA","000000ba"]) self.assertTrue(CombinationalCircuits.Sign_extend(F).toHex() in ["FFFFFF73","ffffff73"]) def test_ALU_add(self): '''Testing ALU add method''' control ={"F0":True,"F1":True,"ENA":True,"ENB":True, "INVA":False,"INCA":False,"SL":False,"SR":False,"amt":0} result,zero = CombinationalCircuits.ALU(self.A,self.B,control) self.assertEqual(result.toHex(),"41222221") self.assertFalse(zero) def test_ALU_subtract(self): '''Testing ALU subtraction''' control ={"F0":True,"F1":True,"ENA":True,"ENB":True, "INVA":True,"INCA":True,"SL":False,"SR":False,"amt":0} result,zero = CombinationalCircuits.ALU(self.A,self.B,control) self.assertTrue(result.toHex() in["3EDB9753","3edb9753"]) self.assertFalse(zero) def test_ALU_zero(self): '''Testing zero bit''' control ={"F0":True,"F1":True,"ENA":True,"ENB":True, "INVA":True,"INCA":True,"SL":False,"SR":False,"amt":0} result,zero = CombinationalCircuits.ALU(self.A,self.A,control) self.assertEqual(result.toHex(),"00000000") self.assertTrue(zero) def test_ALU_NOP(self): '''Testing ALU NOP''' control ={"F0":False,"F1":True,"ENA":True,"ENB":False, "INVA":False,"INCA":False,"SL":False,"SR":False,"amt":0} result,zero = CombinationalCircuits.ALU(self.A,self.B,control) self.assertEqual(self.A.toHex(),result.toHex()) def test_ALU_OR(self): '''Testing ALU OR''' control ={"F0":False,"F1":True,"ENA":True,"ENB":True, "INVA":False,"INCA":False,"SL":False,"SR":False,"amt":0} result,zero = CombinationalCircuits.ALU(self.A,self.B,control) self.assertTrue(result.toHex() in ["3FFFDDFF","3fffddff"]) self.assertFalse(zero) def test_ALU_AND(self): '''Testing ALU AND''' control ={"F0":False,"F1":False,"ENA":True,"ENB":True, "INVA":False,"INCA":False,"SL":False,"SR":False,"amt":0} result,zero = CombinationalCircuits.ALU(self.A,self.B,control) self.assertEqual(result.toHex(),"01224422") self.assertFalse(zero) def test_ALU_shiftleft(self): '''Testing ALU shift left''' control ={"F0":False,"F1":True,"ENA":True,"ENB":False, "INVA":False,"INCA":False,"SL":True,"SR":False,"amt":3} result,zero = CombinationalCircuits.ALU(self.A,self.B,control) self.assertTrue(result.toHex() in ["091A2B38","091a2b38"]) self.assertFalse(zero) def test_ALU_shiftright(self): '''Testing ALU shift right''' control ={"F0":False,"F1":True,"ENA":True,"ENB":False, "INVA":False,"INCA":False,"SL":False,"SR":True,"amt":7} result,zero = CombinationalCircuits.ALU(self.A,self.B,control) self.assertTrue(result.toHex() in ["0002468A","0002468a"]) self.assertFalse(zero) def test_Adder(self): '''Testing Adder''' result = CombinationalCircuits.Add(self.C,self.D) self.assertTrue(result.toHex() in ["020318BC","020318bc"]) def test_CU_00(self): '''Testing op 00''' rd,j,b,mr,m2r,mw,s,rw="RegDst","Jump","Branch","MemRead","MemtoReg","MemWrite","ALUSrc","RegWrite" # op 0x00 d = CombinationalCircuits.ControlUnit(BoolArray("00",6)) self.assertTrue(d["RegDst"] and not d["Jump"] and not d["Branch"] and not d["MemWrite"] and not d["ALUSrc"] and d["RegWrite"] and not d["ALUOp"][0] and not d["ALUOp"][1]) def test_CU_02(self): '''Testing op 02''' d = CombinationalCircuits.ControlUnit(BoolArray("02",6)) self.assertTrue(d["Jump"] and not d["RegWrite"]) def test_CU_04(self): '''Testing op 04''' d = CombinationalCircuits.ControlUnit(BoolArray("04",6)) self.assertTrue(not d["Jump"] and d["Branch"] and not d["MemWrite"] and not d["ALUSrc"] and not d["RegWrite"] and d["ALUOp"][0] and not d["ALUOp"][1]) def test_CU_08(self): '''Testing op 08''' d = CombinationalCircuits.ControlUnit(BoolArray("08",6)) self.assertTrue (not d["RegDst"] and not d["Jump"] and not d["Branch"] and not d["MemRead"] and not d["MemtoReg"] and not d["MemWrite"] and d["ALUSrc"] and d["RegWrite"] and not d["ALUOp"][0] and d["ALUOp"][1]) def test_CU_23(self): '''Testing op 23''' d = CombinationalCircuits.ControlUnit(BoolArray("23",6)) self.assertTrue(not d["RegDst"] and not d["Jump"] and not d["Branch"] and d["MemRead"] and d["MemtoReg"] and not d["MemWrite"] and d["ALUSrc"] and d["RegWrite"] and not d["ALUOp"][0] and d["ALUOp"][1]) def test_CU_2B(self): '''Testing op 2B''' d = CombinationalCircuits.ControlUnit(BoolArray("2B",6)) assert (not d["Jump"] and not d["Branch"] and d["MemWrite"] and d["ALUSrc"] and not d["RegWrite"] and not d["ALUOp"][0] and d["ALUOp"][1]) def test_ALUcontrol_add(self): # ALUop (F,T) (add) c = CombinationalCircuits.ALUControl((False,True),BoolArray("0",11)) self.assertTrue (c["F0"] and c["F1"] and c["ENA"] and c["ENB"] and not c["INVA"] and not c["INCA"] and not c["SL"] and not c["SR"] and c["amt"]==0 ) def test_ALUcontrol_sub(self): # ALUop (T,F) (sub) c = CombinationalCircuits.ALUControl((True,False),BoolArray("0",11)) self.assertTrue(c["F0"] and c["F1"] and c["ENA"] and c["ENB"] and c["INVA"] and c["INCA"] and not c["SL"] and not c["SR"] and c["amt"]==0) def test_ALUcontrol_shiftleft(self): # ALUop (F,F), funct = x00 S c = CombinationalCircuits.ALUControl((False,False),BoolArray("C0",11)) self.assertTrue(not c["F0"] and c["F1"] and c["ENA"] and not c["ENB"] and not c["INVA"] and not c["INCA"] and c["SL"] and not c["SR"] and c["amt"]==3 ) def test_ALUcontrol_shiftright(self): # ALUop (F,F), funct = x02 SR c = CombinationalCircuits.ALUControl((False,False),BoolArray("C2",11)) self.assertTrue(not c["F0"] and c["F1"] and c["ENA"] and not c["ENB"] and not c["INVA"] and not c["INCA"] and not c["SL"] and c["SR"] and c["amt"]==3) def test_ALUcontrol_f20(self): # ALUop (F,F), funct = x20 plus c = CombinationalCircuits.ALUControl((False,False),BoolArray("20",11)) self.assertTrue(c["F0"] and c["F1"] and c["ENA"] and c["ENB"] and not c["INVA"] and not c["INCA"] and not c["SL"] and not c["SR"] and c["amt"]==0 ) def test_ALUcontrol_f22(self): # ALUop (F,F), funct = x22 minus c = CombinationalCircuits.ALUControl((False,False),BoolArray("22",11)) self.assertTrue(c["F0"] and c["F1"] and c["ENA"] and c["ENB"] and c["INVA"] and c["INCA"] and not c["SL"] and not c["SR"] and c["amt"]==0 ) def test_ALUControl_f24(self): # ALUop (F,F), funct = x24 and c = CombinationalCircuits.ALUControl((False,False),BoolArray("24",11)) self.assertTrue(not c["F0"] and not c["F1"] and c["ENA"] and c["ENB"] and not c["INVA"] and not c["INCA"] and not c["SL"] and not c["SR"] and c["amt"]==0 ) def test_ALUcontrol_25(self): # ALUop (F,F), funct = x25 or c = CombinationalCircuits.ALUControl((False,False),BoolArray("25",11)) self.assertTrue(not c["F0"] and c["F1"] and c["ENA"] and c["ENB"] and not c["INVA"] and not c["INCA"] and not c["SL"] and not c["SR"] and c["amt"]==0 ) if __name__ == "__main__": unittest.main() <file_sep># phase two, all the combinational circuit components # as functions in module Circuit #By: Dennis from MIPSPhase1 import BoolArray from copy import deepcopy class CombinationalCircuits: def ControlUnit(op): # return a dictionary with keys: "RegDest", "Jump", "Branch", "MemRead", # "MemToReg", "ALUOp", "MemWrite", "ALUSrc", and "RegWrite" # with appropriate boolean values for each (see handout or text) # ALUOp is set to # (False, False) if op in x00, # (False,True) if op is x08, x23,or x2B # (True,False) if op is x04 opco=op opc=opco.toHex() if opc=="00": dictionary={"RegDst":True, "Jump":False, "Branch":False, "MemRead":False, "MemtoReg":False, "ALUOp":(False,False), "MemWrite":False, "ALUSrc":False, "RegWrite":True} elif opc =="02": dictionary={"RegDst":False, "Jump":True, "Branch":False, "MemRead":False, "MemtoReg":False, "ALUOp":(False,False), "MemWrite":False, "ALUSrc":False, "RegWrite":False} elif opc=="04": dictionary={"RegDst":False, "Jump":False, "Branch":True, "MemRead":False, "MemtoReg":False, "ALUOp":(True,False), "MemWrite":False, "ALUSrc":False, "RegWrite":False} elif opc=="08": dictionary={"RegDst":False, "Jump":False, "Branch":False, "MemRead":False, "MemtoReg":False, "ALUOp":(False,True), "MemWrite":False, "ALUSrc":True, "RegWrite":True} elif opc=="23": dictionary={"RegDst":False, "Jump":False, "Branch":False, "MemRead":True, "MemtoReg":True, "ALUOp":(False,True), "MemWrite":False, "ALUSrc":True, "RegWrite":True} elif opc=="2B" or opc=="2b": dictionary={"RegDst":False, "Jump":False, "Branch":False, "MemRead":False, "MemtoReg":False, "ALUOp":(False,True), "MemWrite":True, "ALUSrc":True, "RegWrite":False} else: return return dictionary #------------------------------------------------------------------------------------------------------------------------------ def ALUControl(ALUOp,shftfunc): # function is bits 0..5, shftamt is bits 6..10 # create and return a dictionary with keys: # "ENA", "ENB", "INVA", "INC", "SL", "SR", "amt" # depending on ALUOp and shft func (see handout or text) # "amt" is an integer 0..31, the rest are boolean f=shftfunc function=f.subArray(0,6) funct=function.toHex() shiftamount=f.subArray(6,11) shiftamt=int(shiftamount) val1,val2=ALUOp[0],ALUOp[1] if (val1==False and val2==True) : dictionary={"F0":True,"F1":True,"ENA":True,"ENB":True,"INVA":False,"INCA":False,"SL":False,"SR":False,"amt":shiftamt} elif (val1==True and val2==False) : dictionary={"F0":True,"F1":True,"ENA":True,"ENB":True,"INVA":True,"INCA":True,"SL":False,"SR":False,"amt":shiftamt} elif (val1==False and val2==False) and funct=="00": dictionary={"F0":False,"F1":True,"ENA":True,"ENB":False,"INVA":False,"INCA":False,"SL":True,"SR":False,"amt":shiftamt} elif (val1==False and val2==False) and funct=="02": dictionary={"F0":False,"F1":True,"ENA":True,"ENB":False,"INVA":False,"INCA":False,"SL":False,"SR":True,"amt":shiftamt} elif (val1==False and val2==False) and funct=="20": dictionary={"F0":True,"F1":True,"ENA":True,"ENB":True,"INVA":False,"INCA":False,"SL":False,"SR":False,"amt":shiftamt} elif (val1==False and val2==False) and funct=="22": dictionary={"F0":True,"F1":True,"ENA":True,"ENB":True,"INVA":True,"INCA":True,"SL":False,"SR":False,"amt":shiftamt} elif (val1==False and val2==False) and funct=="24": dictionary={"F0":False,"F1":False,"ENA":True,"ENB":True,"INVA":False,"INCA":False,"SL":False,"SR":False,"amt":shiftamt} elif (val1==False and val2==False) and funct=="25": dictionary={"F0":False,"F1":True,"ENA":True,"ENB":True,"INVA":False,"INCA":False,"SL":False,"SR":False,"amt":shiftamt} else: print("ALU Control internal error<unrecognised function or ALUOp>") return dictionary #------------------------------------------------------------------------------------------------------------------------------ def Mux(A0,A1,c): # a two way multiplexor # A0 and A1 are BoolArray objects of equal length # if c is False it returns a copy of A0 # if c is True it returns a copy of A1 A00=deepcopy(A0) A11=deepcopy(A1) if c: return A11 elif not c: return A00 else: return #------------------------------------------------------------------------------------------------------------------------------ def shift(A,ALUcontrol): # A is a 32-bit BoolArray # ALUcontrol is a dict with keys "SL","SR", "amt" (and possibly others) # amt is a non-neg integer, SL and SR are boolean b=BoolArray("0",32) SL,SR=ALUcontrol["SL"],ALUcontrol["SR"] b.setBit(0,((A.getBit(0) and not SL and not SR) or (A.getBit(1) and SR) )) b.setBit(31,(A.getBit(30) and SL) or(A.getBit(31) and (not SL) and (not SR))) for i in range(1,31): b.setBit(i,( (A.getBit(i-1) and SL) or (A.getBit(i) and (not SR) and (not SL)) or (A.getBit(i+1) and SR))) return b #------------------------------------------------------------------------------------------------------------------------------ def Shift_left_2(A): # return a BoolArray which is A shifted two bits left (logically) # if b is more than 32 bits chop high order bits to make 32 dic={"SL":True,"SR":False} b=CombinationalCircuits.shift(A,dic) c=CombinationalCircuits.shift(b,dic) return c #------------------------------------------------------------------------------------------------------------------------------ def ALU_1(A,B,F0,F1,ENA,ENB,INVA,C): # implements the 1 bit ALU given on the class handout # returns c_out,s_out, (a carry and sum bit) both boolean # it is called 32 times by the AL T1 = B and ENB T2 = ENA and A T3 = INVA and not T2 or not INVA and T2 T4 = not F0 and not F1 T5 = not F0 and F1 T6 = F0 and not F1 T7 = F0 and F1 T8 = T3 and T1 T9 = T3 or T1 T10 = not T1 T11 = T8 and T4 T12 = T9 and T5 T13 = T10 and T6 T14 = T3 and not T1 or not T3 and T1 T15 = T1 and T3 and T7 T16 = T7 and T14 and C T17 = T15 or T16 T18 = C and not T14 or not C and T14 T19 = T18 and T7 c_out = T17 s_out = T11 or T12 or T13 or T19 return c_out,s_out #------------------------------------------------------------------------------------------------------------------------------ def ALU(A,B,control): # a 32 ripple ALU that chains 32 1-bit ALUs # the intermediate b is then set to the shifter # to produce the final return b #################################################### # A and B are 32-bit BoolArray # control is a dictionary as output by ControlUnit # returns R,z where R is a 32-bit BoolArray and z is a boolean that # that is True of R is zero F0,F1,ENA,ENB,INVA,INCA,SL,SR,amt=control["F0"],control["F1"],control["ENA"],control["ENB"],control["INVA"],control["INCA"],control["SL"],control["SR"],control["amt"] sum1=BoolArray("0",32) c=INCA for i in range(32): c,s=CombinationalCircuits.ALU_1(A.getBit(i),B.getBit(i),F0,F1,ENA,ENB,INVA,c) sum1.setBit(i,s) for i in range(amt): sum1=CombinationalCircuits.shift(sum1,control) zero=int(sum1)==0 return sum1,zero #------------------------------------------------------------------------------------------------------------------------------ def Add(A,B): # A and B are 32-bit BoolArrays # returns A+B a 32-bit BoolArray (may or may not use ALU) a=int(A) b=int(B) h=a+b return BoolArray(hex(h)[2:],32) #------------------------------------------------------------------------------------------------------------------------------ def Sign_extend(A): # A is a 16-bit BoolArray # returns 32-bit BoolArray that is A with its sign extended bit=A.getBit(15) B=BoolArray(A.toHex(),32) for i in range(16,32): B.setBit(i,bit) return B #------------------------------------------------------------------------------------------------------------------------------ <file_sep># phase4 #By: <NAME> & Nobert from MIPSPhase1 import BoolArray from MIPSphase2 import CombinationalCircuits from stage3outline import Memory,RegisterFile from time import sleep class MIPS: def __init__(self): # Create and initalize the various permanent components # of the system diagram. {BoolArrays and Sequential circuit objects} # recall: The combinational components are simulated by functions # not objects and can not be made into instance variables self.regs=RegisterFile() self.mem=Memory() self.pc=BoolArray("0",32) self.opcode=BoolArray("0",32) self.contrSig={} self.IR=self.mem.instrCycle(self.pc) self.pc4=BoolArray("0",32) self.jumpAdd=0 self.rdData1=BoolArray("0",32) self.rdData2=BoolArray("0",32) self.extended=BoolArray("0",32) self.ir=BoolArray("0",32) self.data=0 self.sum1,self.zero,self.memData,self.writeReg=0,0,0,0 #-------------------------------------------------------------------------- #ADD helper functions as needed def run(self): #while opcode is not 63=3F=111111: # instruction fetch cycle # instruction decode cycle # register read cycle # execute cycle # memory access cycle # write back cycle # IO cycle r=0 while self.opcode.toHex() !="3f " or self.opcode !=None: self._fetchCycle() self._decodeCycle() self._regReadCycle() self._executeCycle() self._accessCycle() self._ioCycle() r+=1 print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++") print("THE END OF CIRCLE:",r) print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++") input("return to continue") #-------------------------------------------------------------------------------------------------------- def _fetchCycle(self): self.pc4=CombinationalCircuits.Add(self.pc,BoolArray("00000004",32)) print("*************************************************************************************") print("The PC + 4 value is:",self.pc4) print("*************************************************************************************\n") self.IR=self.mem.instrCycle(self.pc) print("The instruction Register IR is:",self.IR) print("*************************************************************************************\n") self.opcode=self.IR.subArray(26,32) print("The opcode is:",self.opcode) print("*************************************************************************************\n") #-------------------------------------------------------------------------------------------------------- def _decodeCycle(self): self.contrSig=CombinationalCircuits.ControlUnit(self.opcode) print("The control Signal is:\n",self.contrSig) print("*************************************************************************************\n\n") p=self.IR.subArray(0,26) t="0000"+str(p)+"00" self.jumpAdd=hex(int(t,2))[2:] print("The jump address is:",self.jumpAdd) print("*************************************************************************************\n") #-------------------------------------------------------------------------------------------------------- def _regReadCycle(self): readReg1,readReg2,self.writeReg=int(self.IR.subArray(21,26)),int(self.IR.subArray(16,21)),int(self.IR.subArray(11,16)) self.rdData1,self.rdData2=self.regs.readCycle(readReg1,readReg2,self.writeReg) print("*************************************************************************************\n") print("------------------------RegRead Circle--------------------------------------------") print("The regReg1 is:",readReg1) print("The regReg2 is:",readReg2) print("The WrtReg is:",self.writeReg) self.ir=self.IR.subArray(0,16) p=BoolArray(self.ir.toHex(),32) self.extended=CombinationalCircuits.Sign_extend(p) print("The sign extended value is:",self.extended) self.data=CombinationalCircuits.Mux(self.rdData2,self.extended,self.contrSig["ALUSrc"]) print("The result from the Multiplexor in readCycle is:",self.data) print("*************************************************************************************\n") #-------------------------------------------------------------------------------------------------------- def _executeCycle(self): a=CombinationalCircuits.ALUControl(self.contrSig["ALUOp"],self.ir) self.sum1,self.zero=CombinationalCircuits.ALU(self.rdData1,self.data,a) print("*************************************************************************************\n") print("-------------------------Execute Cycle-------------------------------------------") print("The output from ALU is:",self.sum1) print("The zero bit is:",self.zero) shiftL2=CombinationalCircuits.Shift_left_2(self.extended) print("The shift left two value is:",shiftL2) adder=CombinationalCircuits.Add(shiftL2,self.pc4) control=self.zero and self.contrSig["Branch"] self.data=CombinationalCircuits.Mux(self.pc4,adder,control) print("First Multiplexor after adder is:",self.data) self.data=CombinationalCircuits.Mux(self.data,BoolArray(self.jumpAdd,32),self.contrSig["Jump"]) self.pc=self.data print("The value of PC is:",self.pc) print("*************************************************************************************\n") #-------------------------------------------------------------------------------------------------------- def _accessCycle(self): self.memData=self.mem.dataCycle(self.sum1,self.rdData2,self.contrSig["MemWrite"],self.contrSig["MemRead"]) print("*************************************************************************************\n") print("--------------------Memory Acces Cycle------------------------------------------") print("The value of the memory output is:",self.memData) self.data=CombinationalCircuits.Mux(self.sum1,self.memData,self.contrSig["MemtoReg"]) print("The output from the multiplexor is:",self.data) self.regs.writeCycle(self.contrSig["RegWrite"],self.data) if self.contrSig["RegWrite"]: print(self.data.toHex(),"store in", self.regs.writeReg) print("The writeReg current value is:",self.writeReg) print("*************************************************************************************\n") #-------------------------------------------------------------------------------------------------------- def _ioCycle(self): print("*************************************************************************************\n") print("--------------------------IO Cycle----------------------------------------------------") print("*************************************************************************************\n") inflag=int(self.mem.instrCycle(BoolArray("3f0",32))) inbuffer=self.mem.instrCycle(BoolArray("3f4",32)) outflag=int(self.mem.instrCycle(BoolArray("3f8",32))) outbuffer=self.mem.instrCycle(BoolArray("3fc",32)) if inflag !=0: inbuffer=BoolArray(input("Enter a 8bit Hexadecimal: "),32) inflag=0 if outflag !=0: print("The output buffer is:\n") print(outbuffer) outflag=0 print("********************************************************************") #-------------------------------------------------------------------------------------------------------- def showMemory(self): # call your Memory object's showMemory() method print("*********************************************************************************") print("------------------------------MEMORY-------------------------------------") self.mem.showMemory() print("-------------------------------------------------\n") #-------------------------------------------------------------------------------------------------------- def showRegisters(self): # call your RegisterFile objects's showRegisters() method print("****************************************************************************") print("---------------------he REGISTERS---------------------------------------") self.regs.showRegisters() #-------------------------------------------------------------------------------------------------------- def loadProgram(self,fname): # call your Memory object's loadProgram() method self.mem.loadProgram(fname) #-------------------------------------------------------------------------------------------------------- if __name__=="__main__": mips=MIPS() mips.loadProgram(input("What machine language file?: ")) mips.run() mips.showMemory() mips.showRegisters()
d7451fa06000975c1b320e45948bd4281820e9bb
[ "Python" ]
6
Python
salewi/MIPS_Simulation
8277812a41eaeb5dd009383f07b0957fd49d4f3a
364d4afa29adcf54b4c640bc477b75557d20b6f7
refs/heads/master
<repo_name>byunjuneseok/pr-scouter<file_sep>/go.mod module github.com/byunjuneseok/pr-scouter go 1.15 <file_sep>/cmd/pr-scouter/main.go package main import "log" func main() { log.Println("Work.") }<file_sep>/README.md # PR-scouter *Work in progress...*
74598f4db1ac988b68ee41059e9e6f36dd48452c
[ "Go", "Go Module", "Markdown" ]
3
Go Module
byunjuneseok/pr-scouter
bc1f6c48681d9655a6a74dd1c9208d463c0d0517
af7dd0f9346630a58b9b0274e3583538af7c7ad1
refs/heads/master
<repo_name>ms77er/divelog<file_sep>/app/controllers/toppages_controller.rb class ToppagesController < ApplicationController def index if logged_in? @user = current_user @diving = current_user.divings.build # form_for 用 @divings = current_user.divings.order('created_at DESC').page(params[:page]) end end end <file_sep>/app/models/diving.rb class Diving < ApplicationRecord belongs_to :user validates :user_id, presence: true validates :DiveNo, length: { maximum: 10 } validates :location, length: { maximum: 255 } validates :MaxDepth, length: { maximum: 3 } validates :AvgDepth, length: { maximum: 3 } validates :WaterTemp, length: { maximum: 3 } validates :Transparancy, length: { maximum: 3 } validates :Memo, length: { maximum: 255 } end <file_sep>/app/controllers/divings_controller.rb class DivingsController < ApplicationController before_action :require_user_logged_in before_action :correct_user, only: [:show, :edit, :update, :destroy] def new @user = User.new @diving = @user.divings.build # form_for 用 end def create @diving = Diving.new(diving_params) if @diving.save flash[:success] = '正常に登録されました' redirect_to @diving else flash.now[:danger] = '登録されませんでした' render :new end end def show @user = current_user @diving = @user.divings.build # form_for 用 @divings = @user.divings.find_by(id: params[:id]) end def update @user = current_user @diving = @user.divings.build # form_for 用 @divingup = @user.divings.find_by(id: params[:id]) if @divingup.update(diving_params) flash[:success] = 'Updated successfully / 正常に更新されました' redirect_to @divingup else flash.now[:danger] = 'Update error / 更新されませんでした' render :edit end end def edit @user = current_user @divingup = @user.divings.find_by(id: params[:id]) end def destroy @user = current_user @divings = @user.divings.find_by(id: params[:id]) @divings.destroy flash[:success] = 'Deleted successfully / 正常に削除されました' redirect_to @user end private def diving_params params.require(:diving).permit(:user_id, :DiveNo, :DiveDate, :DiveIn, :DiveOut, :location, :MaxDepth, :AvgDepth, :WaterTemp, :Transparancy, :Memo) end def correct_user @divings = Diving.find(params[:id]) unless @divings.user_id == current_user.id redirect_to root_url end end end <file_sep>/db/migrate/20170729001718_add_dive_date_todivings.rb class AddDiveDateTodivings < ActiveRecord::Migration[5.0] def change add_column :divings, :DiveDate, :date add_column :divings, :DiveIn, :time add_column :divings, :DiveOut, :time add_column :divings, :MaxDepth, :smallint add_column :divings, :AvgDepth, :smallint add_column :divings, :WaterTemp, :smallint add_column :divings, :Transparancy, :smallint add_column :divings, :Memo, :string end end <file_sep>/app/controllers/users_controller.rb class UsersController < ApplicationController before_action :require_user_logged_in, only: [:show, :edit, :update, :destroy] before_action :correct_user, only: [:show, :edit, :update, :destroy] def show @user = User.find(params[:id]) @diving = @user.divings.build # form_for 用 @divings = @user.divings.order('created_at DESC').page(params[:page]).per(20) @count_divings = @user.divings.count end def new @user = User.new end def create @user = User.new(user_params) if @user.save flash[:success] = 'ユーザを登録しました。' redirect_to @user else flash.now[:danger] = 'ユーザの登録に失敗しました。' render :new end end def update @user = User.find(params[:id]) if @user.update(user_params) flash[:success] = 'Updated successfully / 正常に更新されました' redirect_to @user else flash.now[:danger] = 'Update error / 更新されませんでした' render :edit end end def edit @user = User.find(params[:id]) end private def user_params params.require(:user).permit(:name, :email, :LicenceNo, :password, :password_confirmation) end def correct_user @user = User.find(params[:id]) unless @user.id == current_user.id redirect_to root_url end end end
936b9eee96593c37989bc97fe231496b83037d5d
[ "Ruby" ]
5
Ruby
ms77er/divelog
22ae5532d8e56b630018902ab950ed151167e976
54e6320b0f2b51dd069aec4838b6597af6cddd9c
refs/heads/main
<file_sep>import Head from "next/head"; import Link from "next/link"; // import products from '../products.json' import { fromImageToUrl, API_URL } from "../utils/urls"; import { twoDecimals } from "../utils/format"; export default function Home({products}) { return ( <> <img src="/banner.jpg" alt="banner" className="banner w-100 mb-5 img-fluid"/> <div className="container p-3"> <Head> <title>HypeLocker</title> </Head> <div className="row"> {products.map((product) => ( <div key={product.name} className="col-12 col-md-6 col-lg-4 col-xl-3 product-card" > <Link href={`/products/${product.slug}`}> <a className="text-decoration-none d-flex flex-column"> <img src={fromImageToUrl(product.image)} width={500} height={500} className="img-fluid" /> <div className="d-flex flex-column p-3 position-relative"> <h5 className="mt-2 text-center text-dark line-height-product"> {product.name} </h5> <p className="text-primary text-center position-absolute product-price start-50 translate-middle"> ${twoDecimals(product.price)} </p> </div> </a> </Link> </div> ))} </div> </div> </> ); } export async function getStaticProps(){ const product_res = await fetch(`${API_URL}/products/`) const products = await product_res.json() return{ props: { products } } }<file_sep>import "bootstrap/dist/css/bootstrap.min.css"; const Register = () => { return ( <div> <div className="container"> <form className="form-horizontal" role="form"> <h2>Registration</h2> <div className="form-group mb-2"> <label htmlFor="firstName" className="col-sm-3 control-label"> <span>First Name</span> </label> <div className="col-sm-9"> <input type="text" id="firstName" placeholder="<NAME>" className="form-control" autofocus /> </div> </div> <div className="form-group mb-2"> <label htmlFor="lastName" className="col-sm-3 control-label"> <span>Last Name</span> </label> <div className="col-sm-9"> <input type="text" id="lastName" placeholder="<NAME>" className="form-control" autofocus /> </div> </div> <div className="form-group mb-2"> <label htmlFor="email" className="col-sm-3 control-label"> <span>Email</span> </label> <div className="col-sm-9"> <input type="email" id="email" placeholder="Email" className="form-control" name="email" /> </div> </div> <div className="form-group mb-2"> <label htmlFor="password" className="col-sm-3 control-label"> <span>Password</span> </label> <div className="col-sm-9"> <input type="<PASSWORD>" id="password" placeholder="<PASSWORD>" className="form-control" /> </div> </div> <div className="form-group mb-2"> <label htmlFor="password" className="col-sm-3 control-label"> <span>Confirm</span> </label> <div className="col-sm-9"> <input type="<PASSWORD>" id="password" placeholder="<PASSWORD>" className="form-control" /> </div> </div> <div className="form-group mb-3"> <label htmlFor="phoneNumber" className="col-sm-3 control-label"> <span>Phone number</span> </label> <div className="col-sm-9"> <input type="phoneNumber" id="phoneNumber" placeholder="Phone number" className="form-control" /> </div> </div> <button type="submit" className="btn btn-primary btn-block"> <span>Register</span> </button> </form> </div> </div> ) } export default Register <file_sep>import { useRouter } from "next/router"; import Link from "next/link"; import { useContext } from "react"; import AuthContext from "../context/AuthContext"; const Header = () => { const router = useRouter(); const isHome = router.pathname === "/"; const goBack = (event) => { event.preventDefault(); router.back(); }; const { user } = useContext(AuthContext); return ( <div> <nav className="navbar navbar-expand-lg navbar-dark bg-main"> <div className="container"> <a className="navbar-brand" href="#"> HypeLocker </a> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse justify-content-between" id="navbarSupportedContent" > <ul className="navbar-nav mb-2 mb-lg-0"> <li className="nav-item"> <Link href="/"> <a className="nav-link active" aria-current="page" href="/"> Home </a> </Link> </li> <li className="nav-item"> <a className="nav-link" href="#"> Jordans </a> </li> <li className="nav-item"> <a className="nav-link" href="#"> Yeezys </a> </li> <li className="nav-item"> <a className="nav-link" href="#"> Basketball </a> </li> </ul> <form className="d-flex"> <input className="form-control me-2" type="search" placeholder="Search" aria-label="Search" /> <button className="btn btn-outline-light" type="submit"> Search </button> </form> <div> {user ? ( <Link href="/account"> <a><img src="/user-icon.png" alt={user.email} className="icon"/></a> </Link> ) : ( <Link href="/login"> <btn className="btn btn-primary">Login</btn> </Link> )} </div> </div> </div> </nav> {/* <div className="container"> {!isHome && ( <a href="#" onClick={goBack}> {"<"}Back </a> )} </div> */} </div> ); }; export default Header; <file_sep>// import Head from "next/head"; // import { useContext } from "react"; // import Link from "next/link"; // import AuthContext from "../context/AuthContext"; // export default function Account() { // const { user, logoutUser } = useContext(AuthContext); // if (!user) { // return ( // <div className="container"> // <Link href="/"> // <btn className="btn btn-primary">Go Back</btn> // </Link> // </div> // ); // } // return ( // <div className="container"> // <Head> // <title className="text-center">My Account</title> // <meta name="description" content="View your account" /> // </Head> // <div className="row"> // <div className="col-12"> // <btn href="#" className="btn btn-primary" onClick={logoutUser}> // Logout // </btn> // </div> // </div> // </div> // ); // } import { useContext, useState, useEffect } from "react"; import Link from 'next/link' import Head from 'next/head' import AuthContext from "../context/AuthContext"; import { fromImageToUrl,API_URL } from '../utils/urls' const useOrders = (user, getToken) => { const [orders, setOrders] = useState([]) const [loading, setLoading] = useState(false) useEffect(() => { const fetchOrders = async () => { setLoading(true) if(user){ try{ const token = await getToken() const orderRes = await fetch(`${API_URL}/orders`, { headers: { 'Authorization': `Bearer ${token}` } }) const data = await orderRes.json() setOrders(data) } catch(err){ setOrders([]) } } setLoading(false) } fetchOrders() }, [user]) return {orders, loading} } export default () => { const { user, logoutUser, getToken} = useContext(AuthContext) const { orders, loading } = useOrders(user, getToken) if(!user){ return ( <div> <p>Please Login or Register before accessing this page</p> <Link href="/"><a>Go Back</a></Link> </div> ) } return ( <div className="container account-box"> <div className="row"> <div className="col"> <Head> <title>Your Account</title> <meta name="description" content="Your orders will be shown here" /> </Head > <div className="account_header d-flex align-items-center justify-content-center mb-5"> <h2 className="account-title me-auto ">Account Page</h2> <a href="#" onClick={logoutUser} className="logout text-decoration-none text-dark mb-0">Logout</a> </div> <h3 className="mb-3">Your Orders</h3> {loading && <p>Orders are Loading</p>} {orders.map(order => ( <div className="col-12 mb-3 d-flex align-items-center account-product-title" key={order.id}> <img src={fromImageToUrl(order.product.image)} width={100} height={100} className="order_img img-fluid" /> <div className="me-3"> <h4 className="product_name mb-1">{order.product.name} </h4> <div className="order_sub_content">QTY: {order.quantity} Size: {order.size}</div> <div className="order_sub_content d-flex"><p className="mb-0 me-3">${order.total} <span>{order.Status}</span></p> </div> </div> </div> ))} <hr /> <p >Logged in as {user.email}</p> </div> </div> </div> ) } <file_sep>import Head from "next/head"; import { fromImageToUrl, API_URL } from "../../utils/urls"; import { twoDecimals } from "../../utils/format"; const Product = ({ product }) => { return ( <div className="container product-full-description p-3 d-flex justify-content-center align-items-center"> <Head> {product.meta_title && <title>{product.meta_title} | HypeLocker</title>} {product.meta_description && ( <meta name="description" content={product.meta_description} /> )} </Head> <div className="row"> <div className="col-12 col-lg-6 d-flex flex-column"> <img src={fromImageToUrl(product.image)} className="w-100" /> </div> <div className="col-12 col-lg-6 "> <h5>{product.name}</h5> <p className="text-dark mt-3 mb-5">{product.content}</p> <div className="d-flex justify-content-between align-items-center mb-3 pe-lg-5 "> <span>Size</span> <select className="form-select w-50" aria-label="Default select example"> <option selected>Size</option> <option value="1">7.0</option> <option value="1">7.5</option> <option value="1">8.0</option> <option value="1">8.5</option> <option value="2">9.0</option> <option value="2">9.5</option> <option value="3">10.0</option> </select> </div> <div className="d-flex justify-content-between align-items-center mb-3 pe-lg-5 "> <span>Quantity</span> <input type="number" className="form-control w-50" id="input1" placeholder="Enter Quantity"></input> </div> <div className="d-flex w-100 justify-content-between align-items-center pe-lg-5 "> <h5 className="text-primary mb-0">${twoDecimals(product.price)}</h5> <button type="button" className="btn btn-primary w-50 text-uppercase">Add to Cart</button> </div> </div> </div> </div> ); }; export async function getStaticProps({ params: { slug } }) { const product_res = await fetch(`${API_URL}/products/?slug=${slug}`); const found = await product_res.json(); return { props: { product: found[0], }, }; } export async function getStaticPaths() { const products_res = await fetch(`${API_URL}/products/`); const products = await products_res.json(); return { paths: products.map((product) => ({ params: { slug: String(product.slug) }, })), fallback: false, }; } export default Product; <file_sep>import Head from "next/head"; import { useContext, useState } from "react"; import AuthContext from "../context/AuthContext"; // import styles from "../styles/Login.module.css"; export default function Login() { const [input, setInput] = useState(""); const { loginUser } = useContext(AuthContext); const handleSubmit = (e) => { e.preventDefault(); loginUser(input); }; return ( <div className="container"> <div calssName="row"> <div className="col-12 login_box m-auto p-3 mb-5 mt-5" > <Head> <title >Login</title> <meta name="description" content="Login here to be able to purchase" /> </Head> <h2 className="text-center mb-1">Login</h2> <p className="form-text text-center mb-5"> Powered by Magic.link </p> <form onSubmit={handleSubmit} className="d-flex flex-column"> <label for="exampleFormControlInput1" className="form-label " > Email address </label> <input value={input} onChange={(e) => setInput(e.target.value)} type="email" placeholder="<EMAIL>" className="mb-3 mb-md-5 pt-1 pb-1 border-dark" id="exampleFormControlInput1" /> <button type="submit" className="btn btn-dark mb-5 "> Log In </button> </form> </div> </div> </div> ); }
52d4fde9a1b238f7b5cd9a609ede30077cb79978
[ "JavaScript" ]
6
JavaScript
unsiga25/ecoms-proj3
3d99e7ff2d1f25089723de0d262cca0b1c4bef44
233f18a2a0d6aada8ace75ed32931bc5d2da93ab
refs/heads/master
<file_sep>watch('decorators.*.rb') do system 'rspec -c ./decorators.rspec.rb' end <file_sep>watch('.*\.rb') do system 'ruby metakoans.rb knowledge.rb' end<file_sep>require_relative 'equality_by_attributes' require_relative 'author' require_relative 'book' require_relative 'order' require_relative 'reader' require 'date' require 'base64' # factory class Library attr_accessor :books, :orders, :readers, :authors include EqualityByAttributes def initialize @books = [] @orders = [] @readers = [] @authors = [] end def create_book(title, author) book = Book.new(title, author) record_as :book, book end def create_author(name, biography = nil) author = Author.new(name, biography) record_as :author, author end def create_reader(name, email = nil, city = nil, street = nil, house = nil) reader = Reader.new(name, email, city, street, house) reader.register_in(self) record_as :reader, reader end def create_order(book, reader) order = Order.new(book, reader, DateTime.now) record_as :order, order end # program functionality def best_reader order_most_popular_attribute(:reader) end def bestseller order_most_popular_attribute(:book) end def top_books(size) @orders .group_by(&:book) .max_by(size) { |_book, orders| orders.size } .map(&:first) end def save(path = 'library.file') encode = Base64.encode64(Marshal.dump(self)) File.open(path, 'wb') { |f| f.write(encode) } end def self.load(path = 'library.file') content = File.read(path) Marshal.load(Base64.decode64(content)) end private def order_most_popular_attribute(attribute) @orders.group_by(&attribute).values.max_by(&:size).first.send(attribute) end def record_as(key, obj) key = ('@' + key.to_s + 's').to_sym raise ArgumentError, "Library doesn't have such attribute: #{key}" unless instance_variable_defined?(key) arr = instance_variable_get(key) arr << obj obj end end <file_sep>module EqualityByAttributes def attributes instance_variables.map { |v| instance_variable_get(v) } end def ==(other) other.class == self.class && other.attributes == attributes end end <file_sep>require_relative 'decorators' describe Decorators do let(:klass) do Class.new do include Decorators add_prefix('hello ') def a 'from a' end def b 'from b' end add_prefix('hello2 ') def с(arg1, arg2) "from с, arg1 = #{arg1}, arg2=#{arg2}" end end end let(:instance) { klass.new } it 'should add prefix only to one subsequent method' do expect(instance.a).to eq('hello from a') expect(instance.b).to eq('from b') expect(instance.с 'arg1', 'arg2').to eq('hello2 from с, arg1 = arg1, arg2=arg2') end end <file_sep>watch('factory.*.rb') do |md| system 'rspec -c ./factory.rspec.rb' end <file_sep>watch('lib.*.rb') do |md| system "rspec -c ./spec/lib.rspec.rb" end <file_sep>class Factory def self.new(*f_args, &block) Class.new do attr_accessor(*f_args) define_method :initialize do |*i_args| f_args.zip(i_args).each { |(f_arg, i_arg)| send("#{f_arg}=", i_arg) } end define_method :[] do |param| param = f_args[param] if param.is_a? Numeric send(param) end class_eval(&block) if block_given? end end end <file_sep>class Reader attr_accessor :name, :email, :city, :street, :house include EqualityByAttributes def initialize(name, email, city, street, house) @name = name @email = email @city = city @street = street @house = house end def register_in(library) @library = library end def take(book) handle_empty_library unless @library @library.create_order(book, self) end private def handle_empty_library raise "Reader #{@name} must be registered in library" end end <file_sep>def attribute(name, &default_block) name, default_value = name.to_a.first if name.is_a? Hash default_block ||= proc { default_value } define_method name do if instance_variable_defined? "@#{name}" instance_variable_get "@#{name}" elsif default_block instance_eval(&default_block) end end define_method "#{name}=" do |var| instance_variable_set("@#{name}", var) end alias_method "#{name}?", name end <file_sep>#!/usr/bin/env ruby require_relative 'lib/library' require 'faker' puts 'First, I will create library for you with readers and books' library = Library.new 5.times do |i| tmp_author = instance_variable_set("@author#{i}", library.create_author(Faker::Book.author)) instance_variable_set("@reader#{i}", library.create_reader(Faker::Name.name)) instance_variable_set("@book#{i}", library.create_book(Faker::Book.title, tmp_author)) end 3.times { @reader0.take(@book0) } 5.times { @reader1.take(@book1) } 1.times { @reader2.take(@book2) } 0.times { @reader3.take(@book3) } 1.times { @reader4.take(@book4) } puts 'Lets see what we have' puts " #{library.best_reader.name} is most often takes books" puts " \"#{library.bestseller.title}\" is most popular book" puts " 3 most popular book titles: #{library.top_books(3).map(&:title).join(', ')}" puts 'Also I can save library to file and load from it' library.save other_lib = Library.load puts library == other_lib ? 'And they will be equal' : 'Unfortunately, they are not equal' <file_sep>require_relative 'factory' describe Factory do after(:each) do Object.send(:remove_const, :Customer) end it 'can create class without instance variables' do Customer = Factory.new customer = Customer.new expect(customer.instance_variables).to eq([]) end context 'created class instance' do before(:each) do Customer = Factory.new(:name, :address, :zip) do def greeting "Hello #{name}!" end end end let(:joe) { Customer.new('<NAME>', '123 Maple, Anytown NC', 12345) } it 'have instance variables' do [:name, :address, :zip].each do |arg| expect(joe.instance_variable_defined?("@#{arg}")).to be_truthy end expect(joe.name).to eq('<NAME>') end it 'respond with []' do expect(joe['name']).to eq('<NAME>') expect(joe[:name]).to eq('<NAME>') expect(joe[0]).to eq('<NAME>') end it 'have methods from block' do expect(joe.greeting).to eq('Hello <NAME>!') end end end <file_sep># module Decorators def self.included(receiver) receiver.extend ClassMethods end module ClassMethods def add_prefix(prefix) @watching = true @prefix = prefix end def method_added(method) return unless @watching @watching = false prefix = @prefix alias_method "real_#{method}", method define_method method do |*args, &block| prefix + send("real_#{method}", *args, &block) end end end end <file_sep>require_relative '../lib/library' require 'faker' describe Library do let(:library) { Library.new } let(:author) { library.create_author(Faker::Book.author) } let(:reader) { library.create_reader(Faker::Name.name) } let(:book) { library.create_book(Faker::Book.title, author) } it 'should have empty attributes on init' do expect(library.attributes.map(&:size)).to eq([0, 0, 0, 0]) end it 'should log book orders' do expect { reader.take(book) } .to change { library.orders.size } .from(0) .to(1) end end describe 'Program' do let(:library) { Library.new } 5.times do |i| let!("author#{i}") { library.create_author(Faker::Book.author) } let!("reader#{i}") { library.create_reader(Faker::Name.name) } let!("book#{i}") { library.create_book(Faker::Book.title, send("author#{i}")) } end before do 2.times { reader0.take(book0) } 3.times { reader1.take(book1) } 1.times { reader2.take(book2) } 0.times { reader3.take(book3) } 0.times { reader4.take(book4) } end it 'determine who often takes the book' do best_reader = library.best_reader expect(best_reader).to eq(reader1) end it 'determine what is the most popular book' do bestseller = library.bestseller expect(bestseller).to eq(book1) end it 'determine how many people ordered one of the three most popular books' do arr = library.top_books(3) expect(arr[0]).to eq(book1) expect(arr[1]).to eq(book0) expect(arr[2]).to eq(book2) end it 'save and restore all library data from file' do library.save other_lib = Library.load expect(other_lib).to eq(library) end end
36a6e9f3ed2d1b70bb612011bc0fee0ff5302979
[ "Ruby" ]
14
Ruby
BjornMelgaard/rubygarage_homework
eebb814df4ca42a77596ac5d1a01d5fce7ffea6f
bdf9837dfbc081b5591bde22e82eb1d3e1f12dcc
refs/heads/master
<file_sep>//add.js ``` module.exports = function add(a,b) { return a + b; } ``` var add = require('./add').. 它是同步的,浏览器除了加载该文件,什么事情也做不了。 提出了异步模块AMD<file_sep># 升级某版本xcode后,执行git命令 问题:Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command. 解决:sudo xcodebuild -license [csdn](https://blog.csdn.net/yabusai/article/details/37690783)<file_sep>### 通过nodejs实现前后端分离 #### 开发 1. 利用nodejs中的express框架开启本地服务器 2. 利用nodejs的http-proxy-middleware插件将客户发往nodejs的请求转发给真正的服务器,让nodejs作为中间层 3. 前台使用假数据。通过API文档,利用mock来返回一些假数据 #### 部署 1. 前端代码,利用webpack打包成静态压缩文件 2. nodejs服务器上,利用pm2负载均衡 [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware) [where to learn from](http://www.cnblogs.com/chenjg/p/6992062.htm) ### don't konw Nginx + nodejs + server [compare](https://segmentfault.com/a/1190000009329474?_ea=2038402)<file_sep>var values = [1,2,3,4,5,6,7,8,9]; var answer = sum(values); document.getElementById('answer').innerHTML = answer;<file_sep># in-web-3.0 some understanding about frontEnd and afterEnd > just want to show : **I'm not standing still, I'm on my way.** 1. 前后端分离 2. 服务端渲染or客户端浏览器渲染<file_sep>function reduce(arr,iteratee) { var index = 0, length = arr.length, memo = arr[index]; for(index +=1;index<length;index+=1) { memo = iteratee(memo,arr[index]) } return memo; }<file_sep>function sum(arr) { return reduce(arr,add); }<file_sep>将文件分为多个JavaScript文件,可以重用,但是有如下问题: * 缺乏依赖解析,对文件执行顺序有要求 * 全局命令空间污染<file_sep>通过将每个文件封装到IIFE中,所有的本地变量都保留在函数作用域中,不会污染全局变量。 通过引入myApp对象来访问这些函数 不过这并不完美,依然存在问题: * 缺乏依赖解析,文件顺序依然重要 * 全局命令空间污染,全局变量的数量变成了1,但还不是0。<file_sep>### 实现服务端渲染 express+ejs(jade) react+next.js
5bfe1aac5c7a8fdfb823fffe42b689225863c845
[ "Markdown", "JavaScript" ]
10
Markdown
SeekYou/in-web-3.0
0470d4e723e1a8d4aad09b24e3cdb8b3a2e3098a
d13f7d5a9020397acfadc55fb74a1db3d01b5cf0
refs/heads/master
<repo_name>hifghg/bots-dota2<file_sep>/mode_farm_generic.lua local functions = require( GetScriptDirectory() .."/utility/functions") local constants = require( GetScriptDirectory() .."/utility/constants") local player_desires = require( GetScriptDirectory() .."/utility/player_desires") local move = require( GetScriptDirectory() .."/utility/move") local attack = require( GetScriptDirectory() .."/utility/attack") local memory = require( GetScriptDirectory() .."/utility/memory") local M = {} function GetDesire() return functions.GetNormalizedDesire( player_desires.GetDesire("Bot_Mode_Farm"), constants.MAX_FARM_DESIRE) end
c98d81b1a16f2bd0b34a3be1349ef1d1466ba173
[ "Lua" ]
1
Lua
hifghg/bots-dota2
43bb2be2fef231b72e9bd866733b03c745659e7c
c341521dfdc7940af824c7f376487acd8ba8027f
refs/heads/master
<repo_name>5ju4ypzz/QL_SinhVien<file_sep>/QLY_Sinhvien/frmLop_03.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLY_Sinhvien { public partial class frmLop_03 : Form { DataSet dsLop = new DataSet(); bool blnThem = false; void DieuKhienKhiBinhThuong() { if (Mypublic.strQuyenSD == "AdminKhoa") { btnThem.Enabled = true; btnChinhsua.Enabled = true; btnXoa.Enabled = true; } else { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnXoa.Enabled = false; } btnLuu.Enabled = false; btnKhongluu.Enabled = false; btnDong.Enabled = true; txtMSLop.ReadOnly = true; txtMSLop.BackColor = Color.White; txtTenLop.ReadOnly = true; txtTenLop.BackColor = Color.White; txtKhoaHoc.ReadOnly = true; txtKhoaHoc.BackColor = Color.White; } void DieuKhienKhiThem() { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnLuu.Enabled = true; btnKhongluu.Enabled = true; btnXoa.Enabled = false; btnDong.Enabled = false; txtKhoaHoc.ReadOnly = false; txtMSLop.ReadOnly = false; txtTenLop.ReadOnly = false; txtKhoaHoc.Clear(); txtMSLop.Clear(); txtTenLop.Clear(); txtMSLop.Focus(); } void DieuKhienKhiChinhSua() { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnLuu.Enabled = true; btnKhongluu.Enabled = true; btnXoa.Enabled = false; btnDong.Enabled = false; txtKhoaHoc.ReadOnly = false; txtTenLop.ReadOnly = false; txtTenLop.Focus(); } void NhanDuLieu() { dsLop.Clear(); string strSelect = "Select * From Lop"; Mypublic.OpenData(strSelect, dsLop, "Lop"); dgvLop.DataSource = dsLop; dgvLop.DataMember = "Lop"; } void GanDuLieu() { if (dsLop.Tables["Lop"].Rows.Count > 0) { txtMSLop.Text = dgvLop[0, dgvLop.CurrentRow.Index].Value.ToString(); txtTenLop.Text = dgvLop[1, dgvLop.CurrentRow.Index].Value.ToString(); txtKhoaHoc.Text = dgvLop[2, dgvLop.CurrentRow.Index].Value.ToString(); } else { txtKhoaHoc.Clear(); txtMSLop.Clear(); txtTenLop.Clear(); } } public frmLop_03() { InitializeComponent(); } private void frmLop_03_Load(object sender, EventArgs e) { txtMSLop.MaxLength = 8; txtTenLop.MaxLength = 40; NhanDuLieu(); GanDuLieu(); dgvLop.Width = 440; dgvLop.Columns[0].Width = 95; dgvLop.Columns[0].HeaderText = "Mã số"; dgvLop.Columns[1].Width = 190; dgvLop.Columns[1].HeaderText = "Tên lớp"; dgvLop.Columns[2].Width = 95; dgvLop.Columns[2].HeaderText = "Khóa học"; dgvLop.AllowUserToAddRows = false; dgvLop.AllowUserToDeleteRows = false; dgvLop.EditMode = DataGridViewEditMode.EditProgrammatically; DieuKhienKhiBinhThuong(); } private void dgvLop_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void dgvLop_CellClick(object sender, DataGridViewCellEventArgs e) { GanDuLieu(); } private void btnThem_Click(object sender, EventArgs e) { blnThem = true; DieuKhienKhiThem(); } private void btnChinhsua_Click(object sender, EventArgs e) { DieuKhienKhiChinhSua(); } void LuuLopMoi() { string strSql = "Insert Into Lop Values(@MSLop,@TenLop,@KhoaHoc)"; if (Mypublic.conMyConnection.State==ConnectionState.Closed) { Mypublic.conMyConnection.Open(); } SqlCommand cmdCommand = new SqlCommand(strSql, Mypublic.conMyConnection); cmdCommand.Parameters.AddWithValue("@MSLop", txtMSLop.Text); cmdCommand.Parameters.AddWithValue("@TenLop", txtTenLop.Text); cmdCommand.Parameters.AddWithValue("@KhoaHoc", txtKhoaHoc.Text); cmdCommand.ExecuteNonQuery(); Mypublic.conMyConnection.Close(); dsLop.Clear(); NhanDuLieu(); GanDuLieu(); blnThem = false; DieuKhienKhiBinhThuong(); } void CapNhapLop() { string strSql = "Update Lop Set TenLop = @TenLop, KhoaHoc = @KhoaHoc Where MSLop = @MSLop"; if (Mypublic.conMyConnection.State == ConnectionState.Closed) { Mypublic.conMyConnection.Open(); } SqlCommand cmdCommand = new SqlCommand(strSql, Mypublic.conMyConnection); cmdCommand.Parameters.AddWithValue("@MSLop", txtMSLop.Text); cmdCommand.Parameters.AddWithValue("@TenLop", txtTenLop.Text); cmdCommand.Parameters.AddWithValue("@KhoaHoc", txtKhoaHoc.Text); cmdCommand.ExecuteNonQuery(); Mypublic.conMyConnection.Close(); dgvLop[1, dgvLop.CurrentRow.Index].Value = txtTenLop.Text; dgvLop[2, dgvLop.CurrentRow.Index].Value = txtKhoaHoc.Text; DieuKhienKhiBinhThuong(); } private void btnLuu_Click(object sender, EventArgs e) { int khoa; if ((txtMSLop.Text == "") || (txtTenLop.Text == "") || (txtKhoaHoc.Text == "") || (!int.TryParse(txtKhoaHoc.Text, out khoa)) || (khoa <= 0)) { MessageBox.Show("Lỗi nhập dữ liệu!"); } else { if (blnThem) { if (Mypublic.TonTaiKhoaChinh(txtMSLop.Text, "MSLop", "Lop")) { MessageBox.Show("Mã số lớp này đã có rồi!"); txtMSLop.Focus(); } else { LuuLopMoi(); } } else { CapNhapLop(); } } } private void btnXoa_Click(object sender, EventArgs e) { if (Mypublic.TonTaiKhoaChinh(txtMSLop.Text,"MSLop","SinhVien")) { MessageBox.Show("Phải xóa sinh viên thuộc lớp trước!"); } else { DialogResult blnDongY; blnDongY = MessageBox.Show("Bạn thật sự muốn xóa?", "Xác nhận", MessageBoxButtons.YesNo); if (blnDongY==DialogResult.Yes) { string strDelete = "Delete Lop Where MSLop = @MSLop"; if (Mypublic.conMyConnection.State==ConnectionState.Closed) { Mypublic.conMyConnection.Open(); } SqlCommand cmdConmand = new SqlCommand(strDelete, Mypublic.conMyConnection); cmdConmand.Parameters.AddWithValue("@MSLop", txtMSLop.Text); cmdConmand.ExecuteNonQuery(); Mypublic.conMyConnection.Close(); dgvLop.Rows.RemoveAt(dgvLop.CurrentRow.Index); GanDuLieu(); } } } private void btnKhongluu_Click(object sender, EventArgs e) { blnThem = false; GanDuLieu(); DieuKhienKhiBinhThuong(); } private void btnDong_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>/QLY_Sinhvien/frmLop.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace QLY_Sinhvien { public partial class frmLop : Form { DataSet dsLop = new DataSet(); SqlDataAdapter daLop = new SqlDataAdapter(); BindingSource bsLop = new BindingSource(); bool blnThem = false; void DieuKhienViTri() { if (bsLop.Position > 0) { btnDau.Enabled = true; btnTruoc.Enabled = true; } else { btnDau.Enabled = false; btnTruoc.Enabled = false; } if (bsLop.Position < bsLop.Count - 1) { btnKe.Enabled = true; btnCuoi.Enabled = true; } else { btnKe.Enabled = false; btnCuoi.Enabled = false; } txtVitri.Text = (bsLop.Position + 1) + "/" + bsLop.Count; } void DieuKhienKhiBinhThuong() { if (Mypublic.strQuyenSD=="AdminKhoa") { btnThem.Enabled = true; btnChinhsua.Enabled = true; btnXoa.Enabled = true; } else { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnXoa.Enabled = false; } btnLuu.Enabled = false; btnKhongluu.Enabled = false; btnDong.Enabled = true; txtMSLop.ReadOnly = true; txtMSLop.BackColor = Color.White; txtTenLop.ReadOnly = true; txtTenLop.BackColor = Color.White; txtKhoaHoc.ReadOnly = true; txtKhoaHoc.BackColor = Color.White; cboLop.Enabled = true; DieuKhienViTri(); } void DieuKhienKhiThem() { btnDau.Enabled = false; btnTruoc.Enabled = false; btnKe.Enabled = false; btnCuoi.Enabled = false; btnThem.Enabled = false; btnChinhsua.Enabled = false; btnLuu.Enabled = true; btnKhongluu.Enabled = true; btnXoa.Enabled = false; btnDong.Enabled = false; txtKhoaHoc.ReadOnly = false; txtMSLop.ReadOnly = false; txtTenLop.ReadOnly = false; txtKhoaHoc.Clear(); txtMSLop.Clear(); txtTenLop.Clear(); cboLop.Enabled = false; cboLop.SelectedIndex = -1; txtVitri.Text = bsLop.Count + "/" + bsLop.Count; txtMSLop.Focus(); } void DieuKhienKhiChinhSua() { btnDau.Enabled = false; btnTruoc.Enabled = false; btnKe.Enabled = false; btnCuoi.Enabled = false; btnThem.Enabled = false; btnChinhsua.Enabled = false; btnLuu.Enabled = true; btnKhongluu.Enabled = true; btnXoa.Enabled = false; btnDong.Enabled = false; txtKhoaHoc.ReadOnly = false; txtTenLop.ReadOnly = false; cboLop.Enabled = false; txtTenLop.Focus(); } void GanDuLieu() { txtMSLop.DataBindings.Add(new Binding("Text", bsLop, "MSLop")); txtTenLop.DataBindings.Add(new Binding("Text",bsLop,"TenLop")); txtKhoaHoc.DataBindings.Add(new Binding("Text", bsLop, "KhoaHoc")); } public frmLop() { InitializeComponent(); } private void frmLop_Load(object sender, EventArgs e) { string strSelect = "Select * From Lop"; Mypublic.OpenData(strSelect, dsLop, "Lop", daLop); bsLop.DataSource = dsLop; bsLop.DataMember = "Lop"; cboLop.DisplayMember = "TenLop"; cboLop.ValueMember = "MSLop"; txtMSLop.MaxLength = 8; txtTenLop.MaxLength = 40; txtVitri.ReadOnly = true; txtVitri.BackColor = Color.White; GanDuLieu(); DieuKhienKhiBinhThuong(); } private void cboLop_SelectedIndexChanged(object sender, EventArgs e) { if (cboLop.SelectedIndex!=-1) { bsLop.Position = cboLop.SelectedIndex; DieuKhienViTri(); if (Mypublic.strQuyenSD=="AdminLop") { if (cboLop.SelectedValue.ToString()==Mypublic.strLop) { btnChinhsua.Enabled = true; } else { btnChinhsua.Enabled = false; } } } } private void btnDau_Click(object sender, EventArgs e) { bsLop.MoveFirst(); btnDau.Enabled = false; btnTruoc.Enabled = false; btnKe.Enabled = true; btnCuoi.Enabled = true; txtVitri.Text = (bsLop.Position + 1) + "/" + bsLop.Count; } private void btnTruoc_Click(object sender, EventArgs e) { bsLop.MovePrevious(); btnKe.Enabled = true; btnCuoi.Enabled = true; if (bsLop.Position==0) { btnDau.Enabled = false; btnTruoc.Enabled = false; } txtVitri.Text = (bsLop.Position + 1) + "/" + bsLop.Count; } private void btnKe_Click(object sender, EventArgs e) { bsLop.MoveNext(); btnDau.Enabled = true; btnTruoc.Enabled = true; if (bsLop.Position==bsLop.Count-1) { btnKe.Enabled = false; btnCuoi.Enabled = false; } txtVitri.Text = (bsLop.Position + 1) + "/" + bsLop.Count; } private void btnCuoi_Click(object sender, EventArgs e) { bsLop.MoveLast(); btnDau.Enabled = true; btnTruoc.Enabled = true; btnKe.Enabled = false; btnCuoi.Enabled = false; txtVitri.Text = (bsLop.Position + 1) + "/" + bsLop.Count; } private void btnThem_Click(object sender, EventArgs e) { blnThem = true; bsLop.AddNew(); DieuKhienKhiThem(); } private void btnChinhsua_Click(object sender, EventArgs e) { DieuKhienKhiChinhSua(); } private void btnLuu_Click(object sender, EventArgs e) { int Khoa; if ((txtMSLop.Text=="")||(txtTenLop.Text=="")||(!int.TryParse(txtKhoaHoc.Text,out Khoa))||(Khoa<=0)) { MessageBox.Show("Lỗi nhập dữ liệu !"); } else { if ((blnThem)&(Mypublic.TonTaiKhoaChinh(txtMSLop.Text,"MSLop","Lop"))) { MessageBox.Show("Mã số lớp này đã có rồi!"); txtMSLop.Focus(); } else { bsLop.EndEdit(); daLop.Update(dsLop, "Lop"); dsLop.AcceptChanges(); blnThem = false; DieuKhienKhiBinhThuong(); } } } private void btnKhongluu_Click(object sender, EventArgs e) { bsLop.EndEdit(); dsLop.RejectChanges(); blnThem = false; DieuKhienKhiBinhThuong(); } private void btnXoa_Click(object sender, EventArgs e) { if (Mypublic.TonTaiKhoaChinh(txtMSLop.Text,"MSLop","SinhVien")) { MessageBox.Show("Phải xóa sinh viên thuộc lớp trước!"); } else { DialogResult blnDongY; blnDongY = MessageBox.Show("Bạn thật sự muốn xóa?", "Xác nhận", MessageBoxButtons.YesNo); if (blnDongY==DialogResult.Yes) { bsLop.RemoveCurrent(); daLop.Update(dsLop, "Lop"); dsLop.AcceptChanges(); } } DieuKhienKhiBinhThuong(); } private void btnDong_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>/QLY_Sinhvien/MyPublic.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; namespace QLY_Sinhvien { public static class Mypublic { public static SqlConnection conMyConnection; public static string strsever, strMSSV, strLop, strQuyenSD, strHK, strNK; public static void ConnectionDatabase() { string strConn = "Server= " + strsever + "; Database = QL_SinhVien; Integrated Security = false; UID = TN207User; PWD = <PASSWORD>"; conMyConnection = new SqlConnection(); conMyConnection.ConnectionString = strConn; try { conMyConnection.Open(); } catch (Exception) { } } public static void OpenData(string strSelect, DataSet dsDatabase, string strTableName, SqlDataAdapter daDataAdapter) { try { if (conMyConnection.State == ConnectionState.Closed) conMyConnection.Open(); daDataAdapter.SelectCommand = new SqlCommand(strSelect, conMyConnection); SqlCommandBuilder cmbCommandBuider = new SqlCommandBuilder(daDataAdapter); daDataAdapter.Fill(dsDatabase, strTableName); conMyConnection.Close(); } catch (Exception) { } } public static void OpenData(string strSelect, DataSet dsDatabase, string strTableName) { SqlDataAdapter daDataAdapter = new SqlDataAdapter(); try { if (conMyConnection.State == ConnectionState.Closed) conMyConnection.Open(); daDataAdapter.SelectCommand = new SqlCommand(strSelect, conMyConnection); daDataAdapter.Fill(dsDatabase, strTableName); conMyConnection.Close(); } catch (Exception) { } } public static string MaHoaPassword(string strPassword) { string strTemp1, strTemp2; int i, n; strTemp1 = ""; strTemp2 = ""; n = strPassword.Length; for (i = 0; i < n;i=i+2 ) { strTemp1 += strPassword[i]; if (n > i + 1) strTemp2 += strPassword[i + 1]; } return (strTemp1+strTemp2); } public static bool TonTaiKhoaChinh(string strGiaTri, string strTenTruong, string strTable) { SqlCommand cmdCommand; SqlDataReader drReader; bool blnResult = false; try { string sqlSelect = "Select 1 From" + strTable + " Where " + strTenTruong + "='" + strGiaTri + "'"; if (conMyConnection.State == ConnectionState.Closed) conMyConnection.Open(); cmdCommand = new SqlCommand(sqlSelect, conMyConnection); drReader = cmdCommand.ExecuteReader(); if(drReader.HasRows) blnResult = true; drReader.Close(); conMyConnection.Close(); } catch (Exception) { } return blnResult; } public static void XacDinhHKNK() { int thang = DateTime.Today.Month; if (thang <= 5) { strHK = "2"; strNK = (DateTime.Today.Year - 1) + "-" + (DateTime.Today.Year); } else if (thang <= 7) { strHK = "3"; strNK = (DateTime.Today.Year - 1) + "-" + (DateTime.Today.Year); } else { strHK = "1"; strNK = (DateTime.Today.Year) + "-" + (DateTime.Today.Year + 1); } } } } <file_sep>/QLY_Sinhvien/frmMain.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLY_Sinhvien { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private void mnugthieu_Click(object sender, EventArgs e) { MessageBox.Show("Chương trình quản lý sinh viên 2017","Giới thiệu"); } private void mnudong_Click(object sender, EventArgs e) { Application.Exit(); } private void mnudangnhap_Click(object sender, EventArgs e) { } private void frmMain_Load(object sender, EventArgs e) { frmdangnhap fDangNhap = new frmdangnhap(this); fDangNhap.ShowDialog(); } private void mnuLop_Click(object sender, EventArgs e) { } private void lớpToolStripMenuItem_Click(object sender, EventArgs e) { frmLop flop = new frmLop(); flop.ShowDialog(); } private void lớpGirdViewToolStripMenuItem_Click(object sender, EventArgs e) { frmLop_02 flop2 = new frmLop_02(); flop2.ShowDialog(); } private void lớpCommandToolStripMenuItem_Click(object sender, EventArgs e) { frmLop_03 fLop03 = new frmLop_03(); fLop03.ShowDialog(); } private void mnusinhvien_Click(object sender, EventArgs e) { frmSinhVienTheoLop fsv = new frmSinhVienTheoLop(); fsv.ShowDialog(); } } } <file_sep>/QLY_Sinhvien/frmSinhVienTheoLop.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace QLY_Sinhvien { public partial class frmSinhVienTheoLop : Form { DataSet dsSinhVien = new DataSet(); DataSet dsLop = new DataSet(); DataView dvSinhVien = new DataView(); DataSet dsQuyenSD = new DataSet(); int ViTriLop, ThemSua = 0; void DieuKhienKhiBinhThuong() { if (Mypublic.strQuyenSD == "AdminKhoa") { btnThem.Enabled = true; btnChinhsua.Enabled = true; btnXoa.Enabled = true; } else { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnXoa.Enabled = false; } btnLuu.Enabled = false; btnKhongluu.Enabled = false; btnDong.Enabled = true; txtMSSV.ReadOnly = true; txtMSSV.BackColor = Color.White; txtTen.ReadOnly = true; txtTen.BackColor = Color.White; txtHoLot.ReadOnly = true; txtHoLot.BackColor = Color.White; } void DieuKhienKhiThem() { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnLuu.Enabled = true; btnKhongluu.Enabled = true; btnXoa.Enabled = false; btnDong.Enabled = false; txtMSSV.ReadOnly = false; txtTen.ReadOnly = false; txtHoLot.ReadOnly = false; txtMSSV.Clear(); txtTen.Clear(); txtHoLot.Focus(); } void DieuKhienKhiChinhSua() { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnLuu.Enabled = true; btnKhongluu.Enabled = true; btnXoa.Enabled = false; btnDong.Enabled = false; txtTen.ReadOnly = false; txtHoLot.Focus(); } void NhanDuLieu() { string strSelect = "Select * From SinhVien"; Mypublic.OpenData(strSelect, dsSinhVien, "SinhVien"); } void GanDuLieu() { if (dvSinhVien.Count > 0) { txtMSSV.Text = dgvSinhVien[0, dgvSinhVien.CurrentRow.Index].Value.ToString(); txtHoLot.Text = dgvSinhVien[1, dgvSinhVien.CurrentRow.Index].Value.ToString(); txtTen.Text = dgvSinhVien[2, dgvSinhVien.CurrentRow.Index].Value.ToString(); if (dgvSinhVien[3, dgvSinhVien.CurrentRow.Index].Value.ToString() == "Nam") { rdoNam.Checked = true; } else { rdoNu.Checked = true; } dtpNgaySinh.Value = DateTime.Parse(dgvSinhVien[4, dgvSinhVien.CurrentRow.Index].Value.ToString()); cboQuyenSD.SelectedIndex = cboQuyenSD.FindString(dgvSinhVien[7, dgvSinhVien.CurrentRow.Index].Value.ToString()); } else { txtHoLot.Clear(); txtMSSV.Clear(); txtTen.Clear(); rdoNam.Checked = true; dtpNgaySinh.Value = DateTime.Today; cboQuyenSD.SelectedIndex = -1; } } public frmSinhVienTheoLop() { InitializeComponent(); } private void dateTimePicker3_ValueChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { } private void frmSinhVienTheoLop_Load(object sender, EventArgs e) { string strSelect = "Select MSLop, TenLop From Lop"; Mypublic.OpenData(strSelect, dsLop, "Lop"); cboLop.DataSource = dsLop.Tables["Lop"]; cboLop.DisplayMember = "TenLop"; cboLop.ValueMember = "MSLop"; dsQuyenSD.Tables.Add("DSQuyenSD"); dsQuyenSD.Tables["DSQuyenSD"].Columns.Add("QuyenSD"); dsQuyenSD.Tables["DSQuyenSD"].Rows.Add("User"); dsQuyenSD.Tables["DSQuyenSD"].Rows.Add("AdminLop"); dsQuyenSD.Tables["DSQuyenSD"].Rows.Add("AdminKhoa"); cboQuyenSD.DataSource = dsQuyenSD; cboQuyenSD.DisplayMember = "DSQuyenSD.QuyenSD"; cboQuyenSD.ValueMember = "DSQuyenSD.QuyenSD"; txtHoLot.MaxLength = 30; txtTen.MaxLength = 30; txtMSSV.MaxLength = 8; NhanDuLieu(); dvSinhVien.Table = dsSinhVien.Tables["SinhVien"]; dvSinhVien.RowFilter = "MSLop like'" + cboLop.SelectedValue + "'"; dgvSinhVien.DataSource = dvSinhVien; dgvSinhVien.Width = 790; dgvSinhVien.AllowUserToAddRows = false; dgvSinhVien.AllowUserToDeleteRows = false; dgvSinhVien.Columns[0].Width = 85; dgvSinhVien.Columns[0].HeaderText = "Mã số"; dgvSinhVien.Columns[1].Width = 140; dgvSinhVien.Columns[1].HeaderText = "Họ lót"; dgvSinhVien.Columns[2].Width = 60; dgvSinhVien.Columns[2].HeaderText = "Tên"; dgvSinhVien.Columns[3].Width = 50; dgvSinhVien.Columns[3].HeaderText = "Phái"; dgvSinhVien.Columns[4].Width = 100; dgvSinhVien.Columns[4].HeaderText = "Ngày sinh"; dgvSinhVien.Columns[5].Width = 90; dgvSinhVien.Columns[5].HeaderText = "MS Lớp"; dgvSinhVien.Columns[6].Width = 100; dgvSinhVien.Columns[6].HeaderText = "Mật khẩu"; dgvSinhVien.Columns[7].Width = 100; dgvSinhVien.Columns[7].HeaderText = "Quyền SD"; dgvSinhVien.EditMode = DataGridViewEditMode.EditProgrammatically; dgvSinhVien.CellFormatting += new DataGridViewCellFormattingEventHandler(this.dgvSinhVien_CellFormatting); GanDuLieu(); DieuKhienKhiBinhThuong(); } private void dgvSinhVien_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex==6) { if (e.Value!=null) { e.Value = new string('*', e.Value.ToString().Length); } } } } } <file_sep>/QLY_Sinhvien/Login.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLY_Sinhvien { public partial class frmdangnhap : Form { int intSoLanDangNhap; private frmMain fMain; public frmdangnhap(frmMain fm) : this() { fMain = fm; } public frmdangnhap() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void btndong_Click(object sender, EventArgs e) { if (Mypublic.conMyConnection != null) Mypublic.conMyConnection = null; fMain.mnuDuLieu.Enabled = false; fMain.mnucapnhat.Enabled = false; fMain.mnudoipass.Enabled = false; fMain.mnuthoatDN.Enabled = false; this.Close(); } private void frmdangnhap_Load(object sender, EventArgs e) { intSoLanDangNhap = 0; txtMaychu.Text = "Localhost"; txtMSSV.Text = "1065779"; txtMatkhau.Text = "1679057"; txtMatkhau.PasswordChar = '♥'; txtMSSV.Focus(); } private void btndangnhap_Click(object sender, EventArgs e) { SqlCommand cmdCommand; SqlDataReader drReader; string sqlSelect, strPasswordSV; Mypublic.strsever = txtMaychu.Text; try { Mypublic.ConnectionDatabase(); if (Mypublic.conMyConnection.State == ConnectionState.Open) { Mypublic.strMSSV = txtMSSV.Text; //strPasswordSV = txtMatkhau.Text; strPasswordSV = Mypublic.MaHoaPassword(txtMatkhau.Text); sqlSelect = "Select MSLop, QuyenSD From SinhVien Where MSSV = @MSSV And MatKhau = @MatKhau"; cmdCommand = new SqlCommand(sqlSelect, Mypublic.conMyConnection); cmdCommand.Parameters.AddWithValue("@MSSV", txtMSSV.Text); cmdCommand.Parameters.AddWithValue("@MatKhau", txtMatkhau.Text); drReader = cmdCommand.ExecuteReader(); if (drReader.HasRows) { drReader.Read(); Mypublic.strLop = drReader.GetString(0); Mypublic.strQuyenSD = drReader.GetString(1); drReader.Close(); Mypublic.XacDinhHKNK(); fMain.mnuDuLieu.Enabled = true; fMain.mnucapnhat.Enabled = true; fMain.mnudangnhap.Enabled = true; fMain.mnudoipass.Enabled = true; fMain.mnuthoatDN.Enabled = true; MessageBox.Show("Đăng nhập thành công", "Thông báo"); Mypublic.conMyConnection.Close(); this.Close(); } else if (intSoLanDangNhap < 2) { MessageBox.Show("MSSV hoặc mật khẩu sai!", "Thông báo"); intSoLanDangNhap++; txtMSSV.Focus(); } else { MessageBox.Show("Lỗi đăng nhâp, Form sẽ đóng", "Thông báo"); Mypublic.conMyConnection.Close(); fMain.mnuDuLieu.Enabled = false; fMain.mnucapnhat.Enabled = false; fMain.mnudoipass.Enabled = false; fMain.mnuthoatDN.Enabled = false; } } else MessageBox.Show("Kết nối không thành công", "Thông báo"); } catch (Exception) { MessageBox.Show("Lỗi khi thực hiện kết nối!", "Thông báo"); } } } } <file_sep>/README.md # QL_SinhVien .NET trainning <file_sep>/QLY_Sinhvien/frmdangnhap.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLY_Sinhvien { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private void mnugthieu_Click(object sender, EventArgs e) { MessageBox.Show("Chương trình quản lý sinh viên 2017","Giới thiệu"); } private void mnudong_Click(object sender, EventArgs e) { Application.Exit(); } private void mnudangnhap_Click(object sender, EventArgs e) { } private void frmMain_Load(object sender, EventArgs e) { frmdangnhap fDangNhap = new frmdangnhap(this); fDangNhap.ShowDialog(); } } } <file_sep>/QLY_Sinhvien/frmLop_02.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace QLY_Sinhvien { public partial class frmLop_02 : Form { DataSet dsLop = new DataSet(); SqlDataAdapter daLop = new SqlDataAdapter(); BindingSource bsLop = new BindingSource(); bool blnThem = false; void DieuKhienKhiBinhThuong() { if (Mypublic.strQuyenSD == "AdminKhoa") { btnThem.Enabled = true; btnChinhsua.Enabled = true; btnXoa.Enabled = true; } else { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnXoa.Enabled = false; } btnLuu.Enabled = false; btnKhongluu.Enabled = false; btnDong.Enabled = true; txtMSLop.ReadOnly = true; txtMSLop.BackColor = Color.White; txtTenLop.ReadOnly = true; txtTenLop.BackColor = Color.White; txtKhoaHoc.ReadOnly = true; txtKhoaHoc.BackColor = Color.White; } void DieuKhienKhiThem() { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnLuu.Enabled = true; btnKhongluu.Enabled = true; btnXoa.Enabled = false; btnDong.Enabled = false; txtKhoaHoc.ReadOnly = false; txtMSLop.ReadOnly = false; txtTenLop.ReadOnly = false; txtKhoaHoc.Clear(); txtMSLop.Clear(); txtTenLop.Clear(); txtMSLop.Focus(); } void DieuKhienKhiChinhSua() { btnThem.Enabled = false; btnChinhsua.Enabled = false; btnLuu.Enabled = true; btnKhongluu.Enabled = true; btnXoa.Enabled = false; btnDong.Enabled = false; txtKhoaHoc.ReadOnly = false; txtTenLop.ReadOnly = false; txtTenLop.Focus(); } void GanDuLieu() { txtMSLop.DataBindings.Add(new Binding("Text", bsLop, "MSLop")); txtTenLop.DataBindings.Add(new Binding("Text", bsLop, "TenLop")); txtKhoaHoc.DataBindings.Add(new Binding("Text", bsLop, "KhoaHoc")); } public frmLop_02() { InitializeComponent(); } private void btnThem_Click(object sender, EventArgs e) { blnThem = true; bsLop.AddNew(); bsLop.Position = bsLop.Count; dgvLop.CurrentCell = dgvLop[0, bsLop.Count - 1]; DieuKhienKhiThem(); } private void btnChinhsua_Click(object sender, EventArgs e) { DieuKhienKhiChinhSua(); } private void btnLuu_Click(object sender, EventArgs e) { int Khoa; if ((txtMSLop.Text == "") || (txtTenLop.Text == "") || (!int.TryParse(txtKhoaHoc.Text, out Khoa)) || (Khoa <= 0)) { MessageBox.Show("Lỗi nhập dữ liệu !"); } else { if ((blnThem) & (Mypublic.TonTaiKhoaChinh(txtMSLop.Text, "MSLop", "Lop"))) { MessageBox.Show("Mã số lớp này đã có rồi!"); txtMSLop.Focus(); } else { bsLop.EndEdit(); daLop.Update(dsLop, "Lop"); dsLop.AcceptChanges(); blnThem = false; DieuKhienKhiBinhThuong(); } } } private void btnKhongluu_Click(object sender, EventArgs e) { bsLop.EndEdit(); dsLop.RejectChanges(); blnThem = false; DieuKhienKhiBinhThuong(); } private void btnXoa_Click(object sender, EventArgs e) { if (Mypublic.TonTaiKhoaChinh(txtMSLop.Text, "MSLop", "SinhVien")) { MessageBox.Show("Phải xóa sinh viên thuộc lớp trước!"); } else { DialogResult blnDongY; blnDongY = MessageBox.Show("Bạn thật sự muốn xóa?", "Xác nhận", MessageBoxButtons.YesNo); if (blnDongY == DialogResult.Yes) { bsLop.RemoveCurrent(); daLop.Update(dsLop, "Lop"); dsLop.AcceptChanges(); } } DieuKhienKhiBinhThuong(); } private void btnDong_Click(object sender, EventArgs e) { this.Close(); } private void frmLop_02_Load(object sender, EventArgs e) { string strSelect = "Select * From Lop"; Mypublic.OpenData(strSelect, dsLop, "Lop", daLop); bsLop.DataSource = dsLop; bsLop.DataMember = "Lop"; txtMSLop.MaxLength = 8; txtTenLop.MaxLength = 40; GanDuLieu(); dgvLop.DataSource = dsLop; dgvLop.DataMember = "Lop"; dgvLop.Width = 440; dgvLop.Columns[0].Width = 95; dgvLop.Columns[0].HeaderText = "Mã số"; dgvLop.Columns[1].Width = 190; dgvLop.Columns[1].HeaderText = "Tên lớp"; dgvLop.Columns[2].Width = 95; dgvLop.Columns[2].HeaderText = "Khóa học"; dgvLop.AllowUserToAddRows = false; dgvLop.AllowUserToDeleteRows = false; dgvLop.EditMode = DataGridViewEditMode.EditProgrammatically; DieuKhienKhiBinhThuong(); } private void dgvLop_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void dgvLop_CellClick(object sender, DataGridViewCellEventArgs e) { bsLop.Position = dgvLop.CurrentRow.Index; } } }
2bcbb6fad8dc19b866ce04dcf08fed3b3d2c088d
[ "Markdown", "C#" ]
9
C#
5ju4ypzz/QL_SinhVien
9fdfaf1cd8ced629910810b8eedbca2c4c4eaa96
b3fe0bac61727a3cb4312c7e73664deb56d90d15
refs/heads/master
<repo_name>vejvarm/clear_networks<file_sep>/dense_mnist_classifier.py import tensorflow as tf from matplotlib import pyplot as plt from tensorflow.keras.datasets import mnist from helpers import console_logger from Models import DenseClassifier LOGGER = console_logger(__name__, "DEBUG") TEST_SET_SIZE = 8000 BUFFER_SIZE = 10000 BATCH_SIZE = 64 HIDDEN_SIZE = 16 NUM_CLASSES = 10 OPTIMIZER = tf.keras.optimizers.Adam(learning_rate=1e-4) LOSS = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) METRICS = ['accuracy'] EPOCHS = 5 LOG_PERIOD = 100 LAYER_INDEX_NAME_DICT = None # defaults to what is implemented in the DenseClassifier class LOG_PATH = "./log/dense_mnist" if __name__ == '__main__': LOGGER.info("Import MNIST dataset.") (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 image_shape = x_train.shape[1:] LOGGER.debug(f"image_shape: {image_shape}") LOGGER.info("Convert datasets into data.Dataset structures.") ds_train = tf.data.Dataset.from_tensor_slices((x_train, y_train)) ds_testval = tf.data.Dataset.from_tensor_slices((x_test, y_test)) LOGGER.info("Split test set into test and validation set.") ds_test = ds_testval.take(TEST_SET_SIZE) ds_val = ds_testval.skip(TEST_SET_SIZE) LOGGER.info("Plot examples from the train dataset") for x, y in ds_train.take(2): plt.figure() plt.imshow(x) plt.title(y.numpy()) plt.show() LOGGER.info("Shuffle and batch datasets.") ds_train = ds_train.shuffle(BUFFER_SIZE).batch(BATCH_SIZE) ds_test = ds_test.batch(BATCH_SIZE) ds_val = ds_val.batch(BATCH_SIZE) LOGGER.info("Initialize Dense classifier model.") model = DenseClassifier(image_shape, HIDDEN_SIZE, NUM_CLASSES, LOG_PERIOD, LAYER_INDEX_NAME_DICT, LOG_PATH) LOGGER.info("Compile model.") model.compile(OPTIMIZER, LOSS, METRICS) LOGGER.info("Train model on training data.") history = model.fit(ds_train, epochs=EPOCHS, validation_data=ds_test) LOGGER.debug(f"model: {model.summary()}") # model.w_and_g_writer.close() # TODO: close the writer in the model class itself LOGGER.info("Evaluate model on validation data") metrics = model.evaluate(ds_val) LOGGER.debug(f"metrics: {metrics}")<file_sep>/helpers.py import logging import absl from matplotlib import pyplot as plt def console_logger(name=__name__, level=logging.WARNING): if not isinstance(level, (str, int)): raise TypeError("Logging level data type is not recognised. Should be str or int.") logger = logging.getLogger(name) if logger.hasHandlers(): logger.handlers.clear() logger.setLevel(level) formatter = logging.Formatter('%(levelname)7s (%(name)s) %(asctime)s - %(message)s', datefmt="%Y-%m-%d %H:%M:%S") if "tensorflow" in name: absl.logging.get_absl_handler().setFormatter(formatter) else: console = logging.StreamHandler() console.setLevel(level) console.setFormatter(formatter) logger.addHandler(console) return logger def plot_graphs(history, metric): plt.plot(history.history[metric]) plt.plot(history.history['val_'+metric], '') plt.xlabel("Epochs") plt.ylabel(metric) plt.legend([metric, 'val_'+metric]) plt.show()<file_sep>/Models.py # TODO: global extreme normalization # TODO: saving weights and gradients structures to files # TODO: plotting in something else than tensorboard import os from collections import defaultdict from typing import Tuple, Dict, Optional import tensorflow as tf from matplotlib import pyplot as plt from tensorflow.python.distribute import parameter_server_strategy from tensorflow.python.eager import backprop from tensorflow.python.keras.engine import data_adapter from tensorflow.python.keras.mixed_precision.experimental import loss_scale_optimizer as lso from tensorflow.keras import Model from tensorflow.keras.layers import Dense, Embedding, Flatten, SimpleRNN, GRU class BaseModel(Model): LayerIndex = int # index of the layer in the model.weights sequence LayerName = str # desired name of the layer ParamType = str # either "w" for weight or "b" for bias LayerInfo = Tuple[LayerName, ParamType] LayerIndexNameDict = Optional[Dict[LayerIndex, LayerInfo]] # either Dict or None def __init__(self, log_period: int, layer_index_name_dict: LayerIndexNameDict, log_path: str): """ Base model class for a clear network :param log_period (int): Period (in batches) for logging log weight and gradient values to files (0 == off) :param layer_index_name_dict (Opt[Dict[int: Tuple[str, str]]]): Dictionary of layers for logging :param log_path (str): Where to save the log and .proto files """ super(BaseModel, self).__init__() self.log_period = log_period self.layer_index_name_dict = layer_index_name_dict self.num_logged_layers = len(self.layer_index_name_dict) if self.log_period: self.w_and_g_summary = tf.summary.create_file_writer(log_path) # self.w_and_g_writer = tf.io.TFRecordWriter(os.path.join(log_path, "wg.proto")) self.figs = defaultdict(plt.figure) plt.ion() def train_step(self, data): """The logic for one training step. This method can be overridden to support custom training logic. This method is called by `Model.make_train_function`. This method should contain the mathemetical logic for one step of training. This typically includes the forward pass, loss calculation, backpropagation, and metric updates. Configuration details for *how* this logic is run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should be left to `Model.make_train_function`, which can also be overridden. Arguments: data: A nested structure of `Tensor`s. Returns: A `dict` containing values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s metrics are returned. Example: `{'loss': 0.2, 'accuracy': 0.7}`. """ # These are the only transformations `Model.fit` applies to user-input # data when a `tf.data.Dataset` is provided. These utilities will be exposed # publicly. data = data_adapter.expand_1d(data) x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) step = self.optimizer.iterations with backprop.GradientTape() as tape: y_pred = self(x, training=True) loss = self.compiled_loss(y, y_pred, sample_weight, regularization_losses=self.losses) trainable_variables = self.trainable_variables gradients = tape.gradient(loss, trainable_variables) # self._plot_gs(gradients) # TODO: save weights and gradients to files if self.log_period: tf.cond(tf.cast(step % self.log_period, tf.bool), true_fn=lambda: None, false_fn=lambda: self._log_w_and_g(self.weights, gradients, step)) self.optimizer.apply_gradients(zip(gradients, trainable_variables)) # The _minimize call does a few extra steps unnecessary in most cases, # such as loss scaling and gradient clipping. # _minimize(self.distribute_strategy, tape, self.optimizer, loss, self.trainable_variables) self.compiled_metrics.update_state(y, y_pred, sample_weight) return {m.name: m.result() for m in self.metrics} def _plot_gs(self, gradients): for i, (name, ptype) in self.layer_index_name_dict.items(): fig = self.figs[i] # draw figures if ptype == "w": plt.pcolormesh(gradients[i]) elif ptype == "b": plt.pcolormesh(tf.expand_dims(gradients[i], 1)) # redraw the figure: fig.canvas.draw() def _log_w_and_g(self, weights_list, gradients_list, step): """ R = positive gradient (0. = no positive gradient, 1. = highest positive gradient) G = unused, zeroed out B = negative gradient (0. = no negative gradient, 1. = highest negative gradient) A = weight value (0. = fully transparent, 1. = fully opaque) :param weights_list: :param gradients_list: :param step: """ summary_writer = self.w_and_g_summary wg_list = [] for i, (name, ptype) in self.layer_index_name_dict.items(): w = weights_list[i] g = gradients_list[i] # normalize # TODO: global normalization (how the hell) w = (w - tf.reduce_min(w))/(tf.reduce_max(w) - tf.reduce_min(w)) # normalize to (0., 1.) g = 2 * (g - tf.reduce_min(g))/(tf.reduce_max(g) - tf.reduce_min(g)) - 1 # normalize to (-1., 1.) # split to negative and positive gradients g_pos = tf.clip_by_value(g, 0, 1) g_neg = tf.clip_by_value(g, -1, 0) * (-1) # clip and change to positive values for B channel # stack the g_pos, zeros, g_neg and w to form an R, G, B, A image rgb = tf.stack((g_pos, tf.zeros_like(g_pos), g_neg, w), axis=-1) # prepare for summary if ptype == "w": rgb = tf.expand_dims(rgb, 0) rgb = tf.transpose(rgb, (0, 2, 1, 3)) fullname = name + "_weight" elif ptype == "b": rgb = tf.expand_dims(tf.expand_dims(rgb, 0), 2) rgb = tf.transpose(rgb, (0, 2, 1, 3)) fullname = name + "_bias" else: raise NotImplemented("Parameter type must be either 'w' (weight) or 'b' (bias)") # write to summary with summary_writer.as_default(): tf.summary.image(fullname, rgb, step=step) # write to list for .proto file wg_list.append((fullname, rgb)) # serialize and write to protobuf file # TODO: do further testing (seems to not work with tensors) # serialized = self._serialize_wg(wg_list, step) # self.w_and_g_writer.write(serialized) @staticmethod def _serialize_wg(wg_list, step): feature = {"step": tf.train.Feature(int64_list=tf.train.Int64List(value=[step]))} for i, (fullname, wg) in enumerate(wg_list): # encode into serialized string wg_serial = tf.io.serialize_tensor(wg) # decode with tf.io.parse_tensor print(wg_serial) feature[fullname] = tf.train.Feature(bytes_list=tf.train.BytesList(value=[wg_serial])) example = tf.train.Example(features=tf.train.Features(feature=feature)) return example.SerializeToString() class DenseClassifier(BaseModel): def __init__(self, input_shape: Tuple[int, int], hidden_size: int, num_classes: int, log_period=0, layer_index_name_dict=None, log_path="./log"): """ Simple Dense Neural Network classifier with an input Flatten layer, hidden Dense layer and output Dense layer with Softmax output. :param input_shape (Tuple[int, int]): Shape of the input to the Flatten layer :param hidden_size (int): Number of units in hidden Dense layer :param num_classes (int): Number of units in output Dense layer (classes to classify) :param log_period (int): Period (in batches) at which to log weight values to files (0 == no logging) :param layer_index_name_dict (Opt[Dict[int: Tuple[str, str]]]): Dictionary of layers for logging layer weight and bias shapes: l1w: (flat_input_shape, hidden_size) = Input to hidden - weights l1b: (hidden_size,) = Input to hidden - bias l2w: (hidden_size, num_classes) = Hidden to output - weights l2b: (num_classes,) = Hidden to output - bias """ if not layer_index_name_dict: layer_index_name_dict = {0: ("L1_Inp2Hid", "w"), 1: ("L1_Inp2Hid", "b"), 2: ("L2_Hid2Out", "w"), 3: ("L2_Hid2Out", "b")} super(DenseClassifier, self).__init__(log_period=log_period, layer_index_name_dict=layer_index_name_dict, log_path=log_path) self.input_layer = Flatten(input_shape=input_shape) self.hidden_layer = Dense(hidden_size) self.output_layer = Dense(num_classes, activation="softmax") def call(self, inputs, training=None, mask=None): x = self.input_layer(inputs) x = self.hidden_layer(x) return self.output_layer(x) class RNNClassifier(BaseModel): EmbeddingSize = int RNNSize = int DenseSize = int Sizes = Tuple[EmbeddingSize, RNNSize, DenseSize] def __init__(self, vocab_size: int, rnn_type: str, sizes: Sizes, log_period=0, layer_index_name_dict=None, log_path="./log"): """ Simple RNN/GRU binary classifier with Embedding input and single sigmoid output :param vocab_size (int): Number of unique values in inputs (vocabulary size for embedding) :param rnn_type (str): RNN cell type (so far can be "SimpleRNN", "CuDNNGRU" or "GRU") :param sizes (Tuple[int, int, int]): Number of units in [Embedding, RNN, Dense_output] :param log_period (int): Period (in batches) at which to log weight values to files (0 == no logging) :param layer_index_name_dict (Opt[Dict[int: Tuple[str, str]]]): Dictionary of layers for logging embedding_size == sizes[0] rnn_size == sizes[1] dense_size == sizes[2] layer weight and bias shapes: l1w: (vocab_size, embedding_size) = Input to Embedding - weights l2Whx: (embedding_size, rnn_size) for RNN (embedding_size, embedding_size+rnn_size) for GRU = Input to RNN/GRU hidden - weights l2Whh: (rnn_size, rnn_size) for RNN (rnn_size, embedding_size+rnn_size) for GRU = RNN hidden to RNN hidden/output - weights l2b: (rnn_size, ) for RNN (embedding_size+rnn_size, ) for GRU (2, embedding_size+rnn_size) for CuDNNGRU = RNN hidden to hidden/output - bias l3w: (rnn_size, dense_size) = RNN output to dense1 - weight l3b: (dense_size, ) = RNN output to dense1 - bias l4w: (dense_size, 1) = dense1 to output - weights l4b: (1, ) = dense1 to output - bias """ if not layer_index_name_dict: layer_index_name_dict = {0: ("L0_Embedding", "w"), 4: ("L2_RNN2Hid", "w"), 5: ("L2_RNN2Hid", "b"), 6: ("L3_Hid2Out", "w"), 7: ("L3_Hid2Out", "b")} if "simplernn" in rnn_type.lower(): layer_index_name_dict[1] = ("L1_RNN_Whx", "w") layer_index_name_dict[2] = ("L1_RNN_Whh", "w") layer_index_name_dict[3] = ("L1_RNN_bh", "b") elif "cudnngru" in rnn_type.lower(): layer_index_name_dict[1] = ("L1_GRU_WUx", "w") layer_index_name_dict[2] = ("L1_GRU_WUz", "w") layer_index_name_dict[3] = ("L1_GRU_bz", "w") elif "gru" in rnn_type.lower(): layer_index_name_dict[1] = ("L1_GRU_WUx", "w") layer_index_name_dict[2] = ("L1_GRU_WUz", "w") layer_index_name_dict[3] = ("L1_GRU_bz", "b") else: raise NotImplementedError("RNN types other than 'SimpleRNN', 'CuDNNGRU' and 'GRU' are not supported.") super(RNNClassifier, self).__init__(log_period=log_period, layer_index_name_dict=layer_index_name_dict, log_path=log_path) embedding_size, rnn_size, dense_size = sizes if not embedding_size: embedding_size = 64 if not rnn_size: rnn_size = 64 if not dense_size: dense_size = 64 self.embedding = Embedding(vocab_size, embedding_size, mask_zero=True) if "simplernn" in rnn_type.lower(): self.rnn = SimpleRNN(rnn_size) elif "cudnngru" in rnn_type.lower(): self.rnn = GRU(rnn_size) elif "gru" in rnn_type.lower(): self.rnn = GRU(rnn_size, reset_after=False) else: raise NotImplementedError("RNN types other than 'SimpleRNN', 'CuDNNGRU' and 'GRU' are not supported yet.") self.dense = Dense(dense_size) self.class_out = Dense(1, activation="sigmoid") def call(self, inputs, training=None, mask=None): x = self.embedding(inputs) mask = self.embedding.compute_mask(inputs) x = self.rnn(x, mask=mask) x = self.dense(x) return self.class_out(x) def _minimize(strategy, tape, optimizer, loss, trainable_variables): """Minimizes loss for one step by updating `trainable_variables`. This is roughly equivalent to ```python gradients = tape.gradient(loss, trainable_variables) self.optimizer.apply_gradients(zip(gradients, trainable_variables)) ``` However, this function also applies gradient clipping and loss scaling if the optimizer is a LossScaleOptimizer. Args: strategy: `tf.distribute.Strategy`. tape: A gradient tape. The loss must have been computed under this tape. optimizer: The optimizer used to minimize the loss. loss: The loss tensor. trainable_variables: The variables that will be updated in order to minimize the loss. """ with tape: if isinstance(optimizer, lso.LossScaleOptimizer): loss = optimizer.get_scaled_loss(loss) gradients = tape.gradient(loss, trainable_variables) # Whether to aggregate gradients outside of optimizer. This requires support # of the optimizer and doesn't work with ParameterServerStrategy and # CentralStroageStrategy. aggregate_grads_outside_optimizer = ( optimizer._HAS_AGGREGATE_GRAD and # pylint: disable=protected-access not isinstance(strategy.extended, parameter_server_strategy.ParameterServerStrategyExtended)) if aggregate_grads_outside_optimizer: # We aggregate gradients before unscaling them, in case a subclass of # LossScaleOptimizer all-reduces in fp16. All-reducing in fp16 can only be # done on scaled gradients, not unscaled gradients, for numeric stability. gradients = optimizer._aggregate_gradients(zip(gradients, # pylint: disable=protected-access trainable_variables)) if isinstance(optimizer, lso.LossScaleOptimizer): gradients = optimizer.get_unscaled_gradients(gradients) gradients = optimizer._clip_gradients(gradients) # pylint: disable=protected-access if trainable_variables: if aggregate_grads_outside_optimizer: optimizer.apply_gradients( zip(gradients, trainable_variables), experimental_aggregate_gradients=False) else: optimizer.apply_gradients(zip(gradients, trainable_variables)) <file_sep>/rnn_imdb_classifier.py # inspired by https://www.tensorflow.org/tutorials/text/text_classification_rnn import tensorflow_datasets as tfds import tensorflow as tf from helpers import console_logger, plot_graphs from Models import RNNClassifier LOGGER = console_logger("tensorflow", "DEBUG") DEBUG = False BUFFER_SIZE = 10000 BATCH_SIZE = 64 RNN_TYPE = "GRU" LAYER_SIZES = (32, 16, 8) OPTIMIZER = tf.keras.optimizers.Adam(learning_rate=1e-4) LOSS = tf.keras.losses.BinaryCrossentropy(from_logits=True) METRICS = ['accuracy'] EPOCHS = 10 LOG_PERIOD = 100 LAYER_INDEX_NAME_DICT = None # defaults to what is implemented in the RNNClassifier class if "simplernn" in RNN_TYPE.lower(): LOG_PATH = "./log/rnn_imdb" elif "cudnngru" in RNN_TYPE.lower(): LOG_PATH = "./log/CuDNNGRU_imdb" elif "gru" in RNN_TYPE.lower(): LOG_PATH = "./log/GRU_imdb" else: LOG_PATH = "./log" def load_imdb_dataset(): LOGGER.info("Loading IMDB REVIEWS Dataset") dataset, info = tfds.load('imdb_reviews/subwords8k', with_info=True, as_supervised=True) return dataset['train'], dataset['test'], info def sample_predict(sample_pred_text): encoded_sample_pred_text = encoder.encode(sample_pred_text) encoded_sample_pred_text = tf.cast(encoded_sample_pred_text, tf.float32) predictions = model.predict(tf.expand_dims(encoded_sample_pred_text, 0)) return predictions def infer_sentiment(prediction: tf.float32): if prediction > 0.5: sentiment = "positive" elif prediction == 0.5: sentiment = "neutral" else: sentiment = "negative" return sentiment if __name__ == '__main__': train_dataset, test_dataset, info = load_imdb_dataset() LOGGER.debug(f"info: {info}") LOGGER.info("Initializing english word-level encoder.") encoder = info.features['text'].encoder LOGGER.debug(f"Encoder vocab size: {encoder.vocab_size}") LOGGER.info("Testing encoder integrity.") original_string = "Decode this!" encoded_string = encoder.encode(original_string) decoded_string = encoder.decode(encoded_string) LOGGER.debug(f"original_string: {original_string}") LOGGER.debug(f"encoded_string: {encoded_string}") LOGGER.debug(f"decoded_string: {decoded_string}") assert original_string == decoded_string, "Original and decoded string don't match!" LOGGER.info("Preparing data for training.") train_dataset = (train_dataset .shuffle(BUFFER_SIZE) .padded_batch(BATCH_SIZE, padded_shapes=((None, ), tuple()))) test_dataset = test_dataset.padded_batch(BATCH_SIZE, padded_shapes=((None, ), tuple())) if DEBUG: LOGGER.info("Take only part of the datasets for debugging.") train_dataset = train_dataset.take(20) test_dataset = test_dataset.take(10) LOGGER.info("Initializing GRU-RNN model.") model = RNNClassifier(encoder.vocab_size, RNN_TYPE, LAYER_SIZES, LOG_PERIOD, LAYER_INDEX_NAME_DICT, LOG_PATH) LOGGER.info("Compiling the model.") model.compile(OPTIMIZER, LOSS, METRICS) LOGGER.info("Training the model on IMDB REVIEWS training dataset.") history = model.fit(train_dataset, epochs=EPOCHS, validation_data=test_dataset, validation_steps=30) LOGGER.debug(f"history: {history}") LOGGER.debug(f"model: {model.summary()}") # model.w_and_g_writer.close() # TODO: close the writer in the model class itself LOGGER.info("Evaluating the model on IMDB REVIEWS testing dataset.") metrics = model.evaluate(test_dataset) LOGGER.info(f"Test Loss: {metrics[0]}") LOGGER.info(f"Test Accuracy: {metrics[1]}") LOGGER.info("Predicting sample text with trained model.") sample_pred_text = ("""The movie was cool. The animation and the graphics were out of this world. I would recommend this movie.""") prediction = sample_predict(sample_pred_text) LOGGER.info(f"Prediction: {prediction} | Sentiment: {infer_sentiment(prediction)}")
0951f189fd0c9b9feb0dfa979549aef977d3720a
[ "Python" ]
4
Python
vejvarm/clear_networks
870fdd93f63f42d8e1c1050a4684bd2b82010b77
52998f4be58dbd6e7a651873b34b22d8b513851a
refs/heads/master
<file_sep> ################################## ### Payroll Tax15 from KVS ####### ################################## # Load Payroll Tax15 File from KVS kvs15 <- read.csv(file='KVS15.csv', header=FALSE, skip=65, nrows = 102573, na.strings =c("", NA), stringsAsFactors = FALSE) # Have to fill the NA at the bottom of the dataframe for na.locf to work. Can't start with an NA kvs15[c(102572, 102573), c(4:6)] <- "Anything here" #Adding columns based on last ovservation carry forward, Remove "000" from column. kvs15 <- within(kvs15,{ V5 <- na.locf(V5, fromLast = TRUE) V6 <- na.locf(V6, fromLast = TRUE) V8 <- ifelse(grepl("000", V2), as.character(V2), NA) }) #Run na.locf on account number and remove "-" kvs15 <- within (kvs15, { V8 <- na.locf(V8, fromLast = TRUE) V8 <- gsub("[[:punct:]]", "", V8) }) #Keep only rows with wage retrun record. Other rows are junk kvs15 <- kvs15[which(kvs15$V3=="A WAGE RET."),] #Remove commas from amount column and make it numeric class kvs15$V4 <- as.numeric(gsub(",","", kvs15$V4)) #Keep and order only columns 2, 5, 4, and 8 kvs15 <- kvs15[c("V2", "V5", "V4", "V8")] names(kvs15) <- c("Name", "Date", "Amount", "Account Number") #change column names kvs15$Name <- trimws(kvs15$Name, "both") #trim whitespace from boths ends of column kvs15 <-unique(kvs15)#remove duplicates if they exist #write file for FY 2015 write.csv(kvs15, file="U:/OpenGov/Unique Reports/Finance/PayrollTax/NewData/KVS15_Output.csv", row.names = FALSE) ################################## ### Payroll Tax16 from KVS ####### ################################## #Load Payroll tax16 File from KVS kvs16 <- read.csv(file='KVS16.csv', header=FALSE, skip=65, nrows = 65697, na.strings =c("", NA), stringsAsFactors = FALSE) ## Have to fill the NA at the bottom of the dataframe for na.locf to work. Can't start with an NA kvs16[c(65696, 65697), c(3:5)] <- "Anything here" #Adding columns based on last ovservation carry forward, Remove "000" from column. kvs16 <- within(kvs16, { V4 <- na.locf(V4, fromLast = TRUE) V5 <- na.locf(V5, fromLast = TRUE) V6 <- ifelse(grepl("-000", V1), as.character(V1), NA) }) #Run na.locf on account number and remove "-" kvs16 <- within (kvs16, { V6 <- na.locf(V6, fromLast = TRUE) V6 <- gsub("[[:punct:]]", "", V6) V6 <- str_sub(V6, 9, 17) }) ### Keep only row with wage ret. kvs16 <- kvs16[which(kvs16$V2=="A WAGE RET."),] #Remove commas from amount column and make it numeric class kvs16$V3 <- as.numeric(gsub(",","", kvs16$V3)) kvs16$Name <- str_sub(kvs16$V1, 9, 100) #extract name of business and assign to new column #Keep and order columns Name, 4, 3, and 6 kvs16 <- kvs16[c("Name", "V4", "V3", "V6")] names(kvs16) <- c("Name", "Date", "Amount", "Account Number") #rename columns kvs16$Name <- trimws(kvs16$Name, "both") #trim whitespace from both ends kvs16 <-unique(kvs16)#remove duplicates if they exist ### Created function to speed up fixing missing account numbers fix_missing <- function(a, b, c = kvs16$`Account Number`, d = kvs16$Name){ c[d == a] <- b c } kvs16$`Account Number` <- fix_missing("Name", "Account Number") ###removed all code here as it contains names and account numbers write.csv(kvs16, file="U:/OpenGov/Unique Reports/Finance/PayrollTax/NewData/KVS16_Output.csv", row.names = FALSE) ################################### ### Payroll Tax16 from Spingbrook # ################################### ptax16 <- read.csv(file="Springbrook16.csv", header=FALSE, skip = 1, na.strings = c("", NA, "Payment", NA), stringsAsFactors = FALSE) #remove unneccessary rows with creditcash. ptax16$V1[ptax16$V1 =="CreditCash"] <- NA #Adding columns based on last ovservation carry forward, Remove "000" from column. ptax16 <- within(ptax16, { V1 <- na.locf(V1) V19 <- as.numeric(gsub(",","",V19)) Name <- str_sub(V1, 24, 100) Name <- trimws(Name, "both")#trim white space at both ends. `Account Number` <- str_sub(V1, 12, 20) }) #Remove unneccessary colums and rows ptax16 <- ptax16[c(-2:-4, -6:-12, -14:-18, -20:-25)] ptax16 <- na.omit(ptax16) #Keep only needed columns and change names as needed ptax16 <- ptax16[c("Name", "V13", "V19", "Account Number")] names(ptax16) <- c("Name", "Date", "Amount", "Account Number") ptax16 <- unique(ptax16) #remove duplicates if they exists ptax16 <- ptax16[!(ptax16$Name == ""),] #keep rows where name field is not blank write.csv(kvs16, file="U:/OpenGov/Unique Reports/Finance/PayrollTax/NewData/SpringBrook16_Output.csv", row.names = FALSE) ############################ ### Bind Files Together ### ############################ payroll_tax <- do.call("rbind", list(kvs15, kvs16, ptax16)) payroll_tax <- unique(payroll_tax) #check again for any duplication of rows write.csv(payroll_tax, file="U:/OpenGov/Unique Reports/Finance/PayrollTax/NewData/Combined15-16.csv", row.names = FALSE) #Load Business Infomration and join with payroll tax dataframe businessData <- read.xlsx2("BusinessInformation.xlsx", as.data.frame = TRUE, sheetIndex = 1) payroll_tax_merge <- merge(payroll_tax, businessData, by.x="Account Number", by.y="bt_master_business_no", all.x=TRUE, all.y=FALSE) payroll_tax_merge$customer_city[payroll_tax_merge$customer_address == "2203 FOWLER ST"] <- "CINCINNATI OH" payroll_tax_merge$customer_city[payroll_tax_merge$Name == "UNIVERSITY OF KENTUCKY"] <- "<NAME>" ## Create new columns in merged file payroll_tax_merge <- within(payroll_tax_merge, { City <- str_sub(customer_city, -50, -4) State <- str_sub(customer_city, -2, -1) FullAddress <- paste(customer_address, City, State, customer_zip, sep = " ") }) #Remove unnecessary information form address fields payroll_tax_merge$FullAddress <- gsub("ATTN PAYROLL", " ", payroll_tax_merge$FullAddress) payroll_tax_merge$FullAddress <- gsub("ATTN: <NAME>", " ", payroll_tax_merge$FullAddress) ### Create function to fix city names #### fix_city <- function(a, b, c = payroll_tax_merge$City){ c <- gsub(a, b, c) c } payroll_tax_merge$City <- fix_city("ALEXADNRIA", "ALEXANDRIA") payroll_tax_merge$City <- fix_city("ALEXANDIA", "ALEXANDRIA") payroll_tax_merge$City <- fix_city("\\CINCINNAT\\>", "CINCINNATI") payroll_tax_merge$City <- fix_city("\\CINCINNTI\\>", "CINCINNATI") payroll_tax_merge$City <- fix_city("\\CINTI\\>", "CINCINNATI") payroll_tax_merge$City <- fix_city("SPGS", "SPRINGS") payroll_tax_merge$City <- fix_city("\\<CRES\\>", "CRESCENT") payroll_tax_merge$City <- fix_city("\\<CRESCNT\\>", "CRESCENT") payroll_tax_merge$City <- fix_city("\\<HIGHLND HGTS\\>", "HEIGHTS") payroll_tax_merge$City <- fix_city("LATONIA", "COVINGTON") payroll_tax_merge$City <- fix_city("CINCINNAT", "CINCINNATI") payroll_tax_merge$City <- fix_city("\\<MAYFILED HTS\\>", "MAYFIELD HEIGHTS") payroll_tax_merge$City <- fix_city("\\<PITSSBURGH\\>", "PITTSBURGH") payroll_tax_merge$City <- fix_city("\\<MORNINGVIEW\\>", "MORNING VIEW") payroll_tax_merge$City <- fix_city("\\<HEIGHTS\\>", "HIGHLAND HEIGHTS") payroll_tax_merge$City <- fix_city("\\<HIGHLAND HIGHLAND HEIGHTS\\>", "HIGHLAND HEIGHTS")##Previous gsub created this need payroll_tax_merge$City <- fix_city("\\<RYLAND HIGHLAND HEIGHTS\\>", "RYLAND HEIGHTS")##Previous gsub created this need payroll_tax_merge$City <- fix_city("\\<MAYFIELD HIGHLAND HEIGHTS\\>", "MAYFIELD HEIGHTS")##Previous gsub created this need payroll_tax_merge$City <- fix_city("\\<STERLING HIGHLAND HEIGHTS\\>", "STERLING HEIGHTS")##Previous gsub created this need payroll_tax_merge$City <- fix_city("\\COLD SPRING\\>", "COLD SPRINGS") payroll_tax_merge$City <- fix_city("\\COVNIGTON\\>", "COVINGTON") payroll_tax_merge$City <- fix_city("\\DEVOSSVILLE\\>", "DEMOSSVILLE") payroll_tax_merge$City <- fix_city("\\E PARKER CITY\\>", "PARKER CITY") payroll_tax_merge$City <- fix_city("\\HAMITLON\\>", "HAMILTON") payroll_tax_merge$City <- fix_city("\\<WILLIAMSVLLE\\>", "WILLIAMSVILLE") #Remove punctuation from city column payroll_tax_merge$City <- gsub("[[:punct:]]", "", payroll_tax_merge$City) #Combine city and state for goecoding payroll_tax_merge$City_State <- with(payroll_tax_merge, paste(City, State, sep = " ")) #create new dataframe that mirrors combined file for geocoding payroll_count <- payroll_tax_merge payroll_count$Count <- 1 #assign a count of 1 for each row to wrap up rows by city/state combinations payroll_count1 <- aggregate(Count ~ City_State + City, payroll_count, sum) #perform the aggregation #Geocode city_state column using data science toolkit api and bind results back with aggregated file payroll_city_coordinatesDSK <- geocode(payroll_count1$City_State, source = "dsk") payroll_count1 <- cbind(payroll_count1, payroll_city_coordinatesDSK) #Join geocoded dataframe with original dataframe payroll_tax_merge <- merge(payroll_tax_merge, payroll_count1, by.x="City_State", by.y="City_State", all=TRUE) #Write file to CSV write.csv(payroll_tax_merge, file="U:/OpenGov/Unique Reports/Finance/PayrollTax/NewData/BusinessTaxes.csv", row.names = FALSE) #SQLite storage # payroll <- dbDriver("SQLite") cons.payroll <- dbConnect(payroll, dbname="O:/AllUsers/CovStat/Data Portal/repository/Data/Database Files/PayrollTax.db") dbWriteTable(cons.payroll, "PayrollTax", payroll_tax_merge, overwrite = TRUE) dbDisconnect(cons.payroll) ### Subsetting by Date ### #test <- port.ins[port.ins$NewLeaseDate > as.Date("1899-12-31"),] #as.Date(x, origin = "1970-01-01") <file_sep> #read in checkbook data checkbook <- read.csv(file="Pulled_12.01.2016.csv", header=FALSE, stringsAsFactors = FALSE, quote = "") ## had to disable quoting checkbook$V10 <- NULL checkbook <- rename(checkbook, c("V1"="Account String", "V2"="Amount", "V3"="Check Date", "V4"="Check No.", "V5"="Fiscal Period", "V6"="Fiscal Year", "V7"="Description", "V8"="Vendor No.", "V9"="Account Description")) #Split account string into separate fields checkbook$Fund <- str_sub(checkbook$`Account String`, 1, 4) checkbook$Dept. <- str_sub(checkbook$`Account String`, 6, 9) checkbook$Account <- str_sub(checkbook$`Account String`, 11, 19) #Load Vendor File vendor <- read.csv(file="Vendor12.01.16.csv", header=FALSE, stringsAsFactors = FALSE) vendor <- rename(vendor, c("V1"="Vendor Address", "V2"="Vendor City", "V3"="Vendor Name", "V4"="Vendor State", "V5"="Vendor Number")) #Merge all checkbook data with vendor directory file by vendor number checkbook <- merge(checkbook, vendor, by.x="Vendor No.", by.y="Vendor Number", all.x=TRUE) checkbook$`Vendor Address` <- NULL checkbook <- checkbook[c("Account String", "Fund", "Dept.", "Account", "Amount", "Check Date", "Check No.", "Fiscal Period", "Fiscal Year", "Description", "Vendor No.", "Account Description", "Vendor City", "Vendor Name", "Vendor State")] checkbook$`Vendor City`[checkbook$`Vendor City` == ""] <- "None" checkbook$`Vendor State`[checkbook$`Vendor State` == ""] <- "None" write.csv(checkbook,"U:/OpenGov/Unique Reports/Checkbook/Pulled12.01.2016UpdatedVendor.csv", row.names=FALSE) <file_sep># Finance Code for automating reporting/analysis <file_sep> #Download General Fund data for fiscal years from OpenGov platform and reshape it prediction14 <- read.csv("PredictionFY2014.csv", stringsAsFactors = FALSE, na.strings = c("", NA), header=TRUE) prediction14 <- prediction14%>% melt(id=c("Category", "Object.Type"))%>% na.omit(prediction14) prediction15 <- read.csv("PredictionFY2015.csv", stringsAsFactors = FALSE, na.strings = c("", NA), header=TRUE) prediction15 <- prediction15 %>% melt(id=c("Category", "Object.Type"))%>% na.omit(prediction15) prediction16 <- read.csv("PredictionFY2016.csv", stringsAsFactors = FALSE, na.strings = c("", NA), header=TRUE) prediction16 <- prediction16 %>% melt(id=c("Category", "Object.Type"))%>% na.omit(prediction16) #Combine files and rename a few columns predictions <- do.call("rbind", list(prediction14, prediction15, prediction16)) predictions <- rename(predictions, c("variable"= "Date", "value"="Amount")) #Assign fiscal month for FY 2014 predictions <- within(predictions, { FiscalMonth <- NA FiscalMonth [Date == "July.FY.2014.Actual"] <- "7/31/13" FiscalMonth [Date == "August.FY.2014.Actual"] <- "8/31/13" FiscalMonth [Date == "September.FY.2014.Actual"] <- "9/30/13" FiscalMonth [Date == "October.FY.2014.Actual"] <- "10/31/13" FiscalMonth [Date == "November.FY.2014.Actual"] <- "11/30/13" FiscalMonth [Date == "December.FY.2014.Actual"] <- "12/31/13" FiscalMonth [Date == "January.FY.2014.Actual"] <- "1/31/14" FiscalMonth [Date == "February.FY.2014.Actual"] <- "2/28/14" FiscalMonth [Date == "March.FY.2014.Actual"] <- "3/31/14" FiscalMonth [Date == "April.FY.2014.Actual"] <- "4/30/14" FiscalMonth [Date == "May.FY.2014.Actual"] <- "5/31/14" FiscalMonth [Date == "June.FY.2014.Actual"] <- "6/30/14"}) #Assign fiscal month for FY 2015 predictions <- within(predictions, { FiscalMonth [Date == "July.FY.2015.Actual"] <- "7/31/14" FiscalMonth [Date == "August.FY.2015.Actual"] <- "8/31/14" FiscalMonth [Date == "September.FY.2015.Actual"] <- "9/30/14" FiscalMonth [Date == "October.FY.2015.Actual"] <- "10/31/14" FiscalMonth [Date == "November.FY.2015.Actual"] <- "11/30/14" FiscalMonth [Date == "December.FY.2015.Actual"] <- "12/31/14" FiscalMonth [Date == "January.FY.2015.Actual"] <- "1/31/15" FiscalMonth [Date == "February.FY.2015.Actual"] <- "2/28/15" FiscalMonth [Date == "March.FY.2015.Actual"] <- "3/31/15" FiscalMonth [Date == "April.FY.2015.Actual"] <- "4/30/15" FiscalMonth [Date == "May.FY.2015.Actual"] <- "5/31/15" FiscalMonth [Date == "June.FY.2015.Actual"] <- "6/30/15"}) #Assign fiscal month for FY 2016 predictions <- within(predictions, { FiscalMonth [Date == "July.FY.2016.Actual"] <- "7/31/15" FiscalMonth [Date == "August.FY.2016.Actual"] <- "8/31/15" FiscalMonth [Date == "September.FY.2016.Actual"] <- "9/30/15" FiscalMonth [Date == "October.FY.2016.Actual"] <- "10/31/15" FiscalMonth [Date == "November.FY.2016.Actual"] <- "11/30/15" FiscalMonth [Date == "December.FY.2016.Actual"] <- "12/31/15" FiscalMonth [Date == "January.FY.2016.Actual"] <- "1/31/16" FiscalMonth [Date == "February.FY.2016.Actual"] <- "2/29/16" FiscalMonth [Date == "March.FY.2016.Actual"] <- "3/31/16" FiscalMonth [Date == "April.FY.2016.Actual"] <- "4/30/16" FiscalMonth [Date == "May.FY.2016.Actual"] <- "5/31/16" FiscalMonth [Date == "June.FY.2016.Actual"] <- "6/30/16"}) #drop date column predictions$Date <- NULL #write file for forecasting in tableau write.csv(predictions, "predictions.csv", row.names = FALSE)
7b6bd4d021d4388dd28d830d604cee38830874e0
[ "Markdown", "R" ]
4
R
Karagul/Finance-2
58186d77b4d6d95ce777d3f79b807d892f63cfa1
725149906d00a004f7174dfc303ec06d8f082353
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Windows.Input; using Windows.ApplicationModel.Resources; using Windows.Storage; using Windows.Storage.Streams; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using Mutzl.MvvmLight; using Newtonsoft.Json; using ShoppingListWPApp.Common; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.ViewModels { /// <summary> /// This is the ViewModel for the <c>MainPage</c>-View. /// </summary> class MainPageViewModel : ViewModelBase { #region *** Private Members *** /// <summary> /// This <c>INavigationService</c>-Object is used for navigating between pages. /// </summary> private INavigationService navigationService; /// <summary> /// This <c>IDialogService</c>-Object is used for displaying Dialogs on the Device-Screen. /// </summary> private IDialogService dialogService; /// <summary> /// Filename, where shops are saved. /// </summary> private readonly string shopsFilename; /// <summary> /// Filename, where shopping lists are saved. /// </summary> private readonly string shoppingListsFilename; #endregion #region *** Properties *** /// <summary> /// Holds all <c>Shop</c>-Objects and notifies Views through Data Binding when Changes occur. /// </summary> public ObservableCollection<Shop> Shops { get; set; } /// <summary> /// Holds all <c>ShoppingList</c>-Objects and notifies Views through Data Binding when Changes occur. /// </summary> public ObservableCollection<ShoppingList> ShoppingLists { get; set; } /// <summary> /// The currently selected <c>Shop</c>-Object in the Shops-<c>ListView</c> of the <c>MainPage</c>-View. /// </summary> public Shop SelectedShop { get; set; } /// <summary> /// The currently selected <c>ShoppingList</c>-Object in the ShoppingLists-<c>ListView</c> of the <c>MainPage</c>-View. /// </summary> public ShoppingList SelectedShoppingList { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to add a new Shop. /// </summary> public ICommand AddShopCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to display details of a previously selected Shop. /// </summary> public ICommand DetailsShopCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to modify a previously selected Shop. /// </summary> public ICommand EditShopCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to delete a previously selected Shop. /// </summary> public ICommand DeleteShopCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to add a new ShoppingList. /// </summary> public ICommand AddShoppingListCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to add a new ShoppingListItem. /// </summary> public ICommand AddShoppingListItemCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to delete a previously selected ShoppingList. /// </summary> public ICommand DeleteShoppingListCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to modify a previously selected ShoppingList. /// </summary> public ICommand EditShoppingListCommand { get; set; } #endregion public MainPageViewModel(INavigationService navigationService, IDialogService dialogService) { // Services this.navigationService = navigationService; this.dialogService = dialogService; // Commands AddShopCommand = new RelayCommand(GoToAddShopPage); EditShopCommand = new RelayCommand(GoToEditShopPage); DeleteShopCommand = new RelayCommand(GoToDeleteShop); DetailsShopCommand = new RelayCommand(GoToDetailsShop); AddShoppingListCommand = new DependentRelayCommand(GoToAddShoppingListPage, AreShopsCreated, this, () => Shops); DeleteShoppingListCommand = new RelayCommand(GoToDeleteShoppingList); EditShoppingListCommand = new RelayCommand(GoToEditShoppingListPage); // Load data shopsFilename = "shops.json"; shoppingListsFilename = "lists.json"; LoadShops(); LoadShoppingLists(); } #region *** Shop *** /// <summary> /// Adds a new <c>Shop</c>-Object to the <c>Shops</c>-Collection. /// </summary> /// <param name="shop">The <c>Shop</c>-Object that should added to the <c>Shops</c>-Collection.</param> public void AddShop(Shop shop) { // Add Shop to collection Shops.Add(shop); // Save shops to isolated storage SaveShops(); // Notify for change this.RaisePropertyChanged(() => Shops); // Create new Geofence ServiceLocator.Current.GetInstance<GeoHelper>().AddGeofence(shop); } /// <summary> /// Replaces an old <c>Shop</c>-Object with a modified one. /// </summary> /// <param name="oldShop">The <c>Shop</c>-Object that should be replaced.</param> /// <param name="newShop">The <c>Shop</c>-Object that should be inserted into the Collection.</param> public void EditShop(Shop oldShop, Shop newShop) { // Get index of old object int idx = Shops.IndexOf(oldShop); // Clone ShoppingLists-List var templist = ShoppingLists.ToList(); // Query all shopping lists and update the Shop object of the Shopping lists foreach (ShoppingList list in templist) { if (list.Shop.ID.Equals(oldShop.ID)) { // Get index of old object int listIdx = ShoppingLists.IndexOf(list); // Set new shop list.Shop = newShop; // Remove old object from list and insert new one ShoppingLists.RemoveAt(listIdx); ShoppingLists.Insert(listIdx, list); } } // Remove old object and insert new object at the same position as the old one Shops.Remove(oldShop); Shops.Insert(idx, newShop); // Save data to isolated storage SaveShops(); SaveShoppingLists(); // Replace old Geofence with new one ServiceLocator.Current.GetInstance<GeoHelper>().ModifyGeofence(oldShop.ID, newShop); } /// <summary> /// Removes a <c>Shop</c>-Object from the <c>Shops</c>-Collection. /// </summary> /// <param name="shop">The <c>Shop</c>-Object that should be removed from the Collection.</param> public void DeleteShop(Shop shop) { Shops.Remove(shop); // Clone ShoppingLists-List var templist = ShoppingLists.ToList(); // Query all shopping lists and update the Shop object of the Shopping lists foreach (ShoppingList list in templist) { if (list.Shop.ID.Equals(shop.ID)) { ShoppingLists.Remove(list); } } // Save data to isolated storage SaveShops(); SaveShoppingLists(); // Remove Geofence ServiceLocator.Current.GetInstance<GeoHelper>().RemoveGeofence(shop.ID); } /// <summary> /// Gets the Index of a <c>Shop</c>-Object that is element of the <c>Shops</c>-Collection. /// </summary> /// <param name="shop">The <c>Shop</c>-Object, for which an index should be retrieved.</param> /// <returns>The Index of the passed <c>Shop</c>-Object.</returns> public int IndexOfShop(Shop shop) { return Shops.IndexOf(shop); } /// <summary> /// Gets a <c>Shop</c>-Object at a specified Index out of the <c>Shops</c>-Collection. /// </summary> /// <param name="index">The Index of the <c>Shop</c>-Object in the <c>Shops</c>-Collection.</param> /// <returns>The <c>Shop</c>-Object at the specified Index in the <c>Shops</c>-Collection.</returns> public Shop GetShopByIndex(int index) { return Shops.ElementAt(index); } #endregion #region *** ShoppingList *** /// <summary> /// Adds a new <c>ShoppingList</c>-Object to the <c>ShoppingLists</c>-Collection. /// </summary> /// <param name="shoppingList">The <c>ShoppingList</c>-Object that should added to the <c>ShoppingLists</c>-Collection.</param> public void AddShoppingList(ShoppingList shoppingList) { ShoppingLists.Add(shoppingList); SaveShoppingLists(); } /// <summary> /// Removes a <c>ShoppingList</c>-Object from the <c>ShoppingLists</c>-Collection. /// </summary> /// <param name="shoppingList">The <c>ShoppingList</c>-Object that should be removed from the Collection.</param> public void DeleteShoppingList(ShoppingList shoppingList) { ShoppingLists.Remove(shoppingList); SaveShoppingLists(); } /// <summary> /// Replaces an old <c>ShoppingList</c>-Object with a modified one. /// </summary> /// <param name="oldShoppingList">The <c>Shop</c>-Object that should be replaced.</param> /// <param name="newShoppingList">The <c>Shop</c>-Object that should be inserted into the Collection.</param> public void EditShoppingList(ShoppingList oldShoppingList, ShoppingList newShoppingList) { // Get index of old object int idx = ShoppingLists.IndexOf(oldShoppingList); // Remove old object and insert new object at the same position as the old one ShoppingLists.Remove(oldShoppingList); ShoppingLists.Insert(idx, newShoppingList); // Save data to isolated storage SaveShoppingLists(); } /// <summary> /// Gets a <c>ShoppingList</c>-Object with a specified ID out of the <c>ShoppingLists</c>-Collection. /// </summary> /// <param name="id">The ID of the <c>ShoppingList</c>-Object in the <c>ShoppingLists</c>-Collection.</param> /// <returns>The <c>ShoppingList</c>-Object with the specified ID.</returns> public ShoppingList GetShoppingListByID(string id) { // Get Object ShoppingList list = (from l in ShoppingLists where l.ID.Equals(id) select l).First(); return list; } /// <summary> /// Filters out <c>ShoppingList</c> objects, which are associated with a specific Shop. /// </summary> /// <param name="shop"><c>Shop</c> object for which <c>ShoppingList</c> objects should be found.</param> /// <returns>A collection of <c>ShoppingList</c> objects, which are associated with a specific Shop.</returns> public List<ShoppingList> GetShoppingListsByShopID(string id) { // Get Shopping lists List<ShoppingList> lists = (from list in ShoppingLists where list.Shop.ID.Equals(id) select list).ToList() ?? new List<ShoppingList>(); return lists; } #endregion #region *** Command methods *** /// <summary> /// Checks, if <c>Shop</c> objects are present. /// </summary> /// <returns>False, if no <c>Shop</c> objects are present, otherwise true.</returns> private bool AreShopsCreated() { if (Shops == null || Shops.Count == 0) { return false; } return true; } /// <summary> /// Navigates the User to the <c>AddShop</c>-View. /// </summary> private void GoToAddShopPage() { navigationService.NavigateTo("addShop"); } /// <summary> /// Navigates the User to the <c>EditShop</c>-View. /// </summary> private void GoToEditShopPage() { navigationService.NavigateTo("editShop", SelectedShop); } /// <summary> /// After opening a dialog and asking for confirmation it removes the selected <c>Shop</c>-Object out of the <c>Shops</c>-Collection. /// </summary> private async void GoToDeleteShop() { // Show dialog bool result = await dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("DeleteShopDialogContent"), ResourceLoader.GetForCurrentView().GetString("DeleteShopDialogTitle"), ResourceLoader.GetForCurrentView().GetString("YesText"), ResourceLoader.GetForCurrentView().GetString("NoText"), null); // Check, if user pressed the "Proceed-Button" if (result) { // Delete selected Shop object DeleteShop(SelectedShop); SelectedShop = null; } } /// <summary> /// Navigates the User to the <c>DetailsShop</c>-View. /// </summary> private void GoToDetailsShop() { navigationService.NavigateTo("detailsShop", this.IndexOfShop(SelectedShop)); } /// <summary> /// Navigates the User to the <c>AddShoppingList</c>-View. /// </summary> private void GoToAddShoppingListPage() { ShowDialogShop(); navigationService.NavigateTo("addShoppingList"); } /// <summary> /// Navigates the User to the <c>EditShoppingList</c>-View. /// </summary> private void GoToEditShoppingListPage() { navigationService.NavigateTo("editShoppingList", SelectedShoppingList); } /// <summary> /// After opening a dialog and asking for confirmation it removes the selected <c>ShoppingList</c>-Object out of the <c>ShoppingLists</c>-Collection. /// </summary> private async void GoToDeleteShoppingList() { // Show dialog bool result = await dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("DeleteShoppingListDialogContent"), ResourceLoader.GetForCurrentView().GetString("DeleteShoppingListDialogTitle"), ResourceLoader.GetForCurrentView().GetString("YesText"), ResourceLoader.GetForCurrentView().GetString("NoText"), null); // Check, if user pressed the "Proceed-Button" if (result) { // Delete selected ShoppingList object DeleteShoppingList(SelectedShoppingList); SelectedShoppingList = null; } } /// <summary> /// Checks, if Shops-Collection has items /// </summary> public async void ShowDialogShop() { if (ServiceLocator.Current.GetInstance<AddShoppingListViewModel>().Shops.Count == 0) { bool result = true; result = await dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("AddShopDialogContent"), ResourceLoader.GetForCurrentView().GetString("AddShopDialogTitle"), ResourceLoader.GetForCurrentView().GetString("YesText"), ResourceLoader.GetForCurrentView().GetString("NoText"), null); // Check, if user pressed the "Yes-Button" if (result) { navigationService.NavigateTo("addShop"); } else { navigationService.NavigateTo("main"); } } } #endregion #region *** Input/Output *** /// <summary> /// Saves all created shops in the isolated storage of the device as JSON data. /// </summary> private async void SaveShops() { try { // Get App's folder and create file var folder = ApplicationData.Current.LocalFolder; var file = await folder.CreateFileAsync(shopsFilename, CreationCollisionOption.ReplaceExisting); // Write Shops to file as JSON data await FileIO.WriteTextAsync(file, JsonConvert.SerializeObject(Shops), UnicodeEncoding.Utf8); } catch (Exception ex) { dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("SavingErrorContent"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")); } } /// <summary> /// Saves all created shopping lists in the isolated storage of the device as JSON data. /// </summary> private async void SaveShoppingLists() { try { // Get App's folder and create file var folder = ApplicationData.Current.LocalFolder; var file = await folder.CreateFileAsync(shoppingListsFilename, CreationCollisionOption.ReplaceExisting); // Write Shops to file as JSON data await FileIO.WriteTextAsync(file, JsonConvert.SerializeObject(ShoppingLists), UnicodeEncoding.Utf8); } catch (Exception ex) { dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("SavingErrorContent"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")); } } /// <summary> /// Loads all created shops out of the isolated storage of the device. /// </summary> private async void LoadShops() { try { // Get App's folder and create file var folder = ApplicationData.Current.LocalFolder; var file = await folder.GetFileAsync(shopsFilename); // Load data out of file string data = await FileIO.ReadTextAsync(file, UnicodeEncoding.Utf8); Shops = JsonConvert.DeserializeObject<ObservableCollection<Shop>>(data) ?? new ObservableCollection<Shop>(); } catch (Exception ex) { // Initialize collection Shops = new ObservableCollection<Shop>(); } } /// <summary> /// Loads all created shopping lists out of the isolated storage of the device. /// </summary> private async void LoadShoppingLists() { try { // Get App's folder and create file var folder = ApplicationData.Current.LocalFolder; var file = await folder.GetFileAsync(shoppingListsFilename); // Load data out of file string data = await FileIO.ReadTextAsync(file, UnicodeEncoding.Utf8); ShoppingLists = JsonConvert.DeserializeObject<ObservableCollection<ShoppingList>>(data) ?? new ObservableCollection<ShoppingList>(); } catch (Exception ex) { // Initialize collection ShoppingLists = new ObservableCollection<ShoppingList>(); } } #endregion } } <file_sep>using System; using System.Globalization; using Windows.ApplicationModel.Resources; using Windows.UI.Xaml.Data; namespace ShoppingListWPApp.Converter { /// <summary> /// The <c>RadiusToRadiusWithUnitConverter</c> is used for converting the /// <c>Radius</c>-Value of a <c>Shop</c>-Object into a formatted, regional-specific string. /// </summary> class RadiusToRadiusWithUnitConverter : IValueConverter { /// <summary> /// Converts a <c>Radius</c>-Value of a <c>Shop</c>-Object to a formatted, regional-specifig string. /// </summary> /// <param name="value">The <c>double</c>-Value that should be converted.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">Parameters that can be passed to the Converter.</param> /// <param name="language">Cultural information that can be passed to the Converter.</param> /// <returns>Returns a formatted, regional-specific string representation of <c>value</c>.</returns> public object Convert(object value, Type targetType, object parameter, string language) { double radius = (double)value; // Check, if imperial system is present if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName.StartsWith("en")) { radius = radius * 0.62137; } return radius.ToString("0.00") + " " + ResourceLoader.GetForCurrentView().GetString("GeoFenceShopRadiusUnit"); } /// <summary> /// Converts back a formatted, regional-specifig string to a <c>Radius</c>-Value of a <c>Shop</c>-Object. /// </summary> /// <param name="value">The <c>string</c>-Value that should be converted.</param> /// <param name="targetType">The type to convert to.</param> /// <param name="parameter">Parameters that can be passed to the Converter.</param> /// <param name="language">Cultural information that can be passed to the Converter.</param> /// <returns>Returns a <c>double</c>-Value.</returns> /// <exception cref="System.NotImplementedException">Thrown because this method is not implemented (not used).</exception> public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.ObjectModel; using System.Windows.Input; using Windows.ApplicationModel.Resources; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.ViewModels { /// <summary> /// This is the ViewModel for the <c>AddShoppingList</c>-View. /// </summary> class AddShoppingListViewModel : ViewModelBase { #region *** Private Members *** /// <summary> /// This <c>INavigationService</c>-Object is used for navigating between pages. /// </summary> private INavigationService navigationService; /// <summary> /// This <c>IDialogService</c>-Object is used for displaying Dialogs on the Device-Screen. /// </summary> private IDialogService dialogService; #endregion #region *** Properties *** /// <summary> /// Gets or Sets the ListName of the new ShoppingListItem. /// </summary> public string ListName { get; set; } /// <summary> /// The currently selected <c>Shop</c>-Object in the Shops-<c>ListView</c> of the <c>MainPage</c>-View. /// </summary> public Shop SelectedShop { get; set; } /// <summary> /// Holds all <c>Shop</c>-Objects and notifies Views through Data Binding when Changes occur. /// </summary> public ObservableCollection<Shop> Shops { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to finish the creation-process of a new ShoppingList. /// </summary> public ICommand CreateShoppingListCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to cancel the creation-process of a new ShoppingList. /// </summary> public ICommand CancelCommand { get; set; } #endregion public AddShoppingListViewModel(INavigationService navigationService, IDialogService dialogService) { // Services this.navigationService = navigationService; this.dialogService = dialogService; // Initialize all Fields with standard values InitializeFields(); //Commands CreateShoppingListCommand = new RelayCommand(CreateShoppingList); CancelCommand = new RelayCommand(Cancel); // Gets the Shops-Collection from the MainPageViewModel Shops = ServiceLocator.Current.GetInstance<MainPageViewModel>().Shops; } #region *** Command Methods *** /// <summary> /// Creates a new <c>ShoppingList</c>-Object, adds it to the <c>ShoppingLists</c>-Collection (located in the <c>MainPageViewModel</c>). /// </summary> private async void CreateShoppingList() { if (IsDataValid()) { ShoppingList shList = new ShoppingList(Guid.NewGuid().ToString(), ListName.Trim(), SelectedShop); ServiceLocator.Current.GetInstance<MainPageViewModel>().AddShoppingList(shList); InitializeFields(); navigationService.GoBack(); } else { await dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("AddShoppingListValidationErrorContent"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")); } } /// <summary> /// Cancels the Creation-Process of a new <c>ShoppingList-Object</c> and navigates back to the previous page. /// </summary> private async void Cancel() { bool result = true; if (!string.IsNullOrWhiteSpace(ListName) || SelectedShop != null) { // Show dialog result = await dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("AddShopCancelDialogText"), ResourceLoader.GetForCurrentView().GetString("WarningTitle"), ResourceLoader.GetForCurrentView().GetString("AddShopCancelDialogButtonProceed"), ResourceLoader.GetForCurrentView().GetString("CancelText"), null); } // Check if user pressed the "Proceed-Button" if (result) { navigationService.GoBack(); } } /// <summary> /// Checks, if all required values are inputted and valid. /// </summary> /// <returns>Returns <c>true</c> if all inputted values are valid, <c>false</c> if the provided data is invalid.</returns> private bool IsDataValid() { if (ListName.Trim().Equals(string.Empty) || SelectedShop == null) { return false; } return true; } #endregion #region *** Private methods *** /// <summary> /// Initializes all Fields with standard values. /// </summary> private void InitializeFields() { ListName = string.Empty; SelectedShop = null; } #endregion } } <file_sep>using System.Collections.Generic; using System.Windows.Input; using Windows.ApplicationModel.Resources; using Windows.Devices.Geolocation; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using ShoppingListWPApp.Common; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.ViewModels { /// <summary> /// This is the ViewModel for the <c>DetailsShop</c>-View. /// </summary> class DetailsShopViewModel : ViewModelBase { #region *** Private Members *** /// <summary> /// This <c>INavigationService</c>-Object is used for navigating between pages. /// </summary> private INavigationService navigationService; /// <summary> /// This <c>IDialogService</c>-Object is used for displaying Dialogs on the Device-Screen. /// </summary> private IDialogService dialogService; /// <summary> /// The <c>Shop</c>-Object, for which details should be displayed. /// </summary> private Shop shop; #endregion #region *** Properties *** /// <summary> /// Gets or Sets the Name of the selected Shop. /// </summary> public string Name { get; set; } /// <summary> /// Gets or Sets the Address of the selected Shop. /// </summary> public string Address { get; set; } /// <summary> /// Gets or Sets the Radius of Notification of the selected Shop. /// </summary> public double Radius { get; set; } /// <summary> /// Gets or Sets the Geographical Position (Longitude, Latitude, Altitude) of the selected Shop. /// </summary> public BasicGeoposition? Location { get; set; } /// <summary> /// Gets or Sets the <c>ShoppingList</c> objects which are associated with the selected Shop. /// </summary> public List<ShoppingList> ShoppingLists { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to edit the selected Shop. /// </summary> public ICommand EditCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to delete the selected Shop. /// </summary> public ICommand DeleteCommand { get; set; } #endregion public DetailsShopViewModel(INavigationService navigationService, IDialogService dialogService) { // Services this.navigationService = navigationService; this.dialogService = dialogService; // Commands EditCommand = new RelayCommand(Edit); DeleteCommand = new RelayCommand(Delete); } #region *** Public methods *** /// <summary> /// Sets the selected Shop (Selected in the <c>MainPage</c>-View) and assigns its values to the corresponding Properties. /// </summary> /// <param name="idx">The index of the selected <c>Shop</c>-Object in the <c>Shops</c>-Collection (located in the <c>MainPageViewModel</c>)</param> public void SetShop(int idx) { // Set selected Shop (selected on the previous Page) shop = ServiceLocator.Current.GetInstance<MainPageViewModel>().GetShopByIndex(idx); ShoppingLists = ServiceLocator.Current.GetInstance<MainPageViewModel>().GetShoppingListsByShopID(shop.ID); // Initialize all fields with the values of the selected Shop Name = shop.Name; Address = shop.Address; Radius = shop.Radius; Location = shop.Location; } #endregion #region *** Command methods *** /// <summary> /// The <c>Edit</c> method navigates the user to the <c>EditShop</c>-View, in order to edit the selected shop. /// </summary> private void Edit() { navigationService.NavigateTo("editShop", this.shop); } /// <summary> /// The <c>Delete</c> method deletes the selected shop and navigates back to the previous page. /// </summary> private async void Delete() { // Show dialog bool result = await dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("DeleteShopDialogContent"), ResourceLoader.GetForCurrentView().GetString("DeleteShopDialogTitle"), ResourceLoader.GetForCurrentView().GetString("YesText"), ResourceLoader.GetForCurrentView().GetString("NoText"), null); // Check, if user pressed the "Proceed-Button" if (result) { // Delete Shop object and go back to the previous page ServiceLocator.Current.GetInstance<MainPageViewModel>().DeleteShop(this.shop); navigationService.GoBack(); } } #endregion } } <file_sep>using System; using System.Diagnostics; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.UI; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; using Microsoft.Practices.ServiceLocation; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ShoppingListWPApp.Common; using ShoppingListWPApp.Models; using ShoppingListWPApp.ViewModels; using ShoppingListWPApp.Views; namespace ShoppingListWPApp { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { private TransitionCollection transitions; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = false; } #endif Frame rootFrame = Window.Current.Content as Frame; // Initializing Geofencing ServiceLocator.Current.GetInstance<GeoHelper>().InitGeofencing(); // Get Parameters string launchString = e.Arguments; // Check, if launchString is valid if (!string.IsNullOrEmpty(launchString.Trim())) { try { // Get Parameters of the Toast JObject toastLaunch = (JObject)JsonConvert.DeserializeObject(launchString); string t = toastLaunch.GetValue("type").ToObject<string>(); string id = toastLaunch.GetValue("id").ToObject<string>(); if (t.Equals("toast")) { ShoppingList list = ServiceLocator.Current.GetInstance<MainPageViewModel>().GetShoppingListByID(id); rootFrame.Navigate(typeof(AddShoppingListItems), list); } } catch (Exception ex) { } } // Do not repeat app initialization when the Window already has content, // just ensure that the window is active. if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page. rootFrame = new Frame(); // Associate the frame with a SuspensionManager key. SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate. try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { // Something went wrong restoring state. // Assume there is no state and continue. } } // Place the frame in the current Window. Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter. if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active. Window.Current.Activate(); // Setting the style for the Statusbar StatusBar.GetForCurrentView().BackgroundColor = Color.FromArgb(255, 27, 161, 226); StatusBar.GetForCurrentView().BackgroundOpacity = 1; } /// <summary> /// Restores the content transitions after the app has launched. /// </summary> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); await SuspensionManager.SaveAsync(); deferral.Complete(); } /// <summary> /// Shows or hides a Progressbar in the Statusbar of the device. /// /// If toggle is true, the Progressbar will be shown. If toggle is false, the Progressbar will be hidden. /// If a message is present, a text will be shown in Progressbar, otherwise only the Progressbar will be visible. /// </summary> /// <param name="toggle">If true, Progressbar will be shown. If false, Progressbar will be hidden.</param> /// <param name="message">A text that is displayed, while the Progressbar is visible.</param> public static async void ToggleProgressBar(bool toggle, string message = "") { // Get progressbar StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator; if (toggle) { progressbar.Text = message; await progressbar.ShowAsync(); } else { await progressbar.HideAsync(); } } } } <file_sep>using System; using System.Collections.ObjectModel; using Windows.UI.Xaml.Data; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.Converter { /// <summary> /// The <c>ShoppingListItemsToItemsCountConverter</c> is used for getting the Count /// property of an <c>Items</c> collection of a <c>ShoppingList</c> object. /// </summary> class ShoppingListItemsToItemsCountConverter : IValueConverter { /// <summary> /// Gets the Count of <c>ShoppingListItem</c> objects out of the <c>Items</c> collection of a <c>ShoppingList</c> object. /// </summary> /// <param name="value">The <c>Items</c> collection for which the Count should be retrieved.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">Parameters that can be passed to the Converter.</param> /// <param name="language">Cultural information that can be passed to the Converter.</param> /// <returns>Returns a string representation of the Count property of the <c>Items</c> collection.</returns> public object Convert(object value, Type targetType, object parameter, string language) { ObservableCollection<ShoppingListItem> items = (ObservableCollection<ShoppingListItem>)value; return items.Count.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } } <file_sep>using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using ShoppingListWPApp.ViewModels; using ShoppingListWPApp.Views; namespace ShoppingListWPApp.Common { /// <summary> /// The <c>ViewModelLocator</c> registers all used ViewModels and Services (e. g. NavigationService, IDialogService...) /// </summary> class ViewModelLocator { #region *** ViewModels *** /// <summary> /// ViewModel for the <c>MainPage</c>-View. /// </summary> public MainPageViewModel MainPage { get { return ServiceLocator.Current.GetInstance<MainPageViewModel>(); } } /// <summary> /// ViewModel for the <c>AddShop</c>-View. /// </summary> public AddShopViewModel AddShop { get { return ServiceLocator.Current.GetInstance<AddShopViewModel>(); } } /// <summary> /// ViewModel for the <c>EditShop</c>-View. /// </summary> public EditShopViewModel EditShop { get { return ServiceLocator.Current.GetInstance<EditShopViewModel>(); } } /// <summary> /// ViewModel for the <c>DetailsShop</c>-View. /// </summary> public DetailsShopViewModel DetailsShop { get { return ServiceLocator.Current.GetInstance<DetailsShopViewModel>(); } } /// <summary> /// ViewModel for the <c>AddShoppingList</c>-View. /// </summary> public AddShoppingListViewModel AddShoppingList { get { return ServiceLocator.Current.GetInstance<AddShoppingListViewModel>(); } } /// <summary> /// ViewModel for the <c>AddShoppingListItem</c>-View. /// </summary> public AddShoppingListItemViewModel AddShoppingListItem { get { return ServiceLocator.Current.GetInstance<AddShoppingListItemViewModel>(); } } /// <summary> /// ViewModel for the <c>EditShoppingList</c>-View. /// </summary> public EditShoppingListViewModel EditShoppingList { get { return ServiceLocator.Current.GetInstance<EditShoppingListViewModel>(); } } #endregion static ViewModelLocator() { // Create IoC container ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); // Configure the Navigation Service NavigationService navigationService = new NavigationService(); navigationService.Configure("main", typeof(MainPage)); navigationService.Configure("addShop", typeof(AddShop)); navigationService.Configure("editShop", typeof(EditShop)); navigationService.Configure("detailsShop", typeof(DetailsShop)); navigationService.Configure("addShoppingList", typeof(AddShoppingList)); navigationService.Configure("addShoppingListItem", typeof(AddShoppingListItems)); navigationService.Configure("editShoppingList", typeof(EditShoppingList)); // Register Services SimpleIoc.Default.Register<INavigationService>(() => navigationService); SimpleIoc.Default.Register<IDialogService>(() => new DialogService()); SimpleIoc.Default.Register<GeoHelper>(); // Register ViewModels SimpleIoc.Default.Register<MainPageViewModel>(); SimpleIoc.Default.Register<AddShopViewModel>(); SimpleIoc.Default.Register<EditShopViewModel>(); SimpleIoc.Default.Register<DetailsShopViewModel>(); SimpleIoc.Default.Register<AddShoppingListViewModel>(); SimpleIoc.Default.Register<AddShoppingListItemViewModel>(); SimpleIoc.Default.Register<EditShoppingListViewModel>(); } } } <file_sep>using System.Collections.ObjectModel; namespace ShoppingListWPApp.Models { /// <summary> /// An object which holds information about a Shoppinglist. /// </summary> class ShoppingList { /// <summary> /// Gets the ID of the Shoppinglist. /// </summary> public string ID { get; private set; } /// <summary> /// Gets or Sets the ListName of a Shoppinglist. /// </summary> public string ListName { get; set; } /// <summary> /// Gets or Sets the Shop of a Shoppinglist. /// </summary> public Shop Shop { get; set; } /// <summary> /// Gets or Sets the Items of the Shoppinglist. /// </summary> public ObservableCollection<ShoppingListItem> Items { get; set; } public ShoppingList(string id, string name, Shop shop) { ID = id; ListName = name; Shop = shop; Items = new ObservableCollection<ShoppingListItem>(); } public void AddItem(ShoppingListItem shListItem) { Items.Add(shListItem); } } } <file_sep>using System.Collections.ObjectModel; using System.Windows.Input; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using Mutzl.MvvmLight; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.ViewModels { /// <summary> /// This is the ViewModel for the <c>AddShoppingListItem</c>-View. /// </summary> class AddShoppingListItemViewModel : ViewModelBase { #region *** Private Members *** /// <summary> /// This <c>INavigationService</c>-Object is used for navigating between pages. /// </summary> private INavigationService navigationService; /// <summary> /// This <c>IDialogService</c>-Object is used for displaying Dialogs on the Device-Screen. /// </summary> private IDialogService dialogService; #endregion #region *** Properties *** /// <summary> /// Gets or Sets the Name of the new ShoppingListItem. /// </summary> public string Name { get; set; } /// <summary> /// Gets or Sets the AmountAndMeasure of the new ShoppingListItem. /// </summary> public string AmountAndMeasure { get; set; } /// <summary> /// Gets or Sets the ShoppingList of the new ShoppingListItem. /// </summary> public ShoppingList ShoppingList { get; set; } /// <summary> /// Gets or Sets the ShoppingListItem for delete. /// </summary> public ShoppingListItem ShoppingListItem { get; set; } /// <summary> /// Holds all <c>ShoppingListItem</c>-Objects and notifies Views through Data Binding when Changes occur. /// </summary> public ObservableCollection<ShoppingListItem> Items { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to finish the creation-process of a new ShoppingListItem. /// </summary> public ICommand AddItemCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to finish the delete-process of a ShoppingListItem. /// </summary> public ICommand DeleteItemCommand { get; set; } #endregion public AddShoppingListItemViewModel(INavigationService navigationService, IDialogService dialogService) { // Services this.navigationService = navigationService; this.dialogService = dialogService; // Commands AddItemCommand = new DependentRelayCommand(CreateItem, IsDataValid, this, () => Name, () => AmountAndMeasure); DeleteItemCommand = new RelayCommand(DeleteItem); // Initialize all Fields with standard values InitializeFields(); } #region *** command methods *** /// <summary> /// Creates a new <c>ShoppingListItem</c>-Object, adds it to the <c>ShoppingLists</c>-Collection (located in the <c>MainPageViewModel</c>). /// </summary> private void CreateItem() { ShoppingListItem item = new ShoppingListItem(Name, AmountAndMeasure); ShoppingList.AddItem(item); // Get old object ShoppingList oldShoppingList = ServiceLocator.Current.GetInstance<MainPageViewModel>().GetShoppingListByID(ShoppingList.ID); // Update Shoppinglist ServiceLocator.Current.GetInstance<MainPageViewModel>().EditShoppingList(oldShoppingList, ShoppingList); // Reset all fields InitializeFields(); } /// <summary> /// Removes a <c>ShoppingListItem</c>-Object from the <c>Items</c>-Collection. /// </summary> private void DeleteItem() { Items.Remove(ShoppingListItem); // Get old object ShoppingList oldShoppingList = ServiceLocator.Current.GetInstance<MainPageViewModel>().GetShoppingListByID(ShoppingList.ID); // Update Shoppinglist ServiceLocator.Current.GetInstance<MainPageViewModel>().EditShoppingList(oldShoppingList, ShoppingList); ShoppingListItem = null; } #endregion #region *** private methods *** /// <summary> /// Initializes all Fields with standard values. /// </summary> private void InitializeFields() { Name = string.Empty; AmountAndMeasure = string.Empty; } /// <summary> /// Checks, if all required values are set and valid. /// </summary> /// <returns>Returns <c>true</c> if all inputted values are valid, <c>false</c> if the provided data is invalid.</returns> private bool IsDataValid() { if (Name.Trim().Equals(string.Empty) || AmountAndMeasure.Trim().Equals(string.Empty)) { return false; } return true; } #endregion } } <file_sep>using System; using System.Linq; using Windows.ApplicationModel.Resources; using Windows.Devices.Geolocation; using Windows.Foundation; using Windows.Services.Maps; using Windows.System; using Windows.UI; using Windows.UI.Popups; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Maps; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Shapes; using Microsoft.Practices.ServiceLocation; using ShoppingListWPApp.Common; using ShoppingListWPApp.ViewModels; namespace ShoppingListWPApp.Views { /// <summary> /// This is the corresponding View of the AddShopViewModel. /// </summary> public sealed partial class AddShop : Page { /// <summary> /// NavigationHelper aids in navigation between pages. /// </summary> private NavigationHelper navigationHelper; public AddShop() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += this.NavigationHelper_LoadState; this.navigationHelper.SaveState += this.NavigationHelper_SaveState; // Append MapTapped method of AddShopViewModel to MapTapped event of the MapControl Map.MapTapped += ServiceLocator.Current.GetInstance<AddShopViewModel>().MapTapped; // Initialize Map styles MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleStandard")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleAerial")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleAerialWithRoads")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleTerrain")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleRoads")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleNone")); MapStyles.SelectedIndex = 0; } /// <summary> /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>. /// </summary> public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/> /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager.SessionState"/>. /// </summary> /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param> /// <param name="e">Event data that provides an empty dictionary to be populated with /// serializable state.</param> private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e) { } #region NavigationHelper registration /// <summary> /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// <para> /// Page specific logic should be placed in event handlers for the /// <see cref="NavigationHelper.LoadState"/> /// and <see cref="NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. /// </para> /// </summary> /// <param name="e">Provides data for navigation methods and event /// handlers that cannot cancel the navigation request.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); // Center device's location on the MapControl GetMyLocation(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { this.navigationHelper.OnNavigatedFrom(e); } #endregion #region *** Event methods *** /// <summary> /// Adds a <c>MapIcon</c> to the <c>MapControl</c>, when the user taps on the MapControl. /// </summary> /// <param name="sender">The <c>MapControl</c> that has been tapped by the user.</param> /// <param name="args">Contains the geographical position of the point, where the User tapped on the <c>MapControl</c>.</param> private void Map_MapTapped(MapControl sender, MapInputEventArgs args) { try { // Clear all MapIcons of the MapControl Map.Children.Clear(); // Create pushpin Ellipse pushpin = new Ellipse { Fill = new SolidColorBrush(Color.FromArgb(255, 27, 161, 226)), Stroke = new SolidColorBrush(Colors.White), StrokeThickness = 2, Width = 20, Height = 20, }; // Add Pin to MapControl MapControl.SetLocation(pushpin, args.Location); MapControl.SetNormalizedAnchorPoint(pushpin, new Point(0.5, 0.5)); Map.Children.Add(pushpin); } catch (Exception ex) { } } /// <summary> /// This event gets fired, when the <c>AppbarButton</c> for device location gets tapped. /// /// This event gets the current geographical position of the device and centers this position in the <c>MapControl</c>. /// </summary> /// <param name="sender">The <c>AppbarButton</c> that has been tapped by the user.</param> /// <param name="e">Event arguments</param> /// <seealso cref="GetMyLocation()"/> private void AbtnFindMe_Click(object sender, RoutedEventArgs e) { GetMyLocation(); } /// <summary> /// This event gets fired, when the Find-<c>Button</c> in the Flyout for finding addresses gets tapped. /// This event executes the <c>FindAddress</c> method. /// </summary> /// <param name="sender">The <c>Button</c> that has been tapped by the user.</param> /// <param name="e">Event arguments</param> /// <seealso cref="FindAddress(string)"/> private void BtnFind_Click(object sender, RoutedEventArgs e) { FindAddress(TbxAddress.Text); AbtnFind.Flyout.Hide(); } /// <summary> /// This event gets fired, when the Cancel-<c>Button</c> in the Flyout for finding addresses gets tapped. /// This event hides the Flyout for finding addresses. /// </summary> /// <param name="sender">The <c>Button</c> that has been tapped by the user.</param> /// <param name="e">Event arguments</param> private void BtnCancel_Click(object sender, RoutedEventArgs e) { AbtnFind.Flyout.Hide(); } /// <summary> /// This method hides the soft-keyboard after pressing the Enter-Button in the sof-keyboard and executes the <c>FindAddress</c> method. /// </summary> /// <param name="sender">The sender of the <c>KeyDown</c> event.</param> /// <param name="e">Contains the key that has been pressed by the user.</param> /// <seealso cref="FindAddress(string)"/> private void TbxAddress_KeyDown(object sender, KeyRoutedEventArgs e) { // Check, if the Enter-Button has been pressed if (e.Key.Equals(VirtualKey.Enter)) { FindAddress(TbxAddress.Text); InputPane.GetForCurrentView().TryHide(); AbtnFind.Flyout.Hide(); } } /// <summary> /// Sets the style of the MapControl on the AddShop-View. /// /// This method gets invoked, when the selected item of the <c>MapStyles</c> combobox changes. /// </summary> /// <param name="sender">The combobox, for which the <c>SelectedItem</c> property has changed.</param> /// <param name="e">Event arguments.</param> private void MapStyles_SelectionChanged(object sender, SelectionChangedEventArgs e) { switch (MapStyles.SelectedIndex) { case 0: Map.Style = MapStyle.Road; break; case 1: Map.Style = MapStyle.Aerial; break; case 2: Map.Style = MapStyle.AerialWithRoads; break; case 3: Map.Style = MapStyle.Terrain; break; case 4: Map.Style = MapStyle.Road; break; case 5: Map.Style = MapStyle.None; break; default: Map.Style = MapStyle.None; break; } // Close Flyout AbtnMapStyle.Flyout.Hide(); } #endregion #region *** Private methods *** /// <summary> /// Gets the current location of the device and centers the current position on the <c>MapControl</c>. /// </summary> private async void GetMyLocation() { try { // Getting current location of device Geoposition position; try { App.ToggleProgressBar(true, ResourceLoader.GetForCurrentView().GetString("StatusBarGettingLocation")); position = await ServiceLocator.Current.GetInstance<GeoHelper>().Locator.GetGeopositionAsync(); App.ToggleProgressBar(false, null); } catch (NullReferenceException nullEx) { App.ToggleProgressBar(false, null); return; } catch (Exception ex) { App.ToggleProgressBar(false, null); new MessageDialog( ResourceLoader.GetForCurrentView().GetString("GPSError"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")).ShowAsync(); return; } // Center current position in the MapControl Map.Center = position.Coordinate.Point; Map.DesiredPitch = 0; await Map.TrySetViewAsync(position.Coordinate.Point, 15); } catch (Exception ex) { new MessageDialog( ResourceLoader.GetForCurrentView().GetString("GPSError"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")).ShowAsync(); } } /// <summary> /// This method tries to find the geographical position of a given address. /// </summary> /// <param name="address">Address for which the geographical position should be found.</param> private async void FindAddress(string address) { try { // Getting current location of device Geoposition position; try { App.ToggleProgressBar(true, ResourceLoader.GetForCurrentView().GetString("StatusBarGettingLocation")); position = await ServiceLocator.Current.GetInstance<GeoHelper>().Locator.GetGeopositionAsync(); App.ToggleProgressBar(false, null); } catch (NullReferenceException nullEx) { App.ToggleProgressBar(false, null); return; } catch (Exception ex) { App.ToggleProgressBar(false, null); new MessageDialog( ResourceLoader.GetForCurrentView().GetString("GPSError"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")).ShowAsync(); return; } // Finding geographical position of a given address App.ToggleProgressBar(true, ResourceLoader.GetForCurrentView().GetString("StatusBarSearchingAddress")); MapLocationFinderResult FinderResult = await MapLocationFinder.FindLocationsAsync(address, position.Coordinate.Point); App.ToggleProgressBar(false, null); // Check, if any positions have been found if (FinderResult.Status == MapLocationFinderStatus.Success && FinderResult.Locations.Count > 0) { // Set found position as selected Location in the AddShopViewModel ServiceLocator.Current.GetInstance<AddShopViewModel>().Location = FinderResult.Locations.First().Point.Position; // Get exact address of the found location and set it as the address of the selected location in the AddShopViewModel var selectedLocation = FinderResult.Locations.First(); string format = "{0} {1}, {2} {3}, {4}"; ServiceLocator.Current.GetInstance<AddShopViewModel>().Address = string.Format(format, selectedLocation.Address.Street, selectedLocation.Address.StreetNumber, selectedLocation.Address.PostCode, selectedLocation.Address.Town, selectedLocation.Address.CountryCode); // Clear all MapIcons of the MapControl Map.Children.Clear(); // Create pushpin Ellipse pushpin = new Ellipse { Fill = new SolidColorBrush(Color.FromArgb(255, 27, 161, 226)), Stroke = new SolidColorBrush(Colors.White), StrokeThickness = 2, Width = 20, Height = 20, }; // Add Pin to MapControl MapControl.SetLocation(pushpin, FinderResult.Locations.First().Point); MapControl.SetNormalizedAnchorPoint(pushpin, new Point(0.5, 0.5)); Map.Children.Add(pushpin); // Center found location on the MapControl Map.Center = FinderResult.Locations.First().Point; Map.DesiredPitch = 0; await Map.TrySetViewAsync(FinderResult.Locations.First().Point, 15); } else { await new MessageDialog( ResourceLoader.GetForCurrentView().GetString("AddShopFindAddressDialogNotFoundText"), ResourceLoader.GetForCurrentView().GetString("AddShopFindAddressDialogNotFoundTitle")) .ShowAsync(); } } catch (Exception ex) { new MessageDialog( ResourceLoader.GetForCurrentView().GetString("GetLocationByAddressError"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")).ShowAsync(); } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Windows.ApplicationModel.Background; using Windows.Data.Xml.Dom; using Windows.Devices.Geolocation.Geofencing; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace GeofenceTask { /// <summary> /// This Background Task is used for responding on Geofence events. /// /// This Background Task gets triggered, when the device enters a Geofence that was created by the App. /// </summary> public sealed class BackgroundGeofenceTask : IBackgroundTask { /// <summary> /// A Collection of <c>ShoppingList</c> objects in JSON format. /// /// This collection gets populated by the <c>Run</c> method while loading shopping list data out of the isolated storage. /// </summary> private JArray shoppingLists; /// <summary> /// Reads out current Geofence-Reports and creates corresponding Toast Notifications and displays them. /// /// This method gets invoked, when the device enters a Geofence that was created by the App. /// </summary> /// <param name="taskInstance">The current Instance of the Background Task.</param> public async void Run(IBackgroundTaskInstance taskInstance) { // Get entered Geofences var Reports = GeofenceMonitor.Current.ReadReports(); //Get all Shopping Lists BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try { // Get App's folder and create file var folder = ApplicationData.Current.LocalFolder; var file = await folder.GetFileAsync("lists.json"); // Load data out of file string data = await FileIO.ReadTextAsync(file, UnicodeEncoding.Utf8); shoppingLists = (JArray)JsonConvert.DeserializeObject(data) ?? new JArray(); } catch (Exception ex) { } // Check, if shopping lists were loaded correctly and if the list contains elements if (shoppingLists == null || shoppingLists.Count == 0) { return; } // Iterate through all entered Geofences foreach (var rep in Reports) { // Get Shop ID (Geofence ID == Shop ID) string id = rep.Geofence.Id; // Get all ShoppingLists of a shop IEnumerable<JToken> lists = (from list in shoppingLists where list.Value<JObject>("Shop").Value<string>("ID").Equals(id) select list); // Iterate through all selected lists foreach (JToken list in lists) { // Get Shopping List information string listID = list.Value<string>("ID"); string listName = list.Value<string>("ListName"); // Get Shop information string shopName = list.Value<JObject>("Shop").Value<string>("Name"); string shopAddress = list.Value<JObject>("Shop").Value<string>("Address") ?? string.Empty; string formattedShop; // Check, if Address field is set if (shopAddress.Trim().Equals(string.Empty)) { formattedShop = shopName; } else { formattedShop = shopName + ", " + shopAddress; } // Create Toast template ToastTemplateType toastTemplate = ToastTemplateType.ToastText02; XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text"); // Add content to Toast toastTextElements[0].AppendChild(toastXml.CreateTextNode(listName)); toastTextElements[1].AppendChild(toastXml.CreateTextNode(formattedShop)); // Set parameters of Toast IXmlNode toastNode = toastXml.SelectSingleNode("/toast"); ((XmlElement)toastNode).SetAttribute("launch", "{\"type\":\"toast\",\"id\":\"" + listID + "\"}"); // Create and display Toast ToastNotification toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); } } deferral.Complete(); } } } <file_sep>using Windows.UI.Xaml; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using Microsoft.Xaml.Interactivity; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.Common { /// <summary> /// The class <c>GoToShoppingListItemAction</c> defines an Action that happens, if an Item in the /// ShoppingLists-<c>ListView</c> on the <c>MainPage</c>-View gets tapped by the user. /// </summary> class GoToShoppingListItemAction : DependencyObject, IAction { // <summary> /// Gets the Index of the <c>ShoppingList</c>-Object of the tapped List-Item in the /// ShoppingLists-<c>ListView</c> and navigates with this information to the <c>AddShoppingList</c>-View. /// </summary> /// <param name="sender">The Sender of the <c>Tapped</c>-Event (a List-Item in the <c>ListView</c>)</param> /// <param name="parameter">The parameters that the sender sends to the <c>Execute</c>-Method (specified by the caller)</param> /// <returns><c>null</c></returns> public object Execute(object sender, object parameter) { // Get sender of the Action FrameworkElement senderElement = sender as FrameworkElement; ServiceLocator.Current.GetInstance<INavigationService>().NavigateTo("addShoppingListItem", (ShoppingList)senderElement.DataContext); return null; } } } <file_sep>namespace ShoppingListWPApp.Models { /// <summary> /// An object which holds information about a Shoppinglistitem. /// </summary> class ShoppingListItem { /// <summary> /// Gets or Sets the Name of a Shoppinglistitem. /// </summary> public string Name { get; set; } /// <summary> /// Gets or Sets the AmountAndMeasure of a Shoppinglistitem. /// </summary> public string AmountAndMeasure { get; set; } public ShoppingListItem(string name, string amountAndMeasure) { Name = name; AmountAndMeasure = amountAndMeasure; } } } <file_sep>using Windows.UI.Xaml; using Windows.UI.Xaml.Controls.Primitives; using Microsoft.Practices.ServiceLocation; using Microsoft.Xaml.Interactivity; using ShoppingListWPApp.Models; using ShoppingListWPApp.ViewModels; namespace ShoppingListWPApp.Common { /// <summary> /// The class <c>OpenMenuFlyoutAction</c> defines an Action that happens, if an Item in the /// Shops-<c>ListView</c> on the <c>MainPage</c>-View gets holded by the user. /// </summary> class OpenMenuFlyoutAction : DependencyObject, IAction { /// <summary> /// Gets the <c>Shop</c>-Object of the holded List-Item in the /// Shops-<c>ListView</c> and sets this <c>Shop</c>-Object as the <c>SelectedShop</c>-Object in the <c>MainPageViewModel</c>. /// </summary> /// <param name="sender">The Sender of the <c>Holding</c>-Event (a List-Item in the <c>ListView</c>)</param> /// <param name="parameter">The parameters that the sender sends to the <c>Execute</c>-Method (specified by the caller)</param> /// <returns><c>null</c></returns> public object Execute(object sender, object parameter) { // Get sender of the Action FrameworkElement senderElement = sender as FrameworkElement; if(senderElement.DataContext.GetType() == typeof(Shop)) { // Set the in the ListView currently selected Shop in the MainViewModel ServiceLocator.Current.GetInstance<MainPageViewModel>().SelectedShop = (Shop)senderElement.DataContext; } else if (senderElement.DataContext.GetType() == typeof(ShoppingList)) { // Set the in the ListView currently selected ShoppingList in the MainViewModel ServiceLocator.Current.GetInstance<MainPageViewModel>().SelectedShoppingList = (ShoppingList)senderElement.DataContext; } else if (senderElement.DataContext.GetType() == typeof(ShoppingListItem)) { ServiceLocator.Current.GetInstance<AddShoppingListItemViewModel>().ShoppingListItem = (ShoppingListItem)senderElement.DataContext; } // Show the MenuFlyout FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement); flyoutBase.ShowAt(senderElement); return null; } } } <file_sep>using System; using Windows.UI.Xaml.Data; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.Converter { /// <summary> /// The <c>ShoppingListToShoppingListNameConverter</c> is used for converting the /// <c>Shop</c> object of a <c>ShoppingList</c> object into a formatted string representation of the object. /// </summary> class ShoppingListToShoppingListNameConverter : IValueConverter { /// <summary> /// Gets the <c>Shop</c> object out of a <c>ShoppingList</c> object and returns a string representation of its information. /// </summary> /// <param name="value">The <c>ShoppingList</c> object that should be converted.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">Defines which information of the <c>Shop</c> object should be returned. /// Use either "name" (without asterisks) as parameter for returning the name of the <c>Shop</c> object, /// or "address" for returning a string representation of the <c>Shop</c> object.</param> /// <param name="language">Cultural information that can be passed to the Converter.</param> /// <returns>Returns information about the <c>Shop</c> object of a <c>ShoppingList</c> object depending on the parameter passed to the method.</returns> public object Convert(object value, Type targetType, object parameter, string language) { ShoppingList list = (ShoppingList)value; switch ((string)parameter) { case "name": return list.ListName; case "address": return list.Shop.ToString(); default: return null; } } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } } <file_sep>using Windows.Devices.Geolocation; namespace ShoppingListWPApp.Models { /// <summary> /// An object which holds information about a Shop. /// </summary> public class Shop { /// <summary> /// Gets the ID of a Shop. /// </summary> public string ID { get; private set; } /// <summary> /// Gets or Sets the Name of a Shop. /// </summary> public string Name { get; set; } /// <summary> /// Gets or Sets the Address of a Shop. /// </summary> public string Address { get; set; } /// <summary> /// Gets or Sets the Radius of a Shop. /// </summary> public double Radius { get; set; } /// <summary> /// Gets or Sets the Geographical Position (Longitude, Latitude, Altitude) of a Shop. /// </summary> public BasicGeoposition? Location { get; set; } public Shop(string id, string name, string address, double radius, BasicGeoposition? location) { ID = id; Name = name; Address = address; Radius = radius; Location = location; } /// <summary> /// Gets a formatted representation of the Shop containing the Name and Address of the Shop. /// /// If the Address property is null, only the Name of the Shop will be returned. /// </summary> /// <returns>A formatted representation of the Shop.</returns> public override string ToString() { // Check, if Address property is empty or null if (Address.Trim().Equals(string.Empty) || Address == null) { return Name; } return Name + ", " + Address; } } } <file_sep>using System; using System.Linq; using System.Windows.Input; using Windows.ApplicationModel.Resources; using Windows.Devices.Geolocation; using Windows.Services.Maps; using Windows.UI.Xaml.Controls.Maps; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using Mutzl.MvvmLight; using ShoppingListWPApp.Common; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.ViewModels { /// <summary> /// This is the ViewModel for the <c>EditShop</c>-View. /// </summary> class EditShopViewModel : ViewModelBase { #region *** Private Members *** /// <summary> /// This <c>INavigationService</c>-Object is used for navigating between pages. /// </summary> private INavigationService navigationService; /// <summary> /// This <c>IDialogService</c>-Object is used for displaying Dialogs on the Device-Screen. /// </summary> private IDialogService dialogService; /// <summary> /// The <c>Shop</c>-Object that should be modified. /// </summary> private Shop oldShop; #endregion #region *** Properties *** /// <summary> /// Gets or Sets the Name of the selected Shop. /// </summary> public string Name { get; set; } /// <summary> /// Gets or Sets the Address of the selected Shop. /// </summary> public string Address { get; set; } /// <summary> /// Gets or Sets the Radius of Notification of the selected Shop. /// </summary> public double Radius { get; set; } /// <summary> /// Gets or Sets the Geographical Position (Longitude, Latitude, Altitude) of the selected Shop. /// </summary> public BasicGeoposition? Location { get; set; } /// <summary> /// Gets or Sets the minimum value of the Radius of Notification. /// </summary> public double MinimumRadius { get; set; } /// <summary> /// Gets or Sets the maximum value of the Radius of Notification. /// </summary> public double MaximumRadius { get; set; } /// <summary> /// Gets or Sets the incrementation step value of the Radius of Notification. /// </summary> public double RadiusStepValue { get; set; } /// <summary> /// Gets or Sets the Frequency of Ticks that should be displayed on the Slider for the Radius of Notification. /// </summary> public double TickFrequency { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to finish the editting-process of the selected Shop. /// /// If the Properties <c>Name</c> and <c>Location</c> are not set, the Button for the <c>DoneCommand</c> is disabled. /// </summary> public ICommand DoneCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to cancel the editting-process of the selected Shop. /// </summary> public ICommand CancelCommand { get; set; } #endregion public EditShopViewModel(INavigationService navigationService, IDialogService dialogService) { // Services this.navigationService = navigationService; this.dialogService = new DialogService(); // Commands DoneCommand = new DependentRelayCommand(Edit, IsDataValid, this, () => Name, () => Location); CancelCommand = new RelayCommand(Cancel); // Get regional-specific values for the Radius out of the Resource-File MinimumRadius = 0.05; MaximumRadius = 1; RadiusStepValue = 0.05; TickFrequency = 0.2; } #region *** Public methods *** /// <summary> /// Sets the shop that should be modified and assigns its values to the corresponding values. /// </summary> /// <param name="oldShop">The <c>Shop</c>-Object that should be modified.</param> public void SetShop(Shop oldShop) { // Set selected Shop (selected on the previous Page) this.oldShop = oldShop; // Initialize all fields with the values of the selected Shop Name = oldShop.Name; Address = oldShop.Address; Radius = oldShop.Radius; Location = oldShop.Location; } /// <summary> /// The <c>MapTapped</c> method gets invoked, when the user taps on the <c>MapControl</c> provided by the <c>EditShop</c>-View. /// It gets the geographical position of the point, where the User tapped on the <c>MapControl</c>. With this position, /// the method estimates an address and saves the gathered values to its Properties (<c>Location</c> and <c>Address</c>). /// /// If there are no results for the address, the values for the Properties don't get set. /// </summary> /// <param name="sender">The <c>MapControl</c> provided by the View, which was tapped by the User.</param> /// <param name="args">Contains the geographical position of the point, where the User tapped on the <c>MapControl</c>.</param> public async void MapTapped(MapControl sender, MapInputEventArgs args) { try { // Set tapped Location as selected location Location = args.Location.Position; // Find corresponding address of the location MapLocationFinderResult FinderResult = await MapLocationFinder.FindLocationsAtAsync(args.Location); // Check, if any address has been found if (FinderResult.Status == MapLocationFinderStatus.Success && FinderResult.Locations.Count > 0) { // Format and set address of the selected location var selectedLocation = FinderResult.Locations.First(); string format = "{0} {1}, {2} {3}, {4}"; Address = string.Format(format, selectedLocation.Address.Street, selectedLocation.Address.StreetNumber, selectedLocation.Address.PostCode, selectedLocation.Address.Town, selectedLocation.Address.CountryCode); } else { Address = string.Empty; } } catch (Exception ex) { Address = string.Empty; dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("FindAddressError"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")); } } #endregion #region *** Command methods *** /// <summary> /// Checks, if all required values are inputted and valid. /// </summary> /// <returns>Returns <c>true</c> if all inputted values are valid, <c>false</c> if the provided data is invalid.</returns> private bool IsDataValid() { if (Name.Trim().Equals(string.Empty) || Location == null) { return false; } return true; } /// <summary> /// Creates a new <c>Shop</c>-Object with the modified values of the previously selected shop, /// replaces the old object with the new one in the <c>Shops</c>-Collection (located in the <c>MainPageViewModel</c>) and navigates back to the previous page. /// </summary> private void Edit() { // Create new Shop object and replace old object with new one Shop newShop = new Shop(Guid.NewGuid().ToString(), Name.Trim(), Address, Radius, Location); ServiceLocator.Current.GetInstance<MainPageViewModel>().EditShop(oldShop, newShop); // Go back to previous Page navigationService.GoBack(); } /// <summary> /// Cancels the Editting-Process of the selected <c>Shop</c>-Object and navigates back to the previous page. /// </summary> private async void Cancel() { // Show dialog bool result = await dialogService.ShowMessage(ResourceLoader.GetForCurrentView().GetString("AddShopCancelDialogText"), ResourceLoader.GetForCurrentView().GetString("WarningTitle"), ResourceLoader.GetForCurrentView().GetString("AddShopCancelDialogButtonProceed"), ResourceLoader.GetForCurrentView().GetString("CancelText"), null); // Check, if user pressed the "Proceed-Button" if (result) { // Go back to the previous page navigationService.GoBack(); } } #endregion } } <file_sep>using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; namespace ShoppingListWPApp.Converter { /// <summary> /// The <c>ShoppingListsToVisibilityConverter</c> is used for getting the Visibility status /// based on the Count value of a <c>ItemCollection</c> object. /// </summary> class ShoppingListsToVisibilityConverter : IValueConverter { /// <summary> /// Gets the Count value of a <c>ItemCollection</c> object and returns the Visibility Status based on this value. /// </summary> /// <param name="value">The <c>ItemCollection</c> object for which a Visiblity status should be returned.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">Parameters that can be passed to the Converter.</param> /// <param name="language">Cultural information that can be passed to the Converter.</param> /// <returns>Visibility.Collapsed, if the <c>ItemCollection</c> object is empty, otherwise Visibility.Visible</returns> public object Convert(object value, Type targetType, object parameter, string language) { ItemCollection col = (ItemCollection)value; // Check if Collection is empty if (col.Count == 0) { return Visibility.Collapsed; } return Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.ObjectModel; using System.Linq; using System.Windows.Input; using Windows.ApplicationModel.Resources; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using Mutzl.MvvmLight; using ShoppingListWPApp.Common; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.ViewModels { /// <summary> /// This is the ViewModel for the <c>EditShoppingList</c>-View. /// </summary> class EditShoppingListViewModel : ViewModelBase { #region *** Private Members *** /// <summary> /// This <c>INavigationService</c>-Object is used for navigating between pages. /// </summary> private INavigationService navigationService; /// <summary> /// This <c>IDialogService</c>-Object is used for displaying Dialogs on the Device-Screen. /// </summary> private IDialogService dialogService; /// <summary> /// The <c>ShoppingList</c>-Object that should be modified. /// </summary> private ShoppingList oldShoppingList; #endregion #region *** Properties *** /// <summary> /// Gets or Sets the ListName of the new ShoppingListItem. /// </summary> public string ListName { get; set; } /// <summary> /// The currently selected <c>Shop</c>-Object in the Shops-<c>ListView</c> of the <c>MainPage</c>-View. /// </summary> public Shop SelectedShop { get; set; } /// <summary> /// Holds all <c>Shop</c>-Objects and notifies Views through Data Binding when Changes occur. /// </summary> public ObservableCollection<Shop> Shops { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to finish the creation-process of a new ShoppingList. /// </summary> public ICommand EditShoppingListCommand { get; set; } /// <summary> /// Gets or Sets the Command that is issued by the user, in order to cancel the creation-process of a new ShoppingList. /// </summary> public ICommand CancelCommand { get; set; } #endregion public EditShoppingListViewModel(INavigationService navigationService, IDialogService dialogService) { //Service this.navigationService = navigationService; this.dialogService = dialogService; //Commands EditShoppingListCommand = new DependentRelayCommand(Edit, IsDataValid, this, () => ListName, () => SelectedShop); CancelCommand = new RelayCommand(Cancel); } #region *** Public methods *** /// <summary> /// Sets the shoppinglist that should be modified and assigns its values to the corresponding values. /// </summary> /// <param name="oldShoppingList">The <c>ShoppingList</c>-Object that should be modified.</param> public void SetShoppingList(ShoppingList oldShoppingList) { // Set selected ShoppingList (selected on the previous Page) this.oldShoppingList = oldShoppingList; // Set Shops Shops = ServiceLocator.Current.GetInstance<MainPageViewModel>().Shops; // Initialize all fields with the values of the selected Shoppinglist ListName = oldShoppingList.ListName; SelectedShop = (from s in Shops where s.ID.Equals(oldShoppingList.Shop.ID) select s).First(); } #endregion #region *** Command methods *** /// <summary> /// Checks, if all required values are inputted and valid. /// </summary> /// <returns>Returns <c>true</c> if all inputted values are valid, <c>false</c> if the provided data is invalid.</returns> private bool IsDataValid() { return !string.IsNullOrWhiteSpace(ListName) && SelectedShop != null; } /// <summary> /// Creates a new <c>ShoppingList</c>-Object with the modified values of the previously selected shoppingList, /// replaces the old object with the new one in the <c>Shops</c>-Collection (located in the <c>MainPageViewModel</c>) and navigates back to the previous page. /// </summary> private void Edit() { // Create new Shop object and replace old object with new one ShoppingList newShoppingList = new ShoppingList(Guid.NewGuid().ToString(), ListName.Trim(), SelectedShop); newShoppingList.Items = oldShoppingList.Items; ServiceLocator.Current.GetInstance<MainPageViewModel>().EditShoppingList(oldShoppingList, newShoppingList); // Go back to previous Page navigationService.GoBack(); } /// <summary> /// Cancels the Editting-Process of the selected <c>ShoppingList</c>-Object and navigates back to the previous page. /// </summary> private async void Cancel() { // Show dialog bool result = await dialogService.ShowMessage(ResourceLoader.GetForCurrentView().GetString("AddShopCancelDialogText"), ResourceLoader.GetForCurrentView().GetString("WarningTitle"), ResourceLoader.GetForCurrentView().GetString("AddShopCancelDialogButtonProceed"), ResourceLoader.GetForCurrentView().GetString("CancelText"), null); // Check, if user pressed the "Proceed-Button" if (result) { // Go back to the previous page navigationService.GoBack(); } } #endregion } } <file_sep>using System; using Windows.ApplicationModel.Resources; using Windows.Devices.Geolocation; using Windows.Foundation; using Windows.UI; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Maps; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Shapes; using Microsoft.Practices.ServiceLocation; using ShoppingListWPApp.Common; using ShoppingListWPApp.ViewModels; namespace ShoppingListWPApp.Views { /// <summary> /// This is the corresponding View of the DetailsShopViewModel. /// </summary> public sealed partial class DetailsShop : Page { /// <summary> /// NavigationHelper aids in navigation between pages. /// </summary> private NavigationHelper navigationHelper; public DetailsShop() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += this.NavigationHelper_LoadState; this.navigationHelper.SaveState += this.NavigationHelper_SaveState; // Initialize Map styles MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleStandard")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleAerial")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleAerialWithRoads")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleTerrain")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleRoads")); MapStyles.Items.Add(ResourceLoader.GetForCurrentView().GetString("MapStyleNone")); MapStyles.SelectedIndex = 0; } /// <summary> /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>. /// </summary> public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/> /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { // Set selected shop (selected on the MainPage) in the DetailsShopViewModel ServiceLocator.Current.GetInstance<DetailsShopViewModel>().SetShop((int)e.NavigationParameter); } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager.SessionState"/>. /// </summary> /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param> /// <param name="e">Event data that provides an empty dictionary to be populated with /// serializable state.</param> private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e) { } #region NavigationHelper registration /// <summary> /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// <para> /// Page specific logic should be placed in event handlers for the /// <see cref="NavigationHelper.LoadState"/> /// and <see cref="NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. /// </para> /// </summary> /// <param name="e">Provides data for navigation methods and event /// handlers that cannot cancel the navigation request.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); try { // Clear all MapIcons of the MapControl Map.Children.Clear(); // Add a MapIcon with the location of the selected Shop (selected on the MainPage) to the MapControl Geopoint point = new Geopoint((BasicGeoposition)ServiceLocator.Current.GetInstance<DetailsShopViewModel>().Location); // Create pushpin Ellipse pushpin = new Ellipse { Fill = new SolidColorBrush(Color.FromArgb(255, 27, 161, 226)), Stroke = new SolidColorBrush(Colors.White), StrokeThickness = 2, Width = 20, Height = 20, }; // Add Pin to MapControl MapControl.SetLocation(pushpin, point); MapControl.SetNormalizedAnchorPoint(pushpin, new Point(0.5, 0.5)); Map.Children.Add(pushpin); // Center the selected location on the MapControl Map.Center = point; Map.DesiredPitch = 0; await Map.TrySetViewAsync(point, 15); } catch (Exception ex) { } } protected override void OnNavigatedFrom(NavigationEventArgs e) { this.navigationHelper.OnNavigatedFrom(e); } #endregion /// <summary> /// Sets the style of the MapControl on the DetailsShop-View. /// /// This method gets invoked, when the selected item of the <c>MapStyles</c> combobox changes. /// </summary> /// <param name="sender">The combobox, for which the <c>SelectedItem</c> property has changed.</param> /// <param name="e">Event arguments.</param> private void MapStyles_SelectionChanged(object sender, SelectionChangedEventArgs e) { switch (MapStyles.SelectedIndex) { case 0: Map.Style = MapStyle.Road; break; case 1: Map.Style = MapStyle.Aerial; break; case 2: Map.Style = MapStyle.AerialWithRoads; break; case 3: Map.Style = MapStyle.Terrain; break; case 4: Map.Style = MapStyle.Road; break; case 5: Map.Style = MapStyle.None; break; default: Map.Style = MapStyle.None; break; } // Close Flyout AbtnMapStyle.Flyout.Hide(); } } } <file_sep>using System; using Windows.UI.Xaml.Data; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.Converter { class ShopToNameConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { Shop shop = (Shop)value; return shop.Name + ", " + shop.Address; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } } <file_sep>using Windows.UI.Xaml; using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using Microsoft.Xaml.Interactivity; using ShoppingListWPApp.Models; using ShoppingListWPApp.ViewModels; namespace ShoppingListWPApp.Common { /// <summary> /// The class <c>GoToShopDetailsAction</c> defines an Action that happens, if an Item in the /// Shops-<c>ListView</c> on the <c>MainPage</c>-View gets tapped by the user. /// </summary> class GoToShopDetailsAction : DependencyObject, IAction { /// <summary> /// Gets the Index of the <c>Shop</c>-Object of the tapped List-Item in the /// Shops-<c>ListView</c> and navigates with this information to the <c>DetailsShop</c>-View. /// </summary> /// <param name="sender">The Sender of the <c>Tapped</c>-Event (a List-Item in the <c>ListView</c>)</param> /// <param name="parameter">The parameters that the sender sends to the <c>Execute</c>-Method (specified by the caller)</param> /// <returns><c>null</c></returns> public object Execute(object sender, object parameter) { // Get sender of the Action FrameworkElement senderElement = sender as FrameworkElement; // Get Index of Shop and navigate to Details-Page of the tapped Shop int idx = ServiceLocator.Current.GetInstance<MainPageViewModel>().IndexOfShop((Shop)senderElement.DataContext); ServiceLocator.Current.GetInstance<INavigationService>().NavigateTo("detailsShop", idx); return null; } } } <file_sep>using System; using System.Linq; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.ApplicationModel.Resources; using Windows.Devices.Geolocation; using Windows.Devices.Geolocation.Geofencing; using GalaSoft.MvvmLight.Views; using ShoppingListWPApp.Models; namespace ShoppingListWPApp.Common { /// <summary> /// Helper class, which provides functionality for Geolocation and Geofencing. /// </summary> class GeoHelper { #region *** Private members *** /// <summary> /// This <c>IDialogService</c>-Object is used for displaying Dialogs on the Device-Screen. /// </summary> private readonly IDialogService dialogService; /// <summary> /// This <c>Geolocator</c>-Object is used for retrieving the geographical position of the device. /// </summary> private Geolocator locator; #endregion #region *** Properties *** /// <summary> /// This <c>Geolocator</c>-Object is used for retrieving the geographical position of the device. /// </summary> public Geolocator Locator { get { switch (locator.LocationStatus) { case PositionStatus.Disabled: dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("GPSStatusError"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")); return null; case PositionStatus.NotAvailable: dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("GPSStatusError"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")); return null; } return locator; } private set { locator = value; } } #endregion public GeoHelper(IDialogService dialogService) { // Initialize Services this.dialogService = dialogService; this.Locator = new Geolocator(); } #region *** Geofencing *** /// <summary> /// This method creates a Geofence for a given Shoppinglist. /// </summary> /// <param name="shop">Object for which a Geofence should be created.</param> private Geofence CreateGeofence(Shop shop) { Geocircle circle = new Geocircle((BasicGeoposition)shop.Location, (shop.Radius * 1000)); //Selecting a subset of the events we need to interact with the geofence const MonitoredGeofenceStates geoFenceStates = MonitoredGeofenceStates.Entered; // Setting up how long you need to be in geofence for enter event to fire TimeSpan dwellTime = TimeSpan.FromSeconds(1); // Setting up how long the geofence should be active TimeSpan geoFenceDuration = TimeSpan.FromSeconds(0); // Setting up the start time of the geofence DateTimeOffset geoFenceStartTime = DateTimeOffset.Now; // Create object Geofence fence = new Geofence (shop.ID, circle, geoFenceStates, false, dwellTime, geoFenceStartTime, geoFenceDuration); return fence; } /// <summary> /// Creates a Geofence and adds it to the <c>GeofenceMonitor</c>. /// </summary> /// <param name="shop">Object for which a Geofence should be created.</param> public void AddGeofence(Shop shop) { //Add the geofence to the GeofenceMonitor GeofenceMonitor.Current.Geofences.Add(CreateGeofence(shop)); } /// <summary> /// Replaces a Geofence with a new one. /// </summary> /// <param name="id">ID of the old <c>Geofence</c> object.</param> /// <param name="newShop">The new <c>Shop</c> object that should replace the old one.</param> public void ModifyGeofence(string id, Shop newShop) { // Get old object out of the GeofenceMonitor Geofence old = (from f in GeofenceMonitor.Current.Geofences where f.Id.Equals(id) select f).First(); // Get position of old Geofence in the Geofences-Collection int idx = GeofenceMonitor.Current.Geofences.IndexOf(old); // Replace old Geofence with new one GeofenceMonitor.Current.Geofences.Remove(old); GeofenceMonitor.Current.Geofences.Insert(idx, CreateGeofence(newShop)); } /// <summary> /// Removes a predefined Geofence from GeofenceMonitor. /// </summary> /// <param name="id">ID of Geofence that should be removed.</param> public void RemoveGeofence(string id) { // Get Geofence from GeofenceMonitor var result = (from f in GeofenceMonitor.Current.Geofences where f.Id.Equals(id) select f).ToList(); // Check, if Geofences have been found if (result.Count > 0) { Geofence fence = result.First(); // Remove Geofence from GeofenceMonitor GeofenceMonitor.Current.Geofences.Remove(fence); } } /// <summary> /// Initializes Geofencing for the app. /// </summary> public async void InitGeofencing() { // Check, if Background Task is already registered. if (IsTaskRegistered("ShoppinglistGeofenceTask")) { // Unregister Background Task Unregister("ShoppinglistGeofenceTask"); } // Register Background Task await RegisterGeofenceTask(); } /// <summary> /// Checks, if a Background Task with a specific name is already registered. /// </summary> /// <param name="taskName">The name of the Background Task.</param> /// <returns>False, if the Task is not registered, true if the task is already registered.</returns> private bool IsTaskRegistered(string taskName) { var Registered = false; var entry = BackgroundTaskRegistration.AllTasks.FirstOrDefault(keyval => keyval.Value.Name == taskName); if (entry.Value != null) Registered = true; return Registered; } /// <summary> /// Unregisters a Background Task with a specified name. /// </summary> /// <param name="taskName">The name of the Background Task.</param> private void Unregister(string taskName) { var entry = BackgroundTaskRegistration.AllTasks.FirstOrDefault(keyval => keyval.Value.Name == taskName); if (entry.Value != null) entry.Value.Unregister(true); } /// <summary> /// Registers a Background Task that is used for reacting on Geofence-Reports. /// </summary> /// <returns>A Background Task for reacting on Geofence-Reports.</returns> private async Task RegisterGeofenceTask() { BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); var geofenceTaskBuilder = new BackgroundTaskBuilder { Name = "ShoppinglistGeofenceTask", TaskEntryPoint = "GeofenceTask.BackgroundGeofenceTask" }; var trigger = new LocationTrigger(LocationTriggerType.Geofence); geofenceTaskBuilder.SetTrigger(trigger); var geofenceTask = geofenceTaskBuilder.Register(); switch (backgroundAccessStatus) { case BackgroundAccessStatus.Unspecified: case BackgroundAccessStatus.Denied: await dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("RegisterBackgroundTaskError"), ResourceLoader.GetForCurrentView().GetString("AccessDeniedTitle")); break; } } #endregion } }
4ba7d2f15de3d369f47e8bd000d13ef51aed2602
[ "C#" ]
23
C#
ahosic/GeoShopper
22c9900b54c7d9e8a686aedfbe107500aa535ebb
e8c86cf3ee3ef9774cbbf603ec6904d91e450c29
refs/heads/master
<repo_name>deanbodenham/rcpptime<file_sep>/R/microbench.R #' Compare R and Rcpp implementations #' #' Use the \code{microbenchmark} package to compare the performance (speed) #' of (pure) R and Rcpp implementations of a couple of algorithms. #' #' #' @param showBoxplot A boolean to decide whether or not to show boxplots #' of the times (in microseconds) of the different #' implementations. #' #' #' @details The algorithms are \code{fibonacci} and \code{pisum} from the #' Julia \url{http://julialang.org/} benchmarks, as well as #' \code{sum}, which is just the sum of the first \code{n} integers. #' Each algorithm is run 100 times. #' #' #' @examples #' \dontrun{ #' useMicrobenchmarkRvsRcpp() #' #' useMicrobenchmarkRvsRcpp(showBoxplot=TRUE) #' } #' #' @export useMicrobenchmarkRvsRcpp <- function(showBoxplot=FALSE){ require(microbenchmark) #unit in microseconds, but doesn't really make a difference unit <- "us" cat("===========================================================\n") cat("Comparing algorithms implements in R, and using Rcpp\n") cat("===========================================================\n\n") #Fibonacci trials: #-------------------------------------------------------------------------# fibtrials <- 100L cat("Fibonacci:\n") cat("-----------------------------------------------------------\n") cat("Number of trials for microbenchmark: ", fibtrials, "\n") cat("(speed up compares ratio of median times)\n\n") N <- 20 m1 <- microbenchmark(fib(n=N), fibCppWrap(n=N), times=fibtrials, unit=unit) fibres <- summary(m1) fibRmedian <- fibres$median[1] fibCppmedian <- fibres$median[2] cat("Fibonacci (", N, "), Speed up using Rcpp: ", fibRmedian/fibCppmedian, "\n", sep="") ##using n=30 is a lot slower... # m <- microbenchmark(fib(n=30), fibCppWrap(n=30), times=fibtrials, unit=unit) # fibres <- summary(m) # fibRmedian <- fibres$median[1] # fibCppmedian <- fibres$median[2] # cat("Fibonacci (30), Speed up using Rcpp: ", fibRmedian/fibCppmedian, "\n") #-------------------------------------------------------------------------# cat("-----------------------------------------------------------\n") cat("\n") #pisum trials #-------------------------------------------------------------------------# pisumtrials <- 100L cat("Pisum:\n") cat("-----------------------------------------------------------\n") cat("Number of trials for microbenchmark: ", pisumtrials, "\n") cat("(speed up compares ratio of median times)\n\n") N <- 10000 m2 <- microbenchmark(pisum(N), cppPisumWrap(N), times=pisumtrials, unit=unit) pisumres <- summary(m2) pisumRmedian <- pisumres$median[1] pisumCppmedian <- pisumres$median[2] cat("Pisum (", N, "), Speed up using Rcpp: ", pisumRmedian/pisumCppmedian, "\n", sep="") cat("-----------------------------------------------------------\n") #-------------------------------------------------------------------------# cat("\n") #sum trials #-------------------------------------------------------------------------# sumtrials <- 100L cat("Sum: \n") cat("-----------------------------------------------------------\n") cat("Number of trials for microbenchmark: ", sumtrials, "\n") cat("(speed up compares ratio of median times)\n\n") N <- 100000 # N <- 1000000 m3 <- microbenchmark(sumR(N), sumCppWrap(N), times=pisumtrials, unit=unit) sumres <- summary(m3) sumRmedian <- sumres$median[1] sumCppmedian <- sumres$median[2] cat("Sum (", N, "), Speed up using Rcpp: ", sumRmedian/sumCppmedian, "\n", sep="") m <- microbenchmark(sum(N), sumCppWrap(N), times=pisumtrials, unit=unit) sumres <- summary(m) sumRmedian <- sumres$median[1] sumCppmedian <- sumres$median[2] cat("\n") cat("now comparing R's implementation of sum to my naive Rcpp implementation\n") cat("Sum (", N, "), Speed up using Rcpp: ", sumRmedian/sumCppmedian, "\n", sep="") cat("-----------------------------------------------------------\n") #-------------------------------------------------------------------------# if (showBoxplot){ cat("\ncreating boxplots; times in microseconds\n") # dev.new(width=8, height=6) # boxplot(m1) # dev.new(width=8, height=6) # boxplot(m2) # dev.new(width=8, height=6) # boxplot(m3) # par(mfcol=c(1,3)) # dev.new(width=8, height=6) # par(mfrow=c(3,1)) par(mfrow=c(1,3), pin=c(2, 2)) boxplot(m1) boxplot(m2) boxplot(m3) } } <file_sep>/src/sumCpp.cpp #include<Rcpp.h> #include <ctime> int sumCpp(int n){ int total = 0; n++; for (int i=1; i < n; ++i){ total += i; } return total; } // [[Rcpp::export]] Rcpp::NumericVector sumCppWrap(Rcpp::NumericVector n_){ int n = Rcpp::as<int> (n_); //do sum double total = sumCpp(n); return Rcpp::NumericVector::create(total); } <file_sep>/README.md # rcpptime A quick comparison between Rcpp and R implementations for the following algorithms: - fibonacci - pisum - sum (naive implementation, for loop adding up terms in a vector) - sum (R's sum function) Ideas for benchmarks from [julialang.org](http://julialang.org/) ## Requirements: - `microbenchmark` R package, available [on CRAN](https://CRAN.R-project.org/package=microbenchmark) ## Running the simulation After ``` git clone https://github.com/deanbodenham/rcpptime.git ``` In R, ``` require(microbenchmark) devtools::document() #to load package, otherwise install it and use 'library' useMicrobenchmarkRvsRcpp() ``` ## Results Algorithm | Speed-up using Rcpp ---------------|-------------------- Fibonacci | ~300 times Pisum | ~100 times sum (naive) | ~3500 times sum (internal) | ~0.12 times Note that while there are large speed-ups for the first three implementations, R's internal `sum` is faster than my simple Rcpp implementation. <file_sep>/src/pisumCpp.cpp #include<Rcpp.h> #include <ctime> double cppPisum(int limit){ double t = 0.0; //because will use one more limit++; for (int k=1; k < limit; ++k) { t = t + 1.0/(k*k); } return t; } // [[Rcpp::export]] Rcpp::NumericVector cppPisumWrap(Rcpp::NumericVector lim_){ int limit = Rcpp::as<int> (lim_); //run pisum double t = cppPisum(limit); return Rcpp::NumericVector::create(t); } <file_sep>/R/pisumR.R #https://github.com/JuliaLang/julia/blob/master/test/perf/micro/perf.R ## pi_sum ## pisum <- function(lim) { t <- 0.0 for (k in 1:lim) { t = t + 1.0/(k*k) } return(t) } <file_sep>/R/utils.R #https://github.com/JuliaLang/julia/blob/master/test/perf/micro/perf.R require(compiler) assert = function(bool) { if (!bool) stop('Assertion failed') } timeit = function(name, f, ..., times=10) { tmin = Inf f = cmpfun(f) sumTime <- 0 for (t in 1:times) { t = system.time(f(...))["elapsed"] if (t < tmin) tmin = t # print(t) sumTime <- sumTime + t } # cat(sprintf("r,%s,%.8f\n", name, tmin*1000)) #time is in seconds, so multiply by 1000 to get milliseconds #Cpp returns time in milliseconds avTime <- as.numeric(sumTime / times) * 1000 cat(sprintf("r,%s,%.8f\n", name, avTime)) return(avTime) } <file_sep>/src/fibCpp.cpp #include<Rcpp.h> int fibCpp(int n){ if (n < 2){ return(n); } else { return( fibCpp(n-1) + fibCpp(n-2) ); } } //wrapper for (recursive) cpp function fibCpp // [[Rcpp::export]] Rcpp::NumericVector fibCppWrap(Rcpp::NumericVector n_){ //conversion int n = Rcpp::as<int> (n_); //do fib int fibVal = fibCpp(n); //convert back return( Rcpp::NumericVector::create(fibVal) ); } <file_sep>/R/rcpptime.R #' @useDynLib rcpptime #' @importFrom Rcpp sourceCpp NULL <file_sep>/src/RcppExports.cpp // Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: <PASSWORD> #include <Rcpp.h> using namespace Rcpp; // fibCppWrap Rcpp::NumericVector fibCppWrap(Rcpp::NumericVector n_); RcppExport SEXP rcpptime_fibCppWrap(SEXP n_SEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::NumericVector >::type n_(n_SEXP); rcpp_result_gen = Rcpp::wrap(fibCppWrap(n_)); return rcpp_result_gen; END_RCPP } // cppPisumWrap Rcpp::NumericVector cppPisumWrap(Rcpp::NumericVector lim_); RcppExport SEXP rcpptime_cppPisumWrap(SEXP lim_SEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::NumericVector >::type lim_(lim_SEXP); rcpp_result_gen = Rcpp::wrap(cppPisumWrap(lim_)); return rcpp_result_gen; END_RCPP } // sumCppWrap Rcpp::NumericVector sumCppWrap(Rcpp::NumericVector n_); RcppExport SEXP rcpptime_sumCppWrap(SEXP n_SEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::NumericVector >::type n_(n_SEXP); rcpp_result_gen = Rcpp::wrap(sumCppWrap(n_)); return rcpp_result_gen; END_RCPP } <file_sep>/R/sumR.R ##sum## - my own test sumR <- function(n){ total <- 0 for (i in seq_len(n)){ total <- total + i } return(total) } <file_sep>/R/sleep.R testSleep <- function(x) { p1 <- proc.time() Sys.sleep(x) proc.time() - p1 # The cpu usage should be negligible } <file_sep>/R/fibR.R #https://github.com/JuliaLang/julia/blob/master/test/perf/micro/perf.R ##fib## fib = function(n) { if (n < 2) { return(n) } else { return(fib(n-1) + fib(n-2)) } } <file_sep>/R/RcppExports.R # Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: <PASSWORD> fibCppWrap <- function(n_) { .Call('rcpptime_fibCppWrap', PACKAGE = 'rcpptime', n_) } cppPisumWrap <- function(lim_) { .Call('rcpptime_cppPisumWrap', PACKAGE = 'rcpptime', lim_) } sumCppWrap <- function(n_) { .Call('rcpptime_sumCppWrap', PACKAGE = 'rcpptime', n_) }
05a5f48ddaa851cd60a605cd1b9695c4aff8bc08
[ "Markdown", "R", "C++" ]
13
R
deanbodenham/rcpptime
c4e08b8c4b4c5ada579260053fab5691c490705a
dbbb804aa36ef3dec794960b0890949f1c8aa235