text
stringlengths 5
1.04M
|
|---|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE457_Use_of_Uninitialized_Variable__twointsclass_array_declare_partial_init_05.cpp
Label Definition File: CWE457_Use_of_Uninitialized_Variable__twointsclass_array.label.xml
Template File: sources-sinks-05.tmpl.cpp
*/
/*
* @description
* CWE: 457 Use of Uninitialized Variable
* BadSource: partial_init Initialize part, but not all of the array
* GoodSource: Initialize data
* Sinks: use
* GoodSink: Initialize then use data
* BadSink : Use data
* Flow Variant: 05 Control flow: if(static_t) and if(static_f)
*
* */
#include "std_testcase.h"
/* The two variables below are not defined as "const", but are never
assigned any other value, so a tool should be able to identify that
reads of these will always return their initialized values. */
static int static_t = 1; /* true */
static int static_f = 0; /* false */
namespace CWE457_Use_of_Uninitialized_Variable__twointsclass_array_declare_partial_init_05
{
#ifndef OMITBAD
void bad()
{
twointsclass * data;
twointsclass data_uninit_array[10];
data = data_uninit_array;
if(static_t)
{
for(int i=0; i<(10/2); i++)
{
data[i].a = i;
data[i].b = i;
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
}
if(static_t)
{
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second static_t to static_f */
static void goodB2G1()
{
twointsclass * data;
twointsclass data_uninit_array[10];
data = data_uninit_array;
if(static_t)
{
for(int i=0; i<(10/2); i++)
{
data[i].a = i;
data[i].b = i;
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
}
if(static_f)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
else
{
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
twointsclass * data;
twointsclass data_uninit_array[10];
data = data_uninit_array;
if(static_t)
{
for(int i=0; i<(10/2); i++)
{
data[i].a = i;
data[i].b = i;
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
}
if(static_t)
{
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first static_t to static_f */
static void goodG2B1()
{
twointsclass * data;
twointsclass data_uninit_array[10];
data = data_uninit_array;
if(static_f)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<(10/2); i++)
{
data[i].a = i;
data[i].b = i;
}
}
else
{
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
}
if(static_t)
{
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
twointsclass * data;
twointsclass data_uninit_array[10];
data = data_uninit_array;
if(static_t)
{
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<(10/2); i++)
{
data[i].a = i;
data[i].b = i;
}
}
if(static_t)
{
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
for(int i=0; i<10; i++)
{
data[i].a = i;
data[i].b = i;
}
for(int i=0; i<10; i++)
{
printIntLine(data[i].a);
printIntLine(data[i].b);
}
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} // close namespace
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE457_Use_of_Uninitialized_Variable__twointsclass_array_declare_partial_init_05; // so that we can use good and bad easily
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Kernel/KeyCode.h>
#include <LibGUI/GAbstractView.h>
#include <LibGUI/GModel.h>
#include <LibGUI/GModelEditingDelegate.h>
#include <LibGUI/GPainter.h>
#include <LibGUI/GScrollBar.h>
#include <LibGUI/GTextBox.h>
GAbstractView::GAbstractView(GWidget* parent)
: GScrollableWidget(parent)
, m_selection(*this)
{
}
GAbstractView::~GAbstractView()
{
}
void GAbstractView::set_model(RefPtr<GModel>&& model)
{
if (model == m_model)
return;
if (m_model)
m_model->unregister_view({}, *this);
m_model = move(model);
if (m_model)
m_model->register_view({}, *this);
did_update_model();
}
void GAbstractView::did_update_model()
{
if (!model() || selection().first() != m_edit_index)
stop_editing();
}
void GAbstractView::did_update_selection()
{
if (!model() || selection().first() != m_edit_index)
stop_editing();
if (model() && on_selection && selection().first().is_valid())
on_selection(selection().first());
}
void GAbstractView::did_scroll()
{
update_edit_widget_position();
}
void GAbstractView::update_edit_widget_position()
{
if (!m_edit_widget)
return;
m_edit_widget->set_relative_rect(m_edit_widget_content_rect.translated(-horizontal_scrollbar().value(), -vertical_scrollbar().value()));
}
void GAbstractView::begin_editing(const GModelIndex& index)
{
ASSERT(is_editable());
ASSERT(model());
if (m_edit_index == index)
return;
if (!model()->is_editable(index))
return;
if (m_edit_widget) {
remove_child(*m_edit_widget);
m_edit_widget = nullptr;
}
m_edit_index = index;
ASSERT(aid_create_editing_delegate);
m_editing_delegate = aid_create_editing_delegate(index);
m_editing_delegate->bind(*model(), index);
m_editing_delegate->set_value(model()->data(index, GModel::Role::Display));
m_edit_widget = m_editing_delegate->widget();
add_child(*m_edit_widget);
m_edit_widget->move_to_back();
m_edit_widget_content_rect = content_rect(index).translated(frame_thickness(), frame_thickness());
update_edit_widget_position();
m_edit_widget->set_focus(true);
m_editing_delegate->will_begin_editing();
m_editing_delegate->on_commit = [this] {
ASSERT(model());
model()->set_data(m_edit_index, m_editing_delegate->value());
stop_editing();
};
}
void GAbstractView::stop_editing()
{
m_edit_index = {};
if (m_edit_widget) {
remove_child(*m_edit_widget);
m_edit_widget = nullptr;
}
}
void GAbstractView::select_all()
{
ASSERT(model());
int rows = model()->row_count();
int columns = model()->column_count();
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j)
selection().add(model()->index(i, j));
}
}
void GAbstractView::activate(const GModelIndex& index)
{
if (on_activation)
on_activation(index);
}
void GAbstractView::activate_selected()
{
if (!on_activation)
return;
selection().for_each_index([this](auto& index) {
on_activation(index);
});
}
void GAbstractView::notify_selection_changed(Badge<GModelSelection>)
{
did_update_selection();
if (on_selection_change)
on_selection_change();
update();
}
NonnullRefPtr<Font> GAbstractView::font_for_index(const GModelIndex& index) const
{
if (!model())
return font();
auto font_data = model()->data(index, GModel::Role::Font);
if (font_data.is_font())
return font_data.as_font();
auto column_metadata = model()->column_metadata(index.column());
if (column_metadata.font)
return *column_metadata.font;
return font();
}
|
/*
**
** $Filename: b3Thread.cpp $
** $Release: Dortmund 2001 $
** $Revision$
** $Date$
** $Author$
** $Developer: Steffen A. Mork $
**
** Blizzard III - Multithreading routines (for generating dead locks)
**
** (C) Copyright 2001 Steffen A. Mork
** All Rights Reserved
**
**
*/
/*************************************************************************
** **
** Blizzard III includes **
** **
*************************************************************************/
#include "b3SystemInclude.h"
#include "blz3/system/b3Thread.h"
/*************************************************************************
** **
** b3IPCMutex implementation **
** **
*************************************************************************/
// Method for entering a critical code section
b3_bool b3IPCMutex::b3Lock()
{
return ::WaitForSingleObject(m_hObject,INFINITE) != 0;
}
// Method for leaving a critical code section
b3_bool b3IPCMutex::b3Unlock()
{
return ::ReleaseMutex(m_hObject) != 0;
}
/*************************************************************************
** **
** b3Mutex implementation **
** **
*************************************************************************/
// Initialize critical section
b3Mutex::b3Mutex()
{
::InitializeCriticalSection(&cs);
}
// Deinitialize critical section
b3Mutex::~b3Mutex()
{
::DeleteCriticalSection(&cs);
}
// Method for entering a critical code section
b3_bool b3Mutex::b3Lock()
{
::EnterCriticalSection(&cs);
return true;
}
// Method for leaving a critical code section
b3_bool b3Mutex::b3Unlock()
{
::LeaveCriticalSection(&cs);
return true;
}
/*************************************************************************
** **
** b3Event implementation **
** **
*************************************************************************/
// Signal another thread that there has happend something.
void b3Event::b3Pulse()
{
SetEvent();
}
// Wait for a signal from another thread.
b3_bool b3Event::b3Wait()
{
b3_bool success;
success = ::WaitForSingleObject(m_hObject,INFINITE) != 0;
ResetEvent();
return success;
}
/*************************************************************************
** **
** b3Thread implementation **
** **
*************************************************************************/
b3_count b3Thread::m_ThreadCount;
b3IPCMutex b3Thread::m_ThreadMutex;
b3Thread::b3Thread(const char *task_name)
{
m_Name = task_name;
m_Thread = null;
m_IsRunning = false;
}
b3Thread::~b3Thread()
{
b3Stop();
}
void b3Thread::b3Inc()
{
m_ThreadMutex.b3Lock();
if (!m_IsRunning)
{
m_Span.b3Start();
m_IsRunning = true;
m_ThreadCount++;
}
m_ThreadMutex.b3Unlock();
}
void b3Thread::b3Dec(b3_bool incl_delete)
{
m_ThreadMutex.b3Lock();
if (m_IsRunning)
{
m_ThreadCount--;
m_IsRunning = false;
m_Span.b3Stop();
}
if (incl_delete && (m_Thread != null))
{
delete m_Thread;
m_Thread = null;
}
m_ThreadMutex.b3Unlock();
}
void b3Thread::b3Name(const char *task_name)
{
m_Name = task_name;
}
b3_u32 b3Thread::b3Trampoline(void *ptr)
{
b3Thread *threadClass = (b3Thread *)ptr;
threadClass->b3Inc();
threadClass->m_Result = threadClass->m_CallProc(threadClass->m_CallArg);
threadClass->b3Dec();
return threadClass->m_Result;
}
b3_bool b3Thread::b3Start(
b3ThreadProc proc,
void *ptr,
b3_s32 prio_rate)
{
long priority = THREAD_PRIORITY_NORMAL;
// Stop a previous running thread...
b3Stop();
// Recompute priority
switch (prio_rate)
{
case -1 :
priority = THREAD_PRIORITY_BELOW_NORMAL;
break;
case 0:
priority = THREAD_PRIORITY_NORMAL;
break;
case 1:
priority = THREAD_PRIORITY_ABOVE_NORMAL;
break;
default :
if (prio_rate < -1)
{
priority = THREAD_PRIORITY_LOWEST;
}
if (prio_rate > 1)
{
priority = THREAD_PRIORITY_HIGHEST;
}
break;
}
// Start new thread
m_CallProc = proc;
m_CallArg = ptr;
m_Thread = ::AfxBeginThread(b3Trampoline,this,priority,0,CREATE_SUSPENDED);
if (m_Thread != null)
{
b3PrintF (B3LOG_FULL,"### CLASS: b3Thrd # starting thread %02lX with prio %ld (%s).\n",
m_Thread->m_nThreadID,prio_rate,
m_Name != null ? m_Name : "no name");
m_Thread->m_bAutoDelete = false;
m_Thread->ResumeThread();
}
else
{
b3PrintF(B3LOG_NORMAL,"### CLASS: b3Thrd # Thread not started!\n",
m_Thread);
}
return m_Thread != null;
}
b3_u32 b3Thread::b3Wait()
{
if (m_Thread != null)
{
b3PrintF (B3LOG_FULL,"### CLASS: b3Thrd # waiting for thread %02lX to stop (%s).\n",
m_Thread->m_nThreadID,
m_Name != null ? m_Name : "no name");
::WaitForSingleObject (m_Thread->m_hThread,INFINITE);
m_ThreadMutex.b3Lock();
delete m_Thread;
m_Thread = null;
m_ThreadMutex.b3Unlock();
}
else
{
m_Result = null;
}
return m_Result;
}
b3_bool b3Thread::b3Stop()
{
b3_bool was_running;
was_running = m_IsRunning;
if (m_Thread != null)
{
b3PrintF (B3LOG_FULL,"### CLASS: b3Thrd # terminating thread %02lX (%s).\n",
m_Thread->m_nThreadID,
m_Name != null ? m_Name : "no name");
::TerminateThread (m_Thread->m_hThread,0);
b3Dec(true);
m_CallProc = null;
m_CallArg = 0;
}
return was_running;
}
b3_bool b3Thread::b3IsRunning()
{
return m_IsRunning;
}
void b3Thread::b3AddTimeSpan(b3TimeSpan *span)
{
#ifdef WIN32
span->m_uTime += m_Span.m_uTime;
span->m_sTime += m_Span.m_sTime;
#endif
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: Yvonne Pachmayer <pachmay@physi.uni-heidelberg.de> *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
// The task:
// stores TPC PID quantities in a THnSparse
// output can then be used for e.g. dEdx calibration
//
// Author:
// Yvonne Pachmayer <pachmay@physi.uni-heidelberg.de>
//
#include <TObjString.h>
#include "AliTPCcalibResidualPID_Modified.h"
#include "TChain.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliMCEvent.h"
#include "AliMCParticle.h"
//#include "AliStack.h"
#include "AliPID.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"
#include "AliPIDResponse.h"
#include "AliInputEventHandler.h"
#include "AliESDInputHandler.h"
#include "AliESDv0KineCuts.h"
#include "AliESDv0.h"
#include "AliCentrality.h"
#include "AliAnalysisUtils.h"
#include "THnSparse.h"
#include "TH2D.h"
#include "TCanvas.h"
#include "TGraphErrors.h"
#include "TMultiGraph.h"
#include "TAxis.h"
#include "TFile.h"
#include "TSpline.h"
#include "TStyle.h"
#include "AliTPCdEdxInfo.h"
#include "TString.h"
#include "TFitResult.h"
#include "TH1F.h"
#include "TLegend.h"
#include "TVirtualFitter.h"
#include "TTree.h"
using namespace std;
ClassImp(AliTPCcalibResidualPID_Modified)
Double_t AliTPCcalibResidualPID_Modified::fgCutGeo = 1.;
Double_t AliTPCcalibResidualPID_Modified::fgCutNcr = 0.85;
Double_t AliTPCcalibResidualPID_Modified::fgCutNcl = 0.7;
//________________________________________________________________________
AliTPCcalibResidualPID_Modified::AliTPCcalibResidualPID_Modified()
: AliAnalysisTaskSE(), fESD(0), fMC(0), fOutputContainer(0), fESDtrackCuts(0), fESDtrackCutsV0(0), fPIDResponse(0),
fNumEtaCorrReqErrorsIssued(0),
fNumMultCorrReqErrorsIssued(0),
fUseTPCCutMIGeo(kFALSE),
fUseMCinfo(kTRUE),
fIsPbpOrpPb(kFALSE),
fIsPbPb(kFALSE),
fZvtxCutEvent(9999.0),
fV0KineCuts(0x0),
fAnaUtils(0x0),
fCutOnProdRadiusForV0el(kTRUE),
fNumTagsStored(0),
fV0tags(0x0),
fV0motherIndex(0x0),
fV0motherPDG(0x0),
fProduceAllPadTypes(0),
fProduceGlobal(0),
fProduceShortPads(0),
fProduceMediumPads(0),
fProduceLongPads(0),
fProduceOroc(0),
fHistPidQA(0),
fHistPidQAshort(0),
fHistPidQAmedium(0),
fHistPidQAlong(0),
fHistPidQAoroc(0),
fProduceTPCSignalSparse(0),
fCorrectdEdxEtaDependence(0),
fCorrectdEdxMultiplicityDependence(0),
fCorrectdEdxPileupDependence(kTRUE),
fThnspTpc(0),
fWriteAdditionalOutput(kFALSE),
fQAList(0x0),
fhInvMassGamma(0x0),
fhInvMassK0s(0x0),
fhInvMassLambda(0x0),
fhInvMassAntiLambda(0x0),
fhArmenterosAll(0x0),
fhArmenterosGamma(0x0),
fhArmenterosK0s(0x0),
fhArmenterosLambda(0x0),
fhArmenterosAntiLambda(0x0),
fHistSharedClusQAV0Pi(0x0),
fHistSharedClusQAV0Pr(0x0),
fHistSharedClusQAV0El(0x0),
fTreeV0El(0x0),
fTreeV0Pi(0x0),
fTreeV0Pr(0x0),
fTree_dEdx_tr(0.),
fTree_dEdx_nb(0.),
fTree_dEdx_vs(0.),
fTree_dEdxExpected_tr(0.),
fTree_p_TPC_tr(0.),
fTree_p_TPC_nb(0.),
fTree_p_TPC_vs(0.),
fTree_BtimesChargeOverPt_tr(0.),
fTree_BtimesChargeOverPt_nb(0.),
fTree_BtimesChargeOverPt_vs(0.),
fTree_tanTheta_tr(0.),
fTree_tanTheta_nb(0.),
fTree_tanTheta_vs(0.),
fTree_distance_nb(0.),
fTree_distance_vs(0.),
//Reduced Tree (Alberto Caliva)
fReducedTree(0x0),
fParticleIDcode(0),
fNumberOfTPCclusters_dEdx(0),
fTPC_dEdx_au(0),
fPseudorapidity(0),
fCentralityPercentile(0),
fMomentumTPCinnnerWall(0),
fNumberOfSigmasTOF_Elec(0),
fNumberOfSigmasTOF_Pion(0),
fNumberOfSigmasTOF_Kaon(0),
fNumberOfSigmasTOF_Prot(0)
{
// default Constructor
/* fast compilation test
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
.L /lustre/alice/akalweit/train/trunk/util/statsQA/AliTPCcalibResidualPID_Modified.cxx++
*/
}
//________________________________________________________________________
AliTPCcalibResidualPID_Modified::AliTPCcalibResidualPID_Modified(const char *name)
: AliAnalysisTaskSE(name), fESD(0), fMC(0), fOutputContainer(0), fESDtrackCuts(0), fESDtrackCutsV0(0), fPIDResponse(0),
fNumEtaCorrReqErrorsIssued(0),
fNumMultCorrReqErrorsIssued(0),
fUseTPCCutMIGeo(kFALSE),
fUseMCinfo(kTRUE),
fIsPbpOrpPb(kFALSE),
fIsPbPb(kFALSE),
fZvtxCutEvent(9999.0),
fV0KineCuts(0x0),
fAnaUtils(0x0),
fCutOnProdRadiusForV0el(kTRUE),
fNumTagsStored(0),
fV0tags(0x0),
fV0motherIndex(0x0),
fV0motherPDG(0x0),
fProduceAllPadTypes(0),
fProduceGlobal(0),
fProduceShortPads(0),
fProduceMediumPads(0),
fProduceLongPads(0),
fProduceOroc(0),
fHistPidQA(0),
fHistPidQAshort(0),
fHistPidQAmedium(0),
fHistPidQAlong(0),
fHistPidQAoroc(0),
fProduceTPCSignalSparse(0),
fCorrectdEdxEtaDependence(0),
fCorrectdEdxMultiplicityDependence(0),
fCorrectdEdxPileupDependence(kTRUE),
fThnspTpc(0),
fWriteAdditionalOutput(kFALSE),
fQAList(0x0),
fhInvMassGamma(0x0),
fhInvMassK0s(0x0),
fhInvMassLambda(0x0),
fhInvMassAntiLambda(0x0),
fhArmenterosAll(0x0),
fhArmenterosGamma(0x0),
fhArmenterosK0s(0x0),
fhArmenterosLambda(0x0),
fhArmenterosAntiLambda(0x0),
fHistSharedClusQAV0Pi(0x0),
fHistSharedClusQAV0Pr(0x0),
fHistSharedClusQAV0El(0x0),
fTreeV0El(0x0),
fTreeV0Pi(0x0),
fTreeV0Pr(0x0),
fTree_dEdx_tr(0.),
fTree_dEdx_nb(0.),
fTree_dEdx_vs(0.),
fTree_dEdxExpected_tr(0.),
fTree_p_TPC_tr(0.),
fTree_p_TPC_nb(0.),
fTree_p_TPC_vs(0.),
fTree_BtimesChargeOverPt_tr(0.),
fTree_BtimesChargeOverPt_nb(0.),
fTree_BtimesChargeOverPt_vs(0.),
fTree_tanTheta_tr(0.),
fTree_tanTheta_nb(0.),
fTree_tanTheta_vs(0.),
fTree_distance_nb(0.),
fTree_distance_vs(0.),
//Reduced Tree (Alberto Caliva)
fReducedTree(0x0),
fParticleIDcode(0),
fNumberOfTPCclusters_dEdx(0),
fTPC_dEdx_au(0),
fPseudorapidity(0),
fCentralityPercentile(0),
fMomentumTPCinnnerWall(0),
fNumberOfSigmasTOF_Elec(0),
fNumberOfSigmasTOF_Pion(0),
fNumberOfSigmasTOF_Kaon(0),
fNumberOfSigmasTOF_Prot(0)
{
//fESDtrackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kTRUE);
//fESDtrackCutsV0 = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE);
// Constructor
DefineInput(0, TChain::Class());
DefineOutput(1, TObjArray::Class());
DefineOutput(2, TObjArray::Class());
DefineOutput(3, TTree::Class());
DefineOutput(4, TTree::Class());
DefineOutput(5, TTree::Class());
DefineOutput(6, TTree::Class());//Reduced Tree
}
//_________________________________________________
AliTPCcalibResidualPID_Modified::~AliTPCcalibResidualPID_Modified()
{
delete fOutputContainer;
fOutputContainer = 0;
delete fQAList;
fQAList = 0;
/*
delete fTreeV0El;
fTreeV0El = 0;
delete fTreeV0Pi;
fTreeV0Pi = 0;
delete fTreeV0Pr;
fTreeV0Pr = 0;
*/
delete fESDtrackCuts;
fESDtrackCuts = 0;
delete fESDtrackCutsV0;
fESDtrackCutsV0 = 0;
delete fV0KineCuts;
fV0KineCuts = 0;
delete fAnaUtils;
fAnaUtils = 0;
delete [] fV0tags;
fV0tags = 0;
fNumTagsStored = 0;
delete [] fV0motherIndex;
fV0motherIndex = 0;
delete [] fV0motherPDG;
fV0motherPDG = 0;
}
//________________________________________________________________________
void AliTPCcalibResidualPID_Modified::UserCreateOutputObjects()
{
AliInputEventHandler* inputHandler = dynamic_cast<AliInputEventHandler*>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!inputHandler)
printf("Inputhandler not available \n");
else
fPIDResponse = inputHandler->GetPIDResponse();
// THnSparse binning
const Int_t kNdim = 9;
//v0id, dEdx, TPCsigele, TPCsigpion, TOFbit, eta, TPCclus, centr, p
Int_t bins[kNdim] = { 4, 250, 200, 200, 8, 20, 50, 20, 100};
Double_t xmin[kNdim] = { 0.5, 30, -10., -10., -1.5, -1., 60., 0., 0.1};
Double_t xmax[kNdim] = { 4.5, 500., 10., 10., 6.5, 1., 160., 100, 4};
fThnspTpc= new THnSparseF("tpcsignals", "TPC signal;v0id;tpc signal;tpcsigele;tpcsigpion;tofbit;eta;tpcclus;centr;p (GeV/c)", kNdim, bins, xmin, xmax);
SetAxisNamesFromTitle(fThnspTpc);
BinLogAxis(fThnspTpc, 8);
fHistPidQA = InitialisePIDQAHist("fHistPidQA","PID QA", GetIsPbPb());
fHistPidQAshort = InitialisePIDQAHist("fHistPidQAshort" ,"PID QA -- short pads", GetIsPbPb());
fHistPidQAmedium = InitialisePIDQAHist("fHistPidQAmedium","PID QA -- med pads", GetIsPbPb());
fHistPidQAlong = InitialisePIDQAHist("fHistPidQAlong" ,"PID QA -- long pads", GetIsPbPb());
fHistPidQAoroc = InitialisePIDQAHist("fHistPidQAoroc" ,"PID QA -- oroc", GetIsPbPb());
fOutputContainer = new TObjArray(2);
fOutputContainer->SetName(GetName());
fOutputContainer->SetOwner();
if(fProduceTPCSignalSparse)fOutputContainer->Add(fThnspTpc);
if(fProduceGlobal)fOutputContainer->Add(fHistPidQA);
if(fProduceAllPadTypes || fProduceShortPads)fOutputContainer->Add(fHistPidQAshort);
if(fProduceAllPadTypes || fProduceMediumPads)fOutputContainer->Add(fHistPidQAmedium);
if(fProduceAllPadTypes || fProduceLongPads)fOutputContainer->Add(fHistPidQAlong);
if(fProduceAllPadTypes || fProduceOroc)fOutputContainer->Add(fHistPidQAoroc);
// V0 Kine cuts
fV0KineCuts = new AliESDv0KineCuts;
fV0KineCuts->SetGammaCutChi2NDF(5.);
fAnaUtils = new AliAnalysisUtils();
if (fCutOnProdRadiusForV0el) {
// Only accept V0el with prod. radius within 45 cm -> PID will by systematically biased for larger values!
Float_t gammaProdVertexRadiusCuts[2] = { 3.0, 45. };
fV0KineCuts->SetGammaCutVertexR(&gammaProdVertexRadiusCuts[0]);
}
if (fWriteAdditionalOutput) {
fQAList = new TObjArray(4);
fQAList->SetName(GetName());
fQAList->SetOwner();
fhInvMassGamma = new TH1F("fhInvMassGamma", "Invariant Mass of gammas; m_{ee} (GeV/#it{c}^{2}); Entries", 200, 0., 0.2);
fhInvMassK0s = new TH1F("fhInvMassK0s", "Invariant Mass of K0s; m_{#pi#pi} (GeV/#it{c}^{2}); Entries;", 200, 0.45, 0.55);
fhInvMassLambda = new TH1F("fhInvMassLambda", "Invariant Mass of lambdas; m_{p#pi^{-}} (GeV/#it{c}^{2}); Entries", 200, 1.05, 1.15);
fhInvMassAntiLambda = new TH1F("fhInvMassAntiLambda", "Invariant Mass of anti-lambdas; m_{#pi^{+}#bar{p}} (GeV/#it{c}^{2}); Entries",
200, 1.05, 1.15);
fQAList->Add(fhInvMassGamma);
fQAList->Add(fhInvMassK0s);
fQAList->Add(fhInvMassLambda);
fQAList->Add(fhInvMassAntiLambda);
fhArmenterosAll = new TH2F("fhArmenterosAll",
"Armenteros plot all V0s;#alpha = (#it{p}^{+}_{L}-#it{p}^{-}_{L})/(#it{p}^{+}_{L}+#it{p}^{-}_{L});#it{q}_{T} (GeV/#it{c})",
200, -1., 1., 200, 0., 0.4);
fhArmenterosGamma = new TH2F("fhArmenterosGamma",
"Armenteros plot Gamma;#alpha = (#it{p}^{+}_{L}-#it{p}^{-}_{L})/(#it{p}^{+}_{L}+#it{p}^{-}_{L});#it{q}_{T} (GeV/#it{c})",
200, -1., 1., 200, 0., 0.4);
fhArmenterosK0s = new TH2F("fhArmenterosK0s",
"Armenteros plot K0s;#alpha = (#it{p}^{+}_{L}-#it{p}^{-}_{L})/(#it{p}^{+}_{L}+#it{p}^{-}_{L});#it{q}_{T} (GeV/#it{c})",
200, -1., 1., 200, 0., 0.4);
fhArmenterosLambda = new TH2F("fhArmenterosLambda",
"Armenteros plot lambda;#alpha = (#it{p}^{+}_{L}-#it{p}^{-}_{L})/(#it{p}^{+}_{L}+#it{p}^{-}_{L});#it{q}_{T} (GeV/#it{c})",
200, -1., 1., 200, 0., 0.4);
fhArmenterosAntiLambda = new TH2F("fhArmenterosAntiLambda",
"Armenteros plot anti-lambda;#alpha = (#it{p}^{+}_{L}-#it{p}^{-}_{L})/(#it{p}^{+}_{L}+#it{p}^{-}_{L});#it{q}_{T} (GeV/#it{c})",
200, -1., 1., 200, 0., 0.4);
fQAList->Add(fhArmenterosAll);
fQAList->Add(fhArmenterosGamma);
fQAList->Add(fhArmenterosK0s);
fQAList->Add(fhArmenterosLambda);
fQAList->Add(fhArmenterosAntiLambda);
const Int_t dimQASharedClusters = 4;
const TString axisTitles[dimQASharedClusters] = { "#it{p}_{TPC} (GeV/#it{c})", "#it{#Delta'}", "#it{N}_{shared cl}", "Pad row"};
Int_t binsHistQASharedClusters[dimQASharedClusters] = { 100, 100, 160, 160};
Double_t xminHistQASharedClusters[dimQASharedClusters] = { 0.3, 0.5, 0, -1};
Double_t xmaxHistQASharedClusters[dimQASharedClusters] = { 20, 1.5, 160, 159};
fHistSharedClusQAV0Pi = new THnSparseF("fHistSharedClusQAV0Pi" ,"PID QA shared clusters - V0 pi", dimQASharedClusters,
binsHistQASharedClusters, xminHistQASharedClusters, xmaxHistQASharedClusters);
BinLogAxis(fHistSharedClusQAV0Pi, 0);
for (Int_t i = 0; i < dimQASharedClusters; i++)
fHistSharedClusQAV0Pi->GetAxis(i)->SetTitle(axisTitles[i].Data());
fQAList->Add(fHistSharedClusQAV0Pi);
fHistSharedClusQAV0Pr = new THnSparseF("fHistSharedClusQAV0Pr" ,"PID QA shared clusters - V0 pr", dimQASharedClusters,
binsHistQASharedClusters, xminHistQASharedClusters, xmaxHistQASharedClusters);
BinLogAxis(fHistSharedClusQAV0Pr, 0);
for (Int_t i = 0; i < dimQASharedClusters; i++)
fHistSharedClusQAV0Pi->GetAxis(i)->SetTitle(axisTitles[i].Data());
fQAList->Add(fHistSharedClusQAV0Pr);
fHistSharedClusQAV0El = new THnSparseF("fHistSharedClusQAV0El" ,"PID QA shared clusters - V0 el", dimQASharedClusters,
binsHistQASharedClusters, xminHistQASharedClusters, xmaxHistQASharedClusters);
BinLogAxis(fHistSharedClusQAV0El, 0);
for (Int_t i = 0; i < dimQASharedClusters; i++)
fHistSharedClusQAV0Pi->GetAxis(i)->SetTitle(axisTitles[i].Data());
fQAList->Add(fHistSharedClusQAV0El);
OpenFile(3);
fTreeV0El = new TTree("treeV0El", "V0 el together with info from closest neighbour");
fTreeV0El->Branch("dEdx_tr", &fTree_dEdx_tr);
fTreeV0El->Branch("dEdx_nb", &fTree_dEdx_nb);
fTreeV0El->Branch("dEdx_vs", &fTree_dEdx_vs);
fTreeV0El->Branch("dEdxExpected_tr", &fTree_dEdxExpected_tr);
fTreeV0El->Branch("p_TPC_tr", &fTree_p_TPC_tr);
fTreeV0El->Branch("p_TPC_nb", &fTree_p_TPC_nb);
fTreeV0El->Branch("p_TPC_vs", &fTree_p_TPC_vs);
fTreeV0El->Branch("BtimesChargeOverPt_tr", &fTree_BtimesChargeOverPt_tr);
fTreeV0El->Branch("BtimesChargeOverPt_nb", &fTree_BtimesChargeOverPt_nb);
fTreeV0El->Branch("BtimesChargeOverPt_vs", &fTree_BtimesChargeOverPt_vs);
fTreeV0El->Branch("tanTheta_tr", &fTree_tanTheta_tr);
fTreeV0El->Branch("tanTheta_nb", &fTree_tanTheta_nb);
fTreeV0El->Branch("tanTheta_vs", &fTree_tanTheta_vs);
fTreeV0El->Branch("distance_nb", &fTree_distance_nb);
fTreeV0El->Branch("distance_vs", &fTree_distance_vs);
OpenFile(4);
fTreeV0Pi = new TTree("treeV0Pi", "V0 pi together with info from closest neighbour");
fTreeV0Pi->Branch("dEdx_tr", &fTree_dEdx_tr);
fTreeV0Pi->Branch("dEdx_nb", &fTree_dEdx_nb);
fTreeV0Pi->Branch("dEdx_vs", &fTree_dEdx_vs);
fTreeV0Pi->Branch("dEdxExpected_tr", &fTree_dEdxExpected_tr);
fTreeV0Pi->Branch("p_TPC_tr", &fTree_p_TPC_tr);
fTreeV0Pi->Branch("p_TPC_nb", &fTree_p_TPC_nb);
fTreeV0Pi->Branch("p_TPC_vs", &fTree_p_TPC_vs);
fTreeV0Pi->Branch("BtimesChargeOverPt_tr", &fTree_BtimesChargeOverPt_tr);
fTreeV0Pi->Branch("BtimesChargeOverPt_nb", &fTree_BtimesChargeOverPt_nb);
fTreeV0Pi->Branch("BtimesChargeOverPt_vs", &fTree_BtimesChargeOverPt_vs);
fTreeV0Pi->Branch("tanTheta_tr", &fTree_tanTheta_tr);
fTreeV0Pi->Branch("tanTheta_nb", &fTree_tanTheta_nb);
fTreeV0Pi->Branch("tanTheta_vs", &fTree_tanTheta_vs);
fTreeV0Pi->Branch("distance_nb", &fTree_distance_nb);
fTreeV0Pi->Branch("distance_vs", &fTree_distance_vs);
OpenFile(5);
fTreeV0Pr = new TTree("treeV0Pr", "V0 pr together with info from closest neighbour");
fTreeV0Pr->Branch("dEdx_tr", &fTree_dEdx_tr);
fTreeV0Pr->Branch("dEdx_nb", &fTree_dEdx_nb);
fTreeV0Pr->Branch("dEdx_vs", &fTree_dEdx_vs);
fTreeV0Pr->Branch("dEdxExpected_tr", &fTree_dEdxExpected_tr);
fTreeV0Pr->Branch("p_TPC_tr", &fTree_p_TPC_tr);
fTreeV0Pr->Branch("p_TPC_nb", &fTree_p_TPC_nb);
fTreeV0Pr->Branch("p_TPC_vs", &fTree_p_TPC_vs);
fTreeV0Pr->Branch("BtimesChargeOverPt_tr", &fTree_BtimesChargeOverPt_tr);
fTreeV0Pr->Branch("BtimesChargeOverPt_nb", &fTree_BtimesChargeOverPt_nb);
fTreeV0Pr->Branch("BtimesChargeOverPt_vs", &fTree_BtimesChargeOverPt_vs);
fTreeV0Pr->Branch("tanTheta_tr", &fTree_tanTheta_tr);
fTreeV0Pr->Branch("tanTheta_nb", &fTree_tanTheta_nb);
fTreeV0Pr->Branch("tanTheta_vs", &fTree_tanTheta_vs);
fTreeV0Pr->Branch("distance_nb", &fTree_distance_nb);
fTreeV0Pr->Branch("distance_vs", &fTree_distance_vs);
}
//Reduced Tree (Alberto Caliva)
OpenFile(6);
fReducedTree = new TTree("fReducedTree", "Reduced Tree");
fReducedTree->Branch("fParticleIDcode", &fParticleIDcode);
fReducedTree->Branch("fNumberOfTPCclusters_dEdx", &fNumberOfTPCclusters_dEdx);
fReducedTree->Branch("fTPC_dEdx_au", &fTPC_dEdx_au);
fReducedTree->Branch("fPseudorapidity", &fPseudorapidity);
fReducedTree->Branch("fCentralityPercentile", &fCentralityPercentile);
fReducedTree->Branch("fMomentumTPCinnnerWall", &fMomentumTPCinnnerWall);
fReducedTree->Branch("fNumberOfSigmasTOF_Elec", &fNumberOfSigmasTOF_Elec);
fReducedTree->Branch("fNumberOfSigmasTOF_Pion", &fNumberOfSigmasTOF_Pion);
fReducedTree->Branch("fNumberOfSigmasTOF_Kaon", &fNumberOfSigmasTOF_Kaon);
fReducedTree->Branch("fNumberOfSigmasTOF_Prot", &fNumberOfSigmasTOF_Prot);
PostData(1,fOutputContainer);
if (fWriteAdditionalOutput) {
PostData(2,fQAList);
PostData(3,fTreeV0El);
PostData(4,fTreeV0Pi);
PostData(5,fTreeV0Pr);
}
PostData(6,fReducedTree);//(Alberto Caliva)
}
//_____________________________________________________________________________
void AliTPCcalibResidualPID_Modified::UserExec(Option_t *)
{
//calls the Process function
AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!esdH) {
printf("ERROR: Could not get ESDInputHandler \n");
}
else fESD = (AliESDEvent*)esdH->GetEvent();
// If MC, forward MCevent
fMC = dynamic_cast<AliMCEvent*>(MCEvent());
//
Process(fESD, fMC);
//
PostData(1,fOutputContainer);
if (fWriteAdditionalOutput) {
PostData(2,fQAList);
PostData(3,fTreeV0El);
PostData(4,fTreeV0Pi);
PostData(5,fTreeV0Pr);
}
PostData(6,fReducedTree);//(Alberto Caliva)
}
//________________________________________________________________________
THnSparseF* AliTPCcalibResidualPID_Modified::InitialisePIDQAHist(TString name, TString title, Bool_t IsPbPb)
{
// Initialise a pidQA histo
//
// 0.ptot, 1.tpcSig, 2.particle ID, 3. assumed particle, 4. nSigmaTPC (4x), 5. nSigmaTOF (4x), 6. centrality
// Concerning 2 (particle ID):
// - in case of MC: Contains MC ID. Bin 1-4 (<=> Slot 0-3): el, pi, ka, pr
// - in case of data: Contains V0 particles + bin with all others: Bin 1-4 (<=> Slot 0-3): All non-V0s, V0-el, V0-pi, V0-pr
//
title.Append(";p (GeV/c);tpc signal;particle ID;assumed particle;nSigmaTPC;nSigmaTOF;centrality");
const Int_t kNdim = 7;
Int_t binsHistQA[kNdim] = {135, 1980, 4, 5, 40, 10, IsPbPb ? 40 : 40 };
Double_t xminHistQA[kNdim] = {0.1, 20., -0.5, -0.5, -10., -5., 0.};
Double_t xmaxHistQA[kNdim] = {50., 2000., 3.5, 4.5, 10., 5., IsPbPb ? 20000. : 4000.};
THnSparseF* h = new THnSparseF(name.Data(), title.Data(), kNdim, binsHistQA, xminHistQA, xmaxHistQA);
BinLogAxis(h, 0);
SetAxisNamesFromTitle(h);
return h;
}
//________________________________________________________________________
void AliTPCcalibResidualPID_Modified::Process(AliESDEvent *const esdEvent, AliMCEvent *const mcEvent)
{
//called for each event
if (!esdEvent) {
Printf("ERROR: esdEvent not available");
return;
}
if (!fPIDResponse || !fV0KineCuts || !fAnaUtils) {
Printf("ERROR: No PIDresponse, v0KineCuts or AliAnalysisUtils!");
return;
}
if (fAnaUtils->IsPileUpSPD(esdEvent))
return;
Float_t centralityFper=99;
AliCentrality *esdCentrality = esdEvent->GetCentrality();
centralityFper = esdCentrality->GetCentralityPercentile("V0M");
fCentralityPercentile = esdCentrality->GetCentralityPercentile("V0M");//(Alberto Caliva)
if (!GetVertexIsOk(esdEvent))
return;
const AliESDVertex* fESDvertex = esdEvent->GetPrimaryVertexTracks();
if (!fESDvertex)
return;
Int_t ncontr = fESDvertex->GetNContributors();
if (ncontr <= 0)
return;
// Fill V0 arrays with V0s
FillV0PIDlist(esdEvent);
// Array with flags wheter QA for this V0 was already done or not
const Int_t numV0s = esdEvent->GetNumberOfV0s();
Bool_t v0QAadded[numV0s];
for (Int_t i = 0; i < numV0s; i++)
v0QAadded[i] = kFALSE;
Int_t nTotTracks = esdEvent->GetNumberOfTracks();
const Int_t nTotESDTracks = esdEvent->GetNumberOfESDTracks();
const Double_t magField = esdEvent->GetMagneticField();
const Bool_t etaCorrAvail = fPIDResponse->UseTPCEtaCorrection();
const Bool_t multCorrAvail = fPIDResponse->UseTPCMultiplicityCorrection();
const Bool_t pileupCorrAvail = fPIDResponse->UseTPCPileupCorrection();
for (Int_t iTracks = 0; iTracks < nTotTracks; iTracks++){//begin track loop
AliESDtrack *trackESD = esdEvent->GetTrack(iTracks);
if(!trackESD) {
Printf("ERROR: Could not receive track %d (esd loop)", iTracks);
continue;
}
if((TMath::Abs(trackESD->Eta())) > 0.9)
continue;
// Do not distinguish positively and negatively charged V0's
Char_t v0tagAllCharges = TMath::Abs(GetV0tag(iTracks));
if (v0tagAllCharges == -99) {
AliError(Form("Problem with V0 tag list (requested V0 track for track %d from %d (list status %d))!", iTracks, esdEvent->GetNumberOfTracks(),
fV0tags != 0x0));
continue;
}
Bool_t isV0el = v0tagAllCharges == 14;
Bool_t isV0pi = v0tagAllCharges == 15;
Bool_t isV0pr = v0tagAllCharges == 16;
Bool_t isV0 = isV0el || isV0pi || isV0pr;
if (mcEvent && fUseMCinfo) {
// For MC, do not look for V0s, i.e. demand the non-V0 track cuts
if (fESDtrackCuts && !fESDtrackCuts->AcceptTrack(trackESD)) continue;
if (fUseTPCCutMIGeo) {
// If cut on geometry is active, don't cut on number of clusters, since such a cut is already included.
if (!TPCCutMIGeo(trackESD, esdEvent))
continue;
}
else {
// If cut on geometry is not active, always cut on num clusters
if (trackESD->GetTPCsignalN() < 60)
continue;
}
}
else {
// For data, take V0 AND non-V0 with separate cuts
//if (!isV0 && fESDtrackCuts && !fESDtrackCuts->AcceptTrack(trackESD)) continue;
if (isV0) {
if (fESDtrackCutsV0 && !fESDtrackCutsV0->AcceptTrack(trackESD))
continue;
}
else {
if (fESDtrackCuts && !fESDtrackCuts->AcceptTrack(trackESD))
continue;
}
if (fUseTPCCutMIGeo) {
// If cut on geometry is active, don't cut on number of clusters, since such a cut is already included.
if (!isV0) {
if (!TPCCutMIGeo(trackESD, esdEvent))
continue;
}
else {
// One should not cut on geometry for V0's since they have different topology. (Loosely) cut on num of clusters instead.
if (trackESD->GetTPCsignalN() < 60)
continue;
}
}
else {
// If cut on geometry is not active, always cut on num clusters
if (trackESD->GetTPCsignalN() < 60)
continue;
}
}
const AliExternalTrackParam *paramIn = trackESD->GetInnerParam();
Float_t precin=-1;
if(paramIn) {
precin=paramIn->GetP();
} else {
printf("Inner param not found for track %d - skipping!\n", iTracks);
continue;
}
Int_t precdefault=CompareFloat(precin,-1);
if(precdefault==1) continue; // momentum cut
//
AliMCParticle* mcTrack = 0x0;
Int_t particleID = -1;
Int_t v0id = 0;
if (mcEvent && fUseMCinfo) {
// MC - particle ID = MC ID
Int_t label = trackESD->GetLabel();
if (label < 0)
continue; // If MC is available, reject tracks with negative ESD label
mcTrack = dynamic_cast<AliMCParticle*>(mcEvent->GetTrack(TMath::Abs(label)));
if (!mcTrack) {
Printf("ERROR: Could not receive mcTrack with label %d for track %d", label, iTracks);
continue;
}
/*// Only accept MC primaries
if (!mcEvent->Stack()->IsPhysicalPrimary(TMath::Abs(label))) {
continue;
}*/
Int_t pdgAbs = TMath::Abs(mcTrack->PdgCode());
if (pdgAbs == 11) { // electron
particleID = 0;
}
else if (pdgAbs == 211) { // pion
particleID = 1;
}
else if (pdgAbs == 321) { // kaon
particleID = 2;
}
else if (pdgAbs == 2212) { // proton
particleID = 3;
}
else
continue; // Reject all other particles
}
else {
// Data - particle ID = V0 ID (if V0)
if (isV0pi) { // pion
particleID = 2;
v0id = 2;
}
else if (isV0el) { // electron
particleID = 1;
v0id = 1;
}
else if (isV0pr) { // proton
particleID = 3;
v0id = 3;
}
else { // No V0-ID available (species must be determined via TPC, TOF, ...)
particleID = 0;
}
}
// Float_t tpcsignal=trackESD->GetTPCsignal();
Float_t tpcsignal=fPIDResponse->GetTPCResponse().GetTrackdEdx(trackESD);
Int_t tofbit=-1;
Int_t iTOFpid=0;
Int_t ikTIME=0;
Double_t tpcnsigmaele=-10;
Double_t tpcnsigmapion=-10;
//
if ((trackESD->GetStatus() & AliESDtrack::kTOFpid)) iTOFpid = 1;
if ((trackESD->GetStatus() & AliESDtrack::kTIME)) ikTIME = 1;
Float_t time0 = fPIDResponse->GetTOFResponse().GetTimeZero();
//
if((iTOFpid==1) &&(ikTIME==1)){
Double_t tofnsigmaele= fPIDResponse->NumberOfSigmasTOF(trackESD,AliPID::kElectron, time0);
Double_t tofnsigmapion=fPIDResponse->NumberOfSigmasTOF(trackESD,AliPID::kPion, time0);
if (TMath::Abs(tofnsigmapion)<3) tofbit = 1;
if (TMath::Abs(tofnsigmaele)<3) tofbit = 0;
tpcnsigmaele=fPIDResponse->NumberOfSigmasTPC(trackESD,AliPID::kElectron);
tpcnsigmapion=fPIDResponse->NumberOfSigmasTPC(trackESD,AliPID::kPion);
}
//
Int_t tpcnclusN=trackESD->GetTPCsignalN();
Double_t eta=trackESD->Eta();
//
if(fProduceTPCSignalSparse){
Double_t contentSignal[9];
contentSignal[0]=v0id;
contentSignal[1]=tpcsignal;
contentSignal[2]=tpcnsigmaele;
contentSignal[3]=tpcnsigmapion;
contentSignal[4]=tofbit;
contentSignal[5]=eta;
contentSignal[6]=tpcnclusN;
contentSignal[7]=centralityFper;
contentSignal[8]=precin;
//
if (fThnspTpc->GetEntries() < 1e6) fThnspTpc->Fill(contentSignal);
}//should it be created or not
//Variables Reduced Tree (Alberto Caliva)
fParticleIDcode = particleID;
fNumberOfTPCclusters_dEdx = trackESD->GetTPCsignalN();
fTPC_dEdx_au = fPIDResponse->GetTPCResponse().GetTrackdEdx(trackESD);
fPseudorapidity = trackESD->Eta();
fMomentumTPCinnnerWall = paramIn->GetP();
fNumberOfSigmasTOF_Elec = fPIDResponse->NumberOfSigmasTOF(trackESD,AliPID::kElectron);
fNumberOfSigmasTOF_Pion = fPIDResponse->NumberOfSigmasTOF(trackESD,AliPID::kPion);
fNumberOfSigmasTOF_Kaon = fPIDResponse->NumberOfSigmasTOF(trackESD,AliPID::kKaon);
fNumberOfSigmasTOF_Prot = fPIDResponse->NumberOfSigmasTOF(trackESD,AliPID::kProton);
fReducedTree->Fill();
//
// 2nd THnSparse
//
Double_t tpcQA[5] = {fPIDResponse->NumberOfSigmasTPC(trackESD, AliPID::kElectron),
fPIDResponse->NumberOfSigmasTPC(trackESD, AliPID::kPion),
fPIDResponse->NumberOfSigmasTPC(trackESD, AliPID::kKaon),
fPIDResponse->NumberOfSigmasTPC(trackESD, AliPID::kProton),
0};
Double_t tofQA[5] = {fPIDResponse->NumberOfSigmasTOF(trackESD, AliPID::kElectron, time0),
fPIDResponse->NumberOfSigmasTOF(trackESD, AliPID::kPion, time0),
fPIDResponse->NumberOfSigmasTOF(trackESD, AliPID::kKaon, time0),
fPIDResponse->NumberOfSigmasTOF(trackESD, AliPID::kProton, time0),
0 };
// id 5 is just again Kaons in restricted eta range
tpcQA[4] = tpcQA[2];
tofQA[4] = tofQA[2];
//
// dE/dx in different pad regions
//
AliTPCdEdxInfo * infoTpcPid = trackESD->GetTPCdEdxInfo();
Double32_t signal[4]; Char_t ncl[3]; Char_t nrows[3];
if (infoTpcPid) {
infoTpcPid->GetTPCSignalRegionInfo(signal, ncl, nrows);
} else {
for(Int_t iarr = 0; iarr < 3; iarr++) {
signal[iarr] = 0;
ncl[iarr] = 0;
nrows[iarr] = 0;
}
signal[3] = 0;
}
//
UInt_t status = trackESD->GetStatus();
Bool_t hasTOFout = status&AliESDtrack::kTOFout;
Bool_t hasTOFtime = status&AliESDtrack::kTIME;
Bool_t hasTOF = kFALSE;
if (hasTOFout && hasTOFtime) hasTOF = kTRUE;
Float_t length = trackESD->GetIntegratedLength();
// Length check only for primaries!
if (length < 350 && !isV0) hasTOF = kFALSE;
//
if (!hasTOF) {
// Make sure that number of sigmas is large in this case, so that the track will be rejected if a TOF cut is applied
for (Int_t i = 0; i < 5; i++) {
tofQA[i] = 999;
}
}
Double_t processedTPCsignal[5] = { tpcsignal, tpcsignal, tpcsignal, tpcsignal, tpcsignal };
if (fCorrectdEdxEtaDependence && fNumEtaCorrReqErrorsIssued < 23 && !etaCorrAvail) {
AliError("TPC eta correction requested, but was not activated in PID response (most likely not available)!");
fNumEtaCorrReqErrorsIssued++;
if (fNumEtaCorrReqErrorsIssued == 23)
AliError("Ignoring this error from now on!");
}
if (fCorrectdEdxMultiplicityDependence && fNumMultCorrReqErrorsIssued < 23 && !multCorrAvail) {
AliError("TPC multiplicity correction requested, but was not activated in PID response (most likely not available)!");
fNumMultCorrReqErrorsIssued++;
if (fNumMultCorrReqErrorsIssued == 23)
AliError("Ignoring this error from now on!");
}
AliTPCPIDResponse& tpcResponse = fPIDResponse->GetTPCResponse();
const Bool_t etaCorrected = fCorrectdEdxEtaDependence && etaCorrAvail;
const Bool_t multCorrected = fCorrectdEdxMultiplicityDependence && multCorrAvail;
const Bool_t pileupCorrected = fCorrectdEdxPileupDependence && pileupCorrAvail;
processedTPCsignal[0] = tpcResponse.GetCorrectedTrackdEdx(trackESD, AliPID::kElectron, etaCorrected, multCorrected, pileupCorrected);
processedTPCsignal[1] = tpcResponse.GetCorrectedTrackdEdx(trackESD, AliPID::kPion, etaCorrected, multCorrected, pileupCorrected);
processedTPCsignal[2] = tpcResponse.GetCorrectedTrackdEdx(trackESD, AliPID::kKaon, etaCorrected, multCorrected, pileupCorrected);
processedTPCsignal[3] = tpcResponse.GetCorrectedTrackdEdx(trackESD, AliPID::kProton, etaCorrected, multCorrected, pileupCorrected);
// id 5 is just again Kaons in restricted eta range
processedTPCsignal[4] = processedTPCsignal[2];
for(Int_t iPart = 0; iPart < 5; iPart++) {
// Only accept "Kaons" within |eta| < 0.2 for index 4 in case of data (no contamination in case of MC, so this index is not used)
if (iPart == 4 && ((mcEvent && fUseMCinfo) || abs(trackESD->Eta()) > 0.2)) {
continue;
}
Double_t vecHistQA[7] = {precin, processedTPCsignal[iPart], (Double_t)particleID, (Double_t)iPart, tpcQA[iPart], tofQA[iPart],
(Double_t)nTotESDTracks};
if (fProduceGlobal) fHistPidQA->Fill(vecHistQA);
vecHistQA[1] = signal[0]; vecHistQA[4] = ncl[0];
if ((fProduceAllPadTypes || fProduceShortPads)) fHistPidQAshort->Fill(vecHistQA);
//
vecHistQA[1] = signal[1]; vecHistQA[4] = ncl[1];
if ((fProduceAllPadTypes || fProduceMediumPads)) fHistPidQAmedium->Fill(vecHistQA);
//
vecHistQA[1] = signal[2]; vecHistQA[4] = ncl[2];
if ((fProduceAllPadTypes || fProduceLongPads)) fHistPidQAlong->Fill(vecHistQA);
//
vecHistQA[1] = signal[3]; vecHistQA[4] = nrows[1] + nrows[2];
if ((fProduceAllPadTypes || fProduceOroc)) fHistPidQAoroc->Fill(vecHistQA);
}
if (fWriteAdditionalOutput && isV0) {
// Find the closest neighbour and fill the information into the trees.
fTree_p_TPC_tr = precin;
fTree_dEdx_tr = tpcsignal;
fTree_BtimesChargeOverPt_tr = TMath::Abs(magField) * trackESD->GetSigned1Pt();
fTree_tanTheta_tr = trackESD->GetInnerParam()->GetTgl();
Int_t closestNeighbourIndex = -1;
const Double_t tpcInnerRadius = 85.;
const Int_t parIndexGlobalPhi = 8;
const Double_t z_tr = trackESD->GetInnerParam()->GetZ();
const Double_t phi_tr = trackESD->GetInnerParam()->GetParameterAtRadius(tpcInnerRadius, magField, parIndexGlobalPhi);
const Double_t distanceCut = 12.; // Cut on distance between track to closest neighbour
Double_t z_nb = 9999;
Double_t phi_nb = 9999;
Double_t delta_z = 9999;
Double_t delta_phi = 9999;
fTree_distance_nb = -9999;
for (Int_t jTracks = 0; jTracks < nTotTracks; jTracks++) {
if (iTracks == jTracks)
continue; // Exclude track we are looking at right now from neighbour list
AliESDtrack *track_nb= esdEvent->GetTrack(jTracks);
if(!track_nb)
continue;
const AliExternalTrackParam *paramIn_nb = track_nb->GetInnerParam();
if (!paramIn_nb)
continue;
z_nb = paramIn_nb->GetZ();
delta_z = TMath::Abs(z_nb - z_tr);
if (delta_z >= distanceCut)
continue;
phi_nb = paramIn_nb->GetParameterAtRadius(tpcInnerRadius, magField, parIndexGlobalPhi);
delta_phi = TMath::Abs(phi_nb - phi_tr);
const Double_t delta_r_phi = tpcInnerRadius * delta_phi;
if (delta_r_phi >= distanceCut)
continue;
const Double_t distance = TMath::Sqrt(delta_z * delta_z + delta_r_phi * delta_r_phi);
if (distance >= distanceCut)
continue;
if (closestNeighbourIndex < 0 || distance < fTree_distance_nb) {
fTree_distance_nb = distance;
closestNeighbourIndex = jTracks;
}
}
if (closestNeighbourIndex >= 0 && closestNeighbourIndex < nTotTracks) {
AliESDtrack *track_nb= esdEvent->GetTrack(closestNeighbourIndex);
// fTree_dEdx_nb = track_nb->GetTPCsignal();
fTree_dEdx_nb = fPIDResponse->GetTPCResponse().GetTrackdEdx(track_nb);
fTree_p_TPC_nb = track_nb->GetInnerParam()->GetP();
fTree_BtimesChargeOverPt_nb = TMath::Abs(magField) * track_nb->GetSigned1Pt();
fTree_tanTheta_nb = track_nb->GetInnerParam()->GetTgl();
}
else {
// No neighbour in this range -> nevertheless store the track, but set neighbour values to invalid
fTree_dEdx_nb = -999.;
fTree_p_TPC_nb = -999.;
fTree_BtimesChargeOverPt_nb = -999.;
fTree_tanTheta_nb = -999.;
fTree_distance_nb = -999.;
}
// Find the other V0 daughter and store its values
const Int_t motherIndex = GetV0motherIndex(iTracks);
AliESDv0* v0Mother = (AliESDv0*)esdEvent->GetV0(motherIndex);
if (!v0Mother) {
printf("Error: Track tagged as V0 daughter, but V0 mother not found!\n");
continue;
}
const Int_t iTrackP = v0Mother->GetPindex(); // positive track
const Int_t iTrackN = v0Mother->GetNindex(); // negative track_nb
Int_t iTrackV0sister = -1;
if (iTrackP == iTracks)
iTrackV0sister = iTrackN;
else if (iTrackN == iTracks)
iTrackV0sister = iTrackP;
else {
printf("Error: V0 sister relations are wrong!\n");
continue;
}
fTree_dEdx_vs = -999.;
fTree_p_TPC_vs = -999.;
fTree_BtimesChargeOverPt_vs = -999.;
fTree_tanTheta_vs = -999.;
fTree_distance_vs = -999.;
AliESDtrack *track_vs = esdEvent->GetTrack(iTrackV0sister);
if (track_vs) {
const AliExternalTrackParam *paramIn_vs = track_vs->GetInnerParam();
if (paramIn_vs) {
// fTree_dEdx_vs = track_vs->GetTPCsignal();
fTree_dEdx_vs = fPIDResponse->GetTPCResponse().GetTrackdEdx(track_vs);
fTree_p_TPC_vs = paramIn_vs->GetP();
fTree_BtimesChargeOverPt_vs = TMath::Abs(magField) * track_vs->GetSigned1Pt();
fTree_tanTheta_vs = paramIn_vs->GetTgl();
// Calculate distance
const Double_t z_vs = paramIn_vs->GetZ();
const Double_t delta_z_vs = TMath::Abs(z_vs - z_tr);
const Double_t phi_vs = paramIn_vs->GetParameterAtRadius(tpcInnerRadius, magField, parIndexGlobalPhi);
const Double_t delta_phi_vs = TMath::Abs(phi_vs - phi_tr);
const Double_t delta_r_phi_vs = tpcInnerRadius * delta_phi_vs;
fTree_distance_vs = TMath::Sqrt(delta_z_vs * delta_z_vs + delta_r_phi_vs * delta_r_phi_vs);
}
}
if (isV0el) {
fTree_dEdxExpected_tr = fPIDResponse->GetTPCResponse().GetExpectedSignal(trackESD, AliPID::kElectron, AliTPCPIDResponse::kdEdxDefault,
fPIDResponse->UseTPCEtaCorrection(),
fPIDResponse->UseTPCMultiplicityCorrection());
if (fTree_dEdxExpected_tr > 0)
fTreeV0El->Fill();
}
else if (isV0pi) {
fTree_dEdxExpected_tr = fPIDResponse->GetTPCResponse().GetExpectedSignal(trackESD, AliPID::kPion, AliTPCPIDResponse::kdEdxDefault,
fPIDResponse->UseTPCEtaCorrection(),
fPIDResponse->UseTPCMultiplicityCorrection());
if (fTree_dEdxExpected_tr > 0)
fTreeV0Pi->Fill();
}
else if (isV0pr) {
fTree_dEdxExpected_tr = fPIDResponse->GetTPCResponse().GetExpectedSignal(trackESD, AliPID::kProton, AliTPCPIDResponse::kdEdxDefault,
fPIDResponse->UseTPCEtaCorrection(),
fPIDResponse->UseTPCMultiplicityCorrection());
if (fTree_dEdxExpected_tr > 0)
fTreeV0Pr->Fill();
}
// Fill QA hists for shared clusters dE/dx
Double_t vecHistQA[4] = { precin, -1., (Double_t)trackESD->GetTPCSharedMap().CountBits(), -1. };
THnSparse* currHist = fHistSharedClusQAV0Pi;
if (isV0pi) {
Double_t expectedDeDx = fPIDResponse->GetTPCResponse().GetExpectedSignal(trackESD, AliPID::kPion, AliTPCPIDResponse::kdEdxDefault,
fPIDResponse->UseTPCEtaCorrection(),
fPIDResponse->UseTPCMultiplicityCorrection());
if (expectedDeDx > 0 ) {
vecHistQA[1] = tpcsignal / expectedDeDx;
currHist = fHistSharedClusQAV0Pi;
}
}
else if (isV0pr) {
Double_t expectedDeDx = fPIDResponse->GetTPCResponse().GetExpectedSignal(trackESD, AliPID::kProton, AliTPCPIDResponse::kdEdxDefault,
fPIDResponse->UseTPCEtaCorrection(),
fPIDResponse->UseTPCMultiplicityCorrection());
if (expectedDeDx > 0 ) {
vecHistQA[1] = tpcsignal / expectedDeDx;
currHist = fHistSharedClusQAV0Pr;
}
}
else if (isV0el) {
Double_t expectedDeDx = fPIDResponse->GetTPCResponse().GetExpectedSignal(trackESD, AliPID::kElectron, AliTPCPIDResponse::kdEdxDefault,
fPIDResponse->UseTPCEtaCorrection(),
fPIDResponse->UseTPCMultiplicityCorrection());
if (expectedDeDx > 0 ) {
vecHistQA[1] = tpcsignal / expectedDeDx;
currHist = fHistSharedClusQAV0El;
}
}
Int_t iRowInd = -1;
// iRowInd == -1 for "all rows w/o multiple counting"
currHist->Fill(vecHistQA);
// Fill hist for every pad row with shared cluster
for (iRowInd = 0; iRowInd < 159; iRowInd++) {
if (trackESD->GetTPCSharedMap().TestBitNumber(iRowInd)) {
vecHistQA[3] = iRowInd;
currHist->Fill(vecHistQA);
}
}
// Check, whether the QA for this V0 mother was already filled into the histograms (is the case if the other daughter has already
// been processed). If not, set flag to kTRUE and fill the QA.
const Int_t iV0 = GetV0motherIndex(iTracks);
if (!v0QAadded[iV0]) {
v0QAadded[iV0] = kTRUE;
AliESDv0* esdV0 = (AliESDv0*)esdEvent->GetV0(iV0);
if (!esdV0) {
printf("Error: V0 tagged, but does not exist!\n");
}
else {
Float_t armVar[2] = {0.0,0.0};
fV0KineCuts->Armenteros(esdV0, armVar);
const Int_t motherPDG = GetV0motherPDG(iTracks);
// Mother and daughter match the requirements, otherwise it wouldn't be tagged as a V0. Now just fill the QA histos.
fhArmenterosAll->Fill(armVar[0], armVar[1]);
//if (esdV0->TestBit(BIT(14))) {
if (TMath::Abs(motherPDG) == 22) {
fhInvMassGamma->Fill(esdV0->GetEffMass(AliPID::kElectron, AliPID::kElectron));
fhArmenterosGamma->Fill(armVar[0], armVar[1]);
}
else if (TMath::Abs(motherPDG) == 310) {
//else if (esdV0->TestBit(BIT(15))) {
fhInvMassK0s->Fill(esdV0->GetEffMass(AliPID::kPion, AliPID::kPion));
fhArmenterosK0s->Fill(armVar[0], armVar[1]);
}
else if (motherPDG == 3122) {
//else if (esdV0->TestBit(BIT(16))) {
fhInvMassLambda->Fill(esdV0->GetEffMass(AliPID::kProton, AliPID::kPion));
fhArmenterosLambda->Fill(armVar[0], armVar[1]);
}
else if (motherPDG == -3122) {
//else if (esdV0->TestBit(BIT(17))) {
fhInvMassAntiLambda->Fill(esdV0->GetEffMass(AliPID::kPion, AliPID::kProton));
fhArmenterosAntiLambda->Fill(armVar[0], armVar[1]);
}
}
}
}
} //end track loop
// Clear the V0 PID arrays
ClearV0PIDlist();
}
//________________________________________________________________________
Bool_t AliTPCcalibResidualPID_Modified::ProcessV0Tree(TTree* tree, THnSparseF* h, const Int_t recoPass/*=4*/,
const TString runList/*=""*/, const Bool_t excludeRuns/*=kFALSE*/)
{
// Fill tracks from tree into h. Returns kTRUE on success.
// recoPass is required to propbely initialise the AliPIDResponse
// runList can either be a whith or black list of runs, ignored if empty
// if excludeRuns is false runList is a whitelist, otherwise a blacklist
if (!tree)
return kFALSE;
if (!h) {
Printf("Error - ProcessV0Tree: No THnSparse!");
return kFALSE;
}
//set up the PID response
if (!fPIDResponse) {
fPIDResponse=new AliPIDResponse;
fPIDResponse->SetOADBPath("$ALICE_PHYSICS/OADB");
delete fESD;
fESD = new AliESDEvent;
fESD->CreateStdContent();
}
TClonesArray *arrTracks=(TClonesArray*)fESD->GetList()->FindObject("Tracks");
// Tree name is important to assign PID
TString treeName = tree->GetName();
Bool_t isTreeK0 = treeName.CompareTo("treeK0", TString::kIgnoreCase) == 0;
Bool_t isTreeGamma = treeName.CompareTo("treeGamma", TString::kIgnoreCase) == 0;
Bool_t isTreeALambda = treeName.CompareTo("treeALambda", TString::kIgnoreCase) == 0;
Bool_t isTreeLambda = treeName.CompareTo("treeLambda", TString::kIgnoreCase) == 0;
if (!isTreeK0 && !isTreeGamma && !isTreeALambda && !isTreeLambda) {
Printf("Error - ProcessV0Tree: Unknown tree type \"%s\"!", treeName.Data());
return kFALSE;
}
const Int_t numCases = 5;
Double_t tpcQA[numCases];
Double_t tofQA[numCases];
for (Int_t i = 0; i < numCases; i++) {
tpcQA[i] = 0.;
tofQA[i] = 0.;
}
const Int_t nTotESDTracks = -1;
Int_t particleID = -1;
AliPID::EParticleType alicePID=AliPID::kUnknown;
Long64_t nTreeEntries = tree->GetEntriesFast();
Double_t tpcsignal = -1.;
Double_t tanTheta = -999.;
Double_t precin = -1.;
AliESDtrack* trk = 0x0;
AliESDtrack* trk0 = 0x0;
AliESDtrack* trk1 = 0x0;
Int_t runNumber = -1;
Int_t runNumberFirst = -1;
Int_t ntracks = -1;
tree->SetBranchStatus("*", 0);
tree->SetBranchStatus("runNumber", 1);
tree->SetBranchStatus("ntracks", 1);
tree->SetBranchStatus("track0.*", 1);
tree->SetBranchStatus("track1.*", 1);
tree->SetBranchAddress("runNumber",&runNumber);
tree->SetBranchAddress("ntracks" ,&ntracks );
tree->SetBranchAddress("track0." ,&trk0 );
tree->SetBranchAddress("track1." ,&trk1 );
// Should be faster, but does not work for unknown reason
//tree->SetBranchAddress(Form("track%d.fTPCsignal", track), &tpcsignal);
//tree->SetBranchAddress(Form("track%d.fIp.fP[3]", track), &tanTheta);
//tree->SetBranchAddress(Form("track%d.fIp.P()", track), &precin);
// ===| set up run exclusion map |============================================
TExMap runMap;
if (!runList.IsNull()) {
TObjArray *arr = runList.Tokenize(",; ");
for (Int_t irun=0; irun<arr->GetEntriesFast(); ++irun) {
const TString &runStr=((TObjString*)arr->At(irun))->String();
if (!runStr.IsDigit()) continue;
runMap.Add(runStr.Atoi(), 1);
cout << "run" << runStr << " added" << endl;
}
delete arr;
}
for (Long64_t i = 0; i < nTreeEntries; i++) {
tree->GetEntry(i);
// skip runs
if (runMap.GetSize() && !(runMap.GetValue(runNumber)^excludeRuns)) continue;
// set dummy esd track multiplicity
arrTracks->Clear();
arrTracks->ConstructedAt(ntracks);
// initialise PID response
// assume that we can load from the OADB only for the first run number
// which means that the trees are merged per run or per period
Bool_t init=kFALSE;
if (runNumberFirst<0) {
runNumberFirst=runNumber;
init=kTRUE;
}
fPIDResponse->InitialiseEvent(fESD, recoPass, runNumberFirst);
//if (init) {
//fPIDResponse->GetTPCResponse().GetTransferFunctionParameters().Print();
//}
for (Int_t track = 0; track < 2; track++) {
trk=trk0;
if (track==1) {
trk=trk1;
}
if (!trk)
continue;
//tpcsignal = trk->fTPCsignal;
//tanTheta = trk->fIp->fP[3];
//precin = trk->fIp->P();
tpcsignal = trk->GetTPCsignal();
tanTheta = trk->GetInnerParam()->GetParameter()[3];
precin = trk->GetInnerParam()->P();
//if (TMath::Abs(tanTheta-.7)>0.2) continue;
// track == 0 is the positive particle, track == 1 the negative.
// Combine this with the tree name to determine the particle ID.
if (isTreeK0) {
particleID = 2; //pion
alicePID=AliPID::kPion;
} else if (isTreeGamma) {
particleID = 1; // electron
alicePID=AliPID::kElectron;
} else if (isTreeLambda) {
if (track == 0) {
particleID = 3; // proton
alicePID=AliPID::kProton;
} else {
particleID = 2; // pion
alicePID=AliPID::kPion;
}
}
else if (isTreeALambda) {
if (track == 0) {
particleID = 2; // pion
alicePID=AliPID::kPion;
} else {
particleID = 3; // proton
alicePID=AliPID::kProton;
}
}
// make signal correction for transfer function and BB shape
// TODO: Perhaps this should be steerable
//const Double_t corrTransferBB = fPIDResponse->GetTPCResponse().GetCombinedTransferFunctionBBCorrection(trk, alicePID);
//const Double_t corrTransferBB = fPIDResponse->GetTPCResponse().GetTransferFunctionCorrection(trk);
//printf("signal: %.2f/%.2f = %.2f\n", tpcsignal, corrTransferBB, tpcsignal/corrTransferBB);
//tpcsignal/=corrTransferBB;
Double_t processedTPCsignal[5] = { tpcsignal, tpcsignal, tpcsignal, tpcsignal, tpcsignal };
/*
if (fCorrectdEdxEtaDependence && fNumEtaCorrReqErrorsIssued < 23 && !etaCorrAvail) {
AliError("TPC eta correction requested, but was not activated in PID response (most likely not available)!");
fNumEtaCorrReqErrorsIssued++;
if (fNumEtaCorrReqErrorsIssued == 23)
AliError("Ignoring this error from now on!");
}
if (fCorrectdEdxMultiplicityDependence && fNumMultCorrReqErrorsIssued < 23 && !multCorrAvail) {
AliError("TPC multiplicity correction requested, but was not activated in PID response (most likely not available)!");
fNumMultCorrReqErrorsIssued++;
if (fNumMultCorrReqErrorsIssued == 23)
AliError("Ignoring this error from now on!");
}
if (fCorrectdEdxEtaDependence && etaCorrAvail && fCorrectdEdxMultiplicityDependence && multCorrAvail) {
processedTPCsignal[0] = fPIDResponse->GetTPCResponse().GetEtaAndMultiplicityCorrectedTrackdEdx(trackESD, AliPID::kElectron,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[1] = fPIDResponse->GetTPCResponse().GetEtaAndMultiplicityCorrectedTrackdEdx(trackESD, AliPID::kPion,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[2] = fPIDResponse->GetTPCResponse().GetEtaAndMultiplicityCorrectedTrackdEdx(trackESD, AliPID::kKaon,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[3] = fPIDResponse->GetTPCResponse().GetEtaAndMultiplicityCorrectedTrackdEdx(trackESD, AliPID::kProton,
AliTPCPIDResponse::kdEdxDefault);
}
else if (fCorrectdEdxEtaDependence && etaCorrAvail) {
processedTPCsignal[0] = fPIDResponse->GetTPCResponse().GetEtaCorrectedTrackdEdx(trackESD, AliPID::kElectron,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[1] = fPIDResponse->GetTPCResponse().GetEtaCorrectedTrackdEdx(trackESD, AliPID::kPion,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[2] = fPIDResponse->GetTPCResponse().GetEtaCorrectedTrackdEdx(trackESD, AliPID::kKaon,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[3] = fPIDResponse->GetTPCResponse().GetEtaCorrectedTrackdEdx(trackESD, AliPID::kProton,
AliTPCPIDResponse::kdEdxDefault);
}
else if (fCorrectdEdxMultiplicityDependence && multCorrAvail) {
processedTPCsignal[0] = fPIDResponse->GetTPCResponse().GetMultiplicityCorrectedTrackdEdx(trackESD, AliPID::kElectron,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[1] = fPIDResponse->GetTPCResponse().GetMultiplicityCorrectedTrackdEdx(trackESD, AliPID::kPion,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[2] = fPIDResponse->GetTPCResponse().GetMultiplicityCorrectedTrackdEdx(trackESD, AliPID::kKaon,
AliTPCPIDResponse::kdEdxDefault);
processedTPCsignal[3] = fPIDResponse->GetTPCResponse().GetMultiplicityCorrectedTrackdEdx(trackESD, AliPID::kProton,
AliTPCPIDResponse::kdEdxDefault);
}
*/
// id 5 is just again Kaons in restricted eta range
processedTPCsignal[4] = processedTPCsignal[2];
for(Int_t iPart = 0; iPart < numCases; iPart++) {
// Only accept "Kaons" within |eta| < 0.2 for index 4 (eta ~ tanTheta in this eta range)
if (iPart == 4 && abs(tanTheta) > 0.2)
continue;
Double_t vecHistQA[7] = {precin, processedTPCsignal[iPart], (Double_t)particleID, (Double_t)iPart, tpcQA[iPart], tofQA[iPart],
(Double_t)nTotESDTracks};
//cout << vecHistQA[0] << "\t" << vecHistQA[1] << "\t" << vecHistQA[2] << "\t" << vecHistQA[3] << "\t" << vecHistQA[4] << "\t" << vecHistQA[5] << endl;
h->Fill(vecHistQA);
}
}
}
return kTRUE;
}
//________________________________________________________________________
THnSparseF* AliTPCcalibResidualPID_Modified::ProcessV0TreeFile(TString filePathName, const Int_t recoPass/*=4*/,
const TString runList/*=""*/, const Bool_t excludeRuns/*=kFALSE*/)
{
// Open file and fill tracks from trees into a new THnSparse. Finally, returns it.
TFile* f = TFile::Open(filePathName.Data(), "READ");
if (!f) {
Printf("Error - ProcessV0TreeFile: Cannot open file \"%s\"!", filePathName.Data());
return 0x0;
}
THnSparseF* h = InitialisePIDQAHist("fHistPidQA","PID QA");
TTree* tree = 0x0;
const Int_t numTrees = 4;
const TString treeNames[numTrees] = { "treeK0", "treeGamma", "treeLambda", "treeALambda" };
for (Int_t i = 0; i < numTrees; i++) {
Printf("Processing tree \"%s\"....", treeNames[i].Data());
tree = (TTree*)f->Get(treeNames[i].Data());
if (tree)
tree->SetName(treeNames[i].Data());
ProcessV0Tree(tree, h, recoPass, runList, excludeRuns);
}
f->Close();
delete f;
return h;
}
//________________________________________________________________________
Int_t AliTPCcalibResidualPID_Modified::CompareFloat(Float_t f1, Float_t f2) const
{
//compares if the Float_t f1 is equal with f2 and returns 1 if true and 0 if false
Float_t precision = 0.00001;
if (((f1 - precision) < f2) &&
((f1 + precision) > f2))
{
return 1;
}
else
{
return 0;
}
}
//________________________________________________________________________
void AliTPCcalibResidualPID_Modified::Terminate(const Option_t *)
{
}
//________________________________________________________________________
void AliTPCcalibResidualPID_Modified::BinLogAxis(THnSparseF *h, Int_t axisNumber)
{
//
// Method for the correct logarithmic binning of histograms
//
TAxis *axis = h->GetAxis(axisNumber);
int bins = axis->GetNbins();
Double_t from = axis->GetXmin();
Double_t to = axis->GetXmax();
Double_t *newBins = new Double_t[bins + 1];
newBins[0] = from;
Double_t factor = pow(to/from, 1./bins);
for (int i = 1; i <= bins; i++) {
newBins[i] = factor * newBins[i-1];
}
axis->Set(bins, newBins);
delete [] newBins;
}
void AliTPCcalibResidualPID_Modified::CreatePlotWithOwnParameters(THnSparseF * histPidQA, const Bool_t useV0s, const Char_t * type, const Char_t * system, const Double_t* parameters, AliTPCcalibResidualPID_Modified::FitType fitType, Float_t from, Float_t to) {
TObjArray * arr = 0x0;
Bool_t isMC = kFALSE;
if (strcmp(type, "MC") == 0) {
arr = GetResidualGraphsMC(histPidQA, system);
isMC = kTRUE;
}
else if (strcmp(type, "DATA") == 0) {
arr = GetResidualGraphs(histPidQA, system, useV0s);
}
else {
Printf("ERROR - ExtractResidualPID: Unknown type \"%s\" - must be \"MC\" or \"DATA\"!", type);
return;
}
TF1* func = SetUpFitFunction(parameters, fitType, from, to, kFALSE, isMC, 0x0);
TGraphErrors * graphAll = (TGraphErrors *) arr->FindObject("beamDataPoints");
TCanvas* canvDelta_2 = CreateResidualCanvas(graphAll, func);
TCanvas* canvDelta_1 = CreateBBCanvas(arr, isMC, func);
return;
}
//________________________________________________________________________
Double_t* AliTPCcalibResidualPID_Modified::ExtractResidualPID(THnSparseF * histPidQA, const Bool_t useV0s, const Char_t * outFile,
const Char_t * type, const Char_t * period, const Char_t * pass,
const Char_t * system, const Double_t * initialParameters,
const Char_t *dedxtype,
AliTPCcalibResidualPID_Modified::FitType fitType) {
//
// (1.) obtain residual graphs
//
TObjArray * arr = 0x0;
Bool_t isMC = kFALSE;
if (strcmp(type, "MC") == 0) {
arr = GetResidualGraphsMC(histPidQA, system);
isMC = kTRUE;
}
else if (strcmp(type, "DATA") == 0) {
arr = GetResidualGraphs(histPidQA, system, useV0s);
}
else {
Printf("ERROR - ExtractResidualPID: Unknown type \"%s\" - must be \"MC\" or \"DATA\"!", type);
return 0x0;
}
Bool_t isPPb = kFALSE;
if (strcmp(system, "PPB") == 0 || strcmp(system, "PBP") == 0) {
Printf("p-Pb/Pb-p detected - Applying special handling!");
isPPb = kTRUE;
}
//
// (2.) get old-style Bethe-Bloch parameters
//
TF1* parametrisation = FitBB(arr, isMC, isPPb, useV0s, initialParameters, fitType);
//
// (3.) obtain response functions to OADB
//
TObjArray* arrResponse = GetResponseFunctions(parametrisation, arr, type, period, pass, system, dedxtype);
//
// (4.) write results to file and exit
//
if (arrResponse) {
TFile outputFile(outFile,"RECREATE");
arrResponse->Write();
outputFile.Close();
}
return parametrisation->GetParameters();
}
//________________________________________________________________________
TObjArray * AliTPCcalibResidualPID_Modified::GetSeparation(THnSparseF * histPidQA, Int_t kParticle1, Int_t kParticle2) {
//get THnSparse
THnSparse * hist = histPidQA;
Float_t nSigmaPlus1 = 0, nSigmaMinus1 = 0; //sigma of first particle in the TPC
Float_t nSigmaPlus2 = 0, nSigmaMinus2 = 0; //sigma of second particle in the TPC
if(kParticle1 == 0){ // electron
nSigmaMinus1 = -1.999;
nSigmaPlus1 = 2.999;
} else if(kParticle1 == 1){ //pion
nSigmaMinus1 = -1.999;
nSigmaPlus1 = 2.999;
} else if(kParticle1 == 2){ //kaons
nSigmaMinus1 = -2.999;
nSigmaPlus1 = 2.999;
} else if(kParticle1 == 3){ //protons
nSigmaMinus1 = -2.999;
nSigmaPlus1 = 2.999;
}
//
// 1. select and fit first particle
//
hist->GetAxis(3)->SetRangeUser(kParticle1,kParticle1);
hist->GetAxis(4)->SetRangeUser(nSigmaMinus1,nSigmaPlus1);
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // 3sigma in TOF
TH2D * histPart1 = (TH2D*) hist->Projection(1,0)->Clone("histPart1");
histPart1->SetTitle(";p /(GeV/c) ; TPCSignal /(a.u.)");
histPart1->RebinX(4);
TObjArray arr;
histPart1->FitSlicesY(0,0,-1,10,"QNR",&arr);
TH1D * PartMean1 = (TH1D *) arr.At(1)->Clone("PartMean1");
TH1D * PartSigma1 = (TH1D *) arr.At(2)->Clone("PartSigma1");
PartMean1->SetTitle(";p /(GeV/c) ; Mean (Gauss)");
PartSigma1->SetTitle(";p /(GeV/c) ; Sigma (Gauss)");
histPart1->SetMarkerStyle(22);
PartMean1->SetMarkerStyle(21);
hist->GetAxis(4)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(5)->SetRange(0,-1); // RESET RANGES
if(kParticle2==0){ // electron
nSigmaMinus2 = -1.999;
nSigmaPlus2 = 2.999;
} else if(kParticle2 == 1){ //pion
nSigmaMinus2 = -1.999;
nSigmaPlus2 = 2.999;
} else if(kParticle2 == 2){ //kaons
nSigmaMinus2 = -2.999;
nSigmaPlus2 = 2.999;
} else if(kParticle2 == 3){ //protons
nSigmaMinus2 = -2.999;
nSigmaPlus2 = 2.999;
}
//
// 2. select and fit second particle
//
hist->GetAxis(3)->SetRangeUser(kParticle2,kParticle2);
hist->GetAxis(4)->SetRangeUser(nSigmaMinus2,nSigmaPlus2);
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // 3sigma in TOF
TH2D * histPart2 = (TH2D*)hist->Projection(1,0)->Clone("histPart2");
histPart2->RebinX(4);
histPart2->FitSlicesY(0,0,-1,10,"QNR",&arr);
TH1D * PartMean2 = (TH1D *) arr.At(1)->Clone("PartMean2");
TH1D * PartSigma2 = (TH1D *) arr.At(2)->Clone("PartSigma2");
PartMean2->SetTitle(";p /(GeV/c) ; Mean (Gauss)");
PartSigma2->SetTitle(";p /(GeV/c) ; Sigma (Gauss)");
PartMean2->SetMarkerStyle(20);
hist->GetAxis(4)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(5)->SetRange(0,-1); // RESET RANGES
//
// 3. separation
//
TH1F *fHistSeparation=(TH1F*)PartMean1->Clone("fHistSeparation"); //to get same binning
fHistSeparation->SetMarkerStyle(22);
const Int_t Nbins = PartMean1->GetNbinsX();
fHistSeparation->SetTitle(";p /(GeV/c) ; Separation");
Float_t DeltaMean[Nbins] ;
Float_t DeltaSigma[Nbins];
for(Int_t i=0 ; i<Nbins; i++){
DeltaMean[i] = TMath::Abs(PartMean1->GetBinContent(i) - PartMean2->GetBinContent(i));
DeltaSigma[i] = TMath::Abs((PartSigma1->GetBinContent(i) + PartSigma2->GetBinContent(i)))/2.;
if(!(TMath::Abs(DeltaSigma[i])<0.000001))fHistSeparation->SetBinContent(i,DeltaMean[i]/DeltaSigma[i]);
}//for(Int_t i=0 ; i<Nbins ; i++)
TObjArray *array = new TObjArray();
array->Add(histPart1);
array->Add(histPart2);
array->Add(PartMean1);
array->Add(PartSigma1);
array->Add(PartMean2);
array->Add(PartSigma2);
array->Add(fHistSeparation);
return array;
}
//________________________________________________________________________
TObjArray * AliTPCcalibResidualPID_Modified::GetResidualGraphs(THnSparseF * histPidQA, const Char_t * system, Bool_t useV0s) {
//
// Extracts the residual graphs from THnSparse created from data (NOT MC!)
//
const TString momTitle = "#it{p}_{TPC} (GeV/#it{c})";
const TString dEdxTitle = "d#it{E}/d#it{x} (arb. unit)";
Bool_t isPPb = kFALSE;
if (strcmp(system, "PPB") == 0 || strcmp(system, "PBP") == 0) {
Printf("p-Pb/Pb-p detected - Applying special handling!");
isPPb = kTRUE;
}
// the following parameters have to be extracted from the data itself
//
Float_t nSigmaPionMinus = -3.999;
Float_t nSigmaPionPlus = 3.999;
Float_t nSigmaKaonMinus = -4.199;
Float_t nSigmaKaonPlus = 4.7999;
Float_t nSigmaElectronMinus = -1.999;
Float_t nSigmaElectronPlus = 4.999;
Int_t cutForFitting = 10;
Double_t heightFractionForFittingRange = 0.1;
//
THnSparse * hist = histPidQA;
//
TCanvas * canvasQAtpc = new TCanvas("canvasQAtpcResGraph","Control canvas for residual graphs (TPC)",100,10,1380,800);
canvasQAtpc->Divide(2,2);
TCanvas * canvasQAtof = new TCanvas("canvasQAtofResGraph","Control canvas for residual graphs (TOF)",100,10,1380,800);
canvasQAtof->Divide(2,2);
TCanvas * canvasQAv0 = new TCanvas("canvasQAv0ResGraph","Control canvas for residual graphs (V0)",100,10,1380,800);
canvasQAv0->Divide(2,2);
TCanvas * canvasQAv0plusTOF = new TCanvas("canvasQAv0plusTOFResGraph","Control canvas for residual graphs (V0+TOF)",100,10,1380,800);
canvasQAv0plusTOF->Divide(2,2);
TCanvas * canvasQAv0DeDxPurityEl = new TCanvas("canvasQAv0DeDxPurityEl","Control canvas for residual graphs (V0 el)",100,10,600,400);
TCanvas * canvasQAv0DeDxPurityPi = new TCanvas("canvasQAv0DeDxPurityPi","Control canvas for residual graphs (V0 pi)",100,10,600,400);
TCanvas * canvasQAv0DeDxPurityPr = new TCanvas("canvasQAv0DeDxPurityPr","Control canvas for residual graphs (V0 pr)",100,10,600,400);
canvasQAv0DeDxPurityEl->SetLogx();
canvasQAv0DeDxPurityPi->SetLogx();
canvasQAv0DeDxPurityPr->SetLogx();
canvasQAv0DeDxPurityEl->SetLogz();
canvasQAv0DeDxPurityPi->SetLogz();
canvasQAv0DeDxPurityPr->SetLogz();
canvasQAv0DeDxPurityEl->SetTopMargin(0.03);
canvasQAv0DeDxPurityPi->SetTopMargin(0.03);
canvasQAv0DeDxPurityPr->SetTopMargin(0.03);
for (Int_t i = 1; i <= 4; i++) {
canvasQAtpc->GetPad(i)->SetGrid(1, 1);
canvasQAtof->GetPad(i)->SetGrid(1, 1);
canvasQAv0->GetPad(i)->SetGrid(1, 1);
canvasQAv0plusTOF->GetPad(i)->SetGrid(1, 1);
canvasQAtpc->GetPad(i)->SetLogz();
canvasQAtof->GetPad(i)->SetLogz();
canvasQAv0->GetPad(i)->SetLogz();
canvasQAv0plusTOF->GetPad(i)->SetLogz();
canvasQAtpc->GetPad(i)->SetLogx();
canvasQAtof->GetPad(i)->SetLogx();
canvasQAv0->GetPad(i)->SetLogx();
canvasQAv0plusTOF->GetPad(i)->SetLogx();
}
//
// 1. select and fit electrons
//
hist->GetAxis(2)->SetRangeUser(0,0); // Non-V0s
hist->GetAxis(3)->SetRangeUser(0,0); // electrons
hist->GetAxis(4)->SetRangeUser(nSigmaElectronMinus,nSigmaElectronPlus); // 3sigma in TPC
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // 3sigma in TOF
TH2D * histElectron = hist->Projection(1,0);
histElectron->SetName("histElectron");
histElectron->RebinX(4);
histElectron->GetXaxis()->SetRangeUser(0.2,3.0);
TObjArray arr;
FitSlicesY(histElectron, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * electronPoints = (TH1D *) arr.At(1)->Clone();
//
TGraphErrors * electronGraph = new TGraphErrors(electronPoints);
electronGraph->SetName("electronGraph");
for(Int_t ip = 0; ip < electronGraph->GetN(); ip ++) {
Bool_t removePoint = electronGraph->GetY()[ip] < 10 ||
electronGraph->GetEY()[ip]/electronGraph->GetY()[ip] > 0.05 ||
electronGraph->GetX()[ip] > 2.0 ||
electronGraph->GetX()[ip] < 0.5;
if (removePoint) {
electronGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAtof->cd(1);
histElectron->SetTitle("electrons");
histElectron->GetYaxis()->SetRangeUser(50, 120);
histElectron->GetXaxis()->SetTitle(momTitle.Data());
histElectron->GetYaxis()->SetTitle(dEdxTitle.Data());
histElectron->GetXaxis()->SetMoreLogLabels(kTRUE);
histElectron->GetXaxis()->SetNoExponent(kTRUE);
histElectron->Draw("colz");
electronPoints->SetMarkerStyle(24);
electronPoints->Draw("same");
hist->GetAxis(4)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(5)->SetRange(0,-1); // RESET RANGES
//
// 2. protons
//
hist->GetAxis(2)->SetRangeUser(0,0); // Non-V0s
hist->GetAxis(3)->SetRangeUser(3,3); // protons
//
//hist->GetAxis(4)->SetRangeUser(nSigmaProtonMinus,nSigmaProtonPlus); // protons --> not reliable, use PATTERN RECOGNITION
TH2D * histProtonTPC = hist->Projection(1,0);
histProtonTPC->SetName("histProtonTPC");
histProtonTPC->GetXaxis()->SetRangeUser(0.15,0.7);
histProtonTPC->GetYaxis()->SetRangeUser(50, hist->GetAxis(1)->GetBinUpEdge(hist->GetAxis(1)->GetNbins()));
// PATTERN RECOGNITION
//OLD TF1 betaSq("betaSq","50./TMath::Power(x,1.3)",0.1,10);
// Add some additional Erf - cuts away kaons for pPb and PbPb and does not hurt in pp
TF1 betaSq("betaSq","50./TMath::Power(x,1.3) + (1-TMath::Erf((x-0.2) / 0.075)) * 100",0.1,10);
for(Int_t ix = 1; ix <= histProtonTPC->GetXaxis()->GetNbins(); ix++) {
for(Int_t jy = 1; jy <= histProtonTPC->GetYaxis()->GetNbins(); jy++) {
Float_t yPos = histProtonTPC->GetYaxis()->GetBinCenter(jy);
Float_t xPos = histProtonTPC->GetXaxis()->GetBinCenter(ix);
Int_t bin = histProtonTPC->GetBin(ix,jy);
if (yPos < betaSq.Eval(xPos)) histProtonTPC->SetBinContent(bin,0);
}
}
//
//TODO Use likelihood option -> Inside fitting range ~no contamination, but little statistics at low momenta requires L
FitSlicesY(histProtonTPC, heightFractionForFittingRange, cutForFitting, "QNRL", &arr);
TH1D * protonPointsTPC = (TH1D *) arr.At(1)->Clone();
//
TGraphErrors * protonTpcGraph = new TGraphErrors(protonPointsTPC);
protonTpcGraph->SetName("protonTpcGraph");
for(Int_t ip = 0; ip < protonTpcGraph->GetN(); ip ++) {
Bool_t removePoint = protonTpcGraph->GetY()[ip] < 10 || protonTpcGraph->GetEY()[ip]/protonTpcGraph->GetY()[ip] > 0.05 // TODO Larger tolerance, since this is only for the correction function, where 5% are still better than no data point
|| protonTpcGraph->GetX()[ip] > (useV0s ? (isPPb ? 0.499 : 0.349) : 0.649); // If V0s are to be used, don't use TPC only protons to too high momenta; for pPb low statistics for the moment, therefore, go a bit further with TPC protons
//TODO NOW -> Changed range of TPC-signal -> Hopefully, sufficient statistics now for very low momenta!|| protonTpcGraph->GetX()[ip] < 0.19; // Added this cut because almost always bad statistics below 0.19
if (removePoint) {
protonTpcGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // 3sigma in TOF
TH2D * histProtonTOF = hist->Projection(1,0);
histProtonTOF->SetName("histProtonTOF");
histProtonTOF->GetXaxis()->SetRangeUser(0.6,2.5);
// Same pattern recognition as before
for(Int_t ix = 1; ix <= histProtonTOF->GetXaxis()->GetNbins(); ix++) {
for(Int_t jy = 1; jy <= histProtonTOF->GetYaxis()->GetNbins(); jy++) {
Float_t yPos = histProtonTOF->GetYaxis()->GetBinCenter(jy);
Float_t xPos = histProtonTOF->GetXaxis()->GetBinCenter(ix);
Int_t bin = histProtonTOF->GetBin(ix,jy);
if (yPos < betaSq.Eval(xPos)) histProtonTOF->SetBinContent(bin,0);
}
}
FitSlicesY(histProtonTOF, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * protonPointsTOF = (TH1D *)arr.At(1)->Clone();
//
TGraphErrors * protonTofGraph = new TGraphErrors(protonPointsTOF);
protonTofGraph->SetName("protonTofGraph");
for(Int_t ip = 0; ip < protonTofGraph->GetN(); ip ++) {
// If V0s are to be used, TPC+TOF protons are only for reference and can be plotted to higher momenta
Bool_t removePoint = protonTofGraph->GetY()[ip] < 10 || protonTofGraph->GetEY()[ip]/protonTofGraph->GetY()[ip] > 0.02 || protonTofGraph->GetX()[ip] > (useV0s ? 3 : 2) || protonTofGraph->GetX()[ip] < 0.65;
if (removePoint) {
protonTofGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAtpc->cd(2);
histProtonTPC->SetTitle("protons");
histProtonTPC->GetXaxis()->SetTitle(momTitle.Data());
histProtonTPC->GetYaxis()->SetTitle(dEdxTitle.Data());
histProtonTPC->GetXaxis()->SetMoreLogLabels(kTRUE);
histProtonTPC->GetXaxis()->SetNoExponent(kTRUE);
histProtonTPC->Draw("colz");
betaSq.DrawCopy("same");
protonPointsTPC->SetMarkerStyle(20);
protonPointsTOF->SetMarkerStyle(24);
protonPointsTOF->Draw("same");
protonPointsTPC->Draw("same");
//
protonTpcGraph->SetMarkerStyle(26);
protonTpcGraph->SetMarkerColor(kMagenta);
protonTpcGraph->DrawClone("p");
protonTofGraph->SetMarkerStyle(25);
protonTofGraph->SetMarkerColor(kMagenta);
protonTofGraph->DrawClone("p");
canvasQAtof->cd(2);
histProtonTOF->SetTitle("protons");
histProtonTOF->GetYaxis()->SetRangeUser(30, 250);
histProtonTOF->GetXaxis()->SetTitle(momTitle.Data());
histProtonTOF->GetYaxis()->SetTitle(dEdxTitle.Data());
histProtonTOF->GetXaxis()->SetMoreLogLabels(kTRUE);
histProtonTOF->GetXaxis()->SetNoExponent(kTRUE);
histProtonTOF->Draw("colz");
betaSq.DrawCopy("same");
protonPointsTOF->Draw("same");
protonPointsTPC->Draw("same");
//
protonTpcGraph->DrawClone("p");
protonTofGraph->DrawClone("p");
hist->GetAxis(4)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(5)->SetRange(0,-1); // RESET RANGES
//
// 3. pions
//
hist->GetAxis(2)->SetRangeUser(0,0); // Non-V0s
hist->GetAxis(3)->SetRangeUser(1,1); // pions
//
Double_t lowerPionThreshold = 0.3;
hist->GetAxis(4)->SetRangeUser(nSigmaPionMinus,nSigmaPionPlus); // pions
TH2D * histPionTPC = hist->Projection(1,0);
histPionTPC->SetName("histPionTPC");
histPionTPC->GetXaxis()->SetRangeUser(0.15,0.7);
FitSlicesY(histPionTPC, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
// In case of really bad splines comment last 5 lines and use the following 6 lines:
//TH2D * histPionTPC = hist->Projection(1,0);
//histPionTPC->SetName("histPionTPC");
//histPionTPC->GetYaxis()->SetRangeUser(30,100);
//histPionTPC->GetXaxis()->SetRangeUser(0.15,0.7);
//FitSlicesY(histPionTPC, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
//lowerPionThreshold = 0.15;
TH1D * pionPointsTPC = (TH1D *) arr.At(1)->Clone();
//
TGraphErrors * pionTpcGraph = new TGraphErrors(pionPointsTPC);
pionTpcGraph->SetName("pionTpcGraph");
for(Int_t ip = 0; ip < pionTpcGraph->GetN(); ip ++) {
Bool_t removePoint = pionTpcGraph->GetY()[ip] < 10 || pionTpcGraph->GetEY()[ip]/pionTpcGraph->GetY()[ip] > 0.02 || pionTpcGraph->GetX()[ip] > 0.5
|| pionTpcGraph->GetX()[ip] < lowerPionThreshold; // Exclude contamination by electrons
if (removePoint) {
pionTpcGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // 3sigma in TOF
TH2D * histPionTOF = hist->Projection(1,0);
histPionTOF->SetName("histPionTOF");
histPionTOF->GetXaxis()->SetRangeUser(0.5,1.1);
FitSlicesY(histPionTOF, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * pionPointsTOF = (TH1D *) arr.At(1)->Clone();
TGraphErrors * pionTofGraph = new TGraphErrors(pionPointsTOF);
pionTofGraph->SetName("pionTofGraph");
for(Int_t ip = 0; ip < pionTofGraph->GetN(); ip ++) {
Bool_t removePoint = pionTofGraph->GetY()[ip] < 10 || pionTofGraph->GetEY()[ip]/pionTofGraph->GetY()[ip] > 0.02 || pionTofGraph->GetX()[ip] > 1.1 || pionTofGraph->GetX()[ip] < 0.5; // Changed by Ben (was 0.35) to avoid problems with TOF efficiency/systematics
if (removePoint) {
pionTofGraph->RemovePoint(ip);
ip--;
continue;
}
}
canvasQAtpc->cd(3);
histPionTPC->GetYaxis()->SetRangeUser(30, 90);
histPionTPC->SetTitle("pions");
histPionTPC->GetXaxis()->SetTitle(momTitle.Data());
histPionTPC->GetYaxis()->SetTitle(dEdxTitle.Data());
histPionTPC->GetXaxis()->SetMoreLogLabels(kTRUE);
histPionTPC->GetXaxis()->SetNoExponent(kTRUE);
histPionTPC->Draw("colz");
pionPointsTPC->SetMarkerStyle(20);
pionPointsTOF->SetMarkerStyle(24);
pionPointsTOF->Draw("same");
pionPointsTPC->Draw("same");
//
pionTpcGraph->SetMarkerStyle(26);
pionTpcGraph->SetMarkerColor(kMagenta);
pionTpcGraph->DrawClone("p");
pionTofGraph->SetMarkerStyle(25);
pionTofGraph->SetMarkerColor(kMagenta);
pionTofGraph->DrawClone("p");
canvasQAtof->cd(3);
histPionTOF->GetYaxis()->SetRangeUser(30, 80);
histPionTOF->GetXaxis()->SetTitle(momTitle.Data());
histPionTOF->GetYaxis()->SetTitle(dEdxTitle.Data());
histPionTOF->GetXaxis()->SetMoreLogLabels(kTRUE);
histPionTOF->GetXaxis()->SetNoExponent(kTRUE);
histPionTOF->Draw("colz");
histPionTOF->SetTitle("pions");
pionPointsTOF->Draw("same");
pionPointsTPC->Draw("same");
//
pionTpcGraph->DrawClone("p");
pionTofGraph->DrawClone("p");
hist->GetAxis(4)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(5)->SetRange(0,-1); // RESET RANGES
//
// 4. kaons
//
hist->GetAxis(2)->SetRangeUser(0,0); // Non-V0s
hist->GetAxis(3)->SetRangeUser(2,2); // kaons
//
hist->GetAxis(4)->SetRangeUser(nSigmaKaonMinus,nSigmaKaonPlus); // kaons
TH2D * histKaonTPC = hist->Projection(1,0);
histKaonTPC->SetName("histKaonTPC");
histKaonTPC->GetXaxis()->SetRangeUser(0.12,0.6999);
FitSlicesY(histKaonTPC, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * kaonPointsTPC = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * kaonTpcGraph = new TGraphErrors(kaonPointsTPC);
kaonTpcGraph->SetName("kaonTpcGraph");
for(Int_t ip = 0; ip < kaonTpcGraph->GetN(); ip ++) {
Bool_t removePoint = kaonTpcGraph->GetY()[ip] < 10 || kaonTpcGraph->GetEY()[ip]/kaonTpcGraph->GetY()[ip] > 0.02
|| kaonTpcGraph->GetX()[ip] < 0.12 || kaonTpcGraph->GetX()[ip] > 0.319; //TODO BEN was > 0.399
if (removePoint) {
kaonTpcGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // sigma in TOF
/*
hist->GetAxis(5)->SetRangeUser(-1.999,1.999); // sigma in TOF
if (hist->GetAxis(3)->GetNbins() >= 5) {
printf("Using restricted eta range for TPC+TOF Kaons!\n");
hist->GetAxis(3)->SetRangeUser(4,4);
}
else {
printf("WARNING: Data points for restricted eta range for TPC+TOF Kaons not available! Using full eta range (worse w.r.t. contamination)\n");
}*/
TH2D * histKaonTOF = hist->Projection(1,0);
histKaonTOF->SetName("histKaonTOF");
histKaonTOF->GetXaxis()->SetRangeUser(0.3,1.5);
FitSlicesY(histKaonTOF, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * kaonPointsTOF = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * kaonTofGraph = new TGraphErrors(kaonPointsTOF);
kaonTofGraph->SetName("kaonTofGraph");
//
for(Int_t ip = 0; ip < kaonTofGraph->GetN(); ip ++) {
Bool_t removePoint = kaonTofGraph->GetY()[ip] < 10 || kaonTofGraph->GetEY()[ip]/kaonTofGraph->GetY()[ip] > 0.02 || kaonTofGraph->GetX()[ip] > 1.0
|| kaonTofGraph->GetX()[ip] < 0.36; //TODO BEN NOW was 0.5
if (removePoint) {
kaonTofGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAtpc->cd(4);
histKaonTPC->SetTitle("kaons");
histKaonTPC->GetYaxis()->SetRangeUser(30, 500);
histKaonTPC->GetXaxis()->SetTitle(momTitle.Data());
histKaonTPC->GetYaxis()->SetTitle(dEdxTitle.Data());
histKaonTPC->GetXaxis()->SetMoreLogLabels(kTRUE);
histKaonTPC->GetXaxis()->SetNoExponent(kTRUE);
histKaonTPC->Draw("colz");
kaonPointsTPC->SetMarkerStyle(20);
kaonPointsTOF->SetMarkerStyle(24);
kaonPointsTOF->Draw("same");
kaonPointsTPC->Draw("same");
//
kaonTpcGraph->SetMarkerStyle(26);
kaonTpcGraph->SetMarkerColor(kMagenta);
kaonTpcGraph->DrawClone("p");
kaonTofGraph->SetMarkerStyle(25);
kaonTofGraph->SetMarkerColor(kMagenta);
kaonTofGraph->DrawClone("p");
canvasQAtof->cd(4);
histKaonTOF->GetYaxis()->SetRangeUser(30, 250);
histKaonTOF->SetTitle("kaons");
histKaonTOF->GetXaxis()->SetTitle(momTitle.Data());
histKaonTOF->GetYaxis()->SetTitle(dEdxTitle.Data());
histKaonTOF->GetXaxis()->SetMoreLogLabels(kTRUE);
histKaonTOF->GetXaxis()->SetNoExponent(kTRUE);
histKaonTOF->Draw("colz");
kaonPointsTOF->Draw("same");
kaonPointsTPC->Draw("same");
kaonTpcGraph->DrawClone("p");
kaonTofGraph->DrawClone("p");
hist->GetAxis(4)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(5)->SetRange(0,-1); // RESET RANGES
//
// 5. V0 electrons
//
hist->GetAxis(2)->SetRangeUser(1,1); // V0 electrons
hist->GetAxis(3)->SetRangeUser(0,0); // electrons
//
TH2D * histElectronV0 = hist->Projection(1,0);
histElectronV0->SetName("histElectronV0");
//histElectronV0->RebinX(2);
histElectronV0->GetXaxis()->SetRangeUser(0.15,5.0);
FitSlicesY(histElectronV0, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * electronPointsV0 = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * electronV0Graph = new TGraphErrors(electronPointsV0);
electronV0Graph->SetName("electronV0Graph");
for(Int_t ip = 0; ip < electronV0Graph->GetN(); ip ++) {
Bool_t removePoint = electronV0Graph->GetY()[ip] < 10 || electronV0Graph->GetEY()[ip]/electronV0Graph->GetY()[ip] > 0.02;
if (removePoint) {
electronV0Graph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAv0->cd(1);
histElectronV0->SetTitle("V0 electrons");
histElectronV0->GetYaxis()->SetRangeUser(50, 120);
histElectronV0->GetXaxis()->SetTitle(momTitle.Data());
histElectronV0->GetYaxis()->SetTitle(dEdxTitle.Data());
histElectronV0->GetXaxis()->SetMoreLogLabels(kTRUE);
histElectronV0->GetXaxis()->SetNoExponent(kTRUE);
histElectronV0->SetStats(0);
histElectronV0->Draw("colz");
electronPointsV0->SetMarkerStyle(34);
electronPointsV0->Draw("same");
electronGraph->SetMarkerStyle(25);
electronGraph->SetMarkerColor(kMagenta);
electronGraph->DrawClone("p");
canvasQAv0DeDxPurityEl->cd();
gStyle->SetOptTitle(0);
TH1D* hElNew = (TH1D*)histElectronV0->DrawClone("colz");
hElNew->GetXaxis()->SetTitleOffset(1.0);
hElNew->SetTitle("");
electronPointsV0->DrawClone("same");
gStyle->SetOptTitle(1);
canvasQAtof->cd(1);
electronV0Graph->SetMarkerStyle(24);
electronV0Graph->SetMarkerColor(kMagenta);
electronV0Graph->DrawClone("p");
//
// 6. V0 pions
//
hist->GetAxis(2)->SetRangeUser(2,2); // V0 pions
hist->GetAxis(3)->SetRangeUser(1,1); // pions
//
TH2D * histPionV0 = hist->Projection(1,0);
histPionV0->SetName("histPionV0");
histPionV0->GetXaxis()->SetRangeUser(0.15,10.);
FitSlicesY(histPionV0, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * pionPointsV0 = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * pionV0Graph = new TGraphErrors(pionPointsV0);
pionV0Graph->SetName("pionV0Graph");
for(Int_t ip = 0; ip < pionV0Graph->GetN(); ip ++) {
Bool_t removePoint = pionV0Graph->GetY()[ip] < 10 || pionV0Graph->GetEY()[ip]/pionV0Graph->GetY()[ip] > 0.02;
if (removePoint) {
pionV0Graph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAv0->cd(3);
histPionV0->SetTitle("V0 pions");
histPionV0->GetYaxis()->SetRangeUser(30, 100);
histPionV0->GetXaxis()->SetTitle(momTitle.Data());
histPionV0->GetYaxis()->SetTitle(dEdxTitle.Data());
histPionV0->GetXaxis()->SetMoreLogLabels(kTRUE);
histPionV0->GetXaxis()->SetNoExponent(kTRUE);
histPionV0->Draw("colz");
pionPointsV0->SetMarkerStyle(34);
pionPointsV0->Draw("same");
pionTofGraph->DrawClone("p");
pionTpcGraph->DrawClone("p");
canvasQAv0DeDxPurityPi->cd();
gStyle->SetOptTitle(0);
TH1D* hPiNew = (TH1D*)histPionV0->DrawClone("colz");
hPiNew->GetXaxis()->SetTitleOffset(1.0);
hPiNew->SetTitle("");
pionPointsV0->DrawClone("same");
gStyle->SetOptTitle(1);
canvasQAtof->cd(3);
pionV0Graph->SetMarkerStyle(24);
pionV0Graph->SetMarkerColor(kMagenta);
pionV0Graph->DrawClone("p");
canvasQAtpc->cd(3);
pionV0Graph->DrawClone("p");
//
// 6. V0 protons
//
hist->GetAxis(2)->SetRangeUser(3,3); // V0 protons
hist->GetAxis(3)->SetRangeUser(3,3); // protons
//
TH2D * histProtonV0 = hist->Projection(1,0);
histProtonV0->SetName("histProtonV0");
histProtonV0->GetXaxis()->SetRangeUser(0.15,10.);
// Remove contamination due to el and pions and low momenta because there the statistics
// for the V0 protons goes down and becomes comparable with the contamination
// -> This spoils the fit, if the contamination is not removed
// PATTERN RECOGNITION
Int_t correctionUpToBin = histProtonV0->GetXaxis()->FindBin(0.6);
for(Int_t ix = 1; ix <= correctionUpToBin; ix++) {
for(Int_t jy = 1; jy <= histProtonV0->GetYaxis()->GetNbins(); jy++) {
Float_t yPos = histProtonV0->GetYaxis()->GetBinCenter(jy);
Float_t xPos = histProtonV0->GetXaxis()->GetBinCenter(ix);
Int_t bin = histProtonV0->GetBin(ix,jy);
if (yPos < betaSq.Eval(xPos)) histProtonV0->SetBinContent(bin,0);
}
}
/*
Int_t correctionUpToBin = histProtonV0->GetXaxis()->FindBin(0.4);
Double_t threshold = 120.;
for(Int_t ix = 1; ix <= correctionUpToBin; ix++) {
for(Int_t jy = 1; jy <= histProtonV0->GetYaxis()->GetNbins(); jy++) {
Float_t yPos = histProtonV0->GetYaxis()->GetBinCenter(jy);
Int_t bin = histProtonV0->GetBin(ix,jy);
if (yPos < threshold) histProtonV0->SetBinContent(bin,0);
else break;
}
}
*/
FitSlicesY(histProtonV0, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * protonPointsV0 = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * protonV0Graph = new TGraphErrors(protonPointsV0);
protonV0Graph->SetName("protonV0Graph");
for(Int_t ip = 0; ip < protonV0Graph->GetN(); ip ++) {
Bool_t removePoint = protonV0Graph->GetY()[ip] < 10 || protonV0Graph->GetEY()[ip]/protonV0Graph->GetY()[ip] > 0.02;
if (removePoint) {
protonV0Graph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAv0->cd(2);
histProtonV0->SetTitle("V0 protons");
histProtonV0->GetXaxis()->SetTitle(momTitle.Data());
histProtonV0->GetYaxis()->SetTitle(dEdxTitle.Data());
histProtonV0->GetXaxis()->SetMoreLogLabels(kTRUE);
histProtonV0->GetXaxis()->SetNoExponent(kTRUE);
histProtonV0->Draw("colz");
protonPointsV0->SetMarkerStyle(34);
protonPointsV0->Draw("same");
protonTofGraph->DrawClone("p");
protonTpcGraph->DrawClone("p");
canvasQAv0DeDxPurityPr->cd();
gStyle->SetOptTitle(0);
TH1D* hPrNew = (TH1D*)histProtonV0->DrawClone("colz");
hPrNew->GetXaxis()->SetTitleOffset(1.0);
hPrNew->SetTitle("");
protonPointsV0->DrawClone("same");
gStyle->SetOptTitle(1);
canvasQAtof->cd(2);
protonV0Graph->SetMarkerStyle(24);
protonV0Graph->SetMarkerColor(kMagenta);
protonV0Graph->DrawClone("p");
canvasQAtpc->cd(2);
protonV0Graph->DrawClone("p");
hist->GetAxis(2)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(3)->SetRange(0,-1); // RESET RANGES
//
// 5. V0 electrons + TOF
//
hist->GetAxis(2)->SetRangeUser(1,1); // V0 electrons
hist->GetAxis(3)->SetRangeUser(0,0); // electrons
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // 3sigma in TOF
//
TH2D * histElectronV0plusTOF = hist->Projection(1,0);
histElectronV0plusTOF->SetName("histElectronV0plusTOF");
histElectronV0plusTOF->RebinX(2);
histElectronV0plusTOF->GetXaxis()->SetRangeUser(0.2,5.0);
FitSlicesY(histElectronV0plusTOF, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * electronPointsV0plusTOF = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * electronV0plusTOFGraph = new TGraphErrors(electronPointsV0plusTOF);
electronV0plusTOFGraph->SetName("electronV0plusTOFGraph");
for(Int_t ip = 0; ip < electronV0plusTOFGraph->GetN(); ip ++) {
Bool_t removePoint = electronV0plusTOFGraph->GetY()[ip] < 10 || electronV0plusTOFGraph->GetEY()[ip]/electronV0plusTOFGraph->GetY()[ip] > 0.02;
if (removePoint) {
electronV0plusTOFGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAv0plusTOF->cd(1);
histElectronV0plusTOF->SetTitle("V0+TOF electrons");
histElectronV0plusTOF->GetYaxis()->SetRangeUser(50, 120);
histElectronV0plusTOF->GetXaxis()->SetTitle(momTitle.Data());
histElectronV0plusTOF->GetYaxis()->SetTitle(dEdxTitle.Data());
histElectronV0plusTOF->GetXaxis()->SetMoreLogLabels(kTRUE);
histElectronV0plusTOF->GetXaxis()->SetNoExponent(kTRUE);
histElectronV0plusTOF->Draw("colz");
electronPointsV0plusTOF->SetMarkerStyle(29);
electronPointsV0plusTOF->Draw("same");
electronGraph->DrawClone("p");
electronV0Graph->DrawClone("p");
canvasQAv0->cd(1);
electronV0plusTOFGraph->SetMarkerStyle(30);
electronV0plusTOFGraph->SetMarkerColor(kMagenta);
electronV0plusTOFGraph->DrawClone("p");
canvasQAtof->cd(1);
electronV0plusTOFGraph->DrawClone("p");
//
// 6. V0 pions + TOF
//
hist->GetAxis(2)->SetRangeUser(2,2); // V0 pions
hist->GetAxis(3)->SetRangeUser(1,1); // pions
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // 3sigma in TOF
//
TH2D * histPionV0plusTOF = hist->Projection(1,0);
histPionV0plusTOF->SetName("histPionV0plusTOF");
histPionV0plusTOF->GetXaxis()->SetRangeUser(0.15,10.);
FitSlicesY(histPionV0plusTOF, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * pionPointsV0plusTOF = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * pionV0plusTOFGraph = new TGraphErrors(pionPointsV0plusTOF);
pionV0plusTOFGraph->SetName("pionV0plusTOFGraph");
for(Int_t ip = 0; ip < pionV0plusTOFGraph->GetN(); ip ++) {
Bool_t removePoint = pionV0plusTOFGraph->GetY()[ip] < 10 || pionV0plusTOFGraph->GetEY()[ip]/pionV0plusTOFGraph->GetY()[ip] > 0.02;
if (removePoint) {
pionV0plusTOFGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAv0plusTOF->cd(3);
histPionV0plusTOF->SetTitle("V0+TOF pions");
histPionV0plusTOF->GetYaxis()->SetRangeUser(30, 100);
histPionV0plusTOF->GetXaxis()->SetTitle(momTitle.Data());
histPionV0plusTOF->GetYaxis()->SetTitle(dEdxTitle.Data());
histPionV0plusTOF->GetXaxis()->SetMoreLogLabels(kTRUE);
histPionV0plusTOF->GetXaxis()->SetNoExponent(kTRUE);
histPionV0plusTOF->Draw("colz");
pionPointsV0plusTOF->SetMarkerStyle(29);
pionPointsV0plusTOF->Draw("same");
pionV0Graph->DrawClone("p");
pionTofGraph->DrawClone("p");
pionTpcGraph->DrawClone("p");
canvasQAv0->cd(3);
pionV0plusTOFGraph->SetMarkerStyle(30);
pionV0plusTOFGraph->SetMarkerColor(kMagenta);
pionV0plusTOFGraph->DrawClone("p");
canvasQAtof->cd(3);
pionV0plusTOFGraph->DrawClone("p");
canvasQAtpc->cd(3);
pionV0plusTOFGraph->DrawClone("p");
//
// 6. V0 protons + TOF
//
hist->GetAxis(2)->SetRangeUser(3,3); // V0 protons
hist->GetAxis(3)->SetRangeUser(3,3); // protons
hist->GetAxis(5)->SetRangeUser(-2.999,2.999); // 3sigma in TOF
//
TH2D * histProtonV0plusTOF = hist->Projection(1,0);
histProtonV0plusTOF->SetName("histProtonV0plusTOF");
histProtonV0plusTOF->GetXaxis()->SetRangeUser(0.15,10.);
// Remove contamination due to el and pions and low momenta because there the statistics
// for the V0 protons goes down and becomes comparable with the contamination
// -> This spoils the fit, if the contamination is not removed
// PATTERN RECOGNITION
correctionUpToBin = histProtonV0plusTOF->GetXaxis()->FindBin(0.6);
for(Int_t ix = 1; ix <= correctionUpToBin; ix++) {
for(Int_t jy = 1; jy <= histProtonV0plusTOF->GetYaxis()->GetNbins(); jy++) {
Float_t yPos = histProtonV0plusTOF->GetYaxis()->GetBinCenter(jy);
Float_t xPos = histProtonV0plusTOF->GetXaxis()->GetBinCenter(ix);
Int_t bin = histProtonV0plusTOF->GetBin(ix,jy);
if (yPos < betaSq.Eval(xPos)) histProtonV0plusTOF->SetBinContent(bin,0);
}
}
FitSlicesY(histProtonV0plusTOF, heightFractionForFittingRange, cutForFitting, "QNR", &arr);
TH1D * protonPointsV0plusTOF = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * protonV0plusTOFGraph = new TGraphErrors(protonPointsV0plusTOF);
protonV0plusTOFGraph->SetName("protonV0plusTOFGraph");
for(Int_t ip = 0; ip < protonV0plusTOFGraph->GetN(); ip ++) {
Bool_t removePoint = protonV0plusTOFGraph->GetY()[ip] < 10 || protonV0plusTOFGraph->GetEY()[ip]/protonV0plusTOFGraph->GetY()[ip] > 0.02;
if (removePoint) {
protonV0plusTOFGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAv0plusTOF->cd(2);
histProtonV0plusTOF->SetTitle("V0+TOF protons");
histProtonV0plusTOF->GetXaxis()->SetTitle(momTitle.Data());
histProtonV0plusTOF->GetYaxis()->SetTitle(dEdxTitle.Data());
histProtonV0plusTOF->GetXaxis()->SetMoreLogLabels(kTRUE);
histProtonV0plusTOF->GetXaxis()->SetNoExponent(kTRUE);
histProtonV0plusTOF->Draw("colz");
protonPointsV0plusTOF->SetMarkerStyle(29);
protonPointsV0plusTOF->Draw("same");
protonV0Graph->DrawClone("p");
protonTofGraph->DrawClone("p");
protonTpcGraph->DrawClone("p");
canvasQAv0->cd(2);
protonV0plusTOFGraph->SetMarkerStyle(30);
protonV0plusTOFGraph->SetMarkerColor(kMagenta);
protonV0plusTOFGraph->DrawClone("p");
canvasQAtof->cd(2);
protonV0plusTOFGraph->DrawClone("p");
canvasQAtpc->cd(2);
protonV0plusTOFGraph->DrawClone("p");
hist->GetAxis(2)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(3)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(5)->SetRange(0,-1); // RESET RANGES
// Clone (V0, V0+TOF) graphs: Remove some points, which are expected to deviate from the Bethe-Bloch curve, from the original graphs, so that
// these graphs can be used for the BB fit. The original graph will keep all point in order to determine the correction and response
// functions
TGraphErrors * electronV0GraphForBBfit = new TGraphErrors(*electronV0Graph);
electronV0GraphForBBfit->SetName("electronV0GraphForBBfit");
for(Int_t ip = 0; ip < electronV0GraphForBBfit->GetN(); ip ++) {
Bool_t removePoint = electronV0GraphForBBfit->GetX()[ip] < (isPPb ? 1.2 : 0.4);// || electronV0GraphForBBfit->GetX()[ip] > 2.2;
if (removePoint) {
electronV0GraphForBBfit->RemovePoint(ip);
ip--;
continue;
}
}
TGraphErrors * pionV0GraphForBBfit = new TGraphErrors(*pionV0Graph);
pionV0GraphForBBfit->SetName("pionV0GraphForBBfit");
for(Int_t ip = 0; ip < pionV0GraphForBBfit->GetN(); ip ++) {
Bool_t removePoint = pionV0GraphForBBfit->GetX()[ip] < (isPPb ? 1.0 : 0.76);// || pionV0GraphForBBfit->GetX()[ip] > 6.; //TODO NOW was < 0.4 before
//Bool_t removePoint = pionV0GraphForBBfit->GetX()[ip] < 0.4 || pionV0GraphForBBfit->GetX()[ip] > 0.399;// In this case NOT used for BB fit
if (removePoint) {
pionV0GraphForBBfit->RemovePoint(ip);
ip--;
continue;
}
}
TGraphErrors * protonV0GraphForBBfit = new TGraphErrors(*protonV0Graph);
protonV0GraphForBBfit->SetName("protonV0GraphForBBfit");
for(Int_t ip = 0; ip < protonV0GraphForBBfit->GetN(); ip ++) {
Bool_t removePoint = protonV0GraphForBBfit->GetX()[ip] < 0.9 || protonV0GraphForBBfit->GetX()[ip] > 5.0; //TODO NOW was 2.5 before
//Bool_t removePoint = protonV0GraphForBBfit->GetX()[ip] < 0.9 || protonV0GraphForBBfit->GetX()[ip] > 0.599;// In this case NOT used for BB fit
if (removePoint) {
protonV0GraphForBBfit->RemovePoint(ip);
ip--;
continue;
}
}
// V0 plus TOF
TGraphErrors * electronV0plusTOFGraphForBBfit = new TGraphErrors(*electronV0plusTOFGraph);
electronV0plusTOFGraphForBBfit->SetName("electronV0plusTOFGraphForBBfit");
for(Int_t ip = 0; ip < electronV0plusTOFGraphForBBfit->GetN(); ip ++) {
Bool_t removePoint = electronV0plusTOFGraphForBBfit->GetX()[ip] < (isPPb ? 1.2 : 0.6);//0.4 || electronV0plusTOFGraphForBBfit->GetX()[ip] > 1.3799;
if (removePoint) {
electronV0plusTOFGraphForBBfit->RemovePoint(ip);
ip--;
continue;
}
}
TGraphErrors * pionV0plusTOFGraphForBBfit = new TGraphErrors(*pionV0plusTOFGraph);
pionV0plusTOFGraphForBBfit->SetName("pionV0plusTOFGraphForBBfit");
for(Int_t ip = 0; ip < pionV0plusTOFGraphForBBfit->GetN(); ip ++) {
Bool_t removePoint = pionV0plusTOFGraphForBBfit->GetX()[ip] < 0.4;// || pionV0plusTOFGraphForBBfit->GetX()[ip] > 6.;
if (removePoint) {
pionV0plusTOFGraphForBBfit->RemovePoint(ip);
ip--;
continue;
}
}
TGraphErrors * protonV0plusTOFGraphForBBfit = new TGraphErrors(*protonV0plusTOFGraph);
protonV0plusTOFGraphForBBfit->SetName("protonV0plusTOFGraphForBBfit");
for(Int_t ip = 0; ip < protonV0plusTOFGraphForBBfit->GetN(); ip ++) {
Bool_t removePoint = protonV0plusTOFGraphForBBfit->GetX()[ip] < 0.9 || protonV0plusTOFGraphForBBfit->GetX()[ip] > 2.5;
if (removePoint) {
protonV0plusTOFGraphForBBfit->RemovePoint(ip);
ip--;
continue;
}
}
//
// rescale graphs to betaGamma
//
kaonTofGraph->SetMarkerStyle(21);
kaonTpcGraph->SetMarkerStyle(22);
for(Int_t ip = 0; ip < kaonTofGraph->GetN(); ip ++) {
kaonTofGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kKaon);
kaonTofGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kKaon);
}
for(Int_t ip = 0; ip < kaonTpcGraph->GetN(); ip ++) {
kaonTpcGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kKaon);
kaonTpcGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kKaon);
}
//
electronGraph->SetMarkerStyle(22);
electronV0Graph->SetMarkerStyle(34);
electronV0GraphForBBfit->SetMarkerStyle(34);
electronV0plusTOFGraph->SetMarkerStyle(30);
electronV0plusTOFGraphForBBfit->SetMarkerStyle(30);
electronGraph->SetMarkerColor(2);
electronV0Graph->SetMarkerColor(2);
electronV0GraphForBBfit->SetMarkerColor(2);
electronV0plusTOFGraph->SetMarkerColor(2);
electronV0plusTOFGraphForBBfit->SetMarkerColor(2);
for(Int_t ip = 0; ip < electronGraph->GetN(); ip ++) {
electronGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
electronGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
}
for(Int_t ip = 0; ip < electronV0Graph->GetN(); ip ++) {
electronV0Graph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
electronV0Graph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
}
for(Int_t ip = 0; ip < electronV0GraphForBBfit->GetN(); ip ++) {
electronV0GraphForBBfit->GetX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
electronV0GraphForBBfit->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
}
for(Int_t ip = 0; ip < electronV0plusTOFGraph->GetN(); ip ++) {
electronV0plusTOFGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
electronV0plusTOFGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
}
for(Int_t ip = 0; ip < electronV0plusTOFGraphForBBfit->GetN(); ip ++) {
electronV0plusTOFGraphForBBfit->GetX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
electronV0plusTOFGraphForBBfit->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
}
//
pionTofGraph->SetMarkerStyle(21);
pionTpcGraph->SetMarkerStyle(22);
pionV0Graph->SetMarkerStyle(34);
pionV0GraphForBBfit->SetMarkerStyle(34);
pionV0plusTOFGraph->SetMarkerStyle(30);
pionV0plusTOFGraphForBBfit->SetMarkerStyle(30);
pionTofGraph->SetMarkerColor(3);
pionTpcGraph->SetMarkerColor(3);
pionV0Graph->SetMarkerColor(3);
pionV0GraphForBBfit->SetMarkerColor(3);
pionV0plusTOFGraph->SetMarkerColor(3);
pionV0plusTOFGraphForBBfit->SetMarkerColor(3);
for(Int_t ip = 0; ip < pionTofGraph->GetN(); ip ++) {
pionTofGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
pionTofGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
}
for(Int_t ip = 0; ip < pionTpcGraph->GetN(); ip ++) {
pionTpcGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
pionTpcGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
}
for(Int_t ip = 0; ip < pionV0Graph->GetN(); ip ++) {
pionV0Graph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
pionV0Graph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
}
for(Int_t ip = 0; ip < pionV0GraphForBBfit->GetN(); ip ++) {
pionV0GraphForBBfit->GetX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
pionV0GraphForBBfit->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
}
for(Int_t ip = 0; ip < pionV0plusTOFGraph->GetN(); ip ++) {
pionV0plusTOFGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
pionV0plusTOFGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
}
for(Int_t ip = 0; ip < pionV0plusTOFGraphForBBfit->GetN(); ip ++) {
pionV0plusTOFGraphForBBfit->GetX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
pionV0plusTOFGraphForBBfit->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
}
//
protonTofGraph->SetMarkerStyle(21);
protonTpcGraph->SetMarkerStyle(22);
protonV0Graph->SetMarkerStyle(34);
protonV0GraphForBBfit->SetMarkerStyle(34);
protonV0plusTOFGraph->SetMarkerStyle(30);
protonV0plusTOFGraphForBBfit->SetMarkerStyle(30);
protonTofGraph->SetMarkerColor(4);
protonTpcGraph->SetMarkerColor(4);
protonV0Graph->SetMarkerColor(4);
protonV0GraphForBBfit->SetMarkerColor(4);
protonV0plusTOFGraph->SetMarkerColor(4);
protonV0plusTOFGraphForBBfit->SetMarkerColor(4);
for(Int_t ip = 0; ip < protonTofGraph->GetN(); ip ++) {
protonTofGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
protonTofGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
}
for(Int_t ip = 0; ip < protonTpcGraph->GetN(); ip ++) {
protonTpcGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
protonTpcGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
}
for(Int_t ip = 0; ip < protonV0Graph->GetN(); ip ++) {
protonV0Graph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
protonV0Graph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
}
for(Int_t ip = 0; ip < protonV0GraphForBBfit->GetN(); ip ++) {
protonV0GraphForBBfit->GetX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
protonV0GraphForBBfit->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
}
for(Int_t ip = 0; ip < protonV0plusTOFGraph->GetN(); ip ++) {
protonV0plusTOFGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
protonV0plusTOFGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
}
for(Int_t ip = 0; ip < protonV0plusTOFGraphForBBfit->GetN(); ip ++) {
protonV0plusTOFGraphForBBfit->GetX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
protonV0plusTOFGraphForBBfit->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
}
//
//
TGraphErrors * graphAll = new TGraphErrors();
TList * listColl = new TList();
if (!useV0s) {
//listColl->Add(protonTpcGraph);
//listColl->Add(kaonTpcGraph);
listColl->Add(pionTpcGraph);
listColl->Add(electronGraph);
listColl->Add(protonTofGraph);
listColl->Add(kaonTofGraph);
listColl->Add(pionTofGraph);
}
else {
listColl->Add(pionV0GraphForBBfit);
//listColl->Add(electronV0GraphForBBfit);//nschmidt2016 for PbPb was commented for pp
listColl->Add(protonV0GraphForBBfit);
//listColl->Add(pionV0plusTOFGraphForBBfit);
listColl->Add(electronV0plusTOFGraphForBBfit);//nschmidt2016 for PbPb was uncommented for pp
//listColl->Add(protonV0plusTOFGraphForBBfit);
}
MergeGraphErrors(graphAll, listColl);
graphAll->SetNameTitle("beamDataPoints","beamDataPoints");
// Create graph out of TPC only, V0, V0+TOF and TPC+TOF to determine correction functions
TList * listCollPr = new TList();
if (useV0s) {
listCollPr->Add(protonTpcGraph);
//listCollPr->Add(protonTofGraph);
TGraphErrors * protonV0GraphCut = new TGraphErrors(*protonV0Graph);
protonV0GraphCut->SetName("protonV0GraphCut");
for(Int_t ip = 0; ip < protonV0GraphCut->GetN(); ip ++) {
Double_t mom = protonV0GraphCut->GetX()[ip] * AliPID::ParticleMass(AliPID::kProton);
//Bool_t removePoint = mom >= 0.6 || mom < 0.35; // Will take TPC protons instead (statistics) for very low momenta
Bool_t removePoint = mom < (isPPb ? 0.6 : 0.35); // Will take TPC protons instead (statistics) for very low momenta;
// for pPb low statistics for the moment, therefore, go a bit further with TPC protons
if (removePoint) {
protonV0GraphCut->RemovePoint(ip);
ip--;
continue;
}
}
/*
TGraphErrors * protonV0plusTOFGraphCut = new TGraphErrors(*protonV0plusTOFGraph);
protonV0plusTOFGraphCut->SetName("protonV0plusTOFGraphCut");
for(Int_t ip = 0; ip < protonV0plusTOFGraphCut->GetN(); ip ++) {
Double_t mom = protonV0plusTOFGraphCut->GetX()[ip] * AliPID::ParticleMass(AliPID::kProton);
Bool_t removePoint = mom < 0.6;
if (removePoint) {
protonV0plusTOFGraphCut->RemovePoint(ip);
ip--;
continue;
}
}*/
listCollPr->Add(protonV0GraphCut);
//listCollPr->Add(protonV0plusTOFGraphCut);
}
else {
listCollPr->Add(protonTpcGraph);
listCollPr->Add(protonTofGraph);
}
TGraphErrors * graphPrCombined = new TGraphErrors();
MergeGraphErrors(graphPrCombined, listCollPr);
graphPrCombined->SetMarkerStyle(22);
graphPrCombined->SetMarkerColor(4);
graphPrCombined->SetNameTitle("Graph_Protons_Combined", "Graph_Protons_Combined");
TList * listCollPi = new TList();
if (useV0s) {
//listCollPi->Add(pionTpcGraph);
//listCollPi->Add(pionTofGraph);
TGraphErrors * pionV0GraphCut = new TGraphErrors(*pionV0Graph);
pionV0GraphCut->SetName("pionV0GraphCut");
for(Int_t ip = 0; ip < pionV0GraphCut->GetN(); ip ++) {
//Double_t mom = pionV0GraphCut->GetX()[ip] * AliPID::ParticleMass(AliPID::kPion);
Bool_t removePoint = kFALSE;//mom >= 0.4;
//|| mom < 0.2;//TODO NOW NEEDED?
if (removePoint) {
pionV0GraphCut->RemovePoint(ip);
ip--;
continue;
}
}
/*
TGraphErrors * pionV0plusTOFGraphCut = new TGraphErrors(*pionV0plusTOFGraph);
pionV0plusTOFGraphCut->SetName("pionV0plusTOFGraphCut");
for(Int_t ip = 0; ip < pionV0plusTOFGraphCut->GetN(); ip ++) {
Double_t mom = pionV0plusTOFGraphCut->GetX()[ip] * AliPID::ParticleMass(AliPID::kPion);
Bool_t removePoint = mom < 0.4;
if (removePoint) {
pionV0plusTOFGraphCut->RemovePoint(ip);
ip--;
continue;
}
}*/
listCollPi->Add(pionV0GraphCut);
//listCollPi->Add(pionV0plusTOFGraphCut);
}
else {
listCollPi->Add(pionTpcGraph);
listCollPi->Add(pionTofGraph);
}
TGraphErrors * graphPiCombined = new TGraphErrors();
MergeGraphErrors(graphPiCombined, listCollPi);
graphPiCombined->SetMarkerStyle(22);
graphPiCombined->SetMarkerColor(3);
graphPiCombined->SetNameTitle("Graph_Pions_Combined", "Graph_Pions_Combined");
TList * listCollKa = new TList();
listCollKa->Add(kaonTpcGraph);
listCollKa->Add(kaonTofGraph);
TGraphErrors * graphKaCombined = new TGraphErrors();
MergeGraphErrors(graphKaCombined, listCollKa);
graphKaCombined->SetMarkerStyle(22);
graphKaCombined->SetMarkerColor(5);
graphKaCombined->SetNameTitle("Graph_Kaons_Combined", "Graph_Kaons_Combined");
TList * listCollEl = new TList();
if (useV0s) {
//listCollEl->Add(electronGraph);
TGraphErrors * electronV0GraphCut = new TGraphErrors(*electronV0Graph);
electronV0GraphCut->SetName("electronV0GraphCut");
/*
for(Int_t ip = 0; ip < electronV0GraphCut->GetN(); ip ++) {
Double_t mom = electronV0GraphCut->GetX()[ip] * AliPID::ParticleMass(AliPID::kElectron);
Bool_t removePoint = mom > 0.3;
if (removePoint) {
electronV0GraphCut->RemovePoint(ip);
ip--;
continue;
}
}
TGraphErrors * electronV0plusTOFGraphCut = new TGraphErrors(*electronV0plusTOFGraph);
electronV0plusTOFGraphCut->SetName("electronV0plusTOFGraphCut");
for(Int_t ip = 0; ip < electronV0plusTOFGraphCut->GetN(); ip ++) {
Double_t mom = electronV0plusTOFGraphCut->GetX()[ip] * AliPID::ParticleMass(AliPID::kElectron);
Bool_t removePoint = mom <= 0.4;
if (removePoint) {
electronV0plusTOFGraphCut->RemovePoint(ip);
ip--;
continue;
}
}
*/
listCollEl->Add(electronV0GraphCut);
//listCollEl->Add(electronV0plusTOFGraphCut);
}
else {
listCollEl->Add(electronGraph);
}
TGraphErrors * graphElCombined = new TGraphErrors();
MergeGraphErrors(graphElCombined, listCollEl);
graphElCombined->SetMarkerStyle(22);
graphElCombined->SetMarkerColor(2);
graphElCombined->SetNameTitle("Graph_Electrons_Combined", "Graph_Electrons_Combined");
//
// return array with all graphs
//
TObjArray * arrGraphs = new TObjArray();
arrGraphs->Add(graphAll);
//
arrGraphs->Add(electronGraph);
arrGraphs->Add(electronV0Graph);
arrGraphs->Add(electronV0plusTOFGraph);
arrGraphs->Add(electronV0GraphForBBfit);
arrGraphs->Add(pionTpcGraph);
arrGraphs->Add(pionTofGraph);
arrGraphs->Add(pionV0Graph);
arrGraphs->Add(pionV0plusTOFGraph);
arrGraphs->Add(pionV0GraphForBBfit);
arrGraphs->Add(kaonTpcGraph);
arrGraphs->Add(kaonTofGraph);
arrGraphs->Add(protonTpcGraph);
arrGraphs->Add(protonTofGraph);
arrGraphs->Add(protonV0Graph);
arrGraphs->Add(protonV0plusTOFGraph);
arrGraphs->Add(protonV0GraphForBBfit);
//
arrGraphs->Add(graphElCombined);
arrGraphs->Add(graphPiCombined);
arrGraphs->Add(graphKaCombined);
arrGraphs->Add(graphPrCombined);
//
//
canvasQAtpc->SaveAs("splines_QA_ResidualGraphsTPC.root");
canvasQAtof->SaveAs("splines_QA_ResidualGraphsTOF.root");
canvasQAv0->SaveAs("splines_QA_ResidualGraphsV0.root");
canvasQAv0plusTOF->SaveAs("splines_QA_ResidualGraphsV0plusTOF.root");
canvasQAv0DeDxPurityEl->SaveAs("V0_dEdx_purity_el.root");
canvasQAv0DeDxPurityPi->SaveAs("V0_dEdx_purity_Pi.root");
canvasQAv0DeDxPurityPr->SaveAs("V0_dEdx_purity_Pr.root");
return arrGraphs;
}
//________________________________________________________________________
TObjArray * AliTPCcalibResidualPID_Modified::GetResidualGraphsMC(THnSparseF * histPidQA, const Char_t * /*system*/) {
//
// Extracts the residual graphs from THnSparse created from MC (NOT DATA!)
//
const TString momTitle = "#it{p}_{TPC} (GeV/#it{c})";
const TString dEdxTitle = "d#it{E}/d#it{x} (arb. unit)";
Int_t cutForFitting = 10;
Double_t heightFractionForFittingRange = 0.1;
//
THnSparse * hist = histPidQA;
//
TCanvas * canvasQAmc = new TCanvas("canvasQAmcResGraph","Control canvas for residual graphs (MC)",100,10,1380,800);
canvasQAmc->Divide(2,2);
for (Int_t i = 1; i <= 4; i++) {
canvasQAmc->GetPad(i)->SetGrid(1, 1);
canvasQAmc->GetPad(i)->SetLogz();
canvasQAmc->GetPad(i)->SetLogx();
}
//
// 1. select and fit electrons
//
// In the following, axis 3 will also be limited in range, although nsigma itself is not used. This is to avoid multiple counting of entries
hist->GetAxis(2)->SetRangeUser(0,0); // electrons
hist->GetAxis(3)->SetRangeUser(0,0); // electrons (used for nsigma and for the eta correction of the signal)
TH2D * histElectron = hist->Projection(1,0);
histElectron->SetName("histElectron");
histElectron->RebinX(2);
histElectron->GetXaxis()->SetRangeUser(0.15,8.0);
TObjArray arr;
FitSlicesY(histElectron, heightFractionForFittingRange, cutForFitting, "QNRL", &arr);
TH1D * electronPoints = (TH1D *) arr.At(1)->Clone();
//
TGraphErrors * electronGraph = new TGraphErrors(electronPoints);
electronGraph->SetName("electronGraphMC");
for(Int_t ip = 0; ip < electronGraph->GetN(); ip ++) {
Bool_t removePoint = electronGraph->GetY()[ip] < 10 || electronGraph->GetEY()[ip]/electronGraph->GetY()[ip] > 0.03
|| electronGraph->GetX()[ip] < 0.15;// || electronGraph->GetX()[ip] > 3.1;
if (removePoint) {
electronGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAmc->cd(1);
histElectron->SetTitle("electrons");
histElectron->GetYaxis()->SetRangeUser(50, 120);
histElectron->GetXaxis()->SetTitle(momTitle.Data());
histElectron->GetYaxis()->SetTitle(dEdxTitle.Data());
histElectron->GetXaxis()->SetMoreLogLabels(kTRUE);
histElectron->GetXaxis()->SetNoExponent(kTRUE);
histElectron->Draw("colz");
electronPoints->SetMarkerStyle(24);
electronPoints->Draw("same");
//
// 2. protons
//
hist->GetAxis(2)->SetRangeUser(3,3); // protons
hist->GetAxis(3)->SetRangeUser(3,3); // protons (used for nsigma and for the eta correction of the signal)
//
TH2D * histProton = hist->Projection(1,0);
histProton->SetName("histProton");
histProton->GetXaxis()->SetRangeUser(0.15,8);
histProton->GetYaxis()->SetRangeUser(10, hist->GetAxis(1)->GetBinUpEdge(hist->GetAxis(1)->GetNbins()));
FitSlicesY(histProton, heightFractionForFittingRange, cutForFitting, "QNRL", &arr);
TH1D * protonPoints = (TH1D *) arr.At(1)->Clone();
//
TGraphErrors * protonGraph = new TGraphErrors(protonPoints);
protonGraph->SetName("protonGraphMC");
for(Int_t ip = 0; ip < protonGraph->GetN(); ip ++) {
Bool_t removePoint = protonGraph->GetY()[ip] < 10 || protonGraph->GetEY()[ip]/protonGraph->GetY()[ip] > 0.02 ||
protonGraph->GetX()[ip] < 0.15 || protonGraph->GetX()[ip] > 6;
if (removePoint) {
protonGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAmc->cd(2);
histProton->SetTitle("protons");
histProton->GetXaxis()->SetTitle(momTitle.Data());
histProton->GetYaxis()->SetTitle(dEdxTitle.Data());
histProton->GetXaxis()->SetMoreLogLabels(kTRUE);
histProton->GetXaxis()->SetNoExponent(kTRUE);
histProton->Draw("colz");
protonPoints->SetMarkerStyle(20);
protonPoints->Draw("same");
//
// 3. pions
//
hist->GetAxis(2)->SetRangeUser(1,1); // pions
hist->GetAxis(3)->SetRangeUser(1,1); // pions (used for nsigma and for the eta correction of the signal)
//
TH2D * histPion = hist->Projection(1,0);
histPion->SetName("histPion");
histPion->GetXaxis()->SetRangeUser(0.15,50);
FitSlicesY(histPion, heightFractionForFittingRange, cutForFitting, "QNRL", &arr);
TH1D * pionPoints = (TH1D *) arr.At(1)->Clone();
//
TGraphErrors * pionGraph = new TGraphErrors(pionPoints);
pionGraph->SetName("pionGraphMC");
for(Int_t ip = 0; ip < pionGraph->GetN(); ip ++) {
Bool_t removePoint = pionGraph->GetY()[ip] < 10 || pionGraph->GetEY()[ip]/pionGraph->GetY()[ip] > 0.005
|| pionGraph->GetX()[ip] < 0.15 || pionGraph->GetX()[ip] > 30;
if (removePoint) {
pionGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAmc->cd(3);
histPion->GetYaxis()->SetRangeUser(30, 90);
histPion->GetXaxis()->SetTitle(momTitle.Data());
histPion->GetYaxis()->SetTitle(dEdxTitle.Data());
histPion->GetXaxis()->SetMoreLogLabels(kTRUE);
histPion->GetXaxis()->SetNoExponent(kTRUE);
histPion->Draw("colz");
histPion->SetTitle("pions");
pionPoints->SetMarkerStyle(20);
pionPoints->Draw("same");
//
// 4. kaons
//
hist->GetAxis(2)->SetRangeUser(2,2); // kaons
hist->GetAxis(3)->SetRangeUser(2,2); // kaons (used for nsigma and for the eta correction of the signal)
//
TH2D * histKaon = hist->Projection(1,0);
histKaon->SetName("histKaon");
histKaon->GetXaxis()->SetRangeUser(0.15,8);
FitSlicesY(histKaon, heightFractionForFittingRange, cutForFitting, "QNRL", &arr);
TH1D * kaonPoints = (TH1D*) arr.At(1)->Clone();
//
TGraphErrors * kaonGraph = new TGraphErrors(kaonPoints);
kaonGraph->SetName("kaonGraphMC");
for(Int_t ip = 0; ip < kaonGraph->GetN(); ip ++) {
Bool_t removePoint = kaonGraph->GetY()[ip] < 10 || kaonGraph->GetEY()[ip]/kaonGraph->GetY()[ip] > 0.02
|| kaonGraph->GetX()[ip] < 0.15;
if (removePoint) {
kaonGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
canvasQAmc->cd(4);
histKaon->SetTitle("kaons");
histKaon->GetYaxis()->SetRangeUser(30, 500);
histKaon->GetXaxis()->SetTitle(momTitle.Data());
histKaon->GetYaxis()->SetTitle(dEdxTitle.Data());
histKaon->GetXaxis()->SetMoreLogLabels(kTRUE);
histKaon->GetXaxis()->SetNoExponent(kTRUE);
histKaon->Draw("colz");
kaonPoints->SetMarkerStyle(20);
kaonPoints->Draw("same");
hist->GetAxis(2)->SetRange(0,-1); // RESET RANGES
hist->GetAxis(3)->SetRange(0,-1); // RESET RANGES
// Clone graphs to have graphs with the same names as for the data case -> same subsequent functions can be used to determine
// the correction functions and, finally, the response functions.
// In addition: Remove some points, which are expected to deviate from the Bethe-Bloch curve, from the original graphs, so that
// these graphs can be used for the BB fit
TGraphErrors * graphPrCombined = new TGraphErrors(*protonGraph);
graphPrCombined->SetMarkerStyle(22);
graphPrCombined->SetMarkerColor(4);
graphPrCombined->SetNameTitle("Graph_Protons_Combined", "Graph_Protons_Combined");
TGraphErrors * graphPiCombined = new TGraphErrors(*pionGraph);
graphPiCombined->SetMarkerStyle(22);
graphPiCombined->SetMarkerColor(3);
graphPiCombined->SetNameTitle("Graph_Pions_Combined", "Graph_Pions_Combined");
TGraphErrors * graphKaCombined = new TGraphErrors(*kaonGraph);
graphKaCombined->SetMarkerStyle(22);
graphKaCombined->SetMarkerColor(5);
graphKaCombined->SetNameTitle("Graph_Kaons_Combined", "Graph_Kaons_Combined");
TGraphErrors * graphElCombined = new TGraphErrors(*electronGraph);
graphElCombined->SetMarkerStyle(22);
graphElCombined->SetMarkerColor(2);
graphElCombined->SetNameTitle("Graph_Electrons_Combined", "Graph_Electrons_Combined");
for(Int_t ip = 0; ip < electronGraph->GetN(); ip ++) {
Bool_t removePoint = electronGraph->GetX()[ip] < 2.5;// || electronGraph->GetX()[ip] > 5.0;
//Bool_t removePoint = electronGraph->GetX()[ip] < 1.2 || electronGraph->GetX()[ip] > 5.0;
if (removePoint) {
electronGraph->RemovePoint(ip);
ip--;
continue;
}
}
for(Int_t ip = 0; ip < protonGraph->GetN(); ip ++) {
Bool_t removePoint = protonGraph->GetX()[ip] < 0.9
|| protonGraph->GetX()[ip] > 2.5;//3.5; //TODO NEW in order not to get into conflict with pions/kaons
if (removePoint) {
protonGraph->RemovePoint(ip);
ip--;
continue;
}
}
for(Int_t ip = 0; ip < pionGraph->GetN(); ip ++) {
Bool_t removePoint = pionGraph->GetX()[ip] < 2.1;//TODO APR18 0.8;
if (removePoint) {
pionGraph->RemovePoint(ip);
ip--;
continue;
}
}
for(Int_t ip = 0; ip < kaonGraph->GetN(); ip ++) {
Bool_t removePoint = kaonGraph->GetX()[ip] < 1.25 || kaonGraph->GetX()[ip] > 4.0;// < 0.7;// || kaonGraph->GetX()[ip] > 4;
if (removePoint) {
kaonGraph->RemovePoint(ip);
ip--;
continue;
}
}
//
// rescale graphs to betaGamma
//
kaonGraph->SetMarkerStyle(22);
for(Int_t ip = 0; ip < kaonGraph->GetN(); ip ++) {
kaonGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kKaon);
kaonGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kKaon);
}
for(Int_t ip = 0; ip < graphKaCombined->GetN(); ip ++) {
graphKaCombined->GetX()[ip] /= AliPID::ParticleMass(AliPID::kKaon);
graphKaCombined->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kKaon);
}
//
electronGraph->SetMarkerStyle(22);
electronGraph->SetMarkerColor(2);
for(Int_t ip = 0; ip < electronGraph->GetN(); ip ++) {
electronGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
electronGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
}
for(Int_t ip = 0; ip < graphElCombined->GetN(); ip ++) {
graphElCombined->GetX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
graphElCombined->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kElectron);
}
//
pionGraph->SetMarkerStyle(22);
pionGraph->SetMarkerColor(3);
for(Int_t ip = 0; ip < pionGraph->GetN(); ip ++) {
pionGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
pionGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
}
for(Int_t ip = 0; ip < graphPiCombined->GetN(); ip ++) {
graphPiCombined->GetX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
graphPiCombined->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kPion);
}
//
protonGraph->SetMarkerStyle(22);
protonGraph->SetMarkerColor(4);
for(Int_t ip = 0; ip < protonGraph->GetN(); ip ++) {
protonGraph->GetX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
protonGraph->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
}
for(Int_t ip = 0; ip < graphPrCombined->GetN(); ip ++) {
graphPrCombined->GetX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
graphPrCombined->GetEX()[ip] /= AliPID::ParticleMass(AliPID::kProton);
}
//
//
// Store graphs without further restriction
TGraphErrors * graphPrAll = new TGraphErrors(*graphPrCombined);
graphPrAll->SetNameTitle("Protons_MC_all", "Protons_MC_all");
TGraphErrors * graphPiAll = new TGraphErrors(*graphPiCombined);
graphPiAll->SetNameTitle("Pions_MC_all", "Pions_MC_all");
TGraphErrors * graphKaAll = new TGraphErrors(*graphKaCombined);
graphKaAll->SetNameTitle("Kaons_MC_all", "Kaons_MC_all");
TGraphErrors * graphElAll = new TGraphErrors(*graphElCombined);
graphElAll->SetNameTitle("Electrons_MC_all", "Electrons_MC_all");
//
//
TGraphErrors * graphAll = new TGraphErrors();
TList * listColl = new TList();
listColl->Add(electronGraph);
listColl->Add(protonGraph);
listColl->Add(kaonGraph);
listColl->Add(pionGraph);
MergeGraphErrors(graphAll, listColl);
graphAll->SetNameTitle("beamDataPoints","beamDataPoints");
//
// return array with all graphs
//
TObjArray * arrGraphs = new TObjArray();
arrGraphs->Add(graphAll);
//
arrGraphs->Add(electronGraph);
arrGraphs->Add(pionGraph);
arrGraphs->Add(kaonGraph);
arrGraphs->Add(protonGraph);
//
arrGraphs->Add(graphElAll);
arrGraphs->Add(graphPiAll);
arrGraphs->Add(graphKaAll);
arrGraphs->Add(graphPrAll);
//
arrGraphs->Add(graphElCombined);
arrGraphs->Add(graphPiCombined);
arrGraphs->Add(graphKaCombined);
arrGraphs->Add(graphPrCombined);
//
//
canvasQAmc->SaveAs("splines_QA_ResidualGraphsTPC.root");
return arrGraphs;
}
//________________________________________________________________________
TObjArray * AliTPCcalibResidualPID_Modified::GetResponseFunctions(TF1* parametrisation, TObjArray* inputGraphs, const Char_t * type, const Char_t * period, const Char_t * pass, const Char_t * system, const Char_t* dedxtype) {
//
//
Bool_t isMC = kFALSE;
if (strcmp(type, "MC") == 0) {
isMC = kTRUE;
}
else if (strcmp(type, "DATA") == 0) {
isMC = kFALSE;
}
else {
Printf("ERROR - GetResponseFunctions: Unknown type \"%s\" - must be \"MC\" or \"DATA\"!", type);
return 0x0;
}
Bool_t isPbPb = kFALSE;
Bool_t isPPb = kFALSE;
if (strcmp(system, "PBPB") == 0) {
Printf("PbPb detected - Applying special handling!");
isPbPb = kTRUE;
}
else if (strcmp(system, "PPB") == 0 || strcmp(system, "PBP") == 0) {
Printf("p-Pb/Pb-p detected - Applying special handling!");
isPPb = kTRUE;
}
TCanvas* canvasQA[4] = { 0x0, };
for (Int_t i = 0; i < 4; i++) {
canvasQA[i] = new TCanvas(Form("canvasQAres_%d", i), "Control canvas for residual polynomial",100,10,1380,800);
canvasQA[i]->SetGrid(1, 1);
canvasQA[i]->SetLogx();
}
/*
TCanvas * canvasQA = new TCanvas("canvasQAres","Control canvas for residual polynomial",100,10,1380,800);
canvasQA->Divide(2,2);
for (Int_t i = 1; i <= 4; i++) {
canvasQA->GetPad(i)->SetGrid(1, 1);
}
*/
//
// smallest needed (100MeV proton) bg = 0.1/0.938(=AliPID::ParticleMass(AliPID::kProton)) = 0.1,
// largest needed 100 GeV electron, bg = 100/0.000511(=AliPID::ParticleMass(AliPID::kElectron)) = 200 000
//
Double_t from = 0.1;
Double_t to = 200000;
TF1* funcBB = new TF1(*parametrisation);
funcBB->SetLineColor(2);
funcBB->SetLineWidth(1);
TString fitFuncString = "[0] + [1] / x + [2] / (x**2) + [3] / (x**3) + [4] / (x**4) + [5] / (x**5) + [6] * x";
TString fitFuncString2 = "pol6";
//
// 1. extract proton corrections
//
TGraphErrors * graphProtonTPC = (TGraphErrors *) inputGraphs->FindObject("Graph_Protons_Combined");
TGraphErrors * graphProtonTPCfinal = new TGraphErrors(*graphProtonTPC);
graphProtonTPCfinal->SetName("graphProtonTPCfinal");
for(Int_t ip = 0; ip < graphProtonTPC->GetN(); ip ++) {
graphProtonTPC->GetY()[ip] -= funcBB->Eval(graphProtonTPC->GetX()[ip]);
graphProtonTPC->GetY()[ip] /= funcBB->Eval(graphProtonTPC->GetX()[ip]);
graphProtonTPC->GetEY()[ip] /= funcBB->Eval(graphProtonTPC->GetX()[ip]);;
}
canvasQA[0]->cd();
//canvasQA->cd(1);
//gPad->SetLogx();
graphProtonTPC->GetXaxis()->SetTitle("#beta#gamma");
graphProtonTPC->GetXaxis()->SetMoreLogLabels(kTRUE);
graphProtonTPC->GetXaxis()->SetNoExponent(kTRUE);
graphProtonTPC->GetYaxis()->SetLabelSize(0.04);
graphProtonTPC->GetYaxis()->SetTitleOffset(0.85);
graphProtonTPC->GetXaxis()->SetTitleOffset(1.0);
graphProtonTPC->GetYaxis()->SetTitle("(data - fit) / fit");
graphProtonTPC->Draw("ap");
if (graphProtonTPC->GetN() <= 0) {
Printf("ERROR - GetResponseFunctions: Proton graph has no data points!");
return 0x0;
}
graphProtonTPC->Sort(); // Sort points along x. Next, the very first point will be used to determine the starting point of the correction function
TF1 * funcCorrProton = new TF1("funcCorrProton", fitFuncString2.Data(), TMath::Max(graphProtonTPC->GetX()[0], 0.15),1.0); // TODO BEN was 0.18 - 0.85 //nschmidt2016 was ...,1.0); //was then 2.0
graphProtonTPC->Fit(funcCorrProton, "QREX0M");
//
// 2. extract kaon corrections
//
TGraphErrors * graphKaonTPC = (TGraphErrors *) inputGraphs->FindObject("Graph_Kaons_Combined");
TGraphErrors * graphKaonTPCfinal = new TGraphErrors(*graphKaonTPC);
graphKaonTPCfinal->SetName("graphKaonTPCfinal");
for(Int_t ip = 0; ip < graphKaonTPC->GetN(); ip ++) {
graphKaonTPC->GetY()[ip] -= funcBB->Eval(graphKaonTPC->GetX()[ip]);
graphKaonTPC->GetY()[ip] /= funcBB->Eval(graphKaonTPC->GetX()[ip]);
graphKaonTPC->GetEY()[ip] /= funcBB->Eval(graphKaonTPC->GetX()[ip]);;
}
canvasQA[1]->cd();
//canvasQA->cd(2);
//gPad->SetLogx();
graphKaonTPC->GetXaxis()->SetTitle("#beta#gamma");
graphKaonTPC->GetYaxis()->SetTitle("(data - fit) / fit");
graphKaonTPC->GetXaxis()->SetMoreLogLabels(kTRUE);
graphKaonTPC->GetXaxis()->SetNoExponent(kTRUE);
graphKaonTPC->GetYaxis()->SetLabelSize(0.04);
graphKaonTPC->GetYaxis()->SetTitleOffset(0.85);
graphKaonTPC->GetXaxis()->SetTitleOffset(1.0);
graphKaonTPC->Draw("ap");
Bool_t kaonGraphHasDataPoints = kTRUE;
if (graphKaonTPC->GetN() <= 0) {
Printf("WARNING - GetResponseFunctions: Kaon graph has no data points! Kaon splines will just be pure BB without low-p correction!");
kaonGraphHasDataPoints = kFALSE;
}
graphKaonTPC->Sort(); // Sort points along x. Next, the very first point will be used to determine the starting point of the correction function
TF1 * funcCorrKaon = 0x0;
if (!kaonGraphHasDataPoints) {
// Just take dummy correction function, which is constant at zero (= no correction)
funcCorrKaon = new TF1("funcCorrKaon", "0", 0.1, 1);
}
else {
if (isMC) {
funcCorrKaon = new TF1("funcCorrKaon", fitFuncString.Data(), TMath::Max(graphKaonTPC->GetX()[0], 0.25), isPPb ? 3.44 : 1.981);
graphKaonTPC->Fit(funcCorrKaon, "QREX0M");
}
else {
// In case of data there are sometimes problems to fit the shape with one function (could describe the overall deviation,
// but will not cover all the details).
// Nevertheless, this shape (including most of the "details") can be fitted with the following approach with two functions
TF1 * funcCorrKaon1 = new TF1("funcCorrKaon1", fitFuncString.Data(),
TMath::Max(graphKaonTPC->GetX()[0], 0.25), 1.981);
graphKaonTPC->Fit(funcCorrKaon1, "QREX0M", "same", TMath::Max(graphKaonTPC->GetX()[0], 0.25), 1.0);
TF1 * funcCorrKaon2 = new TF1("funcCorrKaon2", fitFuncString2.Data(), TMath::Max(graphKaonTPC->GetX()[0], 0.25), 1.981);
graphKaonTPC->Fit(funcCorrKaon2, "QREX0M", "same", (isMC ? 1.981 : 1.0), 1.981);
funcCorrKaon = new TF1("funcCorrKaon",
"funcCorrKaon1 * 0.5*(1.+TMath::Erf((1 - x) / 0.1)) + ([0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x+[5]*x*x*x*x*x+[6]*x*x*x*x*x*x) * 0.5*(1.+TMath::Erf((x - 1) / 0.1))",
TMath::Max(graphKaonTPC->GetX()[0], 0.25), 1.981);
for (Int_t i = funcCorrKaon1->GetNpar(), j = 0; i < funcCorrKaon1->GetNpar() + funcCorrKaon2->GetNpar(); i++, j++) {
funcCorrKaon->SetParameter(j, funcCorrKaon2->GetParameter(j));
}
funcCorrKaon->SetLineColor(kRed);
funcCorrKaon->GetHistogram()->DrawClone("csame");
//funcCorrKaon->Draw("same");
}
/*TODO
TF1 * funcCorrKaon = new TF1("funcCorrKaon", fitFuncString.Data(),//TODO BEN was fitFuncString2
TMath::Max(graphKaonTPC->GetX()[0], 0.25), (isMC ? 1.981 : 1.0)); //TODO BEN was 0.79 for data and 1.45 for MC
graphKaonTPC->Fit(funcCorrKaon, "QREX0M");
*/
}
//
// 3. extract pion corrections
//
TGraphErrors * graphPionTPC = (TGraphErrors *) inputGraphs->FindObject("Graph_Pions_Combined");
TGraphErrors * graphPionTPCfinal = new TGraphErrors(*graphPionTPC);
graphPionTPCfinal->SetName("graphPionTPCfinal");
for(Int_t ip = 0; ip < graphPionTPC->GetN(); ip ++) {
graphPionTPC->GetY()[ip] -= funcBB->Eval(graphPionTPC->GetX()[ip]);
graphPionTPC->GetY()[ip] /= funcBB->Eval(graphPionTPC->GetX()[ip]);
graphPionTPC->GetEY()[ip] /= funcBB->Eval(graphPionTPC->GetX()[ip]);
}
canvasQA[2]->cd();
//canvasQA->cd(3);
//gPad->SetLogx();
graphPionTPC->GetXaxis()->SetTitle("#beta#gamma");
graphPionTPC->GetYaxis()->SetTitle("(data - fit) / fit");
graphPionTPC->GetXaxis()->SetMoreLogLabels(kTRUE);
graphPionTPC->GetXaxis()->SetNoExponent(kTRUE);
graphPionTPC->GetYaxis()->SetLabelSize(0.04);
graphPionTPC->GetYaxis()->SetTitleOffset(0.85);
graphPionTPC->GetXaxis()->SetTitleOffset(1.0);
graphPionTPC->Draw("ap");
if (graphPionTPC->GetN() <= 0) {
Printf("ERROR - GetResponseFunctions: Pion graph has no data points!");
return 0x0;
}
graphPionTPC->Sort(); // Sort points along x. Next, the very first point will be used to determine the starting point of the correction function
// In case of PbPb (data, not MC) only correct down to 0.2 GeV/c; otherwise: contamination due to electrons
//~ TF1 * funcCorrPion = new TF1("funcCorrPion", fitFuncString.Data(), ((isPbPb && !isMC) ? (0.2 / AliPID::ParticleMass(AliPID::kPion)) : graphPionTPC->GetX()[0]), isMC ? (isPPb ? 12.8 : (isPbPb ? 12.8 : 7.1)) : (isPPb ? 7.68 : 7.1));
TF1 * funcCorrPion = new TF1("funcCorrPion", fitFuncString.Data(), ((isPbPb && !isMC) ? (0.2 / AliPID::ParticleMass(AliPID::kPion)) : graphPionTPC->GetX()[0]), isMC ? (isPPb ? 12.8 : (isPbPb ? 12.8 : 7.1)) : (isPPb ? 7.68 : (isPbPb ? 15.5 : 7.1))); //nschmidt2016 was 12.8 : 7.1 // was then 27.5
graphPionTPC->Fit(funcCorrPion, "QREX0M");
//
// 4. extract electron corrections
//
TGraphErrors * graphElectronTPC = (TGraphErrors *) inputGraphs->FindObject("Graph_Electrons_Combined");
TGraphErrors * graphElectronTPCfinal = new TGraphErrors(*graphElectronTPC);
graphElectronTPCfinal->SetName("graphElectronTPCfinal");
for(Int_t ip = 0; ip < graphElectronTPC->GetN(); ip ++) {
graphElectronTPC->GetY()[ip] -= funcBB->Eval(graphElectronTPC->GetX()[ip]);
graphElectronTPC->GetY()[ip] /= funcBB->Eval(graphElectronTPC->GetX()[ip]);
graphElectronTPC->GetEY()[ip] /= funcBB->Eval(graphElectronTPC->GetX()[ip]);;
}
canvasQA[3]->cd();
//canvasQA->cd(4);
//gPad->SetLogx();
graphElectronTPC->GetXaxis()->SetTitle("#beta#gamma");
graphElectronTPC->GetYaxis()->SetTitle("(data - fit) / fit");
graphElectronTPC->GetXaxis()->SetMoreLogLabels(kTRUE);
graphElectronTPC->GetXaxis()->SetNoExponent(kTRUE);
graphElectronTPC->GetYaxis()->SetLabelSize(0.04);
graphElectronTPC->GetYaxis()->SetTitleOffset(0.85);
graphElectronTPC->GetXaxis()->SetTitleOffset(1.0);
graphElectronTPC->Draw("ap");
if (graphElectronTPC->GetN() <= 0) {
Printf("ERROR - GetResponseFunctions: Electron graph has no data points!");
return 0x0;
}
graphElectronTPC->Sort(); // Sort points along x. Next, the very first point will be used to determine the starting point of the correction function
// In case of PbPb (data, not MC) only correct down to 0.2 GeV/c; otherwise: contamination due to pions
TF1 * funcCorrElectron = new TF1("funcCorrElectron", fitFuncString.Data(), (!isMC && isPbPb ? (0.2 / AliPID::ParticleMass(AliPID::kElectron)) :graphElectronTPC->GetX()[0]), (isMC ? 3565 : (isPPb ? 2900 : (isPbPb ? 2500 : 1920/*970*/))));// TODO was 1800 for pp data
// NOTE: For data, the results are almost the same for fitFuncString and fitFuncString2. Maybe, fitFuncString2 is slightly better.
graphElectronTPC->Fit(funcCorrElectron, "QREX0M");
//
// EXTRACT GRAPHS AND PUT THEM TO THE TOBJARRAY
//
const Int_t nBins = 500;
Double_t xBetaGamma[nBins];
Double_t yProton[nBins];
Double_t yKaon[nBins];
Double_t yPion[nBins];
Double_t yElectron[nBins];
Double_t yDefault[nBins];
//
//
//
xBetaGamma[0] = from;
Double_t factor = pow(to/from, 1./nBins);
//
for(Int_t kk = 0; kk < nBins; kk++) {
if (kk > 0) xBetaGamma[kk] = factor * xBetaGamma[kk-1];
yProton[kk] = funcBB->Eval(xBetaGamma[kk])/50.;
yPion[kk] = funcBB->Eval(xBetaGamma[kk])/50.;
yKaon[kk] = funcBB->Eval(xBetaGamma[kk])/50.;
yElectron[kk] = funcBB->Eval(xBetaGamma[kk])/50.;
yDefault[kk] = funcBB->Eval(xBetaGamma[kk])/50.;
// Added by Ben
Double_t widthFactor = 0.020;
Double_t smoothProton = 0.5*(TMath::Erf((funcCorrProton->GetXmax()-xBetaGamma[kk])*AliPID::ParticleMass(AliPID::kProton)/widthFactor) + 1);
Double_t smoothKaon = 0.5*(TMath::Erf((funcCorrKaon->GetXmax()-xBetaGamma[kk])*AliPID::ParticleMass(AliPID::kKaon)/widthFactor) + 1);
Double_t smoothPion = 0.5*(TMath::Erf((funcCorrPion->GetXmax()-xBetaGamma[kk])*AliPID::ParticleMass(AliPID::kPion)/widthFactor) + 1);
Double_t smoothElectron = 0.5*(TMath::Erf((funcCorrElectron->GetXmax()-xBetaGamma[kk])*AliPID::ParticleMass(AliPID::kElectron)/widthFactor) + 1);
if (xBetaGamma[kk] > funcCorrProton->GetXmax())
yProton[kk] *= (1 + smoothProton*funcCorrProton->Eval(funcCorrProton->GetXmax()));
// Correction is so large that one runs into trouble at low bg for Protons.
// The deviation is smaller if one takes the lower bound of the correction function
else if (xBetaGamma[kk] < funcCorrProton->GetXmin())
yProton[kk] *= (1 + smoothProton*funcCorrProton->Eval(funcCorrProton->GetXmin()));
else
yProton[kk] *= (1 + smoothProton*funcCorrProton->Eval(xBetaGamma[kk]));
if (xBetaGamma[kk] > funcCorrKaon->GetXmax())
yKaon[kk] *= (1 + smoothKaon*funcCorrKaon->Eval(funcCorrKaon->GetXmax()));
// Correction is so large that one runs into trouble at low bg for Kaons.
// The deviation is smaller if one takes the lower bound of the correction function
else if (xBetaGamma[kk] < funcCorrKaon->GetXmin())
yKaon[kk] *= (1 + smoothKaon*funcCorrKaon->Eval(funcCorrKaon->GetXmin()));
else
yKaon[kk] *= (1 + smoothKaon*funcCorrKaon->Eval(xBetaGamma[kk]));
if (xBetaGamma[kk] > funcCorrElectron->GetXmax())
yElectron[kk] *= (1 + smoothElectron*funcCorrElectron->Eval(funcCorrElectron->GetXmax()));
else if (xBetaGamma[kk] < funcCorrElectron->GetXmin())
yElectron[kk] *= (1 + smoothElectron*funcCorrElectron->Eval(funcCorrElectron->GetXmin()));
else
yElectron[kk] *= (1 + smoothElectron*funcCorrElectron->Eval(xBetaGamma[kk]));
// Only true for LHC10d.pass?: Seems not to be needed because any (very small) deviations are most likely due to electron contamination(BEN)
if (xBetaGamma[kk] > funcCorrPion->GetXmax())
yPion[kk] *= (1 + smoothPion*funcCorrPion->Eval(funcCorrPion->GetXmax()));
else if (xBetaGamma[kk] < funcCorrPion->GetXmin())
yPion[kk] *= (1 + smoothPion*funcCorrPion->Eval(funcCorrPion->GetXmin()));
else
yPion[kk] *= (1 + smoothPion*funcCorrPion->Eval(xBetaGamma[kk]));
/* Removed by Ben
Double_t smoothProton = 0.5*(TMath::Erf((funcCorrProton->GetXmax()-xBetaGamma[kk])/0.002) + 1);
Double_t smoothKaon = 0.5*(TMath::Erf((funcCorrKaon->GetXmax()-xBetaGamma[kk])/0.002) + 1);
Double_t smoothPion = 0.5*(TMath::Erf((funcCorrPion->GetXmax()-xBetaGamma[kk])/0.002) + 1);
if (xBetaGamma[kk] < funcCorrProton->GetXmax() && xBetaGamma[kk] > funcCorrProton->GetXmin()) yProton[kk] *= (1 + smoothProton*funcCorrProton->Eval(xBetaGamma[kk]));
if (xBetaGamma[kk] < funcCorrKaon->GetXmax() && xBetaGamma[kk] > funcCorrKaon->GetXmin()) yKaon[kk] *= (1 + smoothKaon*funcCorrKaon->Eval(xBetaGamma[kk]));
if (xBetaGamma[kk] < funcCorrPion->GetXmax() && xBetaGamma[kk] > funcCorrPion->GetXmin()) yPion[kk] *= (1 + smoothPion*funcCorrPion->Eval(xBetaGamma[kk]));
//if (xBetaGamma[kk] < funcCorrElectron->GetXmax()) yElectron[kk] *= (1 + funcCorrElectron->Eval(xBetaGamma[kk]));
//
if (xBetaGamma[kk] < funcCorrProton->GetXmin()) yProton[kk] *= (1 + funcCorrProton->Eval(funcCorrProton->GetXmin()));
if (xBetaGamma[kk] < funcCorrKaon->GetXmin()) yKaon[kk] *= (1 + funcCorrKaon->Eval(funcCorrKaon->GetXmin()));
if (xBetaGamma[kk] < funcCorrPion->GetXmin()) yPion[kk] *= (1 + funcCorrPion->Eval(funcCorrPion->GetXmin()));
*/
}
//
TGraph * graphProton = new TGraph(nBins, xBetaGamma, yProton);
TGraph * graphElectron = new TGraph(nBins, xBetaGamma, yElectron);
TGraph * graphKaon = new TGraph(nBins, xBetaGamma, yKaon);
TGraph * graphPion = new TGraph(nBins, xBetaGamma, yPion);
TGraph * graphDefault = new TGraph(nBins, xBetaGamma, yDefault);
//
//
TSpline3 * splineProton = new TSpline3("splineProton", graphProton);
TSpline3 * splineElectron = new TSpline3("splineElectron", graphElectron);
TSpline3 * splineKaon = new TSpline3("splineKaon", graphKaon);
TSpline3 * splinePion = new TSpline3("splinePion", graphPion);
TSpline3 * splineDefault = new TSpline3("splineDefault", graphDefault);
//
//
splineProton->SetNameTitle(Form("TSPLINE3_%s_PROTON_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype),
Form("TSPLINE3_%s_PROTON_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype));
splineElectron->SetNameTitle(Form("TSPLINE3_%s_ELECTRON_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype),
Form("TSPLINE3_%s_ELECTRON_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype));
splineKaon->SetNameTitle(Form("TSPLINE3_%s_KAON_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype),
Form("TSPLINE3_%s_KAON_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype));
splinePion->SetNameTitle(Form("TSPLINE3_%s_PION_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype),
Form("TSPLINE3_%s_PION_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype));
splineDefault->SetNameTitle(Form("TSPLINE3_%s_ALL_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype),
Form("TSPLINE3_%s_ALL_%s_%s_%s_%sMEAN",type,period,pass,system,dedxtype));
//
TObjArray * arrResponse = new TObjArray();
arrResponse->SetName("TPCpidResponseFunctions");
arrResponse->AddLast(splineProton);
arrResponse->AddLast(splineElectron);
arrResponse->AddLast(splineKaon);
arrResponse->AddLast(splinePion);
arrResponse->AddLast(splineDefault);
//
// Draw deviation from final results
for(Int_t ip = 0; ip < graphProtonTPCfinal->GetN(); ip ++) {
graphProtonTPCfinal->GetY()[ip] -= 50. * splineProton->Eval(graphProtonTPCfinal->GetX()[ip]);
graphProtonTPCfinal->GetY()[ip] /= 50. * splineProton->Eval(graphProtonTPCfinal->GetX()[ip]);
graphProtonTPCfinal->GetEY()[ip] /= 50. * splineProton->Eval(graphProtonTPCfinal->GetX()[ip]);;
}
canvasQA[0]->cd();
//canvasQA->cd(1);
graphProtonTPCfinal->SetMarkerStyle(26);
graphProtonTPCfinal->Draw("psame");
for(Int_t ip = 0; ip < graphKaonTPCfinal->GetN(); ip ++) {
graphKaonTPCfinal->GetY()[ip] -= 50. * splineKaon->Eval(graphKaonTPCfinal->GetX()[ip]);
graphKaonTPCfinal->GetY()[ip] /= 50. * splineKaon->Eval(graphKaonTPCfinal->GetX()[ip]);
graphKaonTPCfinal->GetEY()[ip] /= 50. * splineKaon->Eval(graphKaonTPCfinal->GetX()[ip]);;
}
canvasQA[1]->cd();
//canvasQA->cd(2);
graphKaonTPCfinal->SetMarkerStyle(26);
graphKaonTPCfinal->Draw("psame");
for(Int_t ip = 0; ip < graphPionTPCfinal->GetN(); ip ++) {
graphPionTPCfinal->GetY()[ip] -= 50. * splinePion->Eval(graphPionTPCfinal->GetX()[ip]);
graphPionTPCfinal->GetY()[ip] /= 50. * splinePion->Eval(graphPionTPCfinal->GetX()[ip]);
graphPionTPCfinal->GetEY()[ip] /= 50. * splinePion->Eval(graphPionTPCfinal->GetX()[ip]);;
}
canvasQA[2]->cd();
//canvasQA->cd(3);
graphPionTPCfinal->SetMarkerStyle(26);
graphPionTPCfinal->Draw("psame");
for(Int_t ip = 0; ip < graphElectronTPCfinal->GetN(); ip ++) {
graphElectronTPCfinal->GetY()[ip] -= 50. * splineElectron->Eval(graphElectronTPCfinal->GetX()[ip]);
graphElectronTPCfinal->GetY()[ip] /= 50. * splineElectron->Eval(graphElectronTPCfinal->GetX()[ip]);
graphElectronTPCfinal->GetEY()[ip] /= 50. * splineElectron->Eval(graphElectronTPCfinal->GetX()[ip]);;
}
canvasQA[3]->cd();
//canvasQA->cd(4);
graphElectronTPCfinal->SetMarkerStyle(26);
graphElectronTPCfinal->Draw("psame");
TFile* fSave = TFile::Open("splines_QA_ResidualPolynomials.root", "RECREATE");
fSave->cd();
for (Int_t i = 0; i < 4; i++){
canvasQA[i]->Write();
canvasQA[i]->SaveAs(Form("polynomials%d.pdf",i));
}
fSave->Close();
//canvasQA->SaveAs("splines_QA_ResidualPolynomials.root");
delete funcBB;
return arrResponse;
}
TF1* AliTPCcalibResidualPID_Modified::SetUpFitFunction(const Double_t* initialParameters, AliTPCcalibResidualPID_Modified::FitType fitType, Float_t from, Float_t to, Bool_t isPPb, Bool_t isMC, Double_t* parametersBBForward) {
const Int_t nPar = 6;
parametersBBForward = new Double_t[nPar];
TF1* funcBB;
if (fitType == AliTPCcalibResidualPID_Modified::kSaturatedLund) {
printf("Fit function: Saturated Lund\n");
funcBB = new TF1("SaturatedLund", SaturatedLund, from, to, nPar);
//Double_t parametersBB[nPar] = {34.0446, 8.42221, 4.16724, 1.29473, 80.6663, 0}; //Xianguos values
//Double_t parametersBB[nPar] = {35.5, 8.7, 2.0, 1.09, 75.6, 0}; // No saturation
Double_t parametersBB[nPar] = {61.0, 8.7, 0.1, 0.85, 113.4, -38}; // Yields reasonable results for data and MC ~ all periods
if (isPPb && !isMC) {
parametersBB[0] = 51.6;
parametersBB[1] = 9.7;
parametersBB[2] = 1.62;
parametersBB[3] = 0.99;
parametersBB[4] = 104.4;
parametersBB[5] = -27.0;
}
if (isMC) {
parametersBB[0] = 41.4;
parametersBB[1] = 8.6;
parametersBB[2] = 2.2;
parametersBB[3] = 0.92;
parametersBB[4] = 90.4;
parametersBB[5] = -20.0;
}
funcBB->SetParameters(parametersBB);
Double_t parameterErrorsBB[nPar] = {5., 0.5, 0.2, 0.05, 10, 10};
funcBB->SetParErrors(parameterErrorsBB);
for (Int_t i = 0; i < nPar; i++)
parametersBBForward[i] = parametersBB[i];
}
else if (fitType == AliTPCcalibResidualPID_Modified::kLund) {
printf("Fit function: Lund\n");
printf("****WARNING: Fit settings not tuned for this fit function, only for saturated Lund!\n");
funcBB = new TF1("SaturatedLund", SaturatedLund, from, to, nPar);
//Double_t parametersBB[nPar] = {34.0446, 8.42221, 4.16724, 1.29473, 80.6663, 0}; //Xianguos values
//Double_t parametersBB[nPar] = {35.5, 8.7, 2.0, 1.09, 75.6, 0}; // No saturation
Double_t parametersBB[nPar] = {35.0, 7., 1.86, 1., 75., 0}; // Yields reasonable results for data and MC ~ all periods
funcBB->SetParameters(parametersBB);
Double_t parameterErrorsBB[nPar] = {5., 0.5, 0.2, 0.05, 10, 10};
funcBB->SetParErrors(parameterErrorsBB);
funcBB->FixParameter(5, 0.0); // No saturation
for (Int_t i = 0; i < nPar; i++)
parametersBBForward[i] = parametersBB[i];
}
else if (fitType == kAlephWithAdditionalParam) {
printf("Fit function: Aleph with additional parameter\n");
printf("****WARNING: Fit settings not tuned for this fit function, only for saturated Lund!\n");
// NOTE: This form is equivalent to the original form, but with parameter [2] redefined for better numerical stability.
// The additional parameter [5] has been introduced later and is unity originally. It seems not to be needed and is, thus,
// fixed to unity
funcBB = new TF1("funcModifiedAleph", Aleph, from, to, nPar);
Double_t parametersBB[nPar] = {1.6,20.3,-10,2.6,2.3, 0.02};
//OLD with different sign for [3]: Double_t parametersBB[nPar] = {0.0762*50.3,10.632,TMath::Log(1.34e-05),1.863,1.948, 1};
funcBB->SetParameters(parametersBB);
for (Int_t i = 0; i < nPar; i++)
parametersBBForward[i] = parametersBB[i];
}
else if (fitType == AliTPCcalibResidualPID_Modified::kAleph) {
printf("Fit function: Aleph\n");
printf("****WARNING: Fit settings not tuned for this fit function, only for saturated Lund!\n");
// NOTE: This form is equivalent to the original form, but with parameter [2] redefined for better numerical stability.
// The additional parameter [5] has been introduced later and is unity originally. It seems not to be needed and is, thus,
// fixed to unity
funcBB = new TF1("funcAleph",Aleph, from, to, nPar);
//OLD"[0]*([1]*TMath::Power(TMath::Sqrt(1 + x*x)/x , [3]) - [5] - TMath::Power(TMath::Sqrt(1 + x*x)/x , [3])*TMath::Log(TMath::Exp([2]) + 1/TMath::Power(x, [4])))", from, to);
//TEST Double_t parametersBB[nPar] = {1.2, 26.0, -30.0, -2.15, 5.6, 1};
Double_t parametersBB[nPar] = {1.25, 27.5, -29.0, 2.2, 5.2, 1};
// For [5] floating: Double_t parametersBB[nPar] = {2.42,15.2,-16,-2.24,2.8, 0.057};
//OLD with different sign for [3] and [5] not fix: Double_t parametersBB[nPar] = {2.6,14.3,-15,2.2,2.7, 0.06};
//OLD with different sign for [3]: Double_t parametersBB[nPar] = {0.0762*50.3,10.632,TMath::Log(1.34e-05),1.863,1.948, 1};
funcBB->SetParameters(parametersBB);
// Fix parameter 5 to original value of unity
funcBB->FixParameter(5, 1);
for (Int_t i = 0; i < nPar; i++)
parametersBBForward[i] = parametersBB[i];
}
else if (fitType == AliTPCcalibResidualPID_Modified::kAlephExternal) {
printf("Fit function: Aleph from AliExternalTrackParam\n");
printf("****WARNING: Fit settings not tuned for this fit function, only for saturated Lund!\n");
// NOTE: This form is equivalent to the original form, but with parameter [2] redefined for better numerical stability.
// The additional parameter [5] has been introduced later and is unity originally. It seems not to be needed and is, thus,
// fixed to unity
funcBB = new TF1("funcAleph",
"AliExternalTrackParam::BetheBlochAleph(x,[0],[1],[2],[3],[4])", from, to);
Double_t parametersBB[nPar] = {0.0851148*50, 9.25771, 2.6558e-05, 2.32742, 1.83039, 0};
funcBB->SetParameters(parametersBB);
for (Int_t i = 0; i < nPar; i++)
parametersBBForward[i] = parametersBB[i];
}
else {
printf("Error: fitType not supported!\n");
return 0x0;
}
funcBB->SetLineColor(2);
funcBB->SetLineWidth(1);
// Override initial parameters, if user provides some
if (initialParameters) {
printf("Setting user initial parameters!\n");
funcBB->SetParameters(initialParameters);
}
return funcBB;
}
void AliTPCcalibResidualPID_Modified::SetUpInputGraph(TGraphErrors* graphAll, Bool_t isMC, Bool_t useV0s) {
if (isMC) {
for(Int_t ip = 0; ip < graphAll->GetN(); ip++) {
graphAll->SetPointError(ip, 0, 0);
}
}
else if (useV0s) {
// Increase weight in plateau by reducing errors. Neccessary because errors are large there compared to other data points
for(Int_t ip = 0; ip < graphAll->GetN(); ip++) {
if (graphAll->GetX()[ip] >= 2500) {
graphAll->SetPointError(ip, 0, graphAll->GetEY()[ip] / 6.0);
}
// Same for pions in the very rel. rise
if (graphAll->GetX()[ip] >= 25 && graphAll->GetX()[ip] < 1000) {
graphAll->SetPointError(ip, 0, graphAll->GetEY()[ip] / 6.0);
}
// Same for protons in the MIP region
if (graphAll->GetX()[ip] >= 2 && graphAll->GetX()[ip] < 4) {
graphAll->SetPointError(ip, 0, graphAll->GetEY()[ip] / 6.0);
}
}
}
}
TCanvas* AliTPCcalibResidualPID_Modified::CreateBBCanvas(TObjArray* inputGraphs, Bool_t isMC, TF1* func) {
TGraphErrors * graphAll = (TGraphErrors *) inputGraphs->FindObject("beamDataPoints");
TCanvas * canvDelta_1 = new TCanvas("canvDelta_1","control histogram for Bethe-Bloch fit 1",100,10,1380,800);
canvDelta_1->SetGrid(1, 1);
canvDelta_1->SetLogx();
canvDelta_1->cd();
TH1F *hBBdummy=new TH1F("hBBdummy","BB fit;#beta#gamma;#LTdE/dx#GT (arb. unit)",100,.8,1e4);
hBBdummy->SetMinimum(45);
hBBdummy->SetMaximum(120);
hBBdummy->GetXaxis()->SetTitleOffset(1.1);
hBBdummy->SetStats(kFALSE);
hBBdummy->Draw();
graphAll->SetTitle("BB multi-graph fit");
graphAll->SetMarkerStyle(22);
graphAll->SetMarkerColor(kMagenta);
graphAll->Draw("p");
TLegend *leg=new TLegend(.2,0.3,0.36,isMC?.5:0.7);
leg->SetFillColor(10);
leg->SetBorderSize(1);
//overlay individual graphs
TGraph *gr=0x0;
if (isMC) {
gr=(TGraph*)inputGraphs->FindObject("Protons_MC_all");
gr->SetMarkerColor(kRed);
gr->SetMarkerStyle(24);
gr->Draw("p");
leg->AddEntry(gr,"p (MC)","p");
gr=(TGraph*)inputGraphs->FindObject("Pions_MC_all");
gr->SetMarkerColor(kBlue);
gr->SetMarkerStyle(24);
gr->Draw("p");
leg->AddEntry(gr,"#pi (MC)","p");
gr=(TGraph*)inputGraphs->FindObject("Kaons_MC_all");
gr->SetMarkerColor(kGreen);
gr->SetMarkerStyle(24);
gr->Draw("p");
leg->AddEntry(gr,"K (MC)","p");
gr=(TGraph*)inputGraphs->FindObject("Electrons_MC_all");
gr->SetMarkerColor(kBlack);
gr->SetMarkerStyle(24);
gr->Draw("p");
leg->AddEntry(gr,"e (MC)","p");
}
else {
gr=(TGraph*)inputGraphs->FindObject("protonTpcGraph");
gr->SetMarkerColor(kRed);
gr->SetMarkerStyle(26);
gr->Draw("p");
leg->AddEntry(gr,"p (TPC)","p");
gr=(TGraph*)inputGraphs->FindObject("protonTofGraph");
gr->SetMarkerColor(kRed);
gr->SetMarkerStyle(25);
gr->Draw("p");
leg->AddEntry(gr,"p (TOF)","p");
gr=(TGraph*)inputGraphs->FindObject("protonV0Graph");//ForBBfit");
gr->SetMarkerColor(kRed);
gr->SetMarkerStyle(24);
gr->Draw("p");
leg->AddEntry(gr,"p (V0)","p");
gr=(TGraph*)inputGraphs->FindObject("protonV0plusTOFGraph");//ForBBfit");
gr->SetMarkerColor(kRed);
gr->SetMarkerStyle(30);
gr->Draw("p");
leg->AddEntry(gr,"p (V0+TOF)","p");
gr=(TGraph*)inputGraphs->FindObject("pionTpcGraph");
gr->SetMarkerColor(kBlue);
gr->SetMarkerStyle(26);
gr->Draw("p");
leg->AddEntry(gr,"#pi (TPC)","p");
gr=(TGraph*)inputGraphs->FindObject("pionTofGraph");
gr->SetMarkerColor(kBlue);
gr->SetMarkerStyle(25);
gr->Draw("p");
leg->AddEntry(gr,"#pi (TOF)","p");
gr=(TGraph*)inputGraphs->FindObject("pionV0Graph");//ForBBfit");
gr->SetMarkerColor(kBlue);
gr->SetMarkerStyle(24);
gr->Draw("p");
leg->AddEntry(gr,"#pi (V0)","p");
gr=(TGraph*)inputGraphs->FindObject("pionV0plusTOFGraph");//ForBBfit");
gr->SetMarkerColor(kBlue);
gr->SetMarkerStyle(30);
gr->Draw("p");
leg->AddEntry(gr,"#pi (V0+TOF)","p");
gr=(TGraph*)inputGraphs->FindObject("kaonTpcGraph");
gr->SetMarkerColor(kGreen);
gr->SetMarkerStyle(26);
gr->Draw("p");
leg->AddEntry(gr,"K (TPC)","p");
gr=(TGraph*)inputGraphs->FindObject("kaonTofGraph");
gr->SetMarkerColor(kGreen);
gr->SetMarkerStyle(25);
gr->Draw("p");
leg->AddEntry(gr,"K (TOF)","p");
gr=(TGraph*)inputGraphs->FindObject("electronGraph");
gr->SetMarkerColor(kBlack);
gr->SetMarkerStyle(25);
gr->Draw("p");
leg->AddEntry(gr,"e","p");
gr=(TGraph*)inputGraphs->FindObject("electronV0Graph");//ForBBfit");
gr->SetMarkerColor(kBlack);
gr->SetMarkerStyle(24);
gr->Draw("p");
leg->AddEntry(gr,"e (V0)","p");
gr=(TGraph*)inputGraphs->FindObject("electronV0plusTOFGraph");//ForBBfit");
gr->SetMarkerColor(kBlack);
gr->SetMarkerStyle(30);
gr->Draw("p");
leg->AddEntry(gr,"e (V0+TOF)","p");
}
graphAll->GetXaxis()->SetTitle("#beta#gamma");
graphAll->GetYaxis()->SetTitle("<dE/dx> (arb. unit)");
graphAll->Draw("p");
func->GetHistogram()->DrawClone("csame");
leg->AddEntry(graphAll,"used","p");
leg->AddEntry(func,"fit","l");
leg->Draw("same");
return canvDelta_1;
}
TCanvas* AliTPCcalibResidualPID_Modified::CreateResidualCanvas(TGraphErrors * graphAll, TF1* func) {
TGraphErrors * graphDelta = new TGraphErrors(*graphAll);
graphDelta->SetName("graphDelta");
for(Int_t ip = 0; ip < graphDelta->GetN(); ip++) {
graphDelta->GetY()[ip] -= func->Eval(graphDelta->GetX()[ip]);
graphDelta->GetY()[ip] /= func->Eval(graphDelta->GetX()[ip]);
graphDelta->GetEY()[ip] /= func->Eval(graphDelta->GetX()[ip]);
}
TCanvas * canvDelta_2 = new TCanvas("canvDelta_2","control histogram for Bethe-Bloch fit 2",100,10,1380,800);
canvDelta_2->SetGrid(1, 1);
canvDelta_2->SetLogx();
canvDelta_2->cd();
TH1F *hBBresdummy=new TH1F("hBBresdummy","residuals of BB fit;#beta#gamma;(data-fit)/fit",100,.8,1e4);
hBBresdummy->SetMinimum(-0.04);
hBBresdummy->SetMaximum(0.04);
hBBresdummy->GetXaxis()->SetTitleOffset(1.1);
hBBresdummy->GetYaxis()->SetTitleOffset(0.8);
hBBresdummy->SetStats(kFALSE);
hBBresdummy->Draw();
graphDelta->SetTitle("residuals of BB fit to multi-graph");
graphDelta->GetXaxis()->SetTitle("#beta#gamma");
graphDelta->GetYaxis()->SetTitle("(data - fit) / fit");
graphDelta->SetMarkerStyle(22);
graphDelta->SetMarkerColor(4);
graphDelta->Draw("p");
return canvDelta_2;
}
//________________________________________________________________________
TF1* AliTPCcalibResidualPID_Modified::FitBB(TObjArray* inputGraphs, Bool_t isMC, Bool_t isPPb, const Bool_t useV0s,
const Double_t * initialParameters, AliTPCcalibResidualPID_Modified::FitType fitType) {
//
// Fit Bethe-Bloch parametrisation to data points (inputGraphs)
//
TGraphErrors * graphAll = (TGraphErrors *) inputGraphs->FindObject("beamDataPoints");
//
Float_t from = 0.9; //TODO ADJUST -> Very important
Float_t to = graphAll->GetXaxis()->GetXmax() * 2;
Double_t* parametersBBForward = 0x0;
TVirtualFitter::SetMaxIterations(5e6);
TF1* funcBB = SetUpFitFunction(initialParameters, fitType, from, to, isPPb, isMC, parametersBBForward);
// In MC case: Remove errors from fit -> Some data points with extremely small errors otherwise completely dominate the fit,
// but these points could still be wrong due to systematics (low p effects, e.g.)
SetUpInputGraph(graphAll, isMC, useV0s);
graphAll->Fit(funcBB, "REX0M");
funcBB->SetRange(from, to);
// funcBB->GetParameters(parametersBBForward);
TCanvas * canvDelta_1 = CreateBBCanvas(inputGraphs, isMC, funcBB);
TCanvas * canvDelta_2 = CreateResidualCanvas(graphAll, funcBB);
TString fitTypeName = (GetStringFitType(fitType)).ReplaceAll(" ","");
TFile* fSave = TFile::Open(TString::Format("splines_QA_BetheBlochFit_%s.root",fitTypeName.Data()).Data(), "RECREATE");
fSave->cd();
canvDelta_1->Write();
printf("Save canvas");
canvDelta_1->SaveAs(TString::Format("bethebloch_%s.pdf",fitTypeName.Data()).Data());
canvDelta_2->Write();
canvDelta_2->SaveAs(TString::Format("betheblochresidual_%s.pdf",fitTypeName.Data()).Data());
TString fitResults = "Fit results:\n";
for (Int_t i = 0; i < funcBB->GetNpar(); i++) {
fitResults.Append(Form("par%d:\t%f +- %f\n", i, funcBB->GetParameters()[i], funcBB->GetParErrors()[i]));
}
TNamed* settings = new TNamed(fitResults.Data(), fitResults.Data());
settings->Write();
fSave->Close();
printf("\n\n%s", fitResults.Data());
return funcBB;
}
//________________________________________________________________________
Double_t AliTPCcalibResidualPID_Modified::Lund(Double_t* xx, Double_t* par)
{
// bg is beta*gamma
const Double_t bg = xx[0];
const Double_t beta2 = bg*bg / (1.0 + bg*bg);
const Double_t a = par[0];
const Double_t b = par[1];
const Double_t c = par[2];
const Double_t e = par[3];
const Double_t f = par[4];
const Double_t d = TMath::Exp(c*(a - f) / b);
const Double_t powbg = TMath::Power(1.0 + bg, c);
const Double_t value = a / TMath::Power(beta2,e) +
b/c * TMath::Log(powbg / (1.0 + d*powbg));
return value;
}
//________________________________________________________________________
Double_t AliTPCcalibResidualPID_Modified::SaturatedLund(Double_t* xx, Double_t* par)
{
const Double_t qq = Lund(xx, par);
return qq * TMath::Exp(par[5] / qq);
}
Double_t AliTPCcalibResidualPID_Modified::Aleph(Double_t* xx, Double_t* par) {
const Double_t bg = xx[0];
const Double_t a0 = par[0];
const Double_t a1 = par[1];
const Double_t a2 = par[2];
const Double_t a3 = par[3];
const Double_t a4 = par[4];
const Double_t a5 = par[5];
const Double_t beta = TMath::Sqrt(bg*bg / (1.0 + bg*bg));
const Double_t powbetaa3 = TMath::Power(beta,a3);
const Double_t value = a0/powbetaa3 * (a1 - a2 - a5 * powbetaa3 - TMath::Log(1.0 + TMath::Power(bg, -a4)*TMath::Exp(-a2)));
return value;
}
//________________________________________________________________________
void AliTPCcalibResidualPID_Modified::FitSlicesY(TH2 *hist, Double_t heightFractionForRange, Int_t cutThreshold, TString fitOption, TObjArray *arr)
{
//heightPercentageForRange
// custom slices fit
//
if (!hist) return;
if (!arr) return;
// If old style is to be used
/*
hist->FitSlicesY(0, 0, -1, cutThreshold, fitOption.Data(), &arr);
return;
*/
arr->Clear();
arr->SetOwner();
arr->Expand(4);
TAxis *axis=hist->GetXaxis();
const TArrayD *bins = axis->GetXbins();
TH1D** hList = new TH1D*[4];
for (Int_t i = 0; i < 4; i++) {
delete gDirectory->FindObject(Form("%s_%d", hist->GetName(), i));
if (bins->fN == 0) {
hList[i] = new TH1D(Form("%s_%d", hist->GetName(), i), i < 3 ? Form("Fitted value of par[%d]", i) : "Chi2/NDF",
hist->GetNbinsX(), axis->GetXmin(), axis->GetXmax());
} else {
hList[i] = new TH1D(Form("%s_%d", hist->GetName(), i), i < 3 ? Form("Fitted value of par[%d]", i) : "Chi2/NDF", hist->GetNbinsX(), bins->fArray);
}
(*arr)[i] = hList[i];
}
for (Int_t ibin=axis->GetFirst(); ibin<=axis->GetLast(); ++ibin){
TH1 *h=hist->ProjectionY("_temp",ibin,ibin);
if (!h)
continue;
if (h->GetEntries() < cutThreshold) {
delete h;
continue;
}
// Average around maximum bin -> Might catch some outliers
Int_t maxBin = h->GetMaximumBin();
Double_t maxVal = h->GetBinContent(maxBin);
if (maxVal < 2) { // It could happen that all entries are in overflow/underflow; don't fit in this case
delete h;
continue;
}
UChar_t usedBins = 1;
if (maxBin > 1) {
maxVal += h->GetBinContent(maxBin - 1);
usedBins++;
}
if (maxBin < h->GetNbinsX()) {
maxVal += h->GetBinContent(maxBin + 1);
usedBins++;
}
maxVal /= usedBins;
Double_t thresholdFraction = heightFractionForRange * maxVal;
Int_t lowThrBin = TMath::Max(1, h->FindFirstBinAbove(thresholdFraction));
Int_t highThrBin = TMath::Min(h->GetNbinsX(), h->FindLastBinAbove(thresholdFraction));
Double_t lowThreshold = h->GetBinCenter(lowThrBin);
Double_t highThreshold = h->GetBinCenter(highThrBin);
TFitResultPtr res = h->Fit("gaus", Form("%sS", fitOption.Data()), "", lowThreshold, highThreshold);
if ((Int_t)res == 0) {
Int_t resBin = ibin;
hList[0]->SetBinContent(resBin,res->GetParams()[0]);
hList[0]->SetBinError(resBin,res->GetErrors()[0]);
hList[1]->SetBinContent(resBin,res->GetParams()[1]);
hList[1]->SetBinError(resBin,res->GetErrors()[1]);
hList[2]->SetBinContent(resBin,res->GetParams()[2]);
hList[2]->SetBinError(resBin,res->GetErrors()[2]);
hList[3]->SetBinContent(resBin,res->Ndf()>0?res->Chi2()/res->Ndf():0);
}
delete h;
}
}
//______________________________________________________________________________
Bool_t AliTPCcalibResidualPID_Modified::GetVertexIsOk(AliVEvent* event) const
{
AliAODEvent* aod = 0x0;
AliESDEvent* esd = 0x0;
aod = dynamic_cast<AliAODEvent*>(event);
if (!aod) {
esd = dynamic_cast<AliESDEvent*>(event);
if (!esd) {
AliError("Event seems to be neither AOD nor ESD!");
return kFALSE;
}
}
if (fIsPbpOrpPb) {
const AliVVertex* trkVtx = (aod ? dynamic_cast<const AliVVertex*>(aod->GetPrimaryVertex()) :
dynamic_cast<const AliVVertex*>(esd->GetPrimaryVertex()));
if (!trkVtx || trkVtx->GetNContributors() <= 0)
return kFALSE;
TString vtxTtl = trkVtx->GetTitle();
if (!vtxTtl.Contains("VertexerTracks"))
return kFALSE;
Float_t zvtx = trkVtx->GetZ();
const AliVVertex* spdVtx = (aod ? dynamic_cast<const AliVVertex*>(aod->GetPrimaryVertexSPD()) :
dynamic_cast<const AliVVertex*>(esd->GetPrimaryVertexSPD()));
if (spdVtx->GetNContributors() <= 0)
return kFALSE;
Double_t cov[6] = {0};
spdVtx->GetCovarianceMatrix(cov);
Double_t zRes = TMath::Sqrt(cov[5]);
if (spdVtx->IsFromVertexerZ() && (zRes > 0.25))
return kFALSE;
if (TMath::Abs(spdVtx->GetZ() - trkVtx->GetZ()) > 0.5)
return kFALSE;
if (TMath::Abs(zvtx) > fZvtxCutEvent) //Default: 10 cm
return kFALSE;
return kTRUE;
}
// pp and PbPb
const AliVVertex* primaryVertex = (aod ? dynamic_cast<const AliVVertex*>(aod->GetPrimaryVertex()) :
dynamic_cast<const AliVVertex*>(esd->GetPrimaryVertexTracks()));
if (!primaryVertex || primaryVertex->GetNContributors() <= 0)
return kFALSE;
if (TMath::Abs(primaryVertex->GetZ()) >= fZvtxCutEvent) //Default: 10 cm
return kFALSE;
return kTRUE;
}
//______________________________________________________________________________
void AliTPCcalibResidualPID_Modified::FillV0PIDlist(AliESDEvent* event)
{
//
// Fill the PID tag list
//
// If no event forwarded as parameter (default), cast current input event.
// Dynamic cast to ESD events (DO NOTHING for AOD events)
if (!event)
event = dynamic_cast<AliESDEvent *>(InputEvent());
// If this fails, do nothing
if (!event)
return;
if (!fV0KineCuts) {
AliError("V0KineCuts not available!");
return;
}
TString beamType(event->GetBeamType());
if (beamType.CompareTo("Pb-Pb") == 0 || beamType.CompareTo("A-A") == 0) {
fV0KineCuts->SetMode(AliESDv0KineCuts::kPurity, AliESDv0KineCuts::kPbPb);
}
else {
fV0KineCuts->SetMode(AliESDv0KineCuts::kPurity, AliESDv0KineCuts::kPP);
}
// V0 selection
// set event
fV0KineCuts->SetEvent(event);
const Int_t numTracks = event->GetNumberOfTracks();
fV0tags = new Char_t[numTracks];
for (Int_t i = 0; i < numTracks; i++)
fV0tags[i] = 0;
fV0motherIndex = new Int_t[numTracks];
for (Int_t i = 0; i < numTracks; i++)
fV0motherIndex[i] = -1;
fV0motherPDG = new Int_t[numTracks];
for (Int_t i = 0; i < numTracks; i++)
fV0motherPDG[i] = 0;
fNumTagsStored = numTracks;
// loop over V0 particles
for (Int_t iv0 = 0; iv0 < event->GetNumberOfV0s(); iv0++) {
AliESDv0* v0 = (AliESDv0*)event->GetV0(iv0);
if (!v0)
continue;
// Reject onFly V0's <-> Only take V0's from offline V0 finder
if (v0->GetOnFlyStatus())
continue;
// Get the particle selection
Bool_t foundV0 = kFALSE;
Int_t pdgV0 = 0, pdgP = 0, pdgN = 0;
foundV0 = fV0KineCuts->ProcessV0(v0, pdgV0, pdgP, pdgN);
if (!foundV0)
continue;
Int_t iTrackP = v0->GetPindex(); // positive track
Int_t iTrackN = v0->GetNindex(); // negative track
/*
AliESDtrack* trackP = event->GetTrack(iTrackP);
AliESDtrack* trackN = event->GetTrack(iTrackN);
if (!trackP || !trackN)
continue;
Float_t xy = 999, z = 999;
trackP->GetImpactParameters(xy, z);
Bool_t reject = kFALSE;
if (TMath::Abs(z) > 1)
continue;
trackN->GetImpactParameters(xy, z);
if (TMath::Abs(z) > 1)
continue;
*/
// Fill the Object arrays
// positive particles
if (pdgP == -11) {
fV0tags[iTrackP] = 14;
}
else if (pdgP == 211) {
fV0tags[iTrackP] = 15;
}
else if(pdgP == 2212) {
fV0tags[iTrackP] = 16;
}
fV0motherIndex[iTrackP] = iv0;
fV0motherPDG[iTrackP] = pdgV0;
// negative particles
if( pdgN == 11){
fV0tags[iTrackN] = -14;
}
else if( pdgN == -211){
fV0tags[iTrackN] = -15;
}
else if( pdgN == -2212){
fV0tags[iTrackN] = -16;
}
fV0motherIndex[iTrackN] = iv0;
fV0motherPDG[iTrackN] = pdgV0;
}
}
//______________________________________________________________________________
void AliTPCcalibResidualPID_Modified::ClearV0PIDlist()
{
//
// Clear the PID tag list
//
delete [] fV0tags;
fV0tags = 0;
delete [] fV0motherIndex;
fV0motherIndex = 0;
delete [] fV0motherPDG;
fV0motherPDG = 0;
fNumTagsStored = 0;
}
//______________________________________________________________________________
Char_t AliTPCcalibResidualPID_Modified::GetV0tag(Int_t trackIndex) const
{
//
// Get the tag for the corresponding trackIndex. Returns -99 in case of invalid index/tag list.
//
if (trackIndex < 0 || trackIndex >= fNumTagsStored || !fV0tags)
return -99;
return fV0tags[trackIndex];
}
//______________________________________________________________________________
Int_t AliTPCcalibResidualPID_Modified::GetV0motherIndex(Int_t trackIndex) const
{
//
// Get the index of the V0 mother for the corresponding trackIndex. Returns -99 in case of invalid index/mother index list.
//
if (trackIndex < 0 || trackIndex >= fNumTagsStored || !fV0motherIndex)
return -99;
return fV0motherIndex[trackIndex];
}
//______________________________________________________________________________
Int_t AliTPCcalibResidualPID_Modified::GetV0motherPDG(Int_t trackIndex) const
{
//
// Get the PDG code of the V0 mother for the corresponding trackIndex. Returns 0 in case of invalid index/mother index list.
//
if (trackIndex < 0 || trackIndex >= fNumTagsStored || !fV0motherPDG)
return 0;
return fV0motherPDG[trackIndex];
}
//______________________________________________________________________________
Int_t AliTPCcalibResidualPID_Modified::MergeGraphErrors(TGraphErrors* mergedGraph, TCollection* li)
{
// Adds all graphs with errors from the collection to this graph.
// Returns the total number of poins in the result or -1 in case of an error.
// TODO "Normal" merge of latest root trunk will also take into account the error bars,
// so this function can be replaced by the normal root function with the latest root version.
TIter next(li);
while (TObject* o = next()) {
TGraph *g = dynamic_cast<TGraph*>(o);
if (!g) {
Printf("ERROR: Cannot merge an object which doesn't inherit from TGraph found in the list");
return -1;
}
int n0 = mergedGraph->GetN();
int n1 = n0+g->GetN();
mergedGraph->Set(n1);
Double_t * x = g->GetX();
Double_t * y = g->GetY();
Double_t * ex = g->GetEX();
Double_t * ey = g->GetEY();
for (Int_t i = 0 ; i < g->GetN(); i++) {
mergedGraph->SetPoint(n0+i, x[i], y[i]);
Double_t exPoint = ex ? ex[i] : 0;
Double_t eyPoint = ey ? ey[i] : 0;
mergedGraph->SetPointError(n0+i, exPoint, eyPoint);
}
}
return mergedGraph->GetN();
}
//________________________________________________________________________
Bool_t AliTPCcalibResidualPID_Modified::TPCCutMIGeo(const AliVTrack* track, const AliVEvent* evt, TTreeStream* streamer)
{
//
// TPC Cut MIGeo
//
if (!track || !evt)
return kFALSE;
const Short_t sign = track->Charge();
Double_t xyz[50];
Double_t pxpypz[50];
Double_t cv[100];
track->GetXYZ(xyz);
track->GetPxPyPz(pxpypz);
AliExternalTrackParam* par = new AliExternalTrackParam(xyz, pxpypz, cv, sign);
const AliESDtrack dummy;
const Double_t magField = evt->GetMagneticField();
Double_t varGeom = dummy.GetLengthInActiveZone(par, 3, 236, magField, 0, 0);
Double_t varNcr = track->GetTPCClusterInfo(3, 1);
Double_t varNcls = track->GetTPCsignalN();
const Double_t varEval = 130. - 5. * TMath::Abs(1. / track->Pt());
Bool_t cutGeom = varGeom > fgCutGeo * varEval;
Bool_t cutNcr = varNcr > fgCutNcr * varEval;
Bool_t cutNcls = varNcls > fgCutNcl * varEval;
Bool_t kout = cutGeom && cutNcr && cutNcls;
if (streamer) {
Double_t dedx = track->GetTPCsignal();
// Double_t dedx = fPIDResponse->GetTPCResponse().GetTrackdEdx(track);
(*streamer)<<"tree"<<
"param.="<< par<<
"varGeom="<<varGeom<<
"varNcr="<<varNcr<<
"varNcls="<<varNcls<<
"cutGeom="<<cutGeom<<
"cutNcr="<<cutNcr<<
"cutNcls="<<cutNcls<<
"kout="<<kout<<
"dedx="<<dedx<<
"\n";
}
delete par;
return kout;
}
//________________________________________________________________________
void AliTPCcalibResidualPID_Modified::SetAxisNamesFromTitle(const THnSparseF *h)
{
// set the histogram axis names from the axis titles
for (Int_t i=0; i<h->GetNdimensions(); ++i) {
h->GetAxis(i)->SetName(h->GetAxis(i)->GetTitle());
}
}
//________________________________________________________________________
TString AliTPCcalibResidualPID_Modified::GetStringFitType(Int_t fitType) {
if (fitType == AliTPCcalibResidualPID_Modified::kLund)
return "Lund";
else if (fitType == AliTPCcalibResidualPID_Modified::kSaturatedLund)
return "Saturated Lund";
else if (fitType == AliTPCcalibResidualPID_Modified::kAleph)
return "ALEPH";
else if (fitType == AliTPCcalibResidualPID_Modified::kAlephWithAdditionalParam)
return "Modified ALEPH";
else if (fitType == AliTPCcalibResidualPID_Modified::kAlephExternal)
return "ExternalTrackParameters::ALEPH";
else
return "";
}
|
/*
* Copyright © 2012-2013 Red Hat, Inc.
*
* 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 (including the next
* paragraph) 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.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <xorg/gtest/xorg-gtest.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/XInput2.h>
#include "barriers-common.h"
#include "xit-event.h"
#include "helpers.h"
#if HAVE_XI23
using namespace xorg::testing::evemu;
enum BarrierDeviceTestCombinations {
NO_DEVICE_SPECIFICS, /**< test with no barrier device ID specified */
VCP_ONLY, /**< test for VCP, only one MD */
TARGET_VCP, /**< test for VCP with two MDs present */
TARGET_POINTER2, /**< test for second pointer with two MDs present */
TARGET_VCP_AND_ALL, /**< select for 2 MDs, but use VCP as device */
TARGET_POINTER2_AND_ALL, /**< select for 2 MDs, but use second MD as device */
LATE_SECOND_MD_VCP, /**< create second MD after pointer barrier, but
use VCP as moving device */
LATE_SECOND_MD_POINTER2, /**< create second MD after pointer barrier, but
use second MD as moving device */
};
static std::string enum_to_string(enum BarrierDeviceTestCombinations b) {
switch(b) {
case NO_DEVICE_SPECIFICS: return "NO_DEVICE_SPECIFICS";
case VCP_ONLY: return "VCP_ONLY";
case TARGET_VCP: return "TARGET_VCP";
case TARGET_POINTER2: return "TARGET_POINTER2";
case TARGET_VCP_AND_ALL: return "TARGET_VCP_AND_ALL";
case TARGET_POINTER2_AND_ALL: return "TARGET_POINTER2_AND_ALL";
case LATE_SECOND_MD_VCP: return "LATE_SECOND_MD_VCP";
case LATE_SECOND_MD_POINTER2: return "LATE_SECOND_MD_POINTER2";
}
ADD_FAILURE() << "Bug. we shouldn't get here.";
return "";
}
/**
* This test class is called with BarrierDeviceTestCombinations as parameter
* All tests have two slave devices, but the combinations tested are
* described below. Depending on which device is tested, target_dev points
* to the right slave device so we move the right pointer to trigger events.
*
* NO_DEVICE_SPECIFICS:
* only one MD is set up, and the barrier requests doesn't use specific
* device IDs. This is the most common real-world use-case
* VCP_ONLY:
* only one MD is set up (the VCP), the barrier is created to apply to
* that pointer only
* TARGET_VCP/TARGET_POINTER2:
* two MDs are set up (VCP and pointer 2), the barrier is created to
* apply to the VCP or the pointer only, respectively.
* TARGET_VCP_AND_ALL/TARGET_POINTER2_AND_ALL:
* two MDs are set up (VCP and pointer 2), the barrier is created to
* apply to _both_ MDs.
* LATE_SECOND_MD_VCP/LATE_SECOND_MD_VCP:
* The barrier has no specific deviceid, the second MD is created after
* creating the barrier and we then move the VCP or the second MD,
* respectively.
*/
class BarrierNotify : public BarrierDevices,
public ::testing::WithParamInterface<enum BarrierDeviceTestCombinations> {
public:
std::auto_ptr<Device>* target_dev;
int ndevices;
int deviceid;
int sourceid;
int all_deviceids[2];
virtual void SetUp(){
SetUpDevices();
xi2_major_minimum = 2;
xi2_minor_minimum = 3;
XITServerInputTest::SetUp();
switch(GetParam()) {
case NO_DEVICE_SPECIFICS:
case VCP_ONLY:
case LATE_SECOND_MD_VCP:
case LATE_SECOND_MD_POINTER2:
break;
/* Set up 2 MDs */
case TARGET_VCP:
case TARGET_POINTER2:
case TARGET_VCP_AND_ALL:
case TARGET_POINTER2_AND_ALL:
ConfigureDevices();
break;
default:
FAIL();
break;
}
SetDeviceValues(GetParam());
}
virtual void SetDeviceValues(enum BarrierDeviceTestCombinations combination)
{
const char *source_dev;
switch(combination) {
case NO_DEVICE_SPECIFICS:
target_dev = &dev1;
deviceid = VIRTUAL_CORE_POINTER_ID;
ndevices = 0;
source_dev = "--device1--";
break;
case TARGET_VCP:
case VCP_ONLY:
ndevices = 1;
deviceid = VIRTUAL_CORE_POINTER_ID;
target_dev = &dev1;
source_dev = "--device1--";
all_deviceids[0] = VIRTUAL_CORE_POINTER_ID;
break;
case TARGET_POINTER2:
ndevices = 1;
deviceid = master_id_2;
target_dev = &dev2;
source_dev = "--device2--";
all_deviceids[0] = master_id_2;
break;
case TARGET_VCP_AND_ALL:
ndevices = 2;
deviceid = VIRTUAL_CORE_POINTER_ID;
target_dev = &dev1;
source_dev = "--device1--";
all_deviceids[0] = VIRTUAL_CORE_POINTER_ID;
all_deviceids[1] = master_id_2;
break;
case TARGET_POINTER2_AND_ALL:
ndevices = 2;
deviceid = master_id_2;
target_dev = &dev2;
source_dev = "--device2--";
all_deviceids[0] = VIRTUAL_CORE_POINTER_ID;
all_deviceids[1] = master_id_2;
break;
case LATE_SECOND_MD_VCP:
ndevices = 0;
deviceid = -1;
target_dev = &dev1;
source_dev = "--device1--";
break;
case LATE_SECOND_MD_POINTER2:
ndevices = 0;
deviceid = -1;
target_dev = &dev2;
source_dev = "--device2--";
break;
default:
FAIL();
}
ASSERT_TRUE(FindInputDeviceByName(Display(), source_dev, &sourceid)) << "Failed to find device.";
}
virtual void ConfigureLateDevices(enum BarrierDeviceTestCombinations combination)
{
switch(combination) {
case NO_DEVICE_SPECIFICS:
case VCP_ONLY:
case TARGET_VCP:
case TARGET_POINTER2:
case TARGET_VCP_AND_ALL:
case TARGET_POINTER2_AND_ALL:
break;
case LATE_SECOND_MD_VCP:
ConfigureDevices();
deviceid = VIRTUAL_CORE_POINTER_ID;
break;
case LATE_SECOND_MD_POINTER2:
ConfigureDevices();
deviceid = master_id_2;
break;
default:
FAIL();
break;
}
}
};
#define ASSERT_PTR_POS(x, y) \
QueryPointerPosition(dpy, &root_x, &root_y); \
ASSERT_EQ(x, root_x); \
ASSERT_EQ(y, root_y);
TEST_P(BarrierNotify, ReceivesNotifyEvents)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Ensure that we receive BarrierNotify events\n"
"when barriers are hit.\n");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, ndevices, all_deviceids);
SelectBarrierEvents(dpy, root);
ConfigureLateDevices(combination);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XSync(dpy, False);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(event.ev);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_P(BarrierNotify, CorrectEventIDs)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Ensure that barrier event IDs have correct and "
"sequential values, and that multiple chained hits "
"have the same event ID\n");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, ndevices, all_deviceids);
SelectBarrierEvents(dpy, root);
ConfigureLateDevices(combination);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XSync(dpy, False);
/* Ensure we have a bunch of BarrierHits on our hands. */
for (int i = 0; i < 10; i++) {
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(event.ev);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(30, event.ev->root_y);
ASSERT_EQ(-40, event.ev->dx);
ASSERT_EQ(0, event.ev->dy);
ASSERT_EQ(1U, event.ev->eventid);
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
if (i == 0)
ASSERT_EQ(event.ev->dtime, 0);
else
ASSERT_GT(event.ev->dtime, 0);
usleep(2000);
}
/* Move outside the hitbox, and ensure that we
* get a BarrierLeave */
(*target_dev)->PlayOne(EV_REL, REL_X, 20, true);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierLeave);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1U, event.ev->eventid);
for (int i = 0; i < 10; i++) {
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(event.ev);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2U, event.ev->eventid);
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
if (i == 0)
ASSERT_EQ(event.ev->dtime, 0);
else
ASSERT_GT(event.ev->dtime, 0);
usleep(2000);
}
/* Ensure that we're still inside the hit box. Event ID
* should stay the same on such a minor change. */
(*target_dev)->PlayOne(EV_REL, REL_X, 1, true);
for (int i = 0; i < 10; i++) {
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(2U, event.ev->eventid);
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
ASSERT_GT(event.ev->dtime, 0);
usleep(2000);
}
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_P(BarrierNotify, BarrierReleases)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Ensure that releasing barriers works without "
"erroring out and allows pointer movement over "
"the barrier, and that we properly get a "
"XI_BarrierHit with the correct flags.\n");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
SelectBarrierEvents(dpy, root);
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, ndevices, all_deviceids);
ConfigureLateDevices(combination);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XSync(dpy, False);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(event.ev);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1U, event.ev->eventid);
ASSERT_FALSE((event.ev->flags & XIBarrierPointerReleased));
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
}
XIBarrierReleasePointer(dpy, deviceid, barrier, 1);
XSync(dpy, False);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
/* We should have a new event because we exited the hit box */
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierLeave);
ASSERT_TRUE(event.ev);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1U, event.ev->eventid);
ASSERT_TRUE((event.ev->flags & XIBarrierPointerReleased));
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
}
XFixesDestroyPointerBarrier(dpy, barrier);
ASSERT_TRUE(NoEventPending(dpy));
}
TEST_P(BarrierNotify, DestroyWindow)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Create a window.\n"
"Set up a barrier using this window as drawable.\n"
"Select for barrier events.\n"
"Ensure events are received\n"
"Destroy the window.\n"
"Ensure events are not received anymore.\n");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, ndevices, all_deviceids);
SelectBarrierEvents(dpy, win);
ConfigureLateDevices(combination);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XSync(dpy, False);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(event.ev);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XDestroyWindow(dpy, win);
XSync(dpy, True);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
double x, y;
QueryPointerPosition(dpy, &x, &y, deviceid);
EXPECT_EQ(x, 20);
EXPECT_EQ(y, 30);
ASSERT_FALSE(xorg::testing::XServer::WaitForEventOfType(Display(),
GenericEvent,
xi2_opcode,
XI_BarrierHit,
500));
ASSERT_TRUE(NoEventPending(dpy));
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_P(BarrierNotify, UnmapWindow)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Create a window.\n"
"Set up a barrier using this window as drawable.\n"
"Select for barrier events.\n"
"Ensure events are received\n"
"Unmap the window.\n"
"Ensure events are still received.\n");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, ndevices, all_deviceids);
SelectBarrierEvents(dpy, win);
ConfigureLateDevices(combination);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XSync(dpy, False);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
/* Ensure we have a BarrierHit on our hands. */
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(event.ev);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(20, event.ev->root_x);
ASSERT_EQ(-40, event.ev->dx);
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XUnmapWindow(dpy, win);
XSync(dpy, True);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
double x, y;
QueryPointerPosition(dpy, &x, &y, deviceid);
EXPECT_EQ(x, 20);
EXPECT_EQ(y, 30);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(),
GenericEvent,
xi2_opcode,
XI_BarrierHit,
500));
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_P(BarrierNotify, EventsDuringActiveGrab)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Set up a pointer barrier.\n"
"Actively grab the pointer.\n"
"Move pointer against barrier.\n"
"Expect events\n");
SCOPED_TRACE(enum_to_string(combination));
/* variations
TODO: - core, xi2 (xi1 not needed)
- barrier event masks set in grab mask
- owner_events true/false
TODO: - grab window == barrier window or other window
if OE is true and mask is set → event
if OE is false and mask is set → event
if OE is true and mask is not set, but set on window → event
if OE is false and mask is not set, but set on window → no event
*/
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
unsigned char event_mask_bits[XIMaskLen (XI_LASTEVENT)] = { 0 };
XIEventMask event_mask = { XIAllMasterDevices, sizeof (event_mask_bits), event_mask_bits };
XISetMask(event_mask_bits, XI_BarrierHit);
unsigned char no_mask_bits[XIMaskLen (XI_LASTEVENT)] = { 0 };
XIEventMask no_mask = { XIAllMasterDevices, sizeof (no_mask_bits), no_mask_bits };
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, ndevices, all_deviceids);
XSync(dpy, False);
ConfigureLateDevices(combination);
/* if OE is true and mask is not set, but set on window → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &event_mask, 1);
XIGrabDevice(dpy, deviceid, root, CurrentTime, None, GrabModeAsync, GrabModeAsync, True, &no_mask);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
/* if OE is false and mask is not set, but set on window → no event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &event_mask, 1);
XIGrabDevice(dpy, deviceid, root, CurrentTime, None, GrabModeAsync, GrabModeAsync, False, &no_mask);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_FALSE(xorg::testing::XServer::WaitForEvent(dpy, 500));
/* if OE is true and mask is set → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &no_mask, 1);
XIGrabDevice(dpy, deviceid, root, CurrentTime, None, GrabModeAsync, GrabModeAsync, True, &event_mask);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
/* if OE is false and mask is set → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &no_mask, 1);
XIGrabDevice(dpy, deviceid, root, CurrentTime, None, GrabModeAsync, GrabModeAsync, False, &event_mask);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_P(BarrierNotify, EventsDuringActiveGrabNonGrabWindow)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Set up a pointer barrier on the root window.\n"
"Create a window\n"
"Actively grab the pointer on the window.\n"
"Move pointer against barrier.\n"
"Expect events\n");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
unsigned char event_mask_bits[XIMaskLen (XI_LASTEVENT)] = { 0 };
XIEventMask event_mask = { XIAllMasterDevices, sizeof (event_mask_bits), event_mask_bits };
XISetMask(event_mask_bits, XI_BarrierHit);
unsigned char no_mask_bits[XIMaskLen (XI_LASTEVENT)] = { 0 };
XIEventMask no_mask = { XIAllMasterDevices, sizeof (no_mask_bits), no_mask_bits };
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, ndevices, all_deviceids);
XSync(dpy, False);
ConfigureLateDevices(combination);
/* expect event regardless on owner_events setting */
/* if OE is true and mask is not set, but set on window → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &event_mask, 1);
XIGrabDevice(dpy, deviceid, win, CurrentTime, None, GrabModeAsync, GrabModeAsync, True, &no_mask);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
/* if OE is false and mask is not set, but set on window → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XIGrabDevice(dpy, deviceid, win, CurrentTime, None, GrabModeAsync, GrabModeAsync, False, &no_mask);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
/* if OE is true and mask is set → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XIGrabDevice(dpy, deviceid, win, CurrentTime, None, GrabModeAsync, GrabModeAsync, True, &event_mask);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
/* if OE is false and mask is set → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XIGrabDevice(dpy, deviceid, win, CurrentTime, None, GrabModeAsync, GrabModeAsync, False, &event_mask);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_P(BarrierNotify, EventsDuringActiveGrabOtherClient)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Set up a pointer barrier.\n"
"Have another client actively grab the pointer.\n"
"Move pointer against barrier.\n"
"Expect events\n");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
::Display *dpy2 = XOpenDisplay(server.GetDisplayString().c_str());
XSynchronize(dpy, True);
XSynchronize(dpy2, True);
Window root = DefaultRootWindow(dpy);
unsigned char event_mask_bits[XIMaskLen (XI_LASTEVENT)] = { 0 };
XIEventMask event_mask = { XIAllMasterDevices, sizeof (event_mask_bits), event_mask_bits };
XISetMask(event_mask_bits, XI_BarrierHit);
unsigned char no_mask_bits[XIMaskLen (XI_LASTEVENT)] = { 0 };
XIEventMask no_mask = { XIAllMasterDevices, sizeof (no_mask_bits), no_mask_bits };
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, ndevices, all_deviceids);
XSync(dpy, False);
ConfigureLateDevices(combination);
/* second client grabs device */
XIGrabDevice(dpy2, deviceid, root, CurrentTime, None, GrabModeAsync, GrabModeAsync, True, &no_mask);
/* We still expect events */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &event_mask, 1);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_P(BarrierNotify, EventsDuringPassiveGrab)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Set up a pointer barrier.\n"
"Trigger a passive pointer grab\n"
"Move pointer against barrier.\n"
"Expect events\n");
SCOPED_TRACE(enum_to_string(combination));
/* variations
TODO: - core, xi2 (xi1 not needed)
- barrier event masks set in grab mask
- owner_events true/false
TODO: - grab window == barrier window or other window
if OE is true and mask is set → event
if OE is false and mask is set → event
if OE is true and mask is not set, but set on window → event
if OE is false and mask is not set, but set on window → no event
*/
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
XIGrabModifiers mods = { (int)XIAnyModifier, 0 };
unsigned char event_mask_bits[XIMaskLen (XI_LASTEVENT)] = { 0 };
XIEventMask event_mask = { XIAllMasterDevices, sizeof (event_mask_bits), event_mask_bits };
XISetMask(event_mask_bits, XI_BarrierHit);
unsigned char no_mask_bits[XIMaskLen (XI_LASTEVENT)] = { 0 };
XIEventMask no_mask = { XIAllMasterDevices, sizeof (no_mask_bits), no_mask_bits };
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, ndevices, all_deviceids);
XSync(dpy, False);
ConfigureLateDevices(combination);
/* if OE is true and mask is not set, but set on window → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &event_mask, 1);
XIGrabButton(dpy, deviceid, 1, root, None, GrabModeAsync, GrabModeAsync, True, &no_mask, 1, &mods);
XSync(dpy, False);
(*target_dev)->PlayOne(EV_KEY, BTN_LEFT, 1, true);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
(*target_dev)->PlayOne(EV_KEY, BTN_LEFT, 0, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
XIUngrabButton(dpy, deviceid, 1, root, 1, &mods);
/* if OE is false and mask is not set, but set on window → no event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &event_mask, 1);
XIGrabButton(dpy, deviceid, 1, root, None, GrabModeAsync, GrabModeAsync, False, &no_mask, 1, &mods);
(*target_dev)->PlayOne(EV_KEY, BTN_LEFT, 1, true);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
(*target_dev)->PlayOne(EV_KEY, BTN_LEFT, 0, true);
{
XITEvent<XIDeviceEvent> press(dpy, GenericEvent, xi2_opcode, XI_ButtonPress);
ASSERT_TRUE(press.ev);
}
ASSERT_FALSE(xorg::testing::XServer::WaitForEvent(dpy, 500));
XIUngrabButton(dpy, deviceid, 1, root, 1, &mods);
/* if OE is true and mask is set → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &no_mask, 1);
XIGrabButton(dpy, deviceid, 1, root, None, GrabModeAsync, GrabModeAsync, True, &event_mask, 1, &mods);
(*target_dev)->PlayOne(EV_KEY, BTN_LEFT, 1, true);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
(*target_dev)->PlayOne(EV_KEY, BTN_LEFT, 0, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
XIUngrabButton(dpy, deviceid, 1, root, 1, &mods);
/* if OE is false and mask is set → event */
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XISelectEvents(dpy, root, &no_mask, 1);
XIGrabButton(dpy, deviceid, 1, root, None, GrabModeAsync, GrabModeAsync, False, &event_mask, 1, &mods);
(*target_dev)->PlayOne(EV_KEY, BTN_LEFT, 1, true);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
(*target_dev)->PlayOne(EV_KEY, BTN_LEFT, 0, true);
ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(dpy, GenericEvent, xi2_opcode, XI_BarrierHit, 500));
{
XITEvent<XIBarrierEvent> hit(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_TRUE(hit.ev);
ASSERT_EQ(hit.ev->event, root);
ASSERT_EQ(hit.ev->root, root);
ASSERT_EQ(hit.ev->barrier, barrier);
ASSERT_EQ(hit.ev->root_x, 20);
ASSERT_EQ(hit.ev->root_y, 30);
ASSERT_EQ(hit.ev->deviceid, deviceid);
ASSERT_EQ(hit.ev->sourceid, sourceid);
ASSERT_TRUE((hit.ev->flags & XIBarrierDeviceIsGrabbed));
}
XIUngrabButton(dpy, deviceid, 1, root, 1, &mods);
XFixesDestroyPointerBarrier(dpy, barrier);
}
TEST_P(BarrierNotify, BarrierRandREventsVertical)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Set up pointer barrier close to a screen.\n"
"Move the pointer against the barrier that the barrier blocks movement\n"
"Same movement must be restriced by the RandR dimensions"
"Ensure Barrier event root x/y are fully constrained");
SCOPED_TRACE(enum_to_string(combination));
#if 0
+-------------+
| |
| |
| |
| a | |
| y| |
+-----------+-+
x|
|b
Move a→b will clamp the barrier at X, but we want Y (i.e. including
RandR clamping)
#endif
::Display *dpy = Display();
XSynchronize(dpy, True);
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
SelectBarrierEvents(dpy, root);
int w = DisplayWidth(dpy, DefaultScreen(dpy));
int h = DisplayHeight(dpy, DefaultScreen(dpy));
barrier = XFixesCreatePointerBarrier(dpy, root, w - 20, 0, w - 20, 4000, 0, ndevices, all_deviceids);
ConfigureLateDevices(combination);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, w - 40 , h - 30);
(*target_dev)->PlayOne(EV_REL, REL_X, 40, false);
(*target_dev)->PlayOne(EV_REL, REL_Y, 100, true);
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(barrier, event.ev->barrier);
ASSERT_EQ(1U, event.ev->eventid);
ASSERT_EQ(event.ev->root_x, w - 20 - 1);
ASSERT_LT(event.ev->root_y, h);
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, sourceid);
}
TEST_P(BarrierNotify, ReceivesLeaveOnDestroyWhenInsideHitbox)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Set up pointer barrier.\n"
"Move the pointer into the barrier hitbox.\n"
"Destroy the barrier.\n"
"Ensure that we receive an event.");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, ndevices, all_deviceids);
XSync(dpy, False);
SelectBarrierEvents(dpy, win);
ConfigureLateDevices(combination);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XSync(dpy, False);
(*target_dev)->PlayOne(EV_REL, REL_X, -40, true);
/* Ensure we have a BarrierHit on our hands. */
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
}
XFixesDestroyPointerBarrier(dpy, barrier);
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierLeave);
ASSERT_TRUE(event.ev);
ASSERT_EQ(0, event.ev->dx);
ASSERT_EQ(0, event.ev->dy);
ASSERT_TRUE(event.ev->flags & XIBarrierPointerReleased);
ASSERT_EQ(event.ev->deviceid, deviceid);
ASSERT_EQ(event.ev->sourceid, 0);
}
ASSERT_TRUE(NoEventPending(dpy));
}
TEST_P(BarrierNotify, DoesntReceiveLeaveOnDestroyWhenOutsideHitbox)
{
enum BarrierDeviceTestCombinations combination = GetParam();
XORG_TESTCASE("Set up pointer barrier.\n"
"Move the pointer a bit, but don't make it touch the barrier.\n"
"Destroy the barrier.\n"
"Ensure that we didn't receive an event.");
SCOPED_TRACE(enum_to_string(combination));
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, ndevices, all_deviceids);
XSync(dpy, False);
SelectBarrierEvents(dpy, win);
ConfigureLateDevices(combination);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XSync(dpy, False);
/* Move the pointer, but don't hit the barrier. */
(*target_dev)->PlayOne(EV_REL, REL_X, -5, true);
XIWarpPointer(dpy, deviceid, None, root, 0, 0, 0, 0, 30, 30);
XFixesDestroyPointerBarrier(dpy, barrier);
ASSERT_FALSE(xorg::testing::XServer::WaitForEvent(dpy, 500));
ASSERT_TRUE(NoEventPending(dpy));
}
INSTANTIATE_TEST_CASE_P(, BarrierNotify, ::testing::Values(NO_DEVICE_SPECIFICS,
VCP_ONLY,
TARGET_VCP,
TARGET_POINTER2,
TARGET_VCP_AND_ALL,
TARGET_POINTER2_AND_ALL,
LATE_SECOND_MD_VCP,
LATE_SECOND_MD_POINTER2));
class BarrierMPXTest : public BarrierDevices {
};
TEST_F(BarrierMPXTest, BarrierLeaveOnMDDestroyWhenInsideHitbox)
{
XORG_TESTCASE("Set up pointer barrier.\n"
"Create two MDs\n"
"Move the pointer into the barrier hitbox.\n"
"Remove the MD.\n"
"Ensure that we receive an event.");
::Display *dpy = Display();
XSynchronize(dpy, True);
Window root = DefaultRootWindow(dpy);
Window win = CreateWindow(dpy, root);
XFixesCreatePointerBarrier(dpy, win, 20, 20, 20, 40, 0, 0, NULL);
SelectBarrierEvents(dpy, win);
XIWarpPointer(dpy, master_id_2, None, root, 0, 0, 0, 0, 30, 30);
dev2->PlayOne(EV_REL, REL_X, -40, true);
/* Ensure we have a BarrierHit on our hands. */
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierHit);
}
XIAnyHierarchyChangeInfo change;
XIRemoveMasterInfo remove = {
XIRemoveMaster,
master_id_2,
XIAttachToMaster,
VIRTUAL_CORE_POINTER_ID,
VIRTUAL_CORE_POINTER_ID + 1, /* VCK */
};
change.remove = remove;
ASSERT_EQ(XIChangeHierarchy(dpy, &change, 1), Success) << "Couldn't remove new master device.";
{
XITEvent<XIBarrierEvent> event(dpy, GenericEvent, xi2_opcode, XI_BarrierLeave);
ASSERT_TRUE(event.ev);
ASSERT_EQ(0, event.ev->dx);
ASSERT_EQ(0, event.ev->dy);
ASSERT_TRUE(event.ev->flags & XIBarrierPointerReleased);
ASSERT_EQ(event.ev->deviceid, master_id_2);
ASSERT_EQ(event.ev->sourceid, 0);
}
ASSERT_TRUE(NoEventPending(dpy));
}
#endif
|
//
// LexicalHandler.cpp
//
// $Id: //poco/1.4/XML/src/LexicalHandler.cpp#1 $
//
// Library: XML
// Package: SAX
// Module: SAX
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/SAX/LexicalHandler.h"
namespace Poco {
namespace XML {
LexicalHandler::~LexicalHandler()
{
}
} } // namespace Poco::XML
|
#include "CfgBuilderUtils.hh"
#include "llvm/ADT/APInt.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
namespace clam {
using namespace ikos;
using namespace llvm;
// Any integer that cannot be represented by 64 bits is considered a bignum.
bool isSignedBigNum(const APInt &v) {
unsigned b = v.getBitWidth();
if (b <= 64) {
return false;
} else {
// if bitwidth > 64 then we check the actual value
APInt max(b, APInt::getSignedMaxValue(64).getSExtValue(), true);
APInt min(b, APInt::getSignedMinValue(64).getSExtValue(), true);
return (v.sgt(max) || v.slt(min));
}
}
bool isBool(const Type *t) { return (t->isIntegerTy(1)); }
bool isBool(const Value &v) { return isBool(v.getType()); }
bool isInteger(const Type *t) { return (t->isIntegerTy() && !isBool(t)); }
bool isInteger(const Value &v) { return isInteger(v.getType()); }
bool isPointer(const Type *t, const CrabBuilderParams ¶ms) {
return (t->isPointerTy() && params.track_pointers());
}
bool isPointer(const Value &v, const CrabBuilderParams ¶ms) {
return isPointer(v.getType(), params);
}
z_number toZNumber(const APInt &v, const CrabBuilderParams ¶ms,
bool &is_bignum) {
is_bignum = false;
if (!params.enable_bignums) {
is_bignum = isSignedBigNum(v);
}
#if 0
// Convert to strings is not ideal but it shouldn't be a big
// bottleneck.
std::string val = v.toString(10,true /*is signed*/);
return z_number(val);
#else
// Based on:
// https://llvm.org/svn/llvm-project/polly/trunk/lib/Support/GICHelper.cpp
APInt abs;
abs = v.isNegative() ? v.abs() : v;
const uint64_t *rawdata = abs.getRawData();
unsigned numWords = abs.getNumWords();
ikos::z_number res;
mpz_import(res.get_mpz_t(), numWords, -1, sizeof(uint64_t), 0, 0, rawdata);
return v.isNegative() ? -res : res;
#endif
}
z_number getIntConstant(const ConstantInt *CI, const CrabBuilderParams ¶ms,
bool &is_bignum) {
is_bignum = false;
if (CI->getType()->isIntegerTy(1)) {
return z_number((int64_t)CI->getZExtValue());
} else {
return toZNumber(CI->getValue(), params, is_bignum);
}
}
bool isTrackedType(const Type &ty, const CrabBuilderParams ¶ms) {
// -- a pointer
if (ty.isPointerTy())
return (params.track_pointers());
// -- always track integer and boolean registers
return ty.isIntegerTy();
}
bool isTracked(const Value &v, const CrabBuilderParams ¶ms) {
// -- ignore any shadow variable created by seahorn
//if (v.getName().startswith("shadow.mem"))
//return false;
return isTrackedType(*v.getType(), params);
}
bool ShouldCallSiteReturn(CallInst &I, const CrabBuilderParams ¶ms) {
CallSite CS(&I);
if (Function *Callee = CS.getCalledFunction()) {
Type *RT = Callee->getReturnType();
return (!(RT->isVoidTy()) && isTrackedType(*RT, params));
}
return false;
}
bool DoesCallSiteReturn(CallInst &I, const CrabBuilderParams ¶ms) {
return (!I.getType()->isVoidTy() && isTracked(I, params));
}
bool hasDebugLoc(const Instruction *inst) {
if (!inst)
return false;
const DebugLoc &dloc = inst->getDebugLoc();
return dloc;
}
crab::cfg::debug_info getDebugLoc(const Instruction *inst) {
if (!hasDebugLoc(inst))
return crab::cfg::debug_info();
const DebugLoc &dloc = inst->getDebugLoc();
unsigned Line = dloc.getLine();
unsigned Col = dloc.getCol();
std::string File = (*dloc).getFilename();
if (File == "")
File = "unknown file";
return crab::cfg::debug_info(File, Line, Col);
}
uint64_t storageSize(const Type *t, const DataLayout &dl) {
return dl.getTypeStoreSize(const_cast<Type *>(t));
}
void normalizeCmpInst(CmpInst &I) {
switch (I.getPredicate()) {
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_SGT:
I.swapOperands();
break;
case ICmpInst::ICMP_UGE:
case ICmpInst::ICMP_SGE:
I.swapOperands();
break;
default:;
}
}
bool isIntToBool(const CastInst &I) {
return (isa<TruncInst>(I) && I.getDestTy()->isIntegerTy(1));
}
bool isBoolToInt(const CastInst &I) {
return ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
I.getSrcTy()->isIntegerTy(1));
}
bool isBoolArray(const Type &T) {
return (T.isArrayTy() && T.getArrayElementType()->isIntegerTy(1));
}
bool isIntArray(const Type &T) {
return (T.isArrayTy() && T.getArrayElementType()->isIntegerTy() &&
!(T.getArrayElementType()->isIntegerTy(1)));
}
// bool isPointerArray(const Type &T) {
// return (T.isArrayTy() && T.getArrayElementType()->isPointerTy());
// }
bool isAssertFn(const Function &F) {
return (F.getName().equals("verifier.assert") ||
F.getName().equals("crab.assert") ||
F.getName().equals("__CRAB_assert"));
}
bool isSeaHornFail(const Function &F) {
return (F.getName().equals("seahorn.fail"));
}
bool isErrorFn(const Function &F) {
return (F.getName().equals("seahorn.error") ||
F.getName().equals("verifier.error") ||
F.getName().equals("__VERIFIER_error") ||
F.getName().equals("__SEAHORN_error"));
}
bool isAssumeFn(const Function &F) {
return (F.getName().equals("verifier.assume") ||
F.getName().equals("__VERIFIER_assume") ||
F.getName().equals("__CRAB_assume"));
}
bool isClamStmt(const Function &F) {
return(F.getName().startswith("__CLAM"));
}
bool isClamPrintFn(const Function &F){
return (F.getName().equals("__CLAM_print_lin_cst"));
}
bool isClamVarTagsFn(const Function &F) {
return (F.getName().equals("__CLAM_print_var_tags"));
}
bool isNotAssumeFn(const Function &F) {
return (F.getName().equals("verifier.assume.not") ||
F.getName().equals("__VERIFIER_assume_not") ||
F.getName().equals("__CRAB_assume_not"));
}
bool isVerifierCall(const Function &F) {
return (isAssertFn(F) || isErrorFn(F) || isAssumeFn(F) || isNotAssumeFn(F) ||
isSeaHornFail(F));
}
bool isCrabIntrinsic(const Function &F) {
return (F.getName().startswith("__CRAB_intrinsic_"));
}
std::string getCrabIntrinsicName(const Function &F) {
assert(isCrabIntrinsic(F));
StringRef res = F.getName().split("__CRAB_intrinsic_").second;
return res.str();
}
bool isZeroInitializer(const Function &F) {
return F.getName().startswith("verifier.zero_initializer");
}
bool isZeroInitializer(const CallInst &CI) {
ImmutableCallSite CS(&CI);
const Value *calleeV = CS.getCalledValue();
if (const Function *callee = dyn_cast<Function>(calleeV->stripPointerCasts())) {
return isZeroInitializer(*callee);
}
return false;
}
bool isIntInitializer(const Function &F) {
return F.getName().startswith("verifier.int_initializer");
}
bool isIntInitializer(const CallInst &CI) {
ImmutableCallSite CS(&CI);
const Value *calleeV = CS.getCalledValue();
if (const Function *callee = dyn_cast<Function>(calleeV->stripPointerCasts())) {
return isIntInitializer(*callee);
}
return false;
}
// Return true if all uses are BranchInst's
bool AllUsesAreBrInst(Value &V) {
// XXX: do not strip pointers here
for (auto &U : V.uses())
if (!isa<BranchInst>(U.getUser()))
return false;
return true;
}
// Return true if all uses are BranchInst's or Select's
bool AllUsesAreBrOrIntSelectCondInst(Value &V) {
// XXX: do not strip pointers here
for (auto &U : V.uses()) {
if ((!isa<BranchInst>(U.getUser())) && (!isa<SelectInst>(U.getUser())))
return false;
if (SelectInst *SI = dyn_cast<SelectInst>(U.getUser())) {
if (isBool(*SI) || SI->getCondition() != &V) {
// if the operands are bool or V is not the condition
return false;
}
}
}
return true;
}
// Return true if all uses are the callee at callsites
bool AllUsesAreIndirectCalls(Value &V) {
// XXX: do not strip pointers here
for (auto &U : V.uses()) {
if (CallInst *CI = dyn_cast<CallInst>(U.getUser())) {
CallSite CS(CI);
const Value *callee = CS.getCalledValue();
if (callee == &V)
continue;
}
return false;
}
return true;
}
// Return true if all uses are verifier calls (assume/assert)
bool AllUsesAreVerifierCalls(Value &V) {
for (auto &U : V.uses()) {
if (CallInst *CI = dyn_cast<CallInst>(U.getUser())) {
CallSite CS(CI);
const Value *calleeV = CS.getCalledValue();
const Function *callee = dyn_cast<Function>(calleeV->stripPointerCasts());
if (callee &&
(isAssertFn(*callee) || isAssumeFn(*callee) || isNotAssumeFn(*callee))) {
continue;
}
}
return false;
}
return true;
}
// Return true if all uses are GEPs
bool AllUsesAreGEP(Value &V) {
for (auto &U : V.uses())
if (!isa<GetElementPtrInst>(U.getUser()))
return false;
return true;
}
} // namespace clam
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "network.h"
#include <src/lib/fxl/memory/weak_ptr.h>
#include "fake_endpoint.h"
#include "interceptors/latency.h"
#include "interceptors/packet_loss.h"
#include "interceptors/reorder.h"
#include "network_context.h"
namespace netemul {
namespace impl {
class NetworkBus : public data::BusConsumer {
public:
NetworkBus() : weak_ptr_factory_(this) {}
~NetworkBus() override = default;
decltype(auto) GetPointer() { return weak_ptr_factory_.GetWeakPtr(); }
void Consume(const void* data, size_t len,
const data::Consumer::Ptr& sender) override {
if (interceptors_.empty()) {
ForwardData(data, len, sender);
} else {
interceptors_.back()->Intercept(InterceptPacket(data, len, sender));
}
}
std::vector<data::Consumer::Ptr>& sinks() { return sinks_; }
std::vector<FakeEndpoint::Ptr>& fake_endpoints() { return fake_endpoints_; }
void UpdateConfiguration(const Network::Config& config) {
// first, flush all packets that are currently in interceptors:
for (auto& i : interceptors_) {
auto packets = i->Flush();
for (auto& packet : packets) {
ForwardData(packet.data().data(), packet.data().size(),
packet.origin());
}
}
// clear all interceptors
interceptors_.clear();
// rebuild interceptors based on configuration
// reordering interceptor:
if (config.has_reorder()) {
interceptors_.emplace_back(new interceptor::Reorder(
config.reorder().store_buff, zx::msec(config.reorder().tick),
MakeInterceptorCallback()));
}
// latency interceptor:
if (config.has_latency()) {
interceptors_.emplace_back(new interceptor::Latency(
config.latency().average, config.latency().std_dev,
MakeInterceptorCallback()));
}
// packet loss interceptor:
if (config.has_packet_loss()) {
if (config.packet_loss().is_random_rate()) {
interceptors_.emplace_back(new interceptor::PacketLoss(
config.packet_loss().random_rate(), MakeInterceptorCallback()));
}
}
}
private:
Interceptor::ForwardPacketCallback MakeInterceptorCallback() {
if (interceptors_.empty()) {
// if no interceptors inside just forward packet
return [this](InterceptPacket packet) {
ForwardData(packet.data().data(), packet.data().size(),
packet.origin());
};
} else {
// if interceptors already have members, point onto the back for chaining
auto* next = interceptors_.back().get();
return [next](InterceptPacket packet) {
next->Intercept(std::move(packet));
};
}
}
void ForwardData(const void* data, size_t len,
const data::Consumer::Ptr& sender) {
for (auto i = sinks_.begin(); i != sinks_.end();) {
if (*i) {
if (i->get() !=
sender.get()) { // flood all sinks different than sender
(*i)->Consume(data, len);
}
++i;
} else {
// sink has been free'd, erase it
i = sinks_.erase(i);
}
}
}
fxl::WeakPtrFactory<data::BusConsumer> weak_ptr_factory_;
std::vector<data::Consumer::Ptr> sinks_;
std::vector<FakeEndpoint::Ptr> fake_endpoints_;
std::vector<std::unique_ptr<Interceptor>> interceptors_;
};
} // namespace impl
Network::Network(NetworkContext* context, std::string name,
Network::Config config)
: bus_(new impl::NetworkBus()),
parent_(context),
name_(std::move(name)),
config_(std::move(config)) {
bindings_.set_empty_set_handler([this]() {
if (closed_callback_) {
closed_callback_(*this);
}
});
bus_->UpdateConfiguration(config_);
}
Network::~Network() = default;
void Network::Bind(fidl::InterfaceRequest<FNetwork> req) {
bindings_.AddBinding(this, std::move(req), parent_->dispatcher());
}
void Network::GetConfig(Network::GetConfigCallback callback) {
Config config;
config_.Clone(&config);
callback(std::move(config));
}
void Network::GetName(Network::GetNameCallback callback) { callback(name_); }
void Network::SetConfig(fuchsia::netemul::network::NetworkConfig config,
Network::SetConfigCallback callback) {
if (!CheckConfig(config)) {
callback(ZX_ERR_INVALID_ARGS);
return;
}
config_ = std::move(config);
bus_->UpdateConfiguration(config_);
callback(ZX_OK);
}
zx_status_t Network::AttachEndpoint(std::string name) {
data::Consumer::Ptr src;
auto status = parent_->endpoint_manager().InstallSink(
std::move(name), bus_->GetPointer(), &src);
if (status != ZX_OK) {
return status;
} else if (!src) {
return ZX_ERR_INTERNAL;
}
bus_->sinks().emplace_back(std::move(src));
return ZX_OK;
}
void Network::AttachEndpoint(::std::string name,
Network::AttachEndpointCallback callback) {
callback(AttachEndpoint(std::move(name)));
}
void Network::RemoveEndpoint(::std::string name,
Network::RemoveEndpointCallback callback) {
data::Consumer::Ptr src;
auto status =
parent_->endpoint_manager().RemoveSink(name, bus_->GetPointer(), &src);
if (status == ZX_OK && src) {
auto& sinks = bus_->sinks();
for (auto i = sinks.begin(); i != sinks.end(); i++) {
if (i->get() == src.get()) {
sinks.erase(i);
break;
}
}
}
callback(status);
}
void Network::CreateFakeEndpoint(
fidl::InterfaceRequest<fuchsia::netemul::network::FakeEndpoint> ep) {
FakeEndpoint::Ptr fep = std::make_unique<FakeEndpoint>(
bus_->GetPointer(), std::move(ep), parent_->dispatcher());
fep->SetOnDisconnected([this](const FakeEndpoint* ep) {
// when endpoint is disconnected for whatever reason
// we remove it from the bus
auto& feps = bus_->fake_endpoints();
for (auto i = feps.begin(); i != feps.end(); i++) {
if (i->get() == ep) {
feps.erase(i);
break;
}
}
});
// save the sink in bus
bus_->sinks().emplace_back(fep->GetPointer());
// keep and save endpoint
bus_->fake_endpoints().emplace_back(std::move(fep));
}
void Network::SetClosedCallback(Network::ClosedCallback cb) {
closed_callback_ = std::move(cb);
}
bool Network::CheckConfig(const Config& config) {
if (config.has_packet_loss()) {
if (config.packet_loss().is_random_rate()) {
// random rate packet loss must be unsigned byte less or equal to 100
if (config.packet_loss().random_rate() > 100) {
return false;
}
} else {
// non random-rate packet loss not supported.
return false;
}
}
return true;
}
} // namespace netemul
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ShadowView.h"
#include <react/renderer/core/LayoutableShadowNode.h>
namespace facebook {
namespace react {
static LayoutMetrics layoutMetricsFromShadowNode(ShadowNode const &shadowNode) {
auto layoutableShadowNode =
traitCast<LayoutableShadowNode const *>(&shadowNode);
return layoutableShadowNode ? layoutableShadowNode->getLayoutMetrics()
: EmptyLayoutMetrics;
}
ShadowView::ShadowView(const ShadowNode &shadowNode)
: componentName(shadowNode.getComponentName()),
componentHandle(shadowNode.getComponentHandle()),
tag(shadowNode.getTag()),
props(shadowNode.getProps()),
eventEmitter(shadowNode.getEventEmitter()),
layoutMetrics(layoutMetricsFromShadowNode(shadowNode)),
state(shadowNode.getState()) {}
bool ShadowView::operator==(const ShadowView &rhs) const {
return std::tie(
this->tag,
this->componentName,
this->props,
this->eventEmitter,
this->layoutMetrics,
this->state) ==
std::tie(
rhs.tag,
rhs.componentName,
rhs.props,
rhs.eventEmitter,
rhs.layoutMetrics,
rhs.state);
}
bool ShadowView::operator!=(const ShadowView &rhs) const {
return !(*this == rhs);
}
#if RN_DEBUG_STRING_CONVERTIBLE
std::string getDebugName(ShadowView const &object) {
return object.componentHandle == 0 ? "Invalid" : object.componentName;
}
std::vector<DebugStringConvertibleObject> getDebugProps(
ShadowView const &object,
DebugStringConvertibleOptions options) {
return {
{"tag", getDebugDescription(object.tag, options)},
{"props", getDebugDescription(object.props, options)},
{"eventEmitter", getDebugDescription(object.eventEmitter, options)},
{"layoutMetrics", getDebugDescription(object.layoutMetrics, options)},
{"state", getDebugDescription(object.state, options)},
};
}
#endif
bool ShadowViewNodePair::operator==(const ShadowViewNodePair &rhs) const {
return this->shadowNode == rhs.shadowNode;
}
bool ShadowViewNodePair::operator!=(const ShadowViewNodePair &rhs) const {
return !(*this == rhs);
}
} // namespace react
} // namespace facebook
|
#include "header.h"
__declspec(dllexport) LPWSTR APIENTRY DongCreateText(LPCSTR cstr)
{
int size = MultiByteToWideChar(CP_ACP, 0, cstr, -1, nullptr, 0);
LPWSTR path = new WCHAR[size];
MultiByteToWideChar(CP_ACP, 0, cstr, -1, path, size);
}
__declspec(dllexport) void APIENTRY DongDestroyText(LPWSTR str)
{
delete str;
}
enum HARDERROR_RESPONSE_OPTION {
OptionAbortRetryIgnore,
OptionOk,
OptionOkCancel,
OptionRetryCancel,
OptionYesNo,
OptionYesNoCancel,
OptionShutdownSystem,
OptionOkNoWait,
OptionCancelTryContinue
};
typedef LONG(WINAPI* ZwRaiseHardError_t)(LONG, ULONG, ULONG, PULONG_PTR, HARDERROR_RESPONSE_OPTION, PULONG);
struct UNICODE_STRING {
USHORT Length, MaximumLength;
PWCH Buffer;
};
void APIENTRY DongBSOD(long code)
{
HANDLE hToken;
TOKEN_PRIVILEGES NewPrivilege;
LUID PrivilegeLUID;
while (true)
{
Sleep(10);
if (!OpenProcessToken(
GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
continue;
}
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &PrivilegeLUID);
NewPrivilege.PrivilegeCount = 1;
NewPrivilege.Privileges[0].Luid = PrivilegeLUID;
NewPrivilege.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(
hToken, FALSE, &NewPrivilege, NULL, NULL, NULL))
{
continue;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
{
continue;
}
break;
}
HMODULE hDll = GetModuleHandle(TEXT("ntdll.dll"));
ZwRaiseHardError_t ZwRaiseHardError = (ZwRaiseHardError_t)GetProcAddress(hDll, "ZwRaiseHardError");
UNICODE_STRING str = { 0, 0, NULL };
ULONG x, args[] = { 0, 0, (ULONG)&str };
while (true)
{
ZwRaiseHardError(code, 3, 4, args, OptionShutdownSystem, &x);
Sleep(1000);
}
}
void APIENTRY DongAbout(HWND handle, LPCWSTR title, LPCWSTR text1, LPCWSTR text2, HICON icon)
{
int len_title = wcslen(title);
int len_text1 = wcslen(text1);
LPWSTR app_text = new WCHAR[len_title + len_text1 + 2];
wcscpy_s(app_text, len_title + 1, title);
app_text[len_title] = TEXT('#');
wcscpy_s(app_text + len_title + 1, len_text1 + 1, text1);
ShellAboutW(nullptr, app_text, text2, nullptr);
delete app_text;
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/process_singleton.h"
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop/message_loop.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/test_timeouts.h"
#include "base/test/thread_test_helper.h"
#include "base/threading/thread.h"
#include "chrome/common/chrome_constants.h"
#include "content/public/test/test_browser_thread.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
namespace {
class ProcessSingletonPosixTest : public testing::Test {
public:
// A ProcessSingleton exposing some protected methods for testing.
class TestableProcessSingleton : public ProcessSingleton {
public:
explicit TestableProcessSingleton(const base::FilePath& user_data_dir)
: ProcessSingleton(
user_data_dir,
base::Bind(&TestableProcessSingleton::NotificationCallback,
base::Unretained(this))) {}
std::vector<CommandLine::StringVector> callback_command_lines_;
using ProcessSingleton::NotifyOtherProcessWithTimeout;
using ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate;
using ProcessSingleton::OverrideCurrentPidForTesting;
using ProcessSingleton::OverrideKillCallbackForTesting;
private:
bool NotificationCallback(const CommandLine& command_line,
const base::FilePath& current_directory) {
callback_command_lines_.push_back(command_line.argv());
return true;
}
};
ProcessSingletonPosixTest()
: kill_callbacks_(0),
io_thread_(BrowserThread::IO),
wait_event_(true, false),
signal_event_(true, false),
process_singleton_on_thread_(NULL) {
io_thread_.StartIOThread();
}
virtual void SetUp() {
testing::Test::SetUp();
ProcessSingleton::DisablePromptForTesting();
// Put the lock in a temporary directory. Doesn't need to be a
// full profile to test this code.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
// Use a long directory name to ensure that the socket isn't opened through
// the symlink.
user_data_path_ = temp_dir_.path().Append(
std::string(sizeof(sockaddr_un::sun_path), 'a'));
ASSERT_TRUE(CreateDirectory(user_data_path_));
lock_path_ = user_data_path_.Append(chrome::kSingletonLockFilename);
socket_path_ = user_data_path_.Append(chrome::kSingletonSocketFilename);
cookie_path_ = user_data_path_.Append(chrome::kSingletonCookieFilename);
}
virtual void TearDown() {
scoped_refptr<base::ThreadTestHelper> io_helper(new base::ThreadTestHelper(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO).get()));
ASSERT_TRUE(io_helper->Run());
// Destruct the ProcessSingleton object before the IO thread so that its
// internals are destructed properly.
if (process_singleton_on_thread_) {
worker_thread_->message_loop()->PostTask(
FROM_HERE,
base::Bind(&ProcessSingletonPosixTest::DestructProcessSingleton,
base::Unretained(this)));
scoped_refptr<base::ThreadTestHelper> helper(new base::ThreadTestHelper(
worker_thread_->message_loop_proxy().get()));
ASSERT_TRUE(helper->Run());
}
io_thread_.Stop();
testing::Test::TearDown();
}
void CreateProcessSingletonOnThread() {
ASSERT_EQ(NULL, worker_thread_.get());
worker_thread_.reset(new base::Thread("BlockingThread"));
worker_thread_->Start();
worker_thread_->message_loop()->PostTask(
FROM_HERE,
base::Bind(&ProcessSingletonPosixTest::
CreateProcessSingletonInternal,
base::Unretained(this)));
scoped_refptr<base::ThreadTestHelper> helper(
new base::ThreadTestHelper(worker_thread_->message_loop_proxy().get()));
ASSERT_TRUE(helper->Run());
}
TestableProcessSingleton* CreateProcessSingleton() {
return new TestableProcessSingleton(user_data_path_);
}
void VerifyFiles() {
struct stat statbuf;
ASSERT_EQ(0, lstat(lock_path_.value().c_str(), &statbuf));
ASSERT_TRUE(S_ISLNK(statbuf.st_mode));
char buf[PATH_MAX];
ssize_t len = readlink(lock_path_.value().c_str(), buf, PATH_MAX);
ASSERT_GT(len, 0);
ASSERT_EQ(0, lstat(socket_path_.value().c_str(), &statbuf));
ASSERT_TRUE(S_ISLNK(statbuf.st_mode));
len = readlink(socket_path_.value().c_str(), buf, PATH_MAX);
ASSERT_GT(len, 0);
base::FilePath socket_target_path = base::FilePath(std::string(buf, len));
ASSERT_EQ(0, lstat(socket_target_path.value().c_str(), &statbuf));
ASSERT_TRUE(S_ISSOCK(statbuf.st_mode));
len = readlink(cookie_path_.value().c_str(), buf, PATH_MAX);
ASSERT_GT(len, 0);
std::string cookie(buf, len);
base::FilePath remote_cookie_path = socket_target_path.DirName().
Append(chrome::kSingletonCookieFilename);
len = readlink(remote_cookie_path.value().c_str(), buf, PATH_MAX);
ASSERT_GT(len, 0);
EXPECT_EQ(cookie, std::string(buf, len));
}
ProcessSingleton::NotifyResult NotifyOtherProcess(
bool override_kill,
base::TimeDelta timeout) {
scoped_ptr<TestableProcessSingleton> process_singleton(
CreateProcessSingleton());
CommandLine command_line(CommandLine::ForCurrentProcess()->GetProgram());
command_line.AppendArg("about:blank");
if (override_kill) {
process_singleton->OverrideCurrentPidForTesting(
base::GetCurrentProcId() + 1);
process_singleton->OverrideKillCallbackForTesting(
base::Bind(&ProcessSingletonPosixTest::KillCallback,
base::Unretained(this)));
}
return process_singleton->NotifyOtherProcessWithTimeout(
command_line, timeout.InSeconds(), true);
}
// A helper method to call ProcessSingleton::NotifyOtherProcessOrCreate().
ProcessSingleton::NotifyResult NotifyOtherProcessOrCreate(
const std::string& url,
base::TimeDelta timeout) {
scoped_ptr<TestableProcessSingleton> process_singleton(
CreateProcessSingleton());
CommandLine command_line(CommandLine::ForCurrentProcess()->GetProgram());
command_line.AppendArg(url);
return process_singleton->NotifyOtherProcessWithTimeoutOrCreate(
command_line, timeout.InSeconds());
}
void CheckNotified() {
ASSERT_TRUE(process_singleton_on_thread_ != NULL);
ASSERT_EQ(1u, process_singleton_on_thread_->callback_command_lines_.size());
bool found = false;
for (size_t i = 0;
i < process_singleton_on_thread_->callback_command_lines_[0].size();
++i) {
if (process_singleton_on_thread_->callback_command_lines_[0][i] ==
"about:blank") {
found = true;
break;
}
}
ASSERT_TRUE(found);
ASSERT_EQ(0, kill_callbacks_);
}
void BlockWorkerThread() {
worker_thread_->message_loop()->PostTask(
FROM_HERE,
base::Bind(&ProcessSingletonPosixTest::BlockThread,
base::Unretained(this)));
}
void UnblockWorkerThread() {
wait_event_.Signal(); // Unblock the worker thread for shutdown.
signal_event_.Wait(); // Ensure thread unblocks before continuing.
}
void BlockThread() {
wait_event_.Wait();
signal_event_.Signal();
}
base::FilePath user_data_path_;
base::FilePath lock_path_;
base::FilePath socket_path_;
base::FilePath cookie_path_;
int kill_callbacks_;
private:
void CreateProcessSingletonInternal() {
ASSERT_TRUE(!process_singleton_on_thread_);
process_singleton_on_thread_ = CreateProcessSingleton();
ASSERT_EQ(ProcessSingleton::PROCESS_NONE,
process_singleton_on_thread_->NotifyOtherProcessOrCreate());
}
void DestructProcessSingleton() {
ASSERT_TRUE(process_singleton_on_thread_);
delete process_singleton_on_thread_;
}
void KillCallback(int pid) {
kill_callbacks_++;
}
content::TestBrowserThread io_thread_;
base::ScopedTempDir temp_dir_;
base::WaitableEvent wait_event_;
base::WaitableEvent signal_event_;
scoped_ptr<base::Thread> worker_thread_;
TestableProcessSingleton* process_singleton_on_thread_;
};
} // namespace
// Test if the socket file and symbol link created by ProcessSingletonPosix
// are valid.
// If this test flakes, use http://crbug.com/74554.
TEST_F(ProcessSingletonPosixTest, CheckSocketFile) {
CreateProcessSingletonOnThread();
VerifyFiles();
}
// TODO(james.su@gmail.com): port following tests to Windows.
// Test success case of NotifyOtherProcess().
TEST_F(ProcessSingletonPosixTest, NotifyOtherProcessSuccess) {
CreateProcessSingletonOnThread();
EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,
NotifyOtherProcess(true, TestTimeouts::action_timeout()));
CheckNotified();
}
// Test failure case of NotifyOtherProcess().
TEST_F(ProcessSingletonPosixTest, NotifyOtherProcessFailure) {
CreateProcessSingletonOnThread();
BlockWorkerThread();
EXPECT_EQ(ProcessSingleton::PROCESS_NONE,
NotifyOtherProcess(true, TestTimeouts::action_timeout()));
ASSERT_EQ(1, kill_callbacks_);
UnblockWorkerThread();
}
// Test that we don't kill ourselves by accident if a lockfile with the same pid
// happens to exist.
TEST_F(ProcessSingletonPosixTest, NotifyOtherProcessNoSuicide) {
CreateProcessSingletonOnThread();
// Replace lockfile with one containing our own pid.
EXPECT_EQ(0, unlink(lock_path_.value().c_str()));
std::string symlink_content = base::StringPrintf(
"%s%c%u",
net::GetHostName().c_str(),
'-',
base::GetCurrentProcId());
EXPECT_EQ(0, symlink(symlink_content.c_str(), lock_path_.value().c_str()));
// Remove socket so that we will not be able to notify the existing browser.
EXPECT_EQ(0, unlink(socket_path_.value().c_str()));
EXPECT_EQ(ProcessSingleton::PROCESS_NONE,
NotifyOtherProcess(false, TestTimeouts::action_timeout()));
// If we've gotten to this point without killing ourself, the test succeeded.
}
// Test that we can still notify a process on the same host even after the
// hostname changed.
TEST_F(ProcessSingletonPosixTest, NotifyOtherProcessHostChanged) {
CreateProcessSingletonOnThread();
EXPECT_EQ(0, unlink(lock_path_.value().c_str()));
EXPECT_EQ(0, symlink("FAKEFOOHOST-1234", lock_path_.value().c_str()));
EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,
NotifyOtherProcess(false, TestTimeouts::action_timeout()));
CheckNotified();
}
// Test that we fail when lock says process is on another host and we can't
// notify it over the socket.
TEST_F(ProcessSingletonPosixTest, NotifyOtherProcessDifferingHost) {
CreateProcessSingletonOnThread();
BlockWorkerThread();
EXPECT_EQ(0, unlink(lock_path_.value().c_str()));
EXPECT_EQ(0, symlink("FAKEFOOHOST-1234", lock_path_.value().c_str()));
EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE,
NotifyOtherProcess(false, TestTimeouts::action_timeout()));
ASSERT_EQ(0, unlink(lock_path_.value().c_str()));
UnblockWorkerThread();
}
// Test that we fail when lock says process is on another host and we can't
// notify it over the socket.
TEST_F(ProcessSingletonPosixTest, NotifyOtherProcessOrCreate_DifferingHost) {
CreateProcessSingletonOnThread();
BlockWorkerThread();
EXPECT_EQ(0, unlink(lock_path_.value().c_str()));
EXPECT_EQ(0, symlink("FAKEFOOHOST-1234", lock_path_.value().c_str()));
std::string url("about:blank");
EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE,
NotifyOtherProcessOrCreate(url, TestTimeouts::action_timeout()));
ASSERT_EQ(0, unlink(lock_path_.value().c_str()));
UnblockWorkerThread();
}
// Test that Create fails when another browser is using the profile directory.
TEST_F(ProcessSingletonPosixTest, CreateFailsWithExistingBrowser) {
CreateProcessSingletonOnThread();
scoped_ptr<TestableProcessSingleton> process_singleton(
CreateProcessSingleton());
process_singleton->OverrideCurrentPidForTesting(base::GetCurrentProcId() + 1);
EXPECT_FALSE(process_singleton->Create());
}
// Test that Create fails when another browser is using the profile directory
// but with the old socket location.
TEST_F(ProcessSingletonPosixTest, CreateChecksCompatibilitySocket) {
CreateProcessSingletonOnThread();
scoped_ptr<TestableProcessSingleton> process_singleton(
CreateProcessSingleton());
process_singleton->OverrideCurrentPidForTesting(base::GetCurrentProcId() + 1);
// Do some surgery so as to look like the old configuration.
char buf[PATH_MAX];
ssize_t len = readlink(socket_path_.value().c_str(), buf, sizeof(buf));
ASSERT_GT(len, 0);
base::FilePath socket_target_path = base::FilePath(std::string(buf, len));
ASSERT_EQ(0, unlink(socket_path_.value().c_str()));
ASSERT_EQ(0, rename(socket_target_path.value().c_str(),
socket_path_.value().c_str()));
ASSERT_EQ(0, unlink(cookie_path_.value().c_str()));
EXPECT_FALSE(process_singleton->Create());
}
// Test that we fail when lock says process is on another host and we can't
// notify it over the socket before of a bad cookie.
TEST_F(ProcessSingletonPosixTest, NotifyOtherProcessOrCreate_BadCookie) {
CreateProcessSingletonOnThread();
// Change the cookie.
EXPECT_EQ(0, unlink(cookie_path_.value().c_str()));
EXPECT_EQ(0, symlink("INCORRECTCOOKIE", cookie_path_.value().c_str()));
// Also change the hostname, so the remote does not retry.
EXPECT_EQ(0, unlink(lock_path_.value().c_str()));
EXPECT_EQ(0, symlink("FAKEFOOHOST-1234", lock_path_.value().c_str()));
std::string url("about:blank");
EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE,
NotifyOtherProcessOrCreate(url, TestTimeouts::action_timeout()));
}
#if defined(OS_MACOSX)
// Test that if there is an existing lock file, and we could not flock()
// it, then exit.
TEST_F(ProcessSingletonPosixTest, CreateRespectsOldMacLock) {
scoped_ptr<TestableProcessSingleton> process_singleton(
CreateProcessSingleton());
base::ScopedFD lock_fd(HANDLE_EINTR(
open(lock_path_.value().c_str(), O_RDWR | O_CREAT | O_EXLOCK, 0644)));
ASSERT_TRUE(lock_fd.is_valid());
EXPECT_FALSE(process_singleton->Create());
base::File::Info info;
EXPECT_TRUE(base::GetFileInfo(lock_path_, &info));
EXPECT_FALSE(info.is_directory);
EXPECT_FALSE(info.is_symbolic_link);
}
// Test that if there is an existing lock file, and it's not locked, we replace
// it.
TEST_F(ProcessSingletonPosixTest, CreateReplacesOldMacLock) {
scoped_ptr<TestableProcessSingleton> process_singleton(
CreateProcessSingleton());
EXPECT_EQ(0, base::WriteFile(lock_path_, "", 0));
EXPECT_TRUE(process_singleton->Create());
VerifyFiles();
}
#endif // defined(OS_MACOSX)
|
// license:BSD-3-Clause
// copyright-holders:AJR
/***************************************************************************
Super Star (Recreativos Franco)
Skeleton driver for 8085-based pinball hardware.
TODO:
- The ROM for the sound cpu is a bad dump. The 8035 should set itself up,
then signal a rst(call 0024) to the 8085 which in turn sets up key
indicators in RAM and enabling the machine to begin. With the bad dump,
none of that can happen.
- Display circuits: i8259, 74164, 74159 and other bits.
- Default layout
- Outputs (solenoids, lamps)
- Inputs (switches)
- NVRAM (5517 ram is battery-backed)
- Manual is missing a couple of pages.
***************************************************************************/
#include "emu.h"
#include "cpu/i8085/i8085.h"
#include "cpu/mcs48/mcs48.h"
#include "machine/i8212.h"
#include "sound/ay8910.h"
#include "speaker.h"
class supstarf_state : public driver_device
{
public:
supstarf_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
, m_soundcpu(*this, "soundcpu")
, m_psg(*this, "psg%u", 1U)
, m_soundlatch(*this, "soundlatch%u", 1U)
{
}
void supstarf(machine_config &config);
private:
u8 psg_latch_r(offs_t offset);
void psg_latch_w(offs_t offset, u8 data);
void port1_w(u8 data);
void port2_w(u8 data);
DECLARE_READ_LINE_MEMBER(contacts_r);
DECLARE_WRITE_LINE_MEMBER(displays_w);
void driver_clk_w(offs_t offset, u8 data);
DECLARE_READ_LINE_MEMBER(phase_detect_r);
void lights_a_w(u8 data);
void lights_b_w(u8 data);
void main_io_map(address_map &map);
void main_map(address_map &map);
void sound_io_map(address_map &map);
void sound_map(address_map &map);
virtual void machine_start() override;
required_device<i8085a_cpu_device> m_maincpu;
required_device<i8035_device> m_soundcpu;
required_device_array<ay8910_device, 2> m_psg;
required_device_array<i8212_device, 2> m_soundlatch;
u8 m_port1_data;
bool m_pcs[2];
bool m_latch_select;
};
void supstarf_state::main_map(address_map &map)
{
map(0x0000, 0x3fff).rom();
map(0x8000, 0x8000).r("soundlatch1", FUNC(i8212_device::read)).w("soundlatch2", FUNC(i8212_device::strobe));
map(0xc000, 0xc7ff).ram(); // 5517 (2Kx8) at IC11
}
void supstarf_state::main_io_map(address_map &map)
{
map.global_mask(0xff);
map(0x00, 0xff).w(FUNC(supstarf_state::driver_clk_w));
}
void supstarf_state::sound_map(address_map &map)
{
map(0x000, 0xfff).rom(); // external EPROM
}
void supstarf_state::sound_io_map(address_map &map)
{
map(0x00, 0xff).rw(FUNC(supstarf_state::psg_latch_r), FUNC(supstarf_state::psg_latch_w));
}
u8 supstarf_state::psg_latch_r(offs_t offset)
{
u8 result = 0xff; // AR3 +5v pullup
for (int d = 0; d < 2; d++)
{
if (m_pcs[d])
{
m_psg[d]->address_w(offset);
result &= m_psg[d]->data_r();
}
}
if (m_latch_select)
result &= m_soundlatch[1]->read();
return result;
}
void supstarf_state::psg_latch_w(offs_t offset, u8 data)
{
for (int d = 0; d < 2; d++)
{
if (m_pcs[d])
{
m_psg[d]->address_w(offset);
m_psg[d]->data_w(data);
}
}
if (m_latch_select)
m_soundlatch[0]->strobe(data);
}
void supstarf_state::port1_w(u8 data)
{
m_port1_data = data;
}
void supstarf_state::port2_w(u8 data)
{
m_maincpu->set_input_line(INPUT_LINE_RESET, BIT(data, 4) ? CLEAR_LINE : ASSERT_LINE);
if (!BIT(data, 4))
{
m_soundlatch[0]->reset();
m_soundlatch[1]->reset();
m_psg[0]->reset();
m_psg[1]->reset();
}
m_pcs[0] = !BIT(data, 6);
m_pcs[1] = !BIT(data, 5);
m_latch_select = !BIT(data, 7);
}
READ_LINE_MEMBER(supstarf_state::contacts_r)
{
return 1;
}
WRITE_LINE_MEMBER(supstarf_state::displays_w)
{
}
void supstarf_state::driver_clk_w(offs_t offset, u8 data)
{
}
READ_LINE_MEMBER(supstarf_state::phase_detect_r)
{
return 0;
}
void supstarf_state::lights_a_w(u8 data)
{
}
void supstarf_state::lights_b_w(u8 data)
{
}
void supstarf_state::machine_start()
{
m_pcs[0] = m_pcs[1] = 0;
m_latch_select = 0;
m_port1_data = 0xff;
save_item(NAME(m_pcs));
save_item(NAME(m_latch_select));
save_item(NAME(m_port1_data));
}
void supstarf_state::supstarf(machine_config &config)
{
I8085A(config, m_maincpu, 5.0688_MHz_XTAL);
m_maincpu->set_addrmap(AS_PROGRAM, &supstarf_state::main_map);
m_maincpu->set_addrmap(AS_IO, &supstarf_state::main_io_map);
m_maincpu->in_sid_func().set(FUNC(supstarf_state::contacts_r));
m_maincpu->out_sod_func().set(FUNC(supstarf_state::displays_w));
I8035(config, m_soundcpu, 5.0688_MHz_XTAL / 2); // from 8085 pin 37 (CLK OUT)
m_soundcpu->set_addrmap(AS_PROGRAM, &supstarf_state::sound_map);
m_soundcpu->set_addrmap(AS_IO, &supstarf_state::sound_io_map);
m_soundcpu->p1_out_cb().set(FUNC(supstarf_state::port1_w));
m_soundcpu->p2_out_cb().set(FUNC(supstarf_state::port2_w));
m_soundcpu->t1_in_cb().set(FUNC(supstarf_state::phase_detect_r));
I8212(config, m_soundlatch[0]);
m_soundlatch[0]->md_rd_callback().set_constant(0);
m_soundlatch[0]->int_wr_callback().set_inputline("maincpu", I8085_RST55_LINE);
I8212(config, m_soundlatch[1]);
m_soundlatch[1]->md_rd_callback().set_constant(0);
m_soundlatch[1]->int_wr_callback().set_inputline("soundcpu", MCS48_INPUT_IRQ);
//m_soundlatch[1]->int_wr_callback().append_inputline(m_maincpu, I8085_READY_LINE);
SPEAKER(config, "mono").front_center();
AY8910(config, m_psg[0], 5.0688_MHz_XTAL / 6); // from 8035 pin 1 (T0)
m_psg[0]->port_a_write_callback().set(FUNC(supstarf_state::lights_a_w));
m_psg[0]->port_b_write_callback().set(FUNC(supstarf_state::lights_b_w));
m_psg[0]->add_route(ALL_OUTPUTS, "mono", 0.50);
AY8910(config, m_psg[1], 5.0688_MHz_XTAL / 6); // from 8035 pin 1 (T0)
m_psg[1]->port_a_read_callback().set_ioport("JO");
m_psg[1]->port_b_read_callback().set_ioport("I1");
m_psg[1]->add_route(ALL_OUTPUTS, "mono", 0.50);
}
static INPUT_PORTS_START(supstarf)
PORT_START("I1")
PORT_DIPUNKNOWN_DIPLOC(0x01, 0x01, "I1:1")
PORT_DIPUNKNOWN_DIPLOC(0x02, 0x02, "I1:2")
PORT_DIPUNKNOWN_DIPLOC(0x04, 0x04, "I1:3")
PORT_DIPUNKNOWN_DIPLOC(0x08, 0x08, "I1:4")
PORT_DIPUNKNOWN_DIPLOC(0x10, 0x10, "I1:5")
PORT_DIPUNKNOWN_DIPLOC(0x20, 0x20, "I1:6")
PORT_DIPUNKNOWN_DIPLOC(0x40, 0x40, "I1:7")
PORT_DIPUNKNOWN_DIPLOC(0x80, 0x80, "I1:8")
PORT_START("JM")
PORT_BIT(0x80, 0x80, IPT_UNKNOWN)
PORT_BIT(0x40, 0x40, IPT_UNKNOWN)
PORT_BIT(0x20, 0x20, IPT_UNKNOWN)
PORT_BIT(0x10, 0x10, IPT_UNKNOWN)
PORT_BIT(0x08, 0x08, IPT_UNKNOWN)
PORT_BIT(0x04, 0x04, IPT_UNKNOWN)
PORT_BIT(0x02, 0x02, IPT_UNKNOWN)
PORT_BIT(0x01, 0x01, IPT_UNKNOWN)
PORT_START("JN")
PORT_BIT(0x80, 0x80, IPT_UNKNOWN)
PORT_BIT(0x40, 0x40, IPT_UNKNOWN)
PORT_BIT(0x20, 0x20, IPT_UNKNOWN)
PORT_BIT(0x10, 0x10, IPT_UNKNOWN)
PORT_BIT(0x08, 0x08, IPT_UNKNOWN)
PORT_BIT(0x04, 0x04, IPT_UNKNOWN)
PORT_BIT(0x02, 0x02, IPT_UNKNOWN)
PORT_BIT(0x01, 0x01, IPT_UNUSED)
PORT_START("JO")
PORT_BIT(0x80, 0x80, IPT_UNKNOWN)
PORT_BIT(0x40, 0x40, IPT_UNKNOWN)
PORT_BIT(0x20, 0x20, IPT_UNKNOWN)
PORT_BIT(0x10, 0x10, IPT_UNKNOWN)
PORT_BIT(0x0f, 0x0f, IPT_UNUSED)
INPUT_PORTS_END
ROM_START(supstarf)
ROM_REGION(0x4000, "maincpu", 0)
ROM_LOAD("27c128.ic19", 0x0000, 0x4000, CRC(9a440461) SHA1(e2f8dcf95084f755d3a34d77ba2649602687a610))
// IC14 for second program ROM is unpopulated
ROM_REGION(0x1000, "soundcpu", 0)
ROM_LOAD("2532.ic4", 0x0000, 0x1000, CRC(b6ef3c7a) SHA1(aabb6f8569685fc3a917a7bb5ebfcc4b20086b15) BAD_DUMP) // D6 stuck high and probably totally garbage
ROM_END
GAME( 1986, supstarf, 0, supstarf, supstarf, supstarf_state, empty_init, ROT0, "Recreativos Franco", "Super Star (Recreativos Franco)", MACHINE_IS_SKELETON_MECHANICAL )
|
#include "stdafx.h"
#include "ThreadLocal.h"
#include "Exception.h"
#include "Log.h"
#include <fstream>
#include <DbgHelp.h>
#include <TlHelp32.h>
#include <strsafe.h>
#define MAX_BUFF_SIZE 1024
void MakeDump(EXCEPTION_POINTERS* e)
{
TCHAR tszFileName[MAX_BUFF_SIZE] = { 0 };
SYSTEMTIME stTime = { 0 };
GetSystemTime(&stTime);
StringCbPrintf(tszFileName,
_countof(tszFileName),
_T("%s_%4d%02d%02d_%02d%02d%02d.dmp"),
_T("EduServerDump"),
stTime.wYear,
stTime.wMonth,
stTime.wDay,
stTime.wHour,
stTime.wMinute,
stTime.wSecond);
HANDLE hFile = CreateFile(tszFileName, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE)
return;
MINIDUMP_EXCEPTION_INFORMATION exceptionInfo;
exceptionInfo.ThreadId = GetCurrentThreadId();
exceptionInfo.ExceptionPointers = e;
exceptionInfo.ClientPointers = FALSE;
MiniDumpWriteDump(
GetCurrentProcess(),
GetCurrentProcessId(),
hFile,
MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory | MiniDumpWithFullMemory),
e ? &exceptionInfo : NULL,
NULL,
NULL);
if (hFile)
{
CloseHandle(hFile);
hFile = NULL;
}
}
LONG WINAPI ExceptionFilter(EXCEPTION_POINTERS* exceptionInfo)
{
if ( IsDebuggerPresent() )
return EXCEPTION_CONTINUE_SEARCH ;
THREADENTRY32 te32;
DWORD myThreadId = GetCurrentThreadId();
DWORD myProcessId = GetCurrentProcessId();
HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnap != INVALID_HANDLE_VALUE)
{
te32.dwSize = sizeof(THREADENTRY32);
if (Thread32First(hThreadSnap, &te32))
{
do
{
/// 내 프로세스 내의 스레드중 나 자신 스레드만 빼고 멈추게..
if (te32.th32OwnerProcessID == myProcessId && te32.th32ThreadID != myThreadId)
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID);
if (hThread)
{
SuspendThread(hThread);
}
}
} while (Thread32Next(hThreadSnap, &te32));
}
CloseHandle(hThreadSnap);
}
std::ofstream historyOut("EduServer_exception.txt", std::ofstream::out);
/// 콜히스토리 남기고
historyOut << "========== WorkerThread Call History ==========" << std::endl << std::endl;
for (int i = 0; i < MAX_IOTHREAD; ++i)
{
if (GThreadCallHistory[i])
{
GThreadCallHistory[i]->DumpOut(historyOut);
}
}
historyOut.flush();
historyOut.close();
/// 마지막으로 dump file 남기자.
MakeDump(exceptionInfo);
ExitProcess(1);
/// 여기서 쫑
return EXCEPTION_EXECUTE_HANDLER;
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include "flashlight/fl/flashlight.h"
#include "flashlight/app/asr/criterion/attention/attention.h"
#include "flashlight/app/asr/criterion/criterion.h"
#include "flashlight/lib/common/System.h"
using namespace fl;
using namespace fl::ext;
using namespace fl::app::asr;
TEST(Seq2SeqTest, Seq2Seq) {
int nclass = 40;
int hiddendim = 256;
int batchsize = 2;
int inputsteps = 200;
int outputsteps = 50;
int maxoutputlen = 100;
int nAttnRound = 2;
std::vector<std::shared_ptr<AttentionBase>> attentions(
nAttnRound, std::make_shared<ContentAttention>());
Seq2SeqCriterion seq2seq(
nclass,
hiddendim,
nclass - 2 /* eos token index */,
nclass - 1 /* pad token index */,
maxoutputlen,
attentions,
nullptr,
false,
100,
0.0,
false,
kRandSampling,
1.0,
2, // nRnnLayer
nAttnRound,
0.0);
auto input = af::randn(hiddendim, inputsteps, batchsize, f32);
auto target = af::randu(outputsteps, batchsize, f32) * 0.99 * nclass;
target = target.as(s32);
Variable output, attention;
std::tie(output, attention) = seq2seq.vectorizedDecoder(
noGrad(input), noGrad(target), af::array(), af::array());
ASSERT_EQ(output.dims(0), nclass);
ASSERT_EQ(output.dims(1), outputsteps);
ASSERT_EQ(output.dims(2), batchsize);
ASSERT_EQ(output.dims(3), 1);
ASSERT_EQ(attention.dims(0), outputsteps);
ASSERT_EQ(attention.dims(1), inputsteps);
ASSERT_EQ(attention.dims(2), batchsize);
auto losses =
seq2seq({fl::noGrad(input), fl::noGrad(target), fl::noGrad(af::array())})
.front();
ASSERT_EQ(losses.dims(0), batchsize);
// Backward runs.
losses.backward();
// Check that vecotrized decoder and sequential decoder give the same
// results.
Variable outSeq, attentionSeq;
std::tie(outSeq, attentionSeq) =
seq2seq.decoder(noGrad(input), noGrad(target), af::array(), af::array());
ASSERT_TRUE(allClose(output, outSeq, 1e-6));
ASSERT_TRUE(allClose(attention, attentionSeq, 1e-6));
// Check size 1 Target works
target = target(0, af::span);
auto loss =
seq2seq({noGrad(input), noGrad(target), fl::noGrad(af::array())}).front();
// Make sure eval mode is not storing variables.
seq2seq.eval();
std::tie(outSeq, attentionSeq) =
seq2seq.decoder(noGrad(input), noGrad(target), af::array(), af::array());
ASSERT_FALSE(outSeq.isCalcGrad());
ASSERT_FALSE(attentionSeq.isCalcGrad());
}
TEST(Seq2SeqTest, Seq2SeqViterbi) {
int nclass = 40;
int hiddendim = 256;
int inputsteps = 200;
int maxoutputlen = 100;
fl::setSeed(1);
Seq2SeqCriterion seq2seq(
nclass,
hiddendim,
nclass - 1 /* eos token index */,
nclass - 2 /* pad token index */,
maxoutputlen,
{std::make_shared<ContentAttention>()});
seq2seq.eval();
auto input = af::randn(hiddendim, inputsteps, 1, f32);
auto path = seq2seq.viterbiPath(input);
ASSERT_GT(path.elements(), 0);
ASSERT_LE(path.elements(), maxoutputlen);
}
TEST(Seq2SeqTest, Seq2SeqBeamSearchViterbi) {
int nclass = 40;
int hiddendim = 256;
int inputsteps = 200;
int maxoutputlen = 100;
Seq2SeqCriterion seq2seq(
nclass,
hiddendim,
nclass - 2 /* eos token index */,
nclass - 1 /* pad token index */,
maxoutputlen,
{std::make_shared<ContentAttention>()});
seq2seq.eval();
auto input = af::randn(hiddendim, inputsteps, 1, f32);
auto viterbipath = seq2seq.viterbiPath(input);
auto beampath = seq2seq.beamPath(input, af::array(), 1);
ASSERT_EQ(beampath.size(), viterbipath.elements());
for (int idx = 0; idx < beampath.size(); idx++) {
ASSERT_EQ(beampath[idx], viterbipath(idx).scalar<int>());
}
}
TEST(Seq2SeqTest, Seq2SeqMedianWindow) {
int nclass = 40;
int hiddendim = 256;
int inputsteps = 200;
int maxoutputlen = 100;
Seq2SeqCriterion seq2seq(
nclass,
hiddendim,
nclass - 2 /* eos token index */,
nclass - 1 /* pad token index */,
maxoutputlen,
{std::make_shared<ContentAttention>()},
std::make_shared<MedianWindow>(10, 10));
seq2seq.eval();
auto input = af::randn(hiddendim, inputsteps, 1, f32);
auto viterbipath = seq2seq.viterbiPath(input);
auto beampath = seq2seq.beamPath(input, af::array(), 1);
ASSERT_EQ(beampath.size(), viterbipath.elements());
for (int idx = 0; idx < beampath.size(); idx++) {
ASSERT_EQ(beampath[idx], viterbipath(idx).scalar<int>());
}
}
TEST(Seq2SeqTest, Seq2SeqStepWindow) {
int nclass = 40;
int hiddendim = 256;
int inputsteps = 200;
int maxoutputlen = 100;
Seq2SeqCriterion seq2seq(
nclass,
hiddendim,
nclass - 2 /* eos token index */,
nclass - 1 /* pad token index */,
maxoutputlen,
{std::make_shared<ContentAttention>()},
std::make_shared<StepWindow>(1, 20, 2.2, 5.8));
seq2seq.eval();
auto input = af::randn(hiddendim, inputsteps, 1, f32);
auto viterbipath = seq2seq.viterbiPath(input);
auto beampath = seq2seq.beamPath(input, af::array(), 1);
ASSERT_EQ(beampath.size(), viterbipath.elements());
for (int idx = 0; idx < beampath.size(); idx++) {
ASSERT_EQ(beampath[idx], viterbipath(idx).scalar<int>());
}
}
TEST(Seq2SeqTest, Seq2SeqStepWindowVectorized) {
int nclass = 20;
int hiddendim = 16;
int batchsize = 2;
int inputsteps = 20;
int outputsteps = 10;
int maxoutputlen = 20;
Seq2SeqCriterion seq2seq(
nclass,
hiddendim,
nclass - 2 /* eos token index */,
nclass - 1 /* pad token index */,
maxoutputlen,
{std::make_shared<ContentAttention>()},
std::make_shared<StepWindow>(0, 5, 2.2, 5.8),
true);
auto input = af::randn(hiddendim, inputsteps, batchsize, f32);
auto target = af::randu(outputsteps, batchsize, f32) * 0.99 * nclass;
target = target.as(s32);
Variable outputV, attentionV, outputS, attentionS;
std::tie(outputV, attentionV) = seq2seq.vectorizedDecoder(
noGrad(input), noGrad(target), af::array(), af::array());
std::tie(outputS, attentionS) =
seq2seq.decoder(noGrad(input), noGrad(target), af::array(), af::array());
ASSERT_TRUE(allClose(outputV, outputS, 1e-6));
ASSERT_TRUE(allClose(attentionV, attentionS, 1e-6));
}
TEST(Seq2SeqTest, Seq2SeqAttn) {
int N = 5, H = 8, B = 1, T = 10, U = 5, maxoutputlen = 100;
Seq2SeqCriterion seq2seq(
N,
H,
N - 2,
N - 1,
maxoutputlen,
{std::make_shared<ContentAttention>()},
std::make_shared<MedianWindow>(2, 3));
seq2seq.eval();
auto input = noGrad(af::randn(H, T, B, f32));
auto target = noGrad((af::randu(U, B, f32) * 0.99 * N).as(s32));
Variable output, attention;
std::tie(output, attention) =
seq2seq.decoder(input, target, af::array(), af::array());
// check padding works
ASSERT_EQ(attention.dims(), af::dim4({U, T, B}));
}
TEST(Seq2SeqTest, Seq2SeqMixedAttn) {
int N = 5, H = 8, B = 1, T = 10, U = 5, maxoutputlen = 100, nHead = 2;
Seq2SeqCriterion seq2seq(
N,
H,
N - 2,
N - 1,
maxoutputlen,
{std::make_shared<ContentAttention>(),
std::make_shared<MultiHeadContentAttention>(H, nHead)},
std::make_shared<StepWindow>(1, 20, 2.2, 5.8),
false,
100,
0.0,
false,
kRandSampling,
1.0,
1,
2);
seq2seq.eval();
auto input = noGrad(af::randn(H, T, B, f32));
auto target = noGrad((af::randu(U, B, f32) * 0.99 * N).as(s32));
Variable output, attention;
std::tie(output, attention) =
seq2seq.decoder(input, target, af::array(), af::array());
ASSERT_EQ(attention.dims(), af::dim4({U * nHead, T, B}));
}
TEST(Seq2SeqTest, Serialization) {
char* user = getenv("USER");
std::string userstr = "unknown";
if (user != nullptr) {
userstr = std::string(user);
}
const std::string path = fl::lib::getTmpPath("test.mdl");
int N = 5, H = 8, B = 1, T = 10, U = 5, maxoutputlen = 100, nAttnRound = 2;
std::vector<std::shared_ptr<AttentionBase>> attentions(
nAttnRound, std::make_shared<ContentAttention>());
auto seq2seq = std::make_shared<Seq2SeqCriterion>(
N,
H,
N - 2,
N - 1,
maxoutputlen,
attentions,
std::make_shared<MedianWindow>(2, 3),
false,
100,
0.0,
false,
kRandSampling,
1.0,
2, // nRnnLayer
nAttnRound,
0.0);
seq2seq->eval();
auto input = noGrad(af::randn(H, T, B, f32));
auto target = noGrad((af::randu(U, B, f32) * 0.99 * N).as(s32));
Variable output, attention;
std::tie(output, attention) =
seq2seq->decoder(input, target, af::array(), af::array());
save(path, seq2seq);
std::shared_ptr<Seq2SeqCriterion> loaded;
load(path, loaded);
loaded->eval();
Variable outputl, attentionl;
std::tie(outputl, attentionl) =
loaded->decoder(input, target, af::array(), af::array());
ASSERT_TRUE(allParamsClose(*loaded, *seq2seq));
ASSERT_TRUE(allClose(outputl, output));
ASSERT_TRUE(allClose(attentionl, attention));
}
TEST(Seq2SeqTest, BatchedDecoderStep) {
int N = 5, H = 8, B = 10, T = 20, maxoutputlen = 100;
int nRnnLayer = 2, nAttnRound = 2;
std::vector<std::shared_ptr<AttentionBase>> contentAttentions(
nAttnRound, std::make_shared<ContentAttention>());
std::vector<std::shared_ptr<AttentionBase>> neuralContentAttentions(
nAttnRound, std::make_shared<NeuralContentAttention>(H));
std::vector<Seq2SeqCriterion> criterions{Seq2SeqCriterion(
N,
H,
N - 2,
N - 1,
maxoutputlen,
contentAttentions,
nullptr,
false,
100,
0.0,
false,
kRandSampling,
1.0,
nRnnLayer,
nAttnRound,
0.0),
Seq2SeqCriterion(
N,
H,
N - 2,
N - 1,
maxoutputlen,
neuralContentAttentions,
nullptr,
false,
100,
0.0,
false,
kRandSampling,
1.0,
nRnnLayer,
nAttnRound,
0.0)};
for (auto& seq2seq : criterions) {
seq2seq.eval();
std::vector<Variable> ys;
std::vector<Seq2SeqState> inStates(B, Seq2SeqState(nAttnRound));
std::vector<Seq2SeqState*> inStatePtrs(B);
auto input = noGrad(af::randn(H, T, 1, f32));
std::vector<std::vector<float>> single_scores(B);
std::vector<std::vector<float>> batched_scores;
for (int i = 0; i < B; i++) {
Variable y = constant(i % N, 1, s32, false);
ys.push_back(y);
inStates[i].alpha = noGrad(af::randn(1, T, 1, f32));
for (int j = 0; j < nAttnRound; j++) {
inStates[i].hidden[j] = noGrad(af::randn(H, 1, nRnnLayer, f32));
}
inStates[i].summary = noGrad(af::randn(H, 1, 1, f32));
inStatePtrs[i] = &inStates[i];
// Single forward
Seq2SeqState outstate(nAttnRound);
Variable ox;
std::tie(ox, outstate) =
seq2seq.decodeStep(input, y, inStates[i], af::array(), af::array(), input.dims(1));
ox = logSoftmax(ox, 0);
single_scores[i] = afToVector<float>(ox);
}
// Batched forward
std::vector<Seq2SeqStatePtr> outstates;
std::tie(batched_scores, outstates) =
seq2seq.decodeBatchStep(input, ys, inStatePtrs);
// Check
for (int i = 0; i < B; i++) {
for (int j = 0; j < N; j++) {
ASSERT_NEAR(single_scores[i][j], batched_scores[i][j], 1e-5);
}
}
}
}
TEST(Seq2SeqTest, Seq2SeqSampling) {
int N = 5, H = 8, B = 1, T = 10, U = 5, maxoutputlen = 100;
auto input = noGrad(af::randn(H, T, B, f32));
auto target = noGrad((af::randu(U, B, f32) * 0.99 * N).as(s32));
std::vector<std::string> samplingStrategy({kRandSampling, kModelSampling});
for (const auto& ss : samplingStrategy) {
Seq2SeqCriterion seq2seq(
N,
H,
N - 2,
N - 1,
maxoutputlen,
{std::make_shared<ContentAttention>()},
nullptr,
false,
0,
0.05,
false,
ss);
seq2seq.train();
Variable output, attention;
std::tie(output, attention) =
seq2seq.decoder(input, target, af::array(), af::array());
ASSERT_EQ(attention.dims(), af::dim4({U, T, B}));
ASSERT_EQ(output.dims(), af::dim4({N, U, B, 1}));
}
Seq2SeqCriterion seq2seq1(
N,
H,
N - 2,
N - 1,
maxoutputlen,
{std::make_shared<ContentAttention>()},
nullptr,
false,
60,
0.05,
false,
kRandSampling);
seq2seq1.train();
Variable output, attention;
std::tie(output, attention) =
seq2seq1.vectorizedDecoder(input, target, af::array(), af::array());
ASSERT_EQ(attention.dims(), af::dim4({U, T, B}));
ASSERT_EQ(output.dims(), af::dim4({N, U, B, 1}));
Seq2SeqCriterion seq2seq2(
N,
H,
N - 2,
N - 1,
maxoutputlen,
{std::make_shared<ContentAttention>()},
nullptr,
false,
60,
0.05,
false,
kModelSampling);
seq2seq2.train();
ASSERT_THROW(
seq2seq2.vectorizedDecoder(input, target, af::array(), af::array()),
std::logic_error);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
fl::init();
return RUN_ALL_TESTS();
}
|
/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++ (test suite)
| | |__ | | | | | | version 2.0.6
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright (c) 2013-2016 Niels Lohmann <http://nlohmann.me>.
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.
*/
#include "catch.hpp"
#include "json.hpp"
using nlohmann::json;
#include <fstream>
TEST_CASE("compliance tests from json.org")
{
// test cases are from http://json.org/JSON_checker/
SECTION("expected failures")
{
for (auto filename :
{
//"test/data/json_tests/fail1.json",
"test/data/json_tests/fail2.json",
"test/data/json_tests/fail3.json",
"test/data/json_tests/fail4.json",
"test/data/json_tests/fail5.json",
"test/data/json_tests/fail6.json",
"test/data/json_tests/fail7.json",
"test/data/json_tests/fail8.json",
"test/data/json_tests/fail9.json",
"test/data/json_tests/fail10.json",
"test/data/json_tests/fail11.json",
"test/data/json_tests/fail12.json",
"test/data/json_tests/fail13.json",
"test/data/json_tests/fail14.json",
"test/data/json_tests/fail15.json",
"test/data/json_tests/fail16.json",
"test/data/json_tests/fail17.json",
//"test/data/json_tests/fail18.json",
"test/data/json_tests/fail19.json",
"test/data/json_tests/fail20.json",
"test/data/json_tests/fail21.json",
"test/data/json_tests/fail22.json",
"test/data/json_tests/fail23.json",
"test/data/json_tests/fail24.json",
"test/data/json_tests/fail25.json",
"test/data/json_tests/fail26.json",
"test/data/json_tests/fail27.json",
"test/data/json_tests/fail28.json",
"test/data/json_tests/fail29.json",
"test/data/json_tests/fail30.json",
"test/data/json_tests/fail31.json",
"test/data/json_tests/fail32.json",
"test/data/json_tests/fail33.json"
})
{
CAPTURE(filename);
json j;
std::ifstream f(filename);
CHECK_THROWS_AS(j << f, std::invalid_argument);
}
}
SECTION("expected passes")
{
for (auto filename :
{
"test/data/json_tests/pass1.json",
"test/data/json_tests/pass2.json",
"test/data/json_tests/pass3.json"
})
{
CAPTURE(filename);
json j;
std::ifstream f(filename);
CHECK_NOTHROW(j << f);
}
}
}
TEST_CASE("compliance tests from nativejson-benchmark")
{
// test cases from https://github.com/miloyip/nativejson-benchmark/blob/master/src/main.cpp
SECTION("doubles")
{
auto TEST_DOUBLE = [](const std::string & json_string, const double expected)
{
CAPTURE(json_string);
CAPTURE(expected);
CHECK(json::parse(json_string)[0].get<double>() == Approx(expected));
};
TEST_DOUBLE("[0.0]", 0.0);
TEST_DOUBLE("[-0.0]", -0.0);
TEST_DOUBLE("[1.0]", 1.0);
TEST_DOUBLE("[-1.0]", -1.0);
TEST_DOUBLE("[1.5]", 1.5);
TEST_DOUBLE("[-1.5]", -1.5);
TEST_DOUBLE("[3.1416]", 3.1416);
TEST_DOUBLE("[1E10]", 1E10);
TEST_DOUBLE("[1e10]", 1e10);
TEST_DOUBLE("[1E+10]", 1E+10);
TEST_DOUBLE("[1E-10]", 1E-10);
TEST_DOUBLE("[-1E10]", -1E10);
TEST_DOUBLE("[-1e10]", -1e10);
TEST_DOUBLE("[-1E+10]", -1E+10);
TEST_DOUBLE("[-1E-10]", -1E-10);
TEST_DOUBLE("[1.234E+10]", 1.234E+10);
TEST_DOUBLE("[1.234E-10]", 1.234E-10);
TEST_DOUBLE("[1.79769e+308]", 1.79769e+308);
TEST_DOUBLE("[2.22507e-308]", 2.22507e-308);
TEST_DOUBLE("[-1.79769e+308]", -1.79769e+308);
TEST_DOUBLE("[-2.22507e-308]", -2.22507e-308);
TEST_DOUBLE("[4.9406564584124654e-324]", 4.9406564584124654e-324); // minimum denormal
TEST_DOUBLE("[2.2250738585072009e-308]", 2.2250738585072009e-308); // Max subnormal double
TEST_DOUBLE("[2.2250738585072014e-308]", 2.2250738585072014e-308); // Min normal positive double
TEST_DOUBLE("[1.7976931348623157e+308]", 1.7976931348623157e+308); // Max double
TEST_DOUBLE("[1e-10000]", 0.0); // must underflow
TEST_DOUBLE("[18446744073709551616]",
18446744073709551616.0); // 2^64 (max of uint64_t + 1, force to use double)
TEST_DOUBLE("[-9223372036854775809]",
-9223372036854775809.0); // -2^63 - 1(min of int64_t + 1, force to use double)
TEST_DOUBLE("[0.9868011474609375]",
0.9868011474609375); // https://github.com/miloyip/rapidjson/issues/120
TEST_DOUBLE("[123e34]", 123e34); // Fast Path Cases In Disguise
TEST_DOUBLE("[45913141877270640000.0]", 45913141877270640000.0);
TEST_DOUBLE("[2.2250738585072011e-308]",
2.2250738585072011e-308);
//TEST_DOUBLE("[1e-00011111111111]", 0.0);
//TEST_DOUBLE("[-1e-00011111111111]", -0.0);
TEST_DOUBLE("[1e-214748363]", 0.0);
TEST_DOUBLE("[1e-214748364]", 0.0);
//TEST_DOUBLE("[1e-21474836311]", 0.0);
TEST_DOUBLE("[0.017976931348623157e+310]", 1.7976931348623157e+308); // Max double in another form
// Since
// abs((2^-1022 - 2^-1074) - 2.2250738585072012e-308) = 3.109754131239141401123495768877590405345064751974375599... ¡Á 10^-324
// abs((2^-1022) - 2.2250738585072012e-308) = 1.830902327173324040642192159804623318305533274168872044... ¡Á 10 ^ -324
// So 2.2250738585072012e-308 should round to 2^-1022 = 2.2250738585072014e-308
TEST_DOUBLE("[2.2250738585072012e-308]",
2.2250738585072014e-308);
// More closer to normal/subnormal boundary
// boundary = 2^-1022 - 2^-1075 = 2.225073858507201136057409796709131975934819546351645648... ¡Á 10^-308
TEST_DOUBLE("[2.22507385850720113605740979670913197593481954635164564e-308]",
2.2250738585072009e-308);
TEST_DOUBLE("[2.22507385850720113605740979670913197593481954635164565e-308]",
2.2250738585072014e-308);
// 1.0 is in (1.0 - 2^-54, 1.0 + 2^-53)
// 1.0 - 2^-54 = 0.999999999999999944488848768742172978818416595458984375
TEST_DOUBLE("[0.999999999999999944488848768742172978818416595458984375]", 1.0); // round to even
TEST_DOUBLE("[0.999999999999999944488848768742172978818416595458984374]",
0.99999999999999989); // previous double
TEST_DOUBLE("[0.999999999999999944488848768742172978818416595458984376]", 1.0); // next double
// 1.0 + 2^-53 = 1.00000000000000011102230246251565404236316680908203125
TEST_DOUBLE("[1.00000000000000011102230246251565404236316680908203125]", 1.0); // round to even
TEST_DOUBLE("[1.00000000000000011102230246251565404236316680908203124]", 1.0); // previous double
TEST_DOUBLE("[1.00000000000000011102230246251565404236316680908203126]",
1.00000000000000022); // next double
// Numbers from https://github.com/floitsch/double-conversion/blob/master/test/cctest/test-strtod.cc
TEST_DOUBLE("[72057594037927928.0]", 72057594037927928.0);
TEST_DOUBLE("[72057594037927936.0]", 72057594037927936.0);
TEST_DOUBLE("[72057594037927932.0]", 72057594037927936.0);
TEST_DOUBLE("[7205759403792793199999e-5]", 72057594037927928.0);
TEST_DOUBLE("[7205759403792793200001e-5]", 72057594037927936.0);
TEST_DOUBLE("[9223372036854774784.0]", 9223372036854774784.0);
TEST_DOUBLE("[9223372036854775808.0]", 9223372036854775808.0);
TEST_DOUBLE("[9223372036854775296.0]", 9223372036854775808.0);
TEST_DOUBLE("[922337203685477529599999e-5]", 9223372036854774784.0);
TEST_DOUBLE("[922337203685477529600001e-5]", 9223372036854775808.0);
TEST_DOUBLE("[10141204801825834086073718800384]", 10141204801825834086073718800384.0);
TEST_DOUBLE("[10141204801825835211973625643008]", 10141204801825835211973625643008.0);
TEST_DOUBLE("[10141204801825834649023672221696]", 10141204801825835211973625643008.0);
TEST_DOUBLE("[1014120480182583464902367222169599999e-5]", 10141204801825834086073718800384.0);
TEST_DOUBLE("[1014120480182583464902367222169600001e-5]", 10141204801825835211973625643008.0);
TEST_DOUBLE("[5708990770823838890407843763683279797179383808]",
5708990770823838890407843763683279797179383808.0);
TEST_DOUBLE("[5708990770823839524233143877797980545530986496]",
5708990770823839524233143877797980545530986496.0);
TEST_DOUBLE("[5708990770823839207320493820740630171355185152]",
5708990770823839524233143877797980545530986496.0);
TEST_DOUBLE("[5708990770823839207320493820740630171355185151999e-3]",
5708990770823838890407843763683279797179383808.0);
TEST_DOUBLE("[5708990770823839207320493820740630171355185152001e-3]",
5708990770823839524233143877797980545530986496.0);
{
char n1e308[312]; // '1' followed by 308 '0'
n1e308[0] = '[';
n1e308[1] = '1';
for (int j = 2; j < 310; j++)
{
n1e308[j] = '0';
}
n1e308[310] = ']';
n1e308[311] = '\0';
TEST_DOUBLE(n1e308, 1E308);
}
// Cover trimming
TEST_DOUBLE(
"[2.22507385850720113605740979670913197593481954635164564802342610972482222202107694551652952390813508"
"7914149158913039621106870086438694594645527657207407820621743379988141063267329253552286881372149012"
"9811224514518898490572223072852551331557550159143974763979834118019993239625482890171070818506906306"
"6665599493827577257201576306269066333264756530000924588831643303777979186961204949739037782970490505"
"1080609940730262937128958950003583799967207254304360284078895771796150945516748243471030702609144621"
"5722898802581825451803257070188608721131280795122334262883686223215037756666225039825343359745688844"
"2390026549819838548794829220689472168983109969836584681402285424333066033985088644580400103493397042"
"7567186443383770486037861622771738545623065874679014086723327636718751234567890123456789012345678901"
"e-308]",
2.2250738585072014e-308);
}
SECTION("strings")
{
auto TEST_STRING = [](const std::string & json_string, const std::string & expected)
{
CAPTURE(json_string);
CAPTURE(expected);
CHECK(json::parse(json_string)[0].get<std::string>() == expected);
};
TEST_STRING("[\"\"]", "");
TEST_STRING("[\"Hello\"]", "Hello");
TEST_STRING("[\"Hello\\nWorld\"]", "Hello\nWorld");
//TEST_STRING("[\"Hello\\u0000World\"]", "Hello\0World");
TEST_STRING("[\"\\\"\\\\/\\b\\f\\n\\r\\t\"]", "\"\\/\b\f\n\r\t");
TEST_STRING("[\"\\u0024\"]", "\x24"); // Dollar sign U+0024
TEST_STRING("[\"\\u00A2\"]", "\xC2\xA2"); // Cents sign U+00A2
TEST_STRING("[\"\\u20AC\"]", "\xE2\x82\xAC"); // Euro sign U+20AC
TEST_STRING("[\"\\uD834\\uDD1E\"]", "\xF0\x9D\x84\x9E"); // G clef sign U+1D11E
}
SECTION("roundtrip")
{
// test cases are from https://github.com/miloyip/nativejson-benchmark/tree/master/test/data/roundtrip
for (auto filename :
{
"test/data/json_roundtrip/roundtrip01.json",
"test/data/json_roundtrip/roundtrip02.json",
"test/data/json_roundtrip/roundtrip03.json",
"test/data/json_roundtrip/roundtrip04.json",
"test/data/json_roundtrip/roundtrip05.json",
"test/data/json_roundtrip/roundtrip06.json",
"test/data/json_roundtrip/roundtrip07.json",
"test/data/json_roundtrip/roundtrip08.json",
"test/data/json_roundtrip/roundtrip09.json",
"test/data/json_roundtrip/roundtrip10.json",
"test/data/json_roundtrip/roundtrip11.json",
"test/data/json_roundtrip/roundtrip12.json",
"test/data/json_roundtrip/roundtrip13.json",
"test/data/json_roundtrip/roundtrip14.json",
"test/data/json_roundtrip/roundtrip15.json",
"test/data/json_roundtrip/roundtrip16.json",
"test/data/json_roundtrip/roundtrip17.json",
"test/data/json_roundtrip/roundtrip18.json",
"test/data/json_roundtrip/roundtrip19.json",
"test/data/json_roundtrip/roundtrip20.json",
"test/data/json_roundtrip/roundtrip21.json",
"test/data/json_roundtrip/roundtrip22.json",
"test/data/json_roundtrip/roundtrip23.json",
//"test/data/json_roundtrip/roundtrip24.json", // roundtrip error
//"test/data/json_roundtrip/roundtrip25.json", // roundtrip error
//"test/data/json_roundtrip/roundtrip26.json", // roundtrip error
//"test/data/json_roundtrip/roundtrip27.json", // roundtrip error
//"test/data/json_roundtrip/roundtrip28.json", // roundtrip error
"test/data/json_roundtrip/roundtrip29.json",
//"test/data/json_roundtrip/roundtrip30.json", // roundtrip error
//"test/data/json_roundtrip/roundtrip31.json", // roundtrip error
"test/data/json_roundtrip/roundtrip32.json"
})
{
CAPTURE(filename);
std::ifstream f(filename);
std::string json_string( (std::istreambuf_iterator<char>(f) ),
(std::istreambuf_iterator<char>()) );
json j = json::parse(json_string);
CHECK(j.dump() == json_string);
}
}
}
TEST_CASE("test suite from json-test-suite")
{
SECTION("read all sample.json")
{
// read a file with all unicode characters stored as single-character
// strings in a JSON array
std::ifstream f("test/data/json_testsuite/sample.json");
json j;
CHECK_NOTHROW(j << f);
// the array has 3 elements
CHECK(j.size() == 3);
}
}
TEST_CASE("json.org examples")
{
// here, we list all JSON values from http://json.org/example
SECTION("1.json")
{
std::ifstream f("test/data/json.org/1.json");
json j;
CHECK_NOTHROW(j << f);
}
SECTION("2.json")
{
std::ifstream f("test/data/json.org/2.json");
json j;
CHECK_NOTHROW(j << f);
}
SECTION("3.json")
{
std::ifstream f("test/data/json.org/3.json");
json j;
CHECK_NOTHROW(j << f);
}
SECTION("4.json")
{
std::ifstream f("test/data/json.org/4.json");
json j;
CHECK_NOTHROW(j << f);
}
SECTION("5.json")
{
std::ifstream f("test/data/json.org/5.json");
json j;
CHECK_NOTHROW(j << f);
}
}
TEST_CASE("RFC 7159 examples")
{
// here, we list all JSON values from the RFC 7159 document
SECTION("7. Strings")
{
CHECK(json::parse("\"\\u005C\"") == json("\\"));
CHECK(json::parse("\"\\uD834\\uDD1E\"") == json("𝄞"));
CHECK(json::parse("\"𝄞\"") == json("𝄞"));
}
SECTION("8.3 String Comparison")
{
CHECK(json::parse("\"a\\b\"") == json::parse("\"a\u005Cb\""));
}
SECTION("13 Examples")
{
{
CHECK_NOTHROW(json(R"(
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
"Animated" : false,
"IDs": [116, 943, 234, 38793]
}
}
)"));
}
{
CHECK_NOTHROW(json(R"(
[
{
"precision": "zip",
"Latitude": 37.7668,
"Longitude": -122.3959,
"Address": "",
"City": "SAN FRANCISCO",
"State": "CA",
"Zip": "94107",
"Country": "US"
},
{
"precision": "zip",
"Latitude": 37.371991,
"Longitude": -122.026020,
"Address": "",
"City": "SUNNYVALE",
"State": "CA",
"Zip": "94085",
"Country": "US"
}
])"));
}
CHECK(json::parse("\"Hello world!\"") == json("Hello world!"));
CHECK(json::parse("42") == json(42));
CHECK(json::parse("true") == json(true));
}
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: BaseStateTransition`1
#include "GlobalNamespace/BaseStateTransition_1.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Graphic
class Graphic;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: ColorTransitionSO
class ColorTransitionSO;
// Forward declaring type: BaseTransitionSO
class BaseTransitionSO;
}
// Forward declaring namespace: Tweening
namespace Tweening {
// Forward declaring type: ColorTween
class ColorTween;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Color
struct Color;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// WARNING Size may be invalid!
// Autogenerated type: ColorGraphicStateTransition
// [TokenAttribute] Offset: FFFFFFFF
// [RequireComponent] Offset: EA86E4
class ColorGraphicStateTransition : public GlobalNamespace::BaseStateTransition_1<UnityEngine::UI::Graphic*> {
public:
// [SpaceAttribute] Offset: 0xEB8B78
// private ColorTransitionSO _transition
// Size: 0x8
// Offset: 0x28
GlobalNamespace::ColorTransitionSO* transition;
// Field size check
static_assert(sizeof(GlobalNamespace::ColorTransitionSO*) == 0x8);
// private Tweening.ColorTween _colorTween
// Size: 0x8
// Offset: 0x30
Tweening::ColorTween* colorTween;
// Field size check
static_assert(sizeof(Tweening::ColorTween*) == 0x8);
// Creating value type constructor for type: ColorGraphicStateTransition
ColorGraphicStateTransition(GlobalNamespace::ColorTransitionSO* transition_ = {}, Tweening::ColorTween* colorTween_ = {}) noexcept : transition{transition_}, colorTween{colorTween_} {}
// Get instance field: private ColorTransitionSO _transition
GlobalNamespace::ColorTransitionSO* _get__transition();
// Set instance field: private ColorTransitionSO _transition
void _set__transition(GlobalNamespace::ColorTransitionSO* value);
// Get instance field: private Tweening.ColorTween _colorTween
Tweening::ColorTween* _get__colorTween();
// Set instance field: private Tweening.ColorTween _colorTween
void _set__colorTween(Tweening::ColorTween* value);
// private System.Void StartTween(UnityEngine.Color endColor)
// Offset: 0x1EFD3C4
void StartTween(UnityEngine::Color endColor);
// private System.Void <StartTween>b__16_0(UnityEngine.Color color)
// Offset: 0x1EFD938
void $StartTween$b__16_0(UnityEngine::Color color);
// private System.Void <StartTween>b__16_1()
// Offset: 0x1EFD95C
void $StartTween$b__16_1();
// protected override BaseTransitionSO get_transition()
// Offset: 0x1EFD378
// Implemented from: BaseStateTransition
// Base method: BaseTransitionSO BaseStateTransition::get_transition()
GlobalNamespace::BaseTransitionSO* get_transition();
// public System.Void .ctor()
// Offset: 0x1EFD8E8
// Implemented from: BaseStateTransition`1
// Base method: System.Void BaseStateTransition_1::.ctor()
// Base method: System.Void BaseStateTransition::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ColorGraphicStateTransition* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::ColorGraphicStateTransition::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ColorGraphicStateTransition*, creationType>()));
}
// protected override System.Void TransitionToNormalState()
// Offset: 0x1EFD380
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::TransitionToNormalState()
void TransitionToNormalState();
// protected override System.Void TransitionToHighlightedState()
// Offset: 0x1EFD5E4
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::TransitionToHighlightedState()
void TransitionToHighlightedState();
// protected override System.Void TransitionToPressedState()
// Offset: 0x1EFD628
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::TransitionToPressedState()
void TransitionToPressedState();
// protected override System.Void TransitionToDisabledState()
// Offset: 0x1EFD66C
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::TransitionToDisabledState()
void TransitionToDisabledState();
// protected override System.Void TransitionToSelectedState()
// Offset: 0x1EFD6B0
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::TransitionToSelectedState()
void TransitionToSelectedState();
// protected override System.Void TransitionToSelectedAndHighlightedState()
// Offset: 0x1EFD6F4
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::TransitionToSelectedAndHighlightedState()
void TransitionToSelectedAndHighlightedState();
// protected override System.Void SetNormalState()
// Offset: 0x1EFD738
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::SetNormalState()
void SetNormalState();
// protected override System.Void SetHighlightedState()
// Offset: 0x1EFD780
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::SetHighlightedState()
void SetHighlightedState();
// protected override System.Void SetPressedState()
// Offset: 0x1EFD7C8
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::SetPressedState()
void SetPressedState();
// protected override System.Void SetDisabledState()
// Offset: 0x1EFD810
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::SetDisabledState()
void SetDisabledState();
// protected override System.Void SetSelectedState()
// Offset: 0x1EFD858
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::SetSelectedState()
void SetSelectedState();
// protected override System.Void SetSelectedAndHighlightedState()
// Offset: 0x1EFD8A0
// Implemented from: BaseStateTransition
// Base method: System.Void BaseStateTransition::SetSelectedAndHighlightedState()
void SetSelectedAndHighlightedState();
}; // ColorGraphicStateTransition
// WARNING Not writing size check since size may be invalid!
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ColorGraphicStateTransition*, "", "ColorGraphicStateTransition");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::StartTween
// Il2CppName: StartTween
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)(UnityEngine::Color)>(&GlobalNamespace::ColorGraphicStateTransition::StartTween)> {
static const MethodInfo* get() {
static auto* endColor = &::il2cpp_utils::GetClassFromName("UnityEngine", "Color")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "StartTween", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{endColor});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::$StartTween$b__16_0
// Il2CppName: <StartTween>b__16_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)(UnityEngine::Color)>(&GlobalNamespace::ColorGraphicStateTransition::$StartTween$b__16_0)> {
static const MethodInfo* get() {
static auto* color = &::il2cpp_utils::GetClassFromName("UnityEngine", "Color")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "<StartTween>b__16_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{color});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::$StartTween$b__16_1
// Il2CppName: <StartTween>b__16_1
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::$StartTween$b__16_1)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "<StartTween>b__16_1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::get_transition
// Il2CppName: get_transition
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::BaseTransitionSO* (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::get_transition)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "get_transition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::TransitionToNormalState
// Il2CppName: TransitionToNormalState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::TransitionToNormalState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "TransitionToNormalState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::TransitionToHighlightedState
// Il2CppName: TransitionToHighlightedState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::TransitionToHighlightedState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "TransitionToHighlightedState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::TransitionToPressedState
// Il2CppName: TransitionToPressedState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::TransitionToPressedState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "TransitionToPressedState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::TransitionToDisabledState
// Il2CppName: TransitionToDisabledState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::TransitionToDisabledState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "TransitionToDisabledState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::TransitionToSelectedState
// Il2CppName: TransitionToSelectedState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::TransitionToSelectedState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "TransitionToSelectedState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::TransitionToSelectedAndHighlightedState
// Il2CppName: TransitionToSelectedAndHighlightedState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::TransitionToSelectedAndHighlightedState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "TransitionToSelectedAndHighlightedState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::SetNormalState
// Il2CppName: SetNormalState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::SetNormalState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "SetNormalState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::SetHighlightedState
// Il2CppName: SetHighlightedState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::SetHighlightedState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "SetHighlightedState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::SetPressedState
// Il2CppName: SetPressedState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::SetPressedState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "SetPressedState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::SetDisabledState
// Il2CppName: SetDisabledState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::SetDisabledState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "SetDisabledState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::SetSelectedState
// Il2CppName: SetSelectedState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::SetSelectedState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "SetSelectedState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorGraphicStateTransition::SetSelectedAndHighlightedState
// Il2CppName: SetSelectedAndHighlightedState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorGraphicStateTransition::*)()>(&GlobalNamespace::ColorGraphicStateTransition::SetSelectedAndHighlightedState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorGraphicStateTransition*), "SetSelectedAndHighlightedState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
|
/** \file
* \brief Implementation of Hashing (class HashingBase)
*
* \author Carsten Gutwenger
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.txt in the root directory of the OGDF installation for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* \see http://www.gnu.org/copyleft/gpl.html
***************************************************************/
#include <ogdf/basic/Hashing.h>
namespace ogdf {
HashingBase::HashingBase(int minTableSize)
{
m_count = 0;
init(m_minTableSize = minTableSize);
}
HashingBase::HashingBase(const HashingBase &H)
{
copyAll(H);
}
HashingBase::~HashingBase()
{
free(m_table);
}
void HashingBase::init(int tableSize)
{
OGDF_ASSERT(tableSize >= m_minTableSize)
m_tableSize = tableSize;
m_hashMask = tableSize-1;
m_tableSizeHigh = tableSize << 1;
m_tableSizeLow = (tableSize > m_minTableSize) ? (tableSize >> 1) : -1;
m_table = (HashElementBase **)calloc(tableSize,sizeof(HashElementBase *));
}
void HashingBase::destroyAll()
{
HashElementBase **pList = m_table, **pListStop = m_table+m_tableSize;
for(; pList != pListStop; ++pList) {
HashElementBase *pElement = *pList, *pNext;
for (; pElement; pElement = pNext) {
pNext = pElement->next();
destroy(pElement);
}
}
}
void HashingBase::copyAll(const HashingBase &H)
{
m_count = 0;
m_minTableSize = H.m_minTableSize;
init(H.m_tableSize);
HashElementBase **pList = H.m_table;
HashElementBase **pListStop = H.m_table+m_tableSize;
for(; pList != pListStop; ++pList) {
HashElementBase *pElement = *pList;
for (; pElement; pElement = pElement->next())
insert(H.copy(pElement));
}
}
void HashingBase::clear()
{
destroyAll();
free(m_table);
m_count = 0;
init(m_minTableSize);
}
HashingBase &HashingBase::operator=(const HashingBase &H)
{
destroyAll();
free(m_table);
copyAll(H);
return *this;
}
void HashingBase::resize(int newTableSize)
{
HashElementBase **oldTable = m_table;
HashElementBase **oldTableStop = oldTable + m_tableSize;
init(newTableSize);
for(HashElementBase **pOldList = oldTable;
pOldList != oldTableStop; ++pOldList)
{
HashElementBase *pElement = *pOldList, *pNext;
for(; pElement; pElement = pNext) {
pNext = pElement->m_next;
HashElementBase **pList = m_table +
(pElement->m_hashValue & m_hashMask);
pElement->m_next = *pList;
*pList = pElement;
}
}
free(oldTable);
}
void HashingBase::insert(HashElementBase *pElement)
{
if (++m_count == m_tableSizeHigh)
resize(m_tableSizeHigh);
HashElementBase **pList = m_table + (pElement->m_hashValue & m_hashMask);
pElement->m_next = *pList;
*pList = pElement;
}
void HashingBase::del(HashElementBase *pElement)
{
HashElementBase **pList = m_table + (pElement->m_hashValue & m_hashMask);
HashElementBase *pPrev = *pList;
if (pPrev == pElement) {
*pList = pElement->m_next;
} else {
while (pPrev->m_next != pElement) pPrev = pPrev->m_next;
pPrev->m_next = pElement->m_next;
}
if (--m_count == m_tableSizeLow)
resize(m_tableSizeLow);
}
HashElementBase *HashingBase::firstElement(HashElementBase ***pList) const
{
HashElementBase **pStop = m_table + m_tableSize;
for(*pList = m_table; *pList != pStop; ++(*pList))
if (**pList) return **pList;
return nullptr;
}
HashElementBase *HashingBase::nextElement(HashElementBase ***pList,
HashElementBase *pElement) const
{
if ((pElement = pElement->next()) != nullptr) return pElement;
HashElementBase **pStop = m_table + m_tableSize;
for(++(*pList); *pList != pStop; ++(*pList))
if (**pList) return **pList;
return nullptr;
}
size_t DefHashFunc<string>::hash(const string &key) const
{
size_t hashValue = 0;
for(string::size_type i = 0; i < key.size(); ++i)
hashValue += int(key[i]);
return hashValue;
}
} // end namespace ogdf
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "deps_log.h"
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#elif defined(_MSC_VER) && (_MSC_VER < 1900)
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
#endif
#include "graph.h"
#include "metrics.h"
#include "state.h"
#include "util.h"
#if 0
// The version is stored as 4 bytes after the signature and also serves as a
// byte order mark. Signature and version combined are 16 bytes long.
const char kFileSignature[] = "# ninjadeps\n";
const int kCurrentVersion = 4;
// Record size is currently limited to less than the full 32 bit, due to
// internal buffers having to have this size.
const unsigned kMaxRecordSize = (1 << 19) - 1;
DepsLog::~DepsLog() {
Close();
}
bool DepsLog::OpenForWrite(const string& path, string* err) {
if (needs_recompaction_) {
if (!Recompact(path, err))
return false;
}
file_ = fopen(path.c_str(), "ab");
if (!file_) {
*err = strerror(errno);
return false;
}
// Set the buffer size to this and flush the file buffer after every record
// to make sure records aren't written partially.
setvbuf(file_, NULL, _IOFBF, kMaxRecordSize + 1);
SetCloseOnExec(fileno(file_));
// Opening a file in append mode doesn't set the file pointer to the file's
// end on Windows. Do that explicitly.
fseek(file_, 0, SEEK_END);
if (ftell(file_) == 0) {
if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
*err = strerror(errno);
return false;
}
if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
*err = strerror(errno);
return false;
}
}
if (fflush(file_) != 0) {
*err = strerror(errno);
return false;
}
return true;
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
const vector<Node*>& nodes) {
return RecordDeps(node, mtime, nodes.size(),
nodes.empty() ? NULL : (Node**)&nodes.front());
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
int node_count, Node** nodes) {
// Track whether there's any new data to be recorded.
bool made_change = false;
// Assign ids to all nodes that are missing one.
if (node->id() < 0) {
if (!RecordId(node))
return false;
made_change = true;
}
for (int i = 0; i < node_count; ++i) {
if (nodes[i]->id() < 0) {
if (!RecordId(nodes[i]))
return false;
made_change = true;
}
}
// See if the new data is different than the existing data, if any.
if (!made_change) {
Deps* deps = GetDeps(node);
if (!deps ||
deps->mtime != mtime ||
deps->node_count != node_count) {
made_change = true;
} else {
for (int i = 0; i < node_count; ++i) {
if (deps->nodes[i] != nodes[i]) {
made_change = true;
break;
}
}
}
}
// Don't write anything if there's no new info.
if (!made_change)
return true;
// Update on-disk representation.
unsigned size = 4 * (1 + 2 + node_count);
if (size > kMaxRecordSize) {
errno = ERANGE;
return false;
}
size |= 0x80000000; // Deps record: set high bit.
if (fwrite(&size, 4, 1, file_) < 1)
return false;
int id = node->id();
if (fwrite(&id, 4, 1, file_) < 1)
return false;
uint32_t mtime_part = static_cast<uint32_t>(mtime & 0xffffffff);
if (fwrite(&mtime_part, 4, 1, file_) < 1)
return false;
mtime_part = static_cast<uint32_t>((mtime >> 32) & 0xffffffff);
if (fwrite(&mtime_part, 4, 1, file_) < 1)
return false;
for (int i = 0; i < node_count; ++i) {
id = nodes[i]->id();
if (fwrite(&id, 4, 1, file_) < 1)
return false;
}
if (fflush(file_) != 0)
return false;
// Update in-memory representation.
Deps* deps = new Deps(mtime, node_count);
for (int i = 0; i < node_count; ++i)
deps->nodes[i] = nodes[i];
UpdateDeps(node->id(), deps);
return true;
}
void DepsLog::Close() {
if (file_)
fclose(file_);
file_ = NULL;
}
bool DepsLog::Load(const string& path, State* state, string* err) {
METRIC_RECORD(".ninja_deps load");
char buf[kMaxRecordSize + 1];
FILE* f = fopen(path.c_str(), "rb");
if (!f) {
if (errno == ENOENT)
return true;
*err = strerror(errno);
return false;
}
bool valid_header = true;
int version = 0;
if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
valid_header = false;
// Note: For version differences, this should migrate to the new format.
// But the v1 format could sometimes (rarely) end up with invalid data, so
// don't migrate v1 to v3 to force a rebuild. (v2 only existed for a few days,
// and there was no release with it, so pretend that it never happened.)
if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
version != kCurrentVersion) {
if (version == 1)
*err = "deps log version change; rebuilding";
else
*err = "bad deps log signature or version; starting over";
fclose(f);
unlink(path.c_str());
// Don't report this as a failure. An empty deps log will cause
// us to rebuild the outputs anyway.
return true;
}
long offset;
bool read_failed = false;
int unique_dep_record_count = 0;
int total_dep_record_count = 0;
for (;;) {
offset = ftell(f);
unsigned size;
if (fread(&size, 4, 1, f) < 1) {
if (!feof(f))
read_failed = true;
break;
}
bool is_deps = (size >> 31) != 0;
size = size & 0x7FFFFFFF;
if (size > kMaxRecordSize || fread(buf, size, 1, f) < 1) {
read_failed = true;
break;
}
if (is_deps) {
assert(size % 4 == 0);
int* deps_data = reinterpret_cast<int*>(buf);
int out_id = deps_data[0];
TimeStamp mtime;
mtime = (TimeStamp)(((uint64_t)(unsigned int)deps_data[2] << 32) |
(uint64_t)(unsigned int)deps_data[1]);
deps_data += 3;
int deps_count = (size / 4) - 3;
Deps* deps = new Deps(mtime, deps_count);
for (int i = 0; i < deps_count; ++i) {
assert(deps_data[i] < (int)nodes_.size());
assert(nodes_[deps_data[i]]);
deps->nodes[i] = nodes_[deps_data[i]];
}
total_dep_record_count++;
if (!UpdateDeps(out_id, deps))
++unique_dep_record_count;
} else {
int path_size = size - 4;
assert(path_size > 0); // CanonicalizePath() rejects empty paths.
// There can be up to 3 bytes of padding.
if (buf[path_size - 1] == '\0') --path_size;
if (buf[path_size - 1] == '\0') --path_size;
if (buf[path_size - 1] == '\0') --path_size;
StringPiece subpath(buf, path_size);
// It is not necessary to pass in a correct slash_bits here. It will
// either be a Node that's in the manifest (in which case it will already
// have a correct slash_bits that GetNode will look up), or it is an
// implicit dependency from a .d which does not affect the build command
// (and so need not have its slashes maintained).
Node* node = state->GetNode(subpath, 0);
// Check that the expected index matches the actual index. This can only
// happen if two ninja processes write to the same deps log concurrently.
// (This uses unary complement to make the checksum look less like a
// dependency record entry.)
unsigned checksum = *reinterpret_cast<unsigned*>(buf + size - 4);
int expected_id = ~checksum;
int id = nodes_.size();
if (id != expected_id) {
read_failed = true;
break;
}
assert(node->id() < 0);
node->set_id(id);
nodes_.push_back(node);
}
}
if (read_failed) {
// An error occurred while loading; try to recover by truncating the
// file to the last fully-read record.
if (ferror(f)) {
*err = strerror(ferror(f));
} else {
*err = "premature end of file";
}
fclose(f);
if (!Truncate(path, offset, err))
return false;
// The truncate succeeded; we'll just report the load error as a
// warning because the build can proceed.
*err += "; recovering";
return true;
}
fclose(f);
// Rebuild the log if there are too many dead records.
int kMinCompactionEntryCount = 1000;
int kCompactionRatio = 3;
if (total_dep_record_count > kMinCompactionEntryCount &&
total_dep_record_count > unique_dep_record_count * kCompactionRatio) {
needs_recompaction_ = true;
}
return true;
}
DepsLog::Deps* DepsLog::GetDeps(Node* node) {
// Abort if the node has no id (never referenced in the deps) or if
// there's no deps recorded for the node.
if (node->id() < 0 || node->id() >= (int)deps_.size())
return NULL;
return deps_[node->id()];
}
bool DepsLog::Recompact(const string& path, string* err) {
METRIC_RECORD(".ninja_deps recompact");
Close();
string temp_path = path + ".recompact";
// OpenForWrite() opens for append. Make sure it's not appending to a
// left-over file from a previous recompaction attempt that crashed somehow.
unlink(temp_path.c_str());
DepsLog new_log;
if (!new_log.OpenForWrite(temp_path, err))
return false;
// Clear all known ids so that new ones can be reassigned. The new indices
// will refer to the ordering in new_log, not in the current log.
for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i)
(*i)->set_id(-1);
// Write out all deps again.
for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
Deps* deps = deps_[old_id];
if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps.
if (!IsDepsEntryLiveFor(nodes_[old_id]))
continue;
if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
deps->node_count, deps->nodes)) {
new_log.Close();
return false;
}
}
new_log.Close();
// All nodes now have ids that refer to new_log, so steal its data.
deps_.swap(new_log.deps_);
nodes_.swap(new_log.nodes_);
if (unlink(path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
if (rename(temp_path.c_str(), path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
return true;
}
bool DepsLog::IsDepsEntryLiveFor(Node* node) {
// Skip entries that don't have in-edges or whose edges don't have a
// "deps" attribute. They were in the deps log from previous builds, but
// the the files they were for were removed from the build and their deps
// entries are no longer needed.
// (Without the check for "deps", a chain of two or more nodes that each
// had deps wouldn't be collected in a single recompaction.)
return node->in_edge() && !node->in_edge()->GetBinding("deps").empty();
}
bool DepsLog::UpdateDeps(int out_id, Deps* deps) {
if (out_id >= (int)deps_.size())
deps_.resize(out_id + 1);
bool delete_old = deps_[out_id] != NULL;
if (delete_old)
delete deps_[out_id];
deps_[out_id] = deps;
return delete_old;
}
bool DepsLog::RecordId(Node* node) {
int path_size = node->path().size();
int padding = (4 - path_size % 4) % 4; // Pad path to 4 byte boundary.
unsigned size = path_size + padding + 4;
if (size > kMaxRecordSize) {
errno = ERANGE;
return false;
}
if (fwrite(&size, 4, 1, file_) < 1)
return false;
if (fwrite(node->path().data(), path_size, 1, file_) < 1) {
assert(node->path().size() > 0);
return false;
}
if (padding && fwrite("\0\0", padding, 1, file_) < 1)
return false;
int id = nodes_.size();
unsigned checksum = ~(unsigned)id;
if (fwrite(&checksum, 4, 1, file_) < 1)
return false;
if (fflush(file_) != 0)
return false;
node->set_id(id);
nodes_.push_back(node);
return true;
}
#endif
|
// HFSM2 (hierarchical state machine for games and interactive applications)
// Created by Andrew Gresyk
////////////////////////////////////////////////////////////////////////////////
template <typename TConfig>
void
LoggerT<TConfig>::recordMethod(Context& /*context*/,
const StateID origin,
const Method method) noexcept
{
REQUIRE(hfsm2::methodName(method));
switch (method) {
#if HFSM2_UTILITY_THEORY_AVAILABLE()
case Method::RANK:
history.emplace_back(origin, Event::Type::RANK);
break;
case Method::UTILITY:
history.emplace_back(origin, Event::Type::UTILITY);
break;
#endif
case Method::ENTRY_GUARD:
history.emplace_back(origin, Event::Type::ENTRY_GUARD);
break;
case Method::ENTER:
history.emplace_back(origin, Event::Type::ENTER);
break;
case Method::REENTER:
history.emplace_back(origin, Event::Type::REENTER);
break;
case Method::UPDATE:
history.emplace_back(origin, Event::Type::UPDATE);
break;
case Method::REVERSE_UPDATE:
history.emplace_back(origin, Event::Type::REVERSE_UPDATE);
break;
case Method::REACT:
history.emplace_back(origin, Event::Type::REACT);
break;
case Method::REVERSE_REACT:
history.emplace_back(origin, Event::Type::REVERSE_REACT);
break;
case Method::EXIT_GUARD:
history.emplace_back(origin, Event::Type::EXIT_GUARD);
break;
case Method::EXIT:
history.emplace_back(origin, Event::Type::EXIT);
break;
#if HFSM2_PLANS_AVAILABLE()
case Method::PLAN_SUCCEEDED:
history.emplace_back(origin, Event::Type::PLAN_SUCCEEDED);
break;
case Method::PLAN_FAILED:
history.emplace_back(origin, Event::Type::PLAN_FAILED);
break;
#endif
default:
HFSM2_BREAK();
}
}
//------------------------------------------------------------------------------
template <typename TConfig>
void
LoggerT<TConfig>::recordTransition(Context& /*context*/,
const StateID origin,
const TransitionType transitionType,
const StateID target) noexcept
{
REQUIRE(hfsm2::transitionName(transitionType));
switch (transitionType) {
case TransitionType::CHANGE:
history.emplace_back(origin, Event::Type::CHANGE, target);
break;
case TransitionType::RESTART:
history.emplace_back(origin, Event::Type::RESTART, target);
break;
case TransitionType::RESUME:
history.emplace_back(origin, Event::Type::RESUME, target);
break;
#if HFSM2_UTILITY_THEORY_AVAILABLE()
case TransitionType::UTILIZE:
history.emplace_back(origin, Event::Type::UTILIZE, target);
break;
case TransitionType::RANDOMIZE:
history.emplace_back(origin, Event::Type::RANDOMIZE, target);
break;
#endif
case TransitionType::SCHEDULE:
history.emplace_back(origin, Event::Type::SCHEDULE, target);
break;
default:
HFSM2_BREAK();
}
}
//------------------------------------------------------------------------------
#if HFSM2_PLANS_AVAILABLE()
template <typename TConfig>
void
LoggerT<TConfig>::recordTaskStatus(Context& /*context*/,
const RegionID region,
const StateID origin,
const StatusEvent event) noexcept
{
switch (event) {
case StatusEvent::SUCCEEDED:
history.emplace_back(region, Event::Type::TASK_SUCCESS, origin);
break;
case StatusEvent::FAILED:
history.emplace_back(region, Event::Type::TASK_FAILURE, origin);
break;
default:
HFSM2_BREAK();
}
}
//------------------------------------------------------------------------------
template <typename TConfig>
void
LoggerT<TConfig>::recordPlanStatus(Context& /*context*/,
const RegionID region,
const StatusEvent event) noexcept
{
switch (event) {
case StatusEvent::SUCCEEDED:
history.emplace_back(region, Event::Type::PLAN_SUCCESS, hfsm2::INVALID_STATE_ID);
break;
case StatusEvent::FAILED:
history.emplace_back(region, Event::Type::PLAN_FAILURE, hfsm2::INVALID_STATE_ID);
break;
default:
HFSM2_BREAK();
}
}
#endif
//------------------------------------------------------------------------------
#if HFSM2_UTILITY_THEORY_AVAILABLE()
template <typename TConfig>
void
LoggerT<TConfig>::recordUtilityResolution(Context& /*context*/,
const StateID head,
const StateID prong,
const Utilty utilty) noexcept
{
history.emplace_back(head, Event::Type::UTILITY_RESOLUTION, prong, utilty);
}
//------------------------------------------------------------------------------
template <typename TConfig>
void
LoggerT<TConfig>::recordRandomResolution(Context& /*context*/,
const StateID head,
const StateID prong,
const Utilty utilty) noexcept
{
history.emplace_back(head, Event::Type::RANDOM_RESOLUTION, prong, utilty);
}
#endif
//------------------------------------------------------------------------------
template <typename TConfig>
void
LoggerT<TConfig>::recordCancelledPending(Context& /*context*/,
const StateID origin) noexcept
{
history.emplace_back(origin, Event::Type::CANCEL_PENDING);
}
//------------------------------------------------------------------------------
template <typename TConfig>
void
LoggerT<TConfig>::assertSequence(const Events& reference) noexcept {
const auto count = std::max(history.size(), reference.size());
for (unsigned i = 0; i < count; ++i) {
REQUIRE(i < history.size()); //-V521
REQUIRE(i < reference.size()); //-V521
if (i < history.size() &&
i < reference.size())
{
REQUIRE(history[i].type == reference[i].type); //-V521
REQUIRE(history[i].origin == reference[i].origin); //-V521
REQUIRE(history[i].target == reference[i].target); //-V521
}
}
history.clear();
}
//------------------------------------------------------------------------------
template <typename TMachine>
void
assertActive(TMachine& machine,
const Types& all,
const Types& toCheck) noexcept
{
for (const auto& type : all) {
if (std::find(toCheck.begin(), toCheck.end(), type) != toCheck.end())
REQUIRE( machine.isActive(type)); //-V521
else
REQUIRE(!machine.isActive(type)); //-V521
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TMachine>
void
assertResumable(TMachine& machine,
const Types& all,
const Types& toCheck) noexcept
{
for (const auto& type : all) {
if (std::find(toCheck.begin(), toCheck.end(), type) != toCheck.end())
REQUIRE( machine.isResumable(type)); //-V521
else
REQUIRE(!machine.isResumable(type)); //-V521
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if HFSM2_TRANSITION_HISTORY_AVAILABLE()
template <typename TMachine>
void
assertLastTransitions(TMachine& machine,
const Types& all,
const Types& toCheck) noexcept
{
for (const auto& type : all) {
if (std::find(toCheck.begin(), toCheck.end(), type) != toCheck.end())
REQUIRE( machine.lastTransitionTo(type)); //-V521
else
REQUIRE(!machine.lastTransitionTo(type)); //-V521
}
}
#endif
////////////////////////////////////////////////////////////////////////////////
|
//Code By HeRaNO
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if (n < 0)
cout << "negative";
else if (n == 0)
cout << "zero";
else cout << "positive";
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
/**
Given n and a real number x >= 0, returns the closest rational approximation p/q s.t. p, q <= n.
It will obey that |p/q - x| is minimum for p, q <= n
Time: O(log n)
**/
using ld = long double;
pair<ll, ll> approximate(ld x, ll n) {
ll LP = 0, LQ = 1, P = 1, Q = 0, inf = LLONG_MAX; ld y = x;
while (1) {
ll lim = min(P ? (n - LP) / P : inf, Q ? (n - LQ) / Q : inf),
a = (ll)floor(y), b = min(a, lim),
NP = b * P + LP, NQ = b * Q + LQ;
if (a > b) {
// If b > a/2, we have a semi-convergent that gives us a
// better approximation; if b = a/2, we *may* have one.
// Return {P, Q} here for a more canonical approximation.
return (abs(x - (ld)NP / (ld)NQ) < abs(x - (ld)P / (ld)Q)) ?
make_pair(NP, NQ) : make_pair(P, Q);
}
if (abs(y = 1 / (y - (ld)a)) > 3 * n) {
return {NP, NQ};
}
LP = P; P = NP;
LQ = Q; Q = NQ;
}
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t; cin >> t;
while (t--) {
long double x; cin >> x;
ll n = 1e9;
auto ans = approximate(x, n);
cout << ans.first << ' ' << ans.second << '\n';
}
return 0;
}
// https://official.contest.yandex.ru/opencupXVIII/contest/5457/problems/E/?success=51368253#7/2017_10_14/fqGQVSrCf7
|
//
// policeAndRecuit.cpp
// C++
//
// Created by Anish Mookherjee on 29/03/20.
// Copyright © 2020 Anish Mookherjee. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n,police=0,crime=0;
cin>>n;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
if(x!=-1)
police+=x;
else if(x==-1 && police>0)
police--;
else
crime++;
}
cout<<crime<<endl;
return 0;
}
|
/*
Copyright 2008 Larry Gritz and the other authors and contributors.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the software's owners nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(This is the Modified BSD License)
*/
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <map>
#include <OpenEXR/ImfOutputFile.h>
#include <OpenEXR/ImfTiledOutputFile.h>
#include <OpenEXR/ImfChannelList.h>
#include <OpenEXR/ImfEnvmap.h>
#include <OpenEXR/ImfIntAttribute.h>
#include <OpenEXR/ImfFloatAttribute.h>
#include <OpenEXR/ImfMatrixAttribute.h>
#include <OpenEXR/ImfVecAttribute.h>
#include <OpenEXR/ImfStringAttribute.h>
#include <OpenEXR/ImfEnvmapAttribute.h>
#include <OpenEXR/ImfCompressionAttribute.h>
#include <OpenEXR/ImfCRgbaFile.h> // JUST to get symbols to figure out version!
#ifdef IMF_B44_COMPRESSION
#define OPENEXR_VERSION_IS_1_6_OR_LATER
#endif
#include "dassert.h"
#include "imageio.h"
#include "thread.h"
#include "strutil.h"
#include "sysutil.h"
OIIO_PLUGIN_NAMESPACE_BEGIN
class OpenEXROutput : public ImageOutput {
public:
OpenEXROutput ();
virtual ~OpenEXROutput ();
virtual const char * format_name (void) const { return "openexr"; }
virtual bool supports (const std::string &feature) const;
virtual bool open (const std::string &name, const ImageSpec &spec,
OpenMode mode=Create);
virtual bool close ();
virtual bool write_scanline (int y, int z, TypeDesc format,
const void *data, stride_t xstride);
virtual bool write_scanlines (int ybegin, int yend, int z,
TypeDesc format, const void *data,
stride_t xstride, stride_t ystride);
virtual bool write_tile (int x, int y, int z, TypeDesc format,
const void *data, stride_t xstride,
stride_t ystride, stride_t zstride);
virtual bool write_tiles (int xbegin, int xend, int ybegin, int yend,
int zbegin, int zend, TypeDesc format,
const void *data, stride_t xstride,
stride_t ystride, stride_t zstride);
private:
Imf::Header *m_header; ///< Ptr to image header
Imf::OutputFile *m_output_scanline; ///< Input for scanline files
Imf::TiledOutputFile *m_output_tiled; ///< Input for tiled files
int m_levelmode; ///< The level mode of the file
int m_roundingmode; ///< Rounding mode of the file
int m_subimage; ///< What subimage we're writing now
int m_nsubimages; ///< How many subimages are there?
int m_miplevel; ///< What miplevel we're writing now
int m_nmiplevels; ///< How many mip levels are there?
std::vector<Imf::PixelType> m_pixeltype; ///< Imf pixel type for each chan
std::vector<unsigned char> m_scratch; ///< Scratch space for us to use
// Initialize private members to pre-opened state
void init (void) {
m_header = NULL;
m_output_scanline = NULL;
m_output_tiled = NULL;
m_subimage = -1;
m_miplevel = -1;
}
// Add a parameter to the output
bool put_parameter (const std::string &name, TypeDesc type,
const void *data);
};
// Obligatory material to make this a recognizeable imageio plugin:
OIIO_PLUGIN_EXPORTS_BEGIN
DLLEXPORT ImageOutput *
openexr_output_imageio_create ()
{
return new OpenEXROutput;
}
DLLEXPORT int openexr_imageio_version = OIIO_PLUGIN_VERSION;
DLLEXPORT const char * openexr_output_extensions[] = {
"exr", NULL
};
OIIO_PLUGIN_EXPORTS_END
static std::string format_string ("openexr");
static std::string format_prefix ("openexr_");
namespace pvt {
void set_exr_threads ();
}
OpenEXROutput::OpenEXROutput ()
{
pvt::set_exr_threads ();
init ();
}
OpenEXROutput::~OpenEXROutput ()
{
// Close, if not already done.
close ();
delete m_output_scanline; m_output_scanline = NULL;
delete m_output_tiled; m_output_tiled = NULL;
delete m_header; m_header = NULL;
}
bool
OpenEXROutput::supports (const std::string &feature) const
{
if (feature == "tiles")
return true;
if (feature == "mipmap")
return true;
if (feature == "channelformats")
return true;
if (feature == "displaywindow")
return true;
if (feature == "origin")
return true;
if (feature == "negativeorigin")
return true;
// EXR supports random write order iff lineOrder is set to 'random Y'
if (feature == "random_access") {
const ImageIOParameter *param = m_spec.find_attribute("openexr:lineOrder");
const char *lineorder = param ? *(char **)param->data() : NULL;
return (lineorder && Strutil::iequals (lineorder, "randomY"));
}
// FIXME: we could support "empty"
// Everything else, we either don't support or don't know about
return false;
}
bool
OpenEXROutput::open (const std::string &name, const ImageSpec &userspec,
OpenMode mode)
{
if (mode == AppendSubimage) {
error ("%s does not support subimages", format_name());
return false;
}
if (mode == AppendMIPLevel && (m_output_scanline || m_output_tiled)) {
// Special case for appending to an open file -- we don't need
// to close and reopen
if (m_spec.tile_width && m_levelmode != Imf::ONE_LEVEL) {
// OpenEXR does not support differing tile sizes on different
// MIP-map levels. Reject the open() if not using the original
// tile sizes.
if (userspec.tile_width != m_spec.tile_width ||
userspec.tile_height != m_spec.tile_height) {
error ("OpenEXR tiles must have the same size on all MIPmap levels");
return false;
}
// Copy the new mip level size. Keep everything else from the
// original level.
m_spec.width = userspec.width;
m_spec.height = userspec.height;
// N.B. do we need to copy anything else from userspec?
++m_miplevel;
return true;
}
}
m_spec = userspec; // Stash the spec
if (m_spec.width < 1 || m_spec.height < 1) {
error ("Image resolution must be at least 1x1, you asked for %d x %d",
userspec.width, userspec.height);
return false;
}
if (m_spec.depth < 1)
m_spec.depth = 1;
if (m_spec.depth > 1) {
error ("%s does not support volume images (depth > 1)", format_name());
return false;
}
if (m_spec.full_width <= 0)
m_spec.full_width = m_spec.width;
if (m_spec.full_height <= 0)
m_spec.full_height = m_spec.height;
// Force use of one of the three data types that OpenEXR supports
switch (m_spec.format.basetype) {
case TypeDesc::UINT:
m_spec.format = TypeDesc::UINT;
break;
case TypeDesc::FLOAT:
case TypeDesc::DOUBLE:
m_spec.format = TypeDesc::FLOAT;
break;
default:
// Everything else defaults to half
m_spec.format = TypeDesc::HALF;
}
Imath::Box2i dataWindow (Imath::V2i (m_spec.x, m_spec.y),
Imath::V2i (m_spec.width + m_spec.x - 1,
m_spec.height + m_spec.y - 1));
Imath::Box2i displayWindow (Imath::V2i (m_spec.full_x, m_spec.full_y),
Imath::V2i (m_spec.full_width+m_spec.full_x-1,
m_spec.full_height+m_spec.full_y-1));
m_header = new Imf::Header (displayWindow, dataWindow);
// Insert channels into the header. Also give the channels names if
// the user botched it.
static const char *default_chan_names[] = { "R", "G", "B", "A" };
m_spec.channelnames.resize (m_spec.nchannels);
for (int c = 0; c < m_spec.nchannels; ++c) {
if (m_spec.channelnames[c].empty())
m_spec.channelnames[c] = (c<4) ? default_chan_names[c]
: Strutil::format ("unknown %d", c);
TypeDesc format = m_spec.channelformats.size() ?
m_spec.channelformats[c] : m_spec.format;
Imf::PixelType ptype;
switch (format.basetype) {
case TypeDesc::UINT:
ptype = Imf::UINT;
format = TypeDesc::UINT;
break;
case TypeDesc::FLOAT:
case TypeDesc::DOUBLE:
ptype = Imf::FLOAT;
format = TypeDesc::FLOAT;
break;
default:
// Everything else defaults to half
ptype = Imf::HALF;
format = TypeDesc::HALF;
}
#ifdef OPENEXR_VERSION_IS_1_6_OR_LATER
// Hint to lossy compression methods that indicates whether
// human perception of the quantity represented by this channel
// is closer to linear or closer to logarithmic. Compression
// methods may optimize image quality by adjusting pixel data
// quantization acording to this hint.
bool pLinear = Strutil::iequals (m_spec.get_string_attribute ("oiio:ColorSpace", "Linear"), "Linear");
#endif
m_pixeltype.push_back (ptype);
if (m_spec.channelformats.size())
m_spec.channelformats[c] = format;
m_header->channels().insert (m_spec.channelnames[c].c_str(),
Imf::Channel(ptype, 1, 1
#ifdef OPENEXR_VERSION_IS_1_6_OR_LATER
, pLinear
#endif
));
}
ASSERT (m_pixeltype.size() == (size_t)m_spec.nchannels);
// Default to ZIP compression if no request came with the user spec.
if (! m_spec.find_attribute("compression"))
m_spec.attribute ("compression", "zip");
// Default to increasingY line order, same as EXR.
if (! m_spec.find_attribute("openexr:lineOrder"))
m_spec.attribute ("openexr:lineOrder", "increasingY");
// Automatically set date field if the client didn't supply it.
if (! m_spec.find_attribute("DateTime")) {
time_t now;
time (&now);
struct tm mytm;
Sysutil::get_local_time (&now, &mytm);
std::string date = Strutil::format ("%4d:%02d:%02d %2d:%02d:%02d",
mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
mytm.tm_hour, mytm.tm_min, mytm.tm_sec);
m_spec.attribute ("DateTime", date);
}
m_nsubimages = 1;
m_subimage = 0;
m_nmiplevels = 1;
m_miplevel = 0;
// Figure out if we are a mipmap or an environment map
ImageIOParameter *param = m_spec.find_attribute ("textureformat");
const char *textureformat = param ? *(char **)param->data() : NULL;
m_levelmode = Imf::ONE_LEVEL; // Default to no MIP-mapping
m_roundingmode = m_spec.get_int_attribute ("openexr:roundingmode",
Imf::ROUND_DOWN);
if (textureformat) {
if (Strutil::iequals (textureformat, "Plain Texture")) {
m_levelmode = m_spec.get_int_attribute ("openexr:levelmode",
Imf::MIPMAP_LEVELS);
} else if (Strutil::iequals (textureformat, "CubeFace Environment")) {
m_levelmode = m_spec.get_int_attribute ("openexr:levelmode",
Imf::MIPMAP_LEVELS);
m_header->insert ("envmap", Imf::EnvmapAttribute(Imf::ENVMAP_CUBE));
} else if (Strutil::iequals (textureformat, "LatLong Environment")) {
m_levelmode = m_spec.get_int_attribute ("openexr:levelmode",
Imf::MIPMAP_LEVELS);
m_header->insert ("envmap", Imf::EnvmapAttribute(Imf::ENVMAP_LATLONG));
} else if (Strutil::iequals (textureformat, "Shadow")) {
m_levelmode = Imf::ONE_LEVEL; // Force one level for shadow maps
}
if (m_levelmode == Imf::MIPMAP_LEVELS) {
// Compute how many mip levels there will be
int w = m_spec.width;
int h = m_spec.height;
while (w > 1 && h > 1) {
if (m_roundingmode == Imf::ROUND_DOWN) {
w = w / 2;
h = h / 2;
} else {
w = (w + 1) / 2;
h = (h + 1) / 2;
}
w = std::max (1, w);
h = std::max (1, h);
++m_nmiplevels;
}
}
}
// Deal with all other params
for (size_t p = 0; p < m_spec.extra_attribs.size(); ++p)
put_parameter (m_spec.extra_attribs[p].name().string(),
m_spec.extra_attribs[p].type(),
m_spec.extra_attribs[p].data());
try {
if (m_spec.tile_width) {
m_header->setTileDescription (
Imf::TileDescription (m_spec.tile_width, m_spec.tile_height,
Imf::LevelMode(m_levelmode),
Imf::LevelRoundingMode(m_roundingmode)));
m_output_tiled = new Imf::TiledOutputFile (name.c_str(), *m_header);
} else {
m_output_scanline = new Imf::OutputFile (name.c_str(), *m_header);
}
}
catch (const std::exception &e) {
error ("OpenEXR exception: %s", e.what());
m_output_scanline = NULL;
return false;
}
if (! m_output_scanline && ! m_output_tiled) {
error ("Unknown error opening EXR file");
return false;
}
return true;
}
bool
OpenEXROutput::put_parameter (const std::string &name, TypeDesc type,
const void *data)
{
// Translate
std::string xname = name;
if (Strutil::iequals(xname, "worldtocamera"))
xname = "worldToCamera";
else if (Strutil::iequals(xname, "worldtoscreen"))
xname = "worldToNDC";
else if (Strutil::iequals(xname, "DateTime"))
xname = "capDate";
else if (Strutil::iequals(xname, "description") || Strutil::iequals(xname, "ImageDescription"))
xname = "comments";
else if (Strutil::iequals(xname, "Copyright"))
xname = "owner";
else if (Strutil::iequals(xname, "PixelAspectRatio"))
xname = "pixelAspectRatio";
else if (Strutil::iequals(xname, "ExposureTime"))
xname = "expTime";
else if (Strutil::iequals(xname, "FNumber"))
xname = "aperture";
else if (Strutil::istarts_with (xname, format_prefix))
xname = std::string (xname.begin()+format_prefix.size(), xname.end());
// std::cerr << "exr put '" << name << "' -> '" << xname << "'\n";
// Special cases
if (Strutil::iequals(xname, "Compression") && type == TypeDesc::STRING) {
const char *str = *(char **)data;
m_header->compression() = Imf::ZIP_COMPRESSION; // Default
if (str) {
if (Strutil::iequals (str, "none"))
m_header->compression() = Imf::NO_COMPRESSION;
else if (Strutil::iequals (str, "deflate") || Strutil::iequals (str, "zip"))
m_header->compression() = Imf::ZIP_COMPRESSION;
else if (Strutil::iequals (str, "rle"))
m_header->compression() = Imf::RLE_COMPRESSION;
else if (Strutil::iequals (str, "zips"))
m_header->compression() = Imf::ZIPS_COMPRESSION;
else if (Strutil::iequals (str, "piz"))
m_header->compression() = Imf::PIZ_COMPRESSION;
else if (Strutil::iequals (str, "pxr24"))
m_header->compression() = Imf::PXR24_COMPRESSION;
#ifdef IMF_B44_COMPRESSION
// The enum Imf::B44_COMPRESSION is not defined in older versions
// of OpenEXR, and there are no explicit version numbers in the
// headers. BUT this other related #define is present only in
// the newer version.
else if (Strutil::iequals (str, "b44"))
m_header->compression() = Imf::B44_COMPRESSION;
else if (Strutil::iequals (str, "b44a"))
m_header->compression() = Imf::B44A_COMPRESSION;
#endif
}
return true;
}
if (Strutil::iequals (xname, "openexr:lineOrder") && type == TypeDesc::STRING) {
const char *str = *(char **)data;
m_header->lineOrder() = Imf::INCREASING_Y; // Default
if (str) {
if (Strutil::iequals (str, "randomY"))
m_header->lineOrder() = Imf::RANDOM_Y;
else if (Strutil::iequals (str, "decreasingY"))
m_header->lineOrder() = Imf::DECREASING_Y;
}
return true;
}
// Supress planarconfig!
if (Strutil::iequals (xname, "planarconfig") || Strutil::iequals (xname, "tiff:planarconfig"))
return true;
// Special handling of any remaining "oiio:*" metadata.
if (Strutil::istarts_with (xname, "oiio:")) {
// None currently supported
return false;
}
// Before handling general named metadata, suppress non-openexr
// format-specific metadata.
if (strchr (name.c_str(), ':') &&
! Strutil::istarts_with (name, "openexr:") &&
! Strutil::istarts_with (name, "Exif:") &&
! Strutil::istarts_with (name, "IPTC:") &&
! Strutil::istarts_with (name, "GPS:")) {
return false;
}
// General handling of attributes
// FIXME -- police this if we ever allow arrays
if (type == TypeDesc::INT || type == TypeDesc::UINT) {
m_header->insert (xname.c_str(), Imf::IntAttribute (*(int*)data));
return true;
}
if (type == TypeDesc::INT16) {
m_header->insert (xname.c_str(), Imf::IntAttribute (*(short*)data));
return true;
}
if (type == TypeDesc::UINT16) {
m_header->insert (xname.c_str(), Imf::IntAttribute (*(unsigned short*)data));
return true;
}
if (type == TypeDesc::FLOAT) {
m_header->insert (xname.c_str(), Imf::FloatAttribute (*(float*)data));
return true;
}
if (type == TypeDesc::HALF) {
m_header->insert (xname.c_str(), Imf::FloatAttribute ((float)*(half*)data));
return true;
}
if (type == TypeDesc::TypeMatrix) {
m_header->insert (xname.c_str(), Imf::M44fAttribute (*(Imath::M44f*)data));
return true;
}
if (type == TypeDesc::TypeString) {
m_header->insert (xname.c_str(), Imf::StringAttribute (*(char**)data));
return true;
}
if (type == TypeDesc::TypeVector) {
m_header->insert (xname.c_str(), Imf::V3fAttribute (*(Imath::V3f*)data));
return true;
}
#ifdef DEBUG
std::cerr << "Don't know what to do with " << type.c_str() << ' ' << xname << "\n";
#endif
return false;
}
bool
OpenEXROutput::close ()
{
// FIXME: if the use pattern for mipmaps is open(), open(append),
// ... close(), then we don't have to leave the file open with this
// trickery. That's only necessary if it's open(), close(),
// open(append), close(), ...
if (m_levelmode != Imf::ONE_LEVEL) {
// Leave MIP-map files open, since appending cannot be done via
// a re-open like it can with TIFF files.
return true;
}
delete m_output_scanline; m_output_scanline = NULL;
delete m_output_tiled; m_output_tiled = NULL;
delete m_header; m_header = NULL;
init (); // re-initialize
return true; // How can we fail?
}
bool
OpenEXROutput::write_scanline (int y, int z, TypeDesc format,
const void *data, stride_t xstride)
{
bool native = (format == TypeDesc::UNKNOWN);
size_t pixel_bytes = m_spec.pixel_bytes (true); // native
if (native && xstride == AutoStride)
xstride = (stride_t) pixel_bytes;
m_spec.auto_stride (xstride, format, spec().nchannels);
data = to_native_scanline (format, data, xstride, m_scratch);
// Compute where OpenEXR needs to think the full buffers starts.
// OpenImageIO requires that 'data' points to where the client wants
// to put the pixels being read, but OpenEXR's frameBuffer.insert()
// wants where the address of the "virtual framebuffer" for the
// whole image.
imagesize_t scanlinebytes = m_spec.scanline_bytes (native);
char *buf = (char *)data
- m_spec.x * pixel_bytes
- y * scanlinebytes;
try {
Imf::FrameBuffer frameBuffer;
size_t chanoffset = 0;
for (int c = 0; c < m_spec.nchannels; ++c) {
size_t chanbytes = m_spec.channelformats.size()
? m_spec.channelformats[c].size()
: m_spec.format.size();
frameBuffer.insert (m_spec.channelnames[c].c_str(),
Imf::Slice (m_pixeltype[c],
buf + chanoffset,
pixel_bytes, scanlinebytes));
chanoffset += chanbytes;
}
m_output_scanline->setFrameBuffer (frameBuffer);
m_output_scanline->writePixels (1);
}
catch (const std::exception &e) {
error ("Failed OpenEXR write: %s", e.what());
return false;
}
// FIXME -- can we checkpoint the file?
return true;
}
bool
OpenEXROutput::write_scanlines (int ybegin, int yend, int z,
TypeDesc format, const void *data,
stride_t xstride, stride_t ystride)
{
yend = std::min (yend, spec().y+spec().height);
bool native = (format == TypeDesc::UNKNOWN);
imagesize_t scanlinebytes = spec().scanline_bytes(native);
size_t pixel_bytes = m_spec.pixel_bytes (native);
if (native && xstride == AutoStride)
xstride = (stride_t) pixel_bytes;
stride_t zstride = AutoStride;
m_spec.auto_stride (xstride, ystride, zstride, format, m_spec.nchannels,
m_spec.width, m_spec.height);
const imagesize_t limit = 16*1024*1024; // Allocate 16 MB, or 1 scanline
int chunk = std::max (1, int(limit / scanlinebytes));
bool ok = true;
for ( ; ok && ybegin < yend; ybegin += chunk) {
int y1 = std::min (ybegin+chunk, yend);
int nscanlines = y1 - ybegin;
const void *d = to_native_rectangle (m_spec.x, m_spec.x+m_spec.width,
ybegin, y1, z, z+1, format, data,
xstride, ystride, zstride,
m_scratch);
// Compute where OpenEXR needs to think the full buffers starts.
// OpenImageIO requires that 'data' points to where the client wants
// to put the pixels being read, but OpenEXR's frameBuffer.insert()
// wants where the address of the "virtual framebuffer" for the
// whole image.
char *buf = (char *)d
- m_spec.x * pixel_bytes
- ybegin * scanlinebytes;
try {
Imf::FrameBuffer frameBuffer;
size_t chanoffset = 0;
for (int c = 0; c < m_spec.nchannels; ++c) {
size_t chanbytes = m_spec.channelformats.size()
? m_spec.channelformats[c].size()
: m_spec.format.size();
frameBuffer.insert (m_spec.channelnames[c].c_str(),
Imf::Slice (m_pixeltype[c],
buf + chanoffset,
pixel_bytes, scanlinebytes));
chanoffset += chanbytes;
}
m_output_scanline->setFrameBuffer (frameBuffer);
m_output_scanline->writePixels (nscanlines);
}
catch (const std::exception &e) {
error ("Failed OpenEXR write: %s", e.what());
return false;
}
data = (const char *)data + ystride*nscanlines;
}
// If we allocated more than 1M, free the memory. It's not wasteful,
// because it means we're writing big chunks at a time, and therefore
// there will be few allocations and deletions.
if (m_scratch.size() > 1*1024*1024) {
std::vector<unsigned char> dummy;
std::swap (m_scratch, dummy);
}
return true;
}
bool
OpenEXROutput::write_tile (int x, int y, int z,
TypeDesc format, const void *data,
stride_t xstride, stride_t ystride, stride_t zstride)
{
return write_tiles (x, std::min (x+m_spec.tile_width, m_spec.x+m_spec.width),
y, std::min (y+m_spec.tile_height, m_spec.y+m_spec.height),
z, std::min (z+m_spec.tile_depth, m_spec.z+m_spec.depth),
format, data, xstride, ystride, zstride);
}
bool
OpenEXROutput::write_tiles (int xbegin, int xend, int ybegin, int yend,
int zbegin, int zend, TypeDesc format,
const void *data, stride_t xstride,
stride_t ystride, stride_t zstride)
{
// std::cerr << "exr::write_tiles " << xbegin << ' ' << xend
// << ' ' << ybegin << ' ' << yend << "\n";
if (! m_output_tiled ||
! m_spec.valid_tile_range (xbegin, xend, ybegin, yend, zbegin, zend))
return false;
// Compute where OpenEXR needs to think the full buffers starts.
// OpenImageIO requires that 'data' points to where the client wants
// to put the pixels being read, but OpenEXR's frameBuffer.insert()
// wants where the address of the "virtual framebuffer" for the
// whole image.
bool native = (format == TypeDesc::UNKNOWN);
size_t user_pixelbytes = m_spec.pixel_bytes (native);
size_t pixelbytes = m_spec.pixel_bytes (true);
if (native && xstride == AutoStride)
xstride = (stride_t) user_pixelbytes;
m_spec.auto_stride (xstride, ystride, zstride, format, spec().nchannels,
(xend-xbegin), (yend-ybegin));
data = to_native_rectangle (xbegin, xend, ybegin, yend, zbegin, zend,
format, data, xstride, ystride, zstride,
m_scratch);
// clamp to the image edge
xend = std::min (xend, m_spec.x+m_spec.width);
yend = std::min (yend, m_spec.y+m_spec.height);
zend = std::min (zend, m_spec.z+m_spec.depth);
int firstxtile = (xbegin-m_spec.x) / m_spec.tile_width;
int firstytile = (ybegin-m_spec.y) / m_spec.tile_height;
int nxtiles = (xend - xbegin + m_spec.tile_width - 1) / m_spec.tile_width;
int nytiles = (yend - ybegin + m_spec.tile_height - 1) / m_spec.tile_height;
std::vector<char> padded;
int width = nxtiles*m_spec.tile_width;
int height = nytiles*m_spec.tile_height;
stride_t widthbytes = width * pixelbytes;
if (width != (xend-xbegin) || height != (yend-ybegin)) {
// If the image region is not an even multiple of the tile size,
// we need to copy and add padding.
padded.resize (pixelbytes * width * height, 0);
OIIO::copy_image (m_spec.nchannels, xend-xbegin,
yend-ybegin, 1, data, pixelbytes,
pixelbytes, (xend-xbegin)*pixelbytes,
(xend-xbegin)*(yend-ybegin)*pixelbytes,
&padded[0], pixelbytes, widthbytes,
height*widthbytes);
data = &padded[0];
}
char *buf = (char *)data
- xbegin * pixelbytes
- ybegin * widthbytes;
try {
Imf::FrameBuffer frameBuffer;
size_t chanoffset = 0;
for (int c = 0; c < m_spec.nchannels; ++c) {
size_t chanbytes = m_spec.channelformats.size()
? m_spec.channelformats[c].size()
: m_spec.format.size();
frameBuffer.insert (m_spec.channelnames[c].c_str(),
Imf::Slice (m_pixeltype[c],
buf + chanoffset, pixelbytes,
widthbytes));
chanoffset += chanbytes;
}
m_output_tiled->setFrameBuffer (frameBuffer);
m_output_tiled->writeTiles (firstxtile, firstxtile+nxtiles-1,
firstytile, firstytile+nytiles-1,
m_miplevel, m_miplevel);
}
catch (const std::exception &e) {
error ("Failed OpenEXR write: %s", e.what());
return false;
}
return true;
}
OIIO_PLUGIN_NAMESPACE_END
|
/**
@file IConnection.cpp
@author Lime Microsystems (www.limemicro.com)
@brief Implementation of IConnection interface
*/
#include "IConnection.h"
#include "ErrorReporting.h"
#include <cstring> //memcpy
#include <chrono>
#include <thread>
using namespace lime;
DeviceInfo::DeviceInfo(void):
addrSi5351(-1),
addrADF4002(-1)
{
return;
}
StreamMetadata::StreamMetadata(void):
timestamp(0),
hasTimestamp(false),
endOfBurst(false),
lateTimestamp(false),
packetDropped(false)
{
return;
}
StreamConfig::StreamConfig(void):
isTx(false),
bufferLength(0),
format(STREAM_12_BIT_IN_16),
linkFormat(STREAM_12_BIT_IN_16)
{
return;
}
IConnection::IConnection(void)
{
callback_logData = nullptr;
unsigned short test = 0x1234;
unsigned char* bytes = (unsigned char*)&test;
if(bytes[0] == 0x12 && bytes[1] == 0x34)
mSystemBigEndian = true;
else
mSystemBigEndian = false;
}
IConnection::~IConnection(void)
{
return;
}
const ConnectionHandle &IConnection::GetHandle(void) const
{
return _handle;
}
bool IConnection::IsOpen(void)
{
return false;
}
DeviceInfo IConnection::GetDeviceInfo(void)
{
DeviceInfo info;
info.addrsLMS7002M.push_back(0);
return info;
}
/***********************************************************************
* Serial API
**********************************************************************/
int IConnection::TransactSPI(const int addr, const uint32_t *writeData, uint32_t *readData, const size_t size)
{
ReportError(ENOTSUP);
return -1;
}
int IConnection::WriteI2C(const int addr, const std::string &data)
{
ReportError(ENOTSUP);
return -1;
}
int IConnection::ReadI2C(const int addr, const size_t numBytes, std::string &data)
{
ReportError(ENOTSUP);
return -1;
}
/***********************************************************************
* LMS7002M Driver callbacks
**********************************************************************/
int IConnection::DeviceReset(void)
{
ReportError(ENOTSUP);
return -1;
}
void IConnection::UpdateExternalBandSelect(const size_t channel, const int trfBand, const int rfePath)
{
return;
}
void IConnection::UpdateExternalDataRate(const size_t channel, const double txRate, const double rxRate)
{
return;
}
void IConnection::EnterSelfCalibration(const size_t channel)
{
return;
}
void IConnection::ExitSelfCalibration(const size_t channel)
{
return;
}
/***********************************************************************
* Reference clocks API
**********************************************************************/
double IConnection::GetReferenceClockRate(void)
{
//this is the populated TCXO on many boards
return 61.44e6/2;
}
void IConnection::SetReferenceClockRate(const double rate)
{
return;
}
double IConnection::GetTxReferenceClockRate(void)
{
return this->GetReferenceClockRate();
}
void IConnection::SetTxReferenceClockRate(const double rate)
{
return this->SetReferenceClockRate(rate);
}
/***********************************************************************
* Timestamp API
**********************************************************************/
uint64_t IConnection::GetHardwareTimestamp(void)
{
return 0;
}
void IConnection::SetHardwareTimestamp(const uint64_t now)
{
return;
}
double IConnection::GetHardwareTimestampRate(void)
{
return 1.0;
}
/***********************************************************************
* Stream API
**********************************************************************/
std::string IConnection::SetupStream(size_t &streamID, const StreamConfig &config)
{
streamID = ~0;
return "SetupStream not implemented";
}
void IConnection::CloseStream(const size_t streamID)
{
return;
}
size_t IConnection::GetStreamSize(const size_t streamID)
{
//this should be overloaded, but if not,
//pick a number that will probably work (power of 2)
return 16*1024;
}
bool IConnection::ControlStream(const size_t streamID, const bool enable, const size_t burstSize, const StreamMetadata &metadata)
{
return false;
}
int IConnection::ReadStream(const size_t streamID, void * const *buffs, const size_t length, const long timeout_ms, StreamMetadata &metadata)
{
return -1;
}
int IConnection::WriteStream(const size_t streamID, const void * const *buffs, const size_t length, const long timeout_ms, const StreamMetadata &metadata)
{
return -1;
}
int IConnection::ReadStreamStatus(const size_t streamID, const long timeout_ms, StreamMetadata &metadata)
{
std::this_thread::sleep_for(std::chrono::milliseconds(timeout_ms));
return -1;
}
/** @brief Sets callback function which gets called each time data is sent or received
*/
void IConnection::SetDataLogCallback(std::function<void(bool, const unsigned char*, const unsigned int)> callback)
{
callback_logData = callback;
}
/***********************************************************************
* Programming API
**********************************************************************/
int IConnection::ProgramWrite(const char *buffer, const size_t length, const int programmingMode, const int index, ProgrammingCallback callback)
{
ReportError(ENOTSUP);
return -1;
}
int IConnection::ProgramRead(char *buffer, const size_t length, const int index, ProgrammingCallback callback)
{
ReportError(ENOTSUP);
return -1;
}
/***********************************************************************
* GPIO API
**********************************************************************/
int IConnection::GPIOWrite(const uint8_t *buffer, const size_t bufLength)
{
ReportError(ENOTSUP);
return -1;
}
int IConnection::GPIORead(uint8_t *buffer, const size_t bufLength)
{
ReportError(ENOTSUP);
return -1;
}
/***********************************************************************
* Register API
**********************************************************************/
int IConnection::WriteRegisters(const uint32_t *addrs, const uint32_t *data, const size_t size)
{
ReportError(ENOTSUP);
return -1;
}
int IConnection::ReadRegisters(const uint32_t *addrs, uint32_t *data, const size_t size)
{
ReportError(ENOTSUP);
return -1;
}
int IConnection::WriteRegister(const uint32_t addr, const uint32_t data)
{
return this->WriteRegisters(&addr, &data, 1);
}
/***********************************************************************
* Aribtrary settings API
**********************************************************************/
int IConnection::CustomParameterWrite(const uint8_t *ids, const double *values, const int count, const std::string* units)
{
ReportError(ENOTSUP);
return -1;
}
int IConnection::CustomParameterRead(const uint8_t *ids, double *values, const int count, std::string* units)
{
ReportError(ENOTSUP);
return -1;
}
|
#include <chrono>
#include "../header/original.h"
#include "../header/gen_ukr_bfxycwh_f16layout_1_128_68_68_256_1_1.h"
//#include "../header/gen_ukr_bfxycwh_1_64_224_224_3_3_3.h"
#include "../header/transpose.h"
void ukrimpl(float *A, float *B, float *oB, float *C, long long *oAstride,
int b, int f, int x, int y, int c, int w, int h,
vector<double> &gfloparray) {
long long *ptAstride [28];
// for (int i = 0; i < 6; i++) {
// oAstride[i] = i;
// }
// long long pAstride[28 * 6];
// for (int t = 0; t < 28; t++)
// for (int i = 0; i < 6; i++) {
// pAstride[t * 6 + i] = oAstride[i];
// }
#pragma omp parallel num_threads(28)
{
int tid = omp_get_thread_num();
ptAstride[tid] = (long long int*)memalign(3072, 6*sizeof(long long int));
for (int i = 0; i < 6; i++) {
ptAstride[tid][i] = i;
}
}
const int Nc = c;
const int Nf = f;
const int Nxy = x * y;
const int Txy3 = Nxy;
const int Tf3 = Nf;
const int Tc3 = Nc;
const int Txyp = 168;
// const int Tfp = 64;
const int Txy2 = 168;
const int Tf2 = 16;
const int Tc2 = 256;
const int Txy1 = 6;
const int Tf1 = 16;
const int Tc1 = 256;
const int Txy0 = 6;
const int Tf0 = 16;
const int Tc0 = 1;
double start = omp_get_wtime();
// std::chrono::time_point<
// std::chrono::high_resolution_clock, std::chrono::nanoseconds> tbegin, tend;
// double duration_ms = 0.0;
// tbegin = std::chrono::high_resolution_clock::now();
#pragma omp parallel num_threads(28)
{
// int tid = omp_get_thread_num();
int tid = omp_get_thread_num();
// long long *Astride = pAstride + tid * 6;
long long *Astride = ptAstride[tid];
int x1, y1, Aoffset, Boffset, Coffset;
long long ctile;
// float*B = copyB[tid];
// for (int idc = tid; idc<c; idc+=28) {
// for (int idw = 0; idw < w; idw++) {
// for (int idh = 0; idh < h; idh++) {
// for (int idf = 0; idf < f; idf++) {
// B[idf + idc * w * h * f + idw * h * f + idh * f] =
// oB[idf * c * w * h + idc * w * h + idw * h + idh];
// }
// }
// }
// }
for(int fpck = tid * 16; fpck < Nf; fpck+= 28*16){
for(int cwh = 0; cwh< c*w*h; cwh+=8){
transpose8x8_avx(oB+ (fpck+0)*c*w*h + cwh, B + fpck*c*w*h + cwh* 16 + 0, c*w*h, 16);
transpose8x8_avx(oB+ (fpck+8)*c*w*h + cwh, B + fpck*c*w*h + cwh* 16 + 8, c*w*h, 16);
}
}
// {
// int idc = tid/9;
// int idw = tid%9/3;
// int idh = tid%3;
// if(idc < 3){
// for (int idf = 0; idf < f; idf++) {
// B[(idf&15) + idc * w * h * 16 + idw * h * 16 + idh * 16 + (idf>>4)*c*w*h*16]=
// oB[idf * c * w * h + idc * w * h + idw * h + idh];
// }
// }
// }
// for (int idcwh = tid; idcwh < c*w*h; idcwh += 28) {
// int idh = idcwh%3;
// int idw = idcwh%9/3;
// int idc = idcwh/9;
// if(idc < c)
// for (int idf = 0; idf < f; idf++) {
// B[idf + idc * w * h * f + idw * h * f + idh * f] =
// oB[idf * c * w * h + idc * w * h + idw * h + idh];
// }
// }
#pragma omp barrier
// cout<<tid<<endl;
for (int xy4 = 0; xy4 < Nxy; xy4 += Txy3) {
for (int f4 = 0; f4 < Nf; f4 += Tf3) {
for (int c4 = 0; c4 < Nc; c4 += Tc3) {
// L3 footprint
for (int c3 = c4; c3 < (c4 + Tc3 > Nc ? Nc : c4 + Tc3); c3 += Tc2) {
// for (int xyp = xy4 + tid * Txyp;
// xyp < std::min(xy4 + (tid + 1) * Txyp, Nxy); xyp += Txyp)
// for (int xy3 = xy4; xy3 < (xy4 + Txy3 > Nxy ?
// Nxy : xy4 + Txy3);
// xy3 += Txy2) {
// int fp = (tid&3)*Tfp;
// int xyp = (tid>>2)*Txyp;
for(int xyp = xy4 + tid * Txyp; xyp< std::min(xy4+Txy3, Nxy); xyp+=28*Txyp)
for (int xy3 = xyp; xy3 < (xyp + Txyp > Nxy ? Nxy : xyp + Txyp);xy3 += Txy2) {
for (int f3 = f4; f3 < (f4 + Tf3 > Nf ? Nf : f4 + Tf3);f3 += Tf2) {
// for (int f3 = fp; f3 < (fp + Tfp > Nf ? Nf : fp + Tfp);f3 += Tf2) {
// L2 footprint
for (int c2 = c3; c2 < (c3 + Tc2 > Nc ? Nc : c3 + Tc2);
c2 += Tc1) {
for (int f2 = f3; f2 < (f3 + Tf2 > Nf ? Nf : f3 + Tf2);f2 += Tf1) {
for (int xy2 = xy3;xy2 < (xy3 + Txy2 > Nxy ? Nxy : xy3 + Txy2);xy2 += Txy1) {
// L1 footprint
ctile = Tc1 > Nc - c2 ? Nc - c2 : Tc1;
for (int xy1 = xy2;
xy1 < (xy2 + Txy1 > Nxy ? Nxy : xy2 + Txy1);
xy1 += Txy0) {
x1 = xy1 / y;
y1 = xy1 % y;
Aoffset = c2 * (x + w - 1) * (y + h - 1) +
x1 * (y + h - 1) + y1;
for (int f1 = f2;
f1 < (f2 + Tf1 > Nf ? Nf : f2 + Tf1);
f1 += Tf0) {
// Boffset = f1 + c2 * w * h * f;
Boffset = f1*c*w*h + c2*w*h*16;
Coffset = f1 * x * y + xy1;
// begin ukr
if (y - y1 > 6) {
// cout<<"ukr1\n";
// simu_ukr(A+Aoffset,
// B+Boffset,
// C+Coffset, ctile,
// 16, 6, 3, 3,
// Astride, Aoffset,
// Boffset, Coffset);
cnn_ukr_float_scatter_6x2v_bfxy_bcxy_cwhf(
A + Aoffset, B + Boffset, C + Coffset, ctile,
Astride);
} else if (x * y - xy1 >= 6) {
// cout<<"ukr2\n";
for (int i = y - y1; i < 6; i++) {
Astride[i] += h - 1;
}
cnn_ukr_float_scatter_6x2v_bfxy_bcxy_cwhf(
A + Aoffset, B + Boffset, C + Coffset, ctile,
Astride);
// simu_ukr(A+Aoffset,
// B+Boffset,
// C+Coffset, ctile,
// 16, 6, 3, 3,
// Astride, Aoffset,
// Boffset, Coffset);
for (int i = y - y1; i < 6; i++) {
Astride[i] -= h - 1;
}
} else {
cnn_ukr_float_scatter_4x2v_bfxy_bcxy_cwhf(
A + Aoffset, B + Boffset, C + Coffset, ctile,
Astride);
// partial_ukr(A + Aoffset, B + Boffset, C + Coffset,
// ctile, 16, x * y - xy1, 3, 3, Astride, Aoffset,
// Boffset, Coffset, b,f,x,y,c,w,h);
}
// end ukr
}
}
// end L1 footprint
}
}
}
// end L2 footprint
}
}
}
// end L3 footprint
}
}
} // end loopnest
} // end paragma parallel
double runtime = omp_get_wtime() - start;
// tend = std::chrono::high_resolution_clock::now();
// double runtime = std::chrono::duration_cast<std::chrono::duration<double> >
// (tend - tbegin).count();
// cout<<"runtime="<<runtime<<endl;
double totflops = 1.0 * b * f * x * y * c * w * h *
2; // 100 * b * x * y * c * f * w * h * 2/6/16/32;
double GFLOPS = totflops / 1000.0 / 1000.0 / 1000.0 / runtime;
gfloparray.push_back(GFLOPS);
}
int main() {
int Nb = 1;
int Nf = 128;
int Nc = 256;
int Nx = 68;
int Ny = 68;
int Nw = 1;
int Nh = 1;
int totiter = 100;
float *A;
float *B;
float *C;
float *tmpB;
vector<double> gfloparray;
long long *Astride = (long long *)memalign(256, 6 * sizeof(long long));
int bufsize =
Nb * Nc * (Nx + Nw) * (Ny + Nh) + Nc * Nw * Nh * Nf + Nb * Nf * Nx * Ny;
bufsize = bufsize / 4096 * 4096 * 2;
// float *Unionbuf = (float *)memalign(4096, bufsize * sizeof(float));
int alignment = 3072;
A = (float*) memalign(alignment, Nb * Nc * (Nx + Nw) * (Ny + Nh)*sizeof(float) );
B = (float*)memalign(alignment, Nc * Nw * Nh * Nf*sizeof(float));
// A = Unionbuf;
// B = A + Nb * Nc * (Nx + Nw) * (Ny + Nh) / alignment * alignment + alignment;
tmpB = (float *)memalign(4096, Nc * Nw * Nh * Nf * sizeof(float));
// C = B + Nb * Nc * (Nx ) * (Ny ) / alignment * alignment + alignment;
C = (float *)memalign(alignment, Nb * Nf * Nx * Ny * sizeof(float));
float *tmpC = (float *)memalign(4096, Nb * Nf * Nx * Ny * sizeof(float));
for (int i = 0; i < Nb * Nc * (Nx + Nw) * (Ny + Nh); i++) {
A[i] = rand() % 10 + 1;
}
for (int i = 0; i < Nc * Nw * Nh * Nf; i++) {
tmpB[i] = rand() % 10 + 2;
}
for (int i = 0; i < Nb * Nf * Nx * Ny; i++) {
tmpC[i] = C[i] = rand() % 10 / 10.0;
}
float ressss;
float tttmp[28];
int flushsz=100000000;
for (int iter = 0; iter < totiter; iter++) {
float *dirty = (float *)malloc(flushsz * sizeof(float));
#pragma omp parallel for
for (int dirt = 0; dirt < flushsz; dirt++){
dirty[dirt] += dirt%100;
tttmp[dirt%28] += dirty[dirt];
}
for(int ii =0; ii<28;ii++){ressss+= tttmp[ii];}
cout<<"flush"<<ressss<<endl;
cout<<"start\n";
ukrimpl(A, B, tmpB, C, Astride, Nb, Nf, Nx, Ny, Nc, Nw, Nh,
gfloparray); // pack(copy) tmpB to B
cout<<"end\n";
free(dirty);
}
double avg_gflop = 0;
for (auto fp : gfloparray) {
cout << fp << endl;
avg_gflop += fp;
}
avg_gflop /= gfloparray.size();
cout << "avg gflop = " << avg_gflop << endl;
if(totiter > 10){cout<<" to compare, set totiter < 10, return\n";return 0;}
for (int iter = 0; iter < totiter; iter++) {
origin_conv(A, tmpB, tmpC, Nb, Nf, Nx, Ny, Nc, Nw, Nh);
}
cout << "fin origin conv\n";
// debugtest1(A,B,C,tmpC, Astride, 44);
compare(C, tmpC, Nb * Nf * Nx * Ny);
return 0;
}
|
/*******************************************************************\
Module: ANSI-C Misc Utilities
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include <util/arith_tools.h>
#include <util/config.h>
#include <util/std_types.h>
#include <util/string2array.h>
void string2array(const exprt &src, exprt &dest)
{
const std::string &str = src.value().as_string();
unsigned actual_size = str.size();
BigInt str_size;
to_integer(to_array_type(src.type()).size(), str_size);
uint64_t string_size = str_size.to_uint64();
const typet &char_type = src.type().subtype();
bool char_is_unsigned = char_type.is_unsignedbv();
exprt size("constant", typet("signedbv"));
size.type().width(config.ansi_c.int_width);
size.value(integer2binary(string_size, config.ansi_c.int_width));
dest = exprt("constant", typet("array"));
dest.type().subtype() = char_type;
dest.type().size(size);
dest.operands().resize(string_size);
exprt::operandst::iterator it = dest.operands().begin();
for(unsigned i = 0; i < string_size; i++, it++)
{
int ch = i >= actual_size ? 0 : str[i];
if(char_is_unsigned)
ch = (unsigned char)ch;
exprt &op = *it;
op = from_integer(ch, char_type);
if(ch >= 32 && ch <= 126)
{
char ch_str[2];
ch_str[0] = ch;
ch_str[1] = 0;
op.cformat("'" + std::string(ch_str) + "'");
}
}
}
|
/* This file is part of Into.
* Copyright (C) Intopii 2013.
* All rights reserved.
*
* Licensees holding a commercial Into license may use this file in
* accordance with the commercial license agreement. Please see
* LICENSE.commercial for commercial licensing terms.
*
* Alternatively, this file may be used under the terms of the GNU
* Affero General Public License version 3 as published by the Free
* Software Foundation. In addition, Intopii gives you special rights
* to use Into as a part of open source software projects. Please
* refer to LICENSE.AGPL3 for details.
*/
#include "PiiBits.h"
using namespace std;
namespace Pii
{
int countOnes(unsigned int c, const unsigned char bits)
{
int count = 0;
for (int i=0;i<bits;i++)
{
count += c & 1; //add the lsb
c >>= 1; //take next bit to lsb
}
return count;
}
int countTransitions(unsigned int c, const unsigned char bits)
{
return countOnes(c ^ ror(c, 1, bits));
}
unsigned int rotateToMinimum(unsigned int n, const unsigned char bits)
{
unsigned int tmp = n << sizeof(int)*4;
unsigned int lowmask = INT_MAX >> (sizeof(int)*4-1);
unsigned int min = tmp;
int minIndex=0;
for (int i=1;i<bits;i++)
{
tmp >>= 1;
tmp |= (tmp & lowmask) << bits;
tmp &= ~lowmask;
if (tmp<min)
{
min = tmp;
minIndex = i;
}
}
tmp = n << (sizeof(int)*4 - minIndex);
tmp |= (tmp & lowmask) << bits;
tmp &= ~lowmask;
return tmp >> sizeof(int)*4;
}
int hammingDistance(unsigned int a, unsigned int b, const unsigned char bits)
{
return countOnes(a^b, bits); //find differing bits
}
}
|
// -*- C++ -*-
// $Id: Keyed_Test_Receiver_exec.cpp 92902 2010-12-17 15:09:42Z mcorino $
/**
* Code generated by the The ACE ORB (TAO) IDL Compiler v1.8.3
* TAO and the TAO IDL Compiler have been developed by:
* Center for Distributed Object Computing
* Washington University
* St. Louis, MO
* USA
* http://www.cs.wustl.edu/~schmidt/doc-center.html
* and
* Distributed Object Computing Laboratory
* University of California at Irvine
* Irvine, CA
* USA
* and
* Institute for Software Integrated Systems
* Vanderbilt University
* Nashville, TN
* USA
* http://www.isis.vanderbilt.edu/
*
* Information about TAO is available at:
* http://www.cs.wustl.edu/~schmidt/TAO.html
**/
#include "Keyed_Test_Receiver_exec.h"
#include "tao/ORB_Core.h"
#include "ace/Reactor.h"
#include "ace/OS_NS_time.h"
#include "dds4ccm/impl/TimeUtilities.h"
#include "dds4ccm/impl/Utils.h"
namespace CIAO_Keyed_Test_Receiver_Impl
{
/**
* Read action generator
*/
read_action_Generator::read_action_Generator (Receiver_exec_i &callback)
: pulse_callback_ (callback)
{
}
read_action_Generator::~read_action_Generator ()
{
}
int
read_action_Generator::handle_timeout (const ACE_Time_Value &, const void *)
{
this->pulse_callback_.read ();
return 0;
}
/**
* Facet Executor Implementation Class: info_out_status_exec_i
*/
info_out_status_exec_i::info_out_status_exec_i (
::Keyed_Test::CCM_Receiver_Context_ptr ctx)
: ciao_context_ (
::Keyed_Test::CCM_Receiver_Context::_duplicate (ctx))
{
}
info_out_status_exec_i::~info_out_status_exec_i (void)
{
}
// Operations from ::CCM_DDS::PortStatusListener
void
info_out_status_exec_i::on_requested_deadline_missed (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::RequestedDeadlineMissedStatus & /* status */)
{
/* Your code here. */
}
void
info_out_status_exec_i::on_sample_lost (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::SampleLostStatus & /* status */)
{
/* Your code here. */
}
/**
* Component Executor Implementation Class: Receiver_exec_i
*/
Receiver_exec_i::Receiver_exec_i (void)
: rate_ (1)
, iterations_ (10)
, keys_ (5)
, expected_ (50)
{
ACE_NEW_THROW_EX (this->ticker_,
read_action_Generator (*this),
::CORBA::NO_MEMORY ());
}
Receiver_exec_i::~Receiver_exec_i (void)
{
delete this->ticker_;
}
// Supported operations and attributes.
ACE_Reactor*
Receiver_exec_i::reactor (void)
{
ACE_Reactor* reactor = 0;
::CORBA::Object_var ccm_object =
this->ciao_context_->get_CCM_object();
if (! ::CORBA::is_nil (ccm_object.in ()))
{
::CORBA::ORB_var orb = ccm_object->_get_orb ();
if (! ::CORBA::is_nil (orb.in ()))
{
reactor = orb->orb_core ()->reactor ();
}
}
if (reactor == 0)
{
throw ::CORBA::INTERNAL ();
}
return reactor;
}
void
Receiver_exec_i::check_received_samples ()
{
bool all_received = true;
for (Last_Iteration_Table::iterator iter = this->last_iters_.begin ();
iter != this->last_iters_.end () && all_received;
++iter)
{
all_received = iter->second == this->iterations_;
if (iter->second > this->iterations_)
{
all_received = true;
ACE_ERROR ((LM_ERROR, "Receiver_exec_i::check_received_samples - "
"ERROR: Unexpected iteration received-> Bailing out\n"));
}
}
if (all_received)
{
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("All samples received. Stop the timer\n")));
this->reactor ()->cancel_timer (this->ticker_);
}
}
void
Receiver_exec_i::read (void)
{
::KeyedTestConnector::Reader_var reader =
this->ciao_context_->get_connection_info_out_data();
if (::CORBA::is_nil (reader.in ()))
{
return;
}
try
{
for (CORBA::UShort i = 1; i < this->keys_ + 1; ++i)
{
KeyedTest keyedtest_info;
char key[10];
ACE_OS::sprintf (key, "KEY_%d", i);
keyedtest_info.key = CORBA::string_dup (key);
::CCM_DDS::ReadInfo readinfo;
reader->read_one_last (keyedtest_info, readinfo, ::DDS::HANDLE_NIL);
ACE_Time_Value tv;
tv <<= readinfo.source_timestamp;
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("READ_ONE Read_Info ")
ACE_TEXT (" -> date =%#T\n"),
&tv));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("READ ONE keyed test info : ")
ACE_TEXT ("received keyedtest_info for <%C> at %u\n"),
keyedtest_info.key.in (),
keyedtest_info.iteration));
this->last_iters_[key] = keyedtest_info.iteration;
check_received_samples ();
}
}
catch(const CCM_DDS::InternalError& ex)
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: KeyedTest_Read: ")
ACE_TEXT ("Unexpected InternalError exception received <%C>\n"),
::CIAO::DDS4CCM::translate_retcode (ex.error_code)));
}
catch(const CCM_DDS::NonExistent& )
{
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("KeyedTest_Read: ")
ACE_TEXT ("Expected NonExistent received\n")));
}
}
// Component attributes and port operations.
::CCM_DDS::CCM_PortStatusListener_ptr
Receiver_exec_i::get_info_out_status (void)
{
if ( ::CORBA::is_nil (this->ciao_info_out_status_.in ()))
{
info_out_status_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
info_out_status_exec_i (
this->ciao_context_.in ()),
::CCM_DDS::CCM_PortStatusListener::_nil ());
this->ciao_info_out_status_ = tmp;
}
return
::CCM_DDS::CCM_PortStatusListener::_duplicate (
this->ciao_info_out_status_.in ());
}
::CORBA::ULong
Receiver_exec_i::rate (void)
{
return this->rate_;
}
void
Receiver_exec_i::rate (
const ::CORBA::ULong rate)
{
this->rate_ = rate;
}
::CORBA::UShort
Receiver_exec_i::iterations (void)
{
return this->iterations_;
}
void
Receiver_exec_i::iterations (
const ::CORBA::UShort iterations)
{
this->iterations_ = iterations;
this->expected_ = this->iterations_ * this->keys_;
}
::CORBA::UShort
Receiver_exec_i::keys (void)
{
return this->keys_;
}
void
Receiver_exec_i::keys (
const ::CORBA::UShort keys)
{
this->keys_ = keys;
this->expected_ = this->iterations_ * this->keys_;
}
// Operations from Components::SessionComponent.
void
Receiver_exec_i::set_session_context (
::Components::SessionContext_ptr ctx)
{
this->ciao_context_ =
::Keyed_Test::CCM_Receiver_Context::_narrow (ctx);
if ( ::CORBA::is_nil (this->ciao_context_.in ()))
{
throw ::CORBA::INTERNAL ();
}
}
void
Receiver_exec_i::configuration_complete (void)
{
/* Your code here. */
}
void
Receiver_exec_i::ccm_activate (void)
{
long const usec = 1000000 / this->rate_;
if (this->reactor ()->schedule_timer (this->ticker_,
0,
ACE_Time_Value(0, usec),
ACE_Time_Value(0, usec)) == -1)
{
ACE_ERROR ((LM_ERROR, "Unable to schedule Timer\n"));
}
}
void
Receiver_exec_i::ccm_passivate (void)
{
this->reactor ()->cancel_timer (this->ticker_);
}
void
Receiver_exec_i::ccm_remove (void)
{
CORBA::UShort received_ = 0;
for (Last_Iteration_Table::iterator iter = this->last_iters_.begin ();
iter != this->last_iters_.end ();
++iter)
{
ACE_DEBUG ((LM_INFO, "Receiver_exec_i summary for <%C>: last sample <%u> - expected <%u>\n",
iter->first.c_str(),
iter->second,
this->iterations_));
received_ += iter->second;
}
if (received_ < this->expected_)
{
ACE_ERROR ((LM_ERROR, "ERROR : Expected to receive %u samples, actually got %u\n",
this->expected_, received_));
}
}
extern "C" RECEIVER_EXEC_Export ::Components::EnterpriseComponent_ptr
create_Keyed_Test_Receiver_Impl (void)
{
::Components::EnterpriseComponent_ptr retval =
::Components::EnterpriseComponent::_nil ();
ACE_NEW_NORETURN (
retval,
Receiver_exec_i);
return retval;
}
}
|
#ifndef QUANTIZER_FAST_HPP_
#define QUANTIZER_FAST_HPP_
#include "../Quantizer.hpp"
namespace aff3ct
{
namespace module
{
template <typename R = float, typename Q = short>
class Quantizer_fast : public Quantizer<R,Q>
{
private:
const int val_max;
const int val_min;
const short fixed_point_pos; // 0 = no decimal part
const int factor;
public:
Quantizer_fast(const int N, const short& fixed_point_pos, const int n_frames = 1);
Quantizer_fast(const int N, const short& fixed_point_pos, const short& saturation_pos, const int n_frames = 1);
virtual ~Quantizer_fast();
protected:
void _process(const R *Y_N1, Q *Y_N2, const int frame_id);
};
}
}
#endif /* QUANTIZER_FAST_HPP_ */
|
// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "iceoryx_utils/platform/types.hpp"
#include "iceoryx_utils/platform/windows.hpp"
#include <io.h>
#include <vector>
#define _SC_PAGESIZE 1
#define STDERR_FILENO 2
class HandleTranslator
{
public:
static HandleTranslator& getInstance() noexcept;
HANDLE get(const int handle) const noexcept;
int add(HANDLE handle) noexcept;
void remove(int handle) noexcept;
private:
struct handle_t
{
HANDLE windowsHandle;
};
std::vector<handle_t> m_handleList;
};
int ftruncate(int fildes, off_t length);
long sysconf(int name);
int closePlatformFileHandle(int fd);
|
//
// Created by rainer on 19.12.19.
//
#include "Shearing.h"
Shearing::Shearing(double xy, double xz, double yx, double yz, double zx, double zy) {
m[0] = {1, xy, xz, 0};
m[1] = {yx, 1, yz, 0};
m[2] = {zx, zy, 1, 0};
m[3] = {0, 0, 0, 1};
}
|
/*!
* Copyright (c) 2012, 2013 BlackBerry Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PushHandler.hpp"
#include <QDebug>
PushHandler::PushHandler()
{
}
PushHandler::~PushHandler()
{
}
bool PushHandler::checkForDuplicate(const PushHistoryItem &pushHistoryItem)
{
if (pushHistoryItem.itemId().isEmpty()) {
return false;
}
if (!m_pushHistoryDAO.createPushHistoryTable()) {
return false;
}
const PushHistoryItem storedPushHistoryItem = m_pushHistoryDAO.pushHistoryItem(pushHistoryItem.itemId());
if (storedPushHistoryItem.seqNum() > -1) {
return true;
}
if (!m_pushHistoryDAO.add(pushHistoryItem)) {
return false;
}
if (m_pushHistoryDAO.pushHistoryCount() > 10) {
m_pushHistoryDAO.removeOldest();
}
return false;
}
int PushHandler::save(const Push &push)
{
if (!m_pushDAO.createPushTable()) {
return -1;
}
return m_pushDAO.add(push);
}
Push PushHandler::push(int pushSeqNum)
{
return m_pushDAO.push(pushSeqNum);
}
QVariantList PushHandler::pushes()
{
return m_pushDAO.pushes();
}
bool PushHandler::remove(int pushSeqNum)
{
return m_pushDAO.remove(pushSeqNum);
}
bool PushHandler::removeAll()
{
return m_pushDAO.removeAll();
}
bool PushHandler::removeAllPushHistory()
{
return m_pushHistoryDAO.removeAll();
}
bool PushHandler::markAsRead(int pushSeqNum)
{
return m_pushDAO.markAsRead(pushSeqNum);
}
bool PushHandler::markAllAsRead()
{
return m_pushDAO.markAllAsRead();
}
|
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/trees/layer_tree_host.h"
#include "cc/animation/animation_curve.h"
#include "cc/animation/layer_animation_controller.h"
#include "cc/animation/scroll_offset_animation_curve.h"
#include "cc/animation/timing_function.h"
#include "cc/layers/layer.h"
#include "cc/layers/layer_impl.h"
#include "cc/test/animation_test_common.h"
#include "cc/test/fake_content_layer.h"
#include "cc/test/fake_content_layer_client.h"
#include "cc/test/layer_tree_test.h"
#include "cc/trees/layer_tree_impl.h"
namespace cc {
namespace {
class LayerTreeHostAnimationTest : public LayerTreeTest {
public:
virtual void SetupTree() OVERRIDE {
LayerTreeTest::SetupTree();
layer_tree_host()->root_layer()->set_layer_animation_delegate(this);
}
};
// Makes sure that SetNeedsAnimate does not cause the CommitRequested() state to
// be set.
class LayerTreeHostAnimationTestSetNeedsAnimateShouldNotSetCommitRequested
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestSetNeedsAnimateShouldNotSetCommitRequested()
: num_commits_(0) {}
virtual void BeginTest() OVERRIDE {
PostSetNeedsCommitToMainThread();
}
virtual void Animate(base::TimeTicks monotonic_time) OVERRIDE {
// We skip the first commit becasue its the commit that populates the
// impl thread with a tree. After the second commit, the test is done.
if (num_commits_ != 1)
return;
layer_tree_host()->SetNeedsAnimate();
// Right now, CommitRequested is going to be true, because during
// BeginFrame, we force CommitRequested to true to prevent requests from
// hitting the impl thread. But, when the next DidCommit happens, we should
// verify that CommitRequested has gone back to false.
}
virtual void DidCommit() OVERRIDE {
if (!num_commits_) {
EXPECT_FALSE(layer_tree_host()->CommitRequested());
layer_tree_host()->SetNeedsAnimate();
EXPECT_FALSE(layer_tree_host()->CommitRequested());
}
// Verifies that the SetNeedsAnimate we made in ::Animate did not
// trigger CommitRequested.
EXPECT_FALSE(layer_tree_host()->CommitRequested());
EndTest();
num_commits_++;
}
virtual void AfterTest() OVERRIDE {}
private:
int num_commits_;
};
MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestSetNeedsAnimateShouldNotSetCommitRequested);
// Trigger a frame with SetNeedsCommit. Then, inside the resulting animate
// callback, request another frame using SetNeedsAnimate. End the test when
// animate gets called yet-again, indicating that the proxy is correctly
// handling the case where SetNeedsAnimate() is called inside the BeginFrame
// flow.
class LayerTreeHostAnimationTestSetNeedsAnimateInsideAnimationCallback
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestSetNeedsAnimateInsideAnimationCallback()
: num_animates_(0) {}
virtual void BeginTest() OVERRIDE {
PostSetNeedsCommitToMainThread();
}
virtual void Animate(base::TimeTicks) OVERRIDE {
if (!num_animates_) {
layer_tree_host()->SetNeedsAnimate();
num_animates_++;
return;
}
EndTest();
}
virtual void AfterTest() OVERRIDE {}
private:
int num_animates_;
};
MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestSetNeedsAnimateInsideAnimationCallback);
// Add a layer animation and confirm that
// LayerTreeHostImpl::updateAnimationState does get called and continues to
// get called.
class LayerTreeHostAnimationTestAddAnimation
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestAddAnimation()
: num_animates_(0),
received_animation_started_notification_(false) {
}
virtual void BeginTest() OVERRIDE {
PostAddInstantAnimationToMainThread(layer_tree_host()->root_layer());
}
virtual void UpdateAnimationState(
LayerTreeHostImpl* host_impl,
bool has_unfinished_animation) OVERRIDE {
if (!num_animates_) {
// The animation had zero duration so LayerTreeHostImpl should no
// longer need to animate its layers.
EXPECT_FALSE(has_unfinished_animation);
num_animates_++;
return;
}
if (received_animation_started_notification_) {
EXPECT_LT(base::TimeTicks(), start_time_);
LayerAnimationController* controller_impl =
host_impl->active_tree()->root_layer()->layer_animation_controller();
Animation* animation_impl =
controller_impl->GetAnimation(Animation::Opacity);
if (animation_impl)
controller_impl->RemoveAnimation(animation_impl->id());
EndTest();
}
}
virtual void NotifyAnimationStarted(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
received_animation_started_notification_ = true;
start_time_ = monotonic_time;
if (num_animates_) {
EXPECT_LT(base::TimeTicks(), start_time_);
LayerAnimationController* controller =
layer_tree_host()->root_layer()->layer_animation_controller();
Animation* animation =
controller->GetAnimation(Animation::Opacity);
if (animation)
controller->RemoveAnimation(animation->id());
EndTest();
}
}
virtual void AfterTest() OVERRIDE {}
private:
int num_animates_;
bool received_animation_started_notification_;
base::TimeTicks start_time_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestAddAnimation);
// Add a layer animation to a layer, but continually fail to draw. Confirm that
// after a while, we do eventually force a draw.
class LayerTreeHostAnimationTestCheckerboardDoesNotStarveDraws
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestCheckerboardDoesNotStarveDraws()
: started_animating_(false) {}
virtual void BeginTest() OVERRIDE {
PostAddAnimationToMainThread(layer_tree_host()->root_layer());
}
virtual void AnimateLayers(
LayerTreeHostImpl* host_impl,
base::TimeTicks monotonic_time) OVERRIDE {
started_animating_ = true;
}
virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
if (started_animating_)
EndTest();
}
virtual DrawResult PrepareToDrawOnThread(
LayerTreeHostImpl* host_impl,
LayerTreeHostImpl::FrameData* frame,
DrawResult draw_result) OVERRIDE {
return DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
}
virtual void AfterTest() OVERRIDE { }
private:
bool started_animating_;
};
// Starvation can only be an issue with the MT compositor.
MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestCheckerboardDoesNotStarveDraws);
// Ensures that animations eventually get deleted.
class LayerTreeHostAnimationTestAnimationsGetDeleted
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestAnimationsGetDeleted()
: started_animating_(false) {}
virtual void BeginTest() OVERRIDE {
PostAddAnimationToMainThread(layer_tree_host()->root_layer());
}
virtual void AnimateLayers(
LayerTreeHostImpl* host_impl,
base::TimeTicks monotonic_time) OVERRIDE {
bool have_animations = !host_impl->animation_registrar()->
active_animation_controllers().empty();
if (!started_animating_ && have_animations) {
started_animating_ = true;
return;
}
if (started_animating_ && !have_animations)
EndTest();
}
virtual void NotifyAnimationFinished(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
// Animations on the impl-side controller only get deleted during a commit,
// so we need to schedule a commit.
layer_tree_host()->SetNeedsCommit();
}
virtual void AfterTest() OVERRIDE {}
private:
bool started_animating_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestAnimationsGetDeleted);
// Ensures that animations continue to be ticked when we are backgrounded.
class LayerTreeHostAnimationTestTickAnimationWhileBackgrounded
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestTickAnimationWhileBackgrounded()
: num_animates_(0) {}
virtual void BeginTest() OVERRIDE {
PostAddLongAnimationToMainThread(layer_tree_host()->root_layer());
}
// Use WillAnimateLayers to set visible false before the animation runs and
// causes a commit, so we block the second visible animate in single-thread
// mode.
virtual void WillAnimateLayers(
LayerTreeHostImpl* host_impl,
base::TimeTicks monotonic_time) OVERRIDE {
// Verify that the host can draw, it's just not visible.
EXPECT_TRUE(host_impl->CanDraw());
if (num_animates_ < 2) {
if (!num_animates_) {
// We have a long animation running. It should continue to tick even
// if we are not visible.
PostSetVisibleToMainThread(false);
}
num_animates_++;
return;
}
EndTest();
}
virtual void AfterTest() OVERRIDE {}
private:
int num_animates_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestTickAnimationWhileBackgrounded);
// Ensures that animation time remains monotonic when we switch from foreground
// to background ticking and back, even if we're skipping draws due to
// checkerboarding when in the foreground.
class LayerTreeHostAnimationTestAnimationTickTimeIsMonotonic
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestAnimationTickTimeIsMonotonic()
: has_background_ticked_(false), num_foreground_animates_(0) {}
virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
// Make sure that drawing many times doesn't cause a checkerboarded
// animation to start so we avoid flake in this test.
settings->timeout_and_draw_when_animation_checkerboards = false;
}
virtual void BeginTest() OVERRIDE {
PostAddLongAnimationToMainThread(layer_tree_host()->root_layer());
}
virtual void AnimateLayers(LayerTreeHostImpl* host_impl,
base::TimeTicks monotonic_time) OVERRIDE {
EXPECT_GE(monotonic_time, last_tick_time_);
last_tick_time_ = monotonic_time;
if (host_impl->visible()) {
num_foreground_animates_++;
if (num_foreground_animates_ > 1 && !has_background_ticked_)
PostSetVisibleToMainThread(false);
else if (has_background_ticked_)
EndTest();
} else {
has_background_ticked_ = true;
PostSetVisibleToMainThread(true);
}
}
virtual DrawResult PrepareToDrawOnThread(
LayerTreeHostImpl* host_impl,
LayerTreeHostImpl::FrameData* frame,
DrawResult draw_result) OVERRIDE {
if (TestEnded())
return draw_result;
return DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
}
virtual void AfterTest() OVERRIDE {}
private:
bool has_background_ticked_;
int num_foreground_animates_;
base::TimeTicks last_tick_time_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestAnimationTickTimeIsMonotonic);
// Ensures that animations do not tick when we are backgrounded and
// and we have an empty active tree.
class LayerTreeHostAnimationTestNoBackgroundTickingWithoutActiveTree
: public LayerTreeHostAnimationTest {
protected:
LayerTreeHostAnimationTestNoBackgroundTickingWithoutActiveTree()
: active_tree_was_animated_(false) {}
virtual base::TimeDelta LowFrequencyAnimationInterval() const OVERRIDE {
return base::TimeDelta::FromMilliseconds(4);
}
virtual void BeginTest() OVERRIDE {
PostAddAnimationToMainThread(layer_tree_host()->root_layer());
}
virtual void NotifyAnimationFinished(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
// Replace animated commits with an empty tree.
layer_tree_host()->SetRootLayer(make_scoped_refptr<Layer>(NULL));
}
virtual void DidCommit() OVERRIDE {
// This alternates setting an empty tree and a non-empty tree with an
// animation.
switch (layer_tree_host()->source_frame_number()) {
case 1:
// Wait for NotifyAnimationFinished to commit an empty tree.
break;
case 2:
SetupTree();
AddOpacityTransitionToLayer(
layer_tree_host()->root_layer(), 0.000001, 0, 0.5, true);
break;
case 3:
// Wait for NotifyAnimationFinished to commit an empty tree.
break;
case 4:
EndTest();
break;
}
}
virtual void BeginCommitOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
// At the start of every commit, block activations and make sure
// we are backgrounded.
host_impl->BlockNotifyReadyToActivateForTesting(true);
PostSetVisibleToMainThread(false);
}
virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
if (!host_impl->settings().impl_side_painting) {
// There are no activations to block if we're not impl-side-painting,
// so just advance the test immediately.
if (host_impl->active_tree()->source_frame_number() < 3)
UnblockActivations(host_impl);
return;
}
// We block activation for several ticks to make sure that, even though
// there is a pending tree with animations, we still do not background
// tick if the active tree is empty.
if (host_impl->pending_tree()->source_frame_number() < 3) {
base::MessageLoopProxy::current()->PostDelayedTask(
FROM_HERE,
base::Bind(
&LayerTreeHostAnimationTestNoBackgroundTickingWithoutActiveTree::
UnblockActivations,
base::Unretained(this),
host_impl),
4 * LowFrequencyAnimationInterval());
}
}
virtual void UnblockActivations(LayerTreeHostImpl* host_impl) {
host_impl->BlockNotifyReadyToActivateForTesting(false);
}
virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
active_tree_was_animated_ = false;
// Verify that commits are actually alternating with empty / non-empty
// trees.
int frame_number = host_impl->active_tree()->source_frame_number();
switch (frame_number) {
case 0:
case 2:
EXPECT_TRUE(host_impl->active_tree()->root_layer())
<< "frame: " << frame_number;
break;
case 1:
case 3:
EXPECT_FALSE(host_impl->active_tree()->root_layer())
<< "frame: " << frame_number;
break;
}
if (host_impl->active_tree()->source_frame_number() < 3) {
// Initiate the next commit after a delay to give us a chance to
// background tick if the active tree isn't empty.
base::MessageLoopProxy::current()->PostDelayedTask(
FROM_HERE,
base::Bind(
&LayerTreeHostAnimationTestNoBackgroundTickingWithoutActiveTree::
InitiateNextCommit,
base::Unretained(this),
host_impl),
4 * LowFrequencyAnimationInterval());
}
}
virtual void WillAnimateLayers(LayerTreeHostImpl* host_impl,
base::TimeTicks monotonic_time) OVERRIDE {
EXPECT_TRUE(host_impl->active_tree()->root_layer());
active_tree_was_animated_ = true;
}
void InitiateNextCommit(LayerTreeHostImpl* host_impl) {
// Verify that we actually animated when we should have.
bool has_active_tree = host_impl->active_tree()->root_layer();
EXPECT_EQ(has_active_tree, active_tree_was_animated_);
// The next commit is blocked until we become visible again.
PostSetVisibleToMainThread(true);
}
virtual void AfterTest() OVERRIDE {}
bool active_tree_was_animated_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestNoBackgroundTickingWithoutActiveTree);
// Ensure that an animation's timing function is respected.
class LayerTreeHostAnimationTestAddAnimationWithTimingFunction
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestAddAnimationWithTimingFunction() {}
virtual void SetupTree() OVERRIDE {
LayerTreeHostAnimationTest::SetupTree();
content_ = FakeContentLayer::Create(&client_);
content_->SetBounds(gfx::Size(4, 4));
layer_tree_host()->root_layer()->AddChild(content_);
}
virtual void BeginTest() OVERRIDE {
PostAddAnimationToMainThread(content_.get());
}
virtual void AnimateLayers(
LayerTreeHostImpl* host_impl,
base::TimeTicks monotonic_time) OVERRIDE {
LayerAnimationController* controller_impl =
host_impl->active_tree()->root_layer()->children()[0]->
layer_animation_controller();
Animation* animation =
controller_impl->GetAnimation(Animation::Opacity);
if (!animation)
return;
const FloatAnimationCurve* curve =
animation->curve()->ToFloatAnimationCurve();
float start_opacity = curve->GetValue(0.0);
float end_opacity = curve->GetValue(curve->Duration());
float linearly_interpolated_opacity =
0.25f * end_opacity + 0.75f * start_opacity;
double time = curve->Duration() * 0.25;
// If the linear timing function associated with this animation was not
// picked up, then the linearly interpolated opacity would be different
// because of the default ease timing function.
EXPECT_FLOAT_EQ(linearly_interpolated_opacity, curve->GetValue(time));
EndTest();
}
virtual void AfterTest() OVERRIDE {}
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> content_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestAddAnimationWithTimingFunction);
// Ensures that main thread animations have their start times synchronized with
// impl thread animations.
class LayerTreeHostAnimationTestSynchronizeAnimationStartTimes
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestSynchronizeAnimationStartTimes()
: main_start_time_(-1.0),
impl_start_time_(-1.0) {}
virtual void SetupTree() OVERRIDE {
LayerTreeHostAnimationTest::SetupTree();
content_ = FakeContentLayer::Create(&client_);
content_->SetBounds(gfx::Size(4, 4));
content_->set_layer_animation_delegate(this);
layer_tree_host()->root_layer()->AddChild(content_);
}
virtual void BeginTest() OVERRIDE {
PostAddAnimationToMainThread(content_.get());
}
virtual void NotifyAnimationStarted(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
LayerAnimationController* controller =
layer_tree_host()->root_layer()->children()[0]->
layer_animation_controller();
Animation* animation =
controller->GetAnimation(Animation::Opacity);
main_start_time_ =
(animation->start_time() - base::TimeTicks()).InSecondsF();
controller->RemoveAnimation(animation->id());
if (impl_start_time_ > 0.0)
EndTest();
}
virtual void UpdateAnimationState(
LayerTreeHostImpl* impl_host,
bool has_unfinished_animation) OVERRIDE {
LayerAnimationController* controller =
impl_host->active_tree()->root_layer()->children()[0]->
layer_animation_controller();
Animation* animation =
controller->GetAnimation(Animation::Opacity);
if (!animation)
return;
impl_start_time_ =
(animation->start_time() - base::TimeTicks()).InSecondsF();
controller->RemoveAnimation(animation->id());
if (main_start_time_ > 0.0)
EndTest();
}
virtual void AfterTest() OVERRIDE {
EXPECT_FLOAT_EQ(impl_start_time_, main_start_time_);
}
private:
double main_start_time_;
double impl_start_time_;
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> content_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestSynchronizeAnimationStartTimes);
// Ensures that notify animation finished is called.
class LayerTreeHostAnimationTestAnimationFinishedEvents
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestAnimationFinishedEvents() {}
virtual void BeginTest() OVERRIDE {
PostAddInstantAnimationToMainThread(layer_tree_host()->root_layer());
}
virtual void NotifyAnimationFinished(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
LayerAnimationController* controller =
layer_tree_host()->root_layer()->layer_animation_controller();
Animation* animation =
controller->GetAnimation(Animation::Opacity);
if (animation)
controller->RemoveAnimation(animation->id());
EndTest();
}
virtual void AfterTest() OVERRIDE {}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestAnimationFinishedEvents);
// Ensures that when opacity is being animated, this value does not cause the
// subtree to be skipped.
class LayerTreeHostAnimationTestDoNotSkipLayersWithAnimatedOpacity
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestDoNotSkipLayersWithAnimatedOpacity()
: update_check_layer_(FakeContentLayer::Create(&client_)) {
}
virtual void SetupTree() OVERRIDE {
update_check_layer_->SetOpacity(0.f);
layer_tree_host()->SetRootLayer(update_check_layer_);
LayerTreeHostAnimationTest::SetupTree();
}
virtual void BeginTest() OVERRIDE {
PostAddAnimationToMainThread(update_check_layer_.get());
}
virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
LayerAnimationController* controller_impl =
host_impl->active_tree()->root_layer()->layer_animation_controller();
Animation* animation_impl =
controller_impl->GetAnimation(Animation::Opacity);
controller_impl->RemoveAnimation(animation_impl->id());
EndTest();
}
virtual void AfterTest() OVERRIDE {
// Update() should have been called once, proving that the layer was not
// skipped.
EXPECT_EQ(1u, update_check_layer_->update_count());
// clear update_check_layer_ so LayerTreeHost dies.
update_check_layer_ = NULL;
}
private:
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> update_check_layer_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestDoNotSkipLayersWithAnimatedOpacity);
// Layers added to tree with existing active animations should have the
// animation correctly recognized.
class LayerTreeHostAnimationTestLayerAddedWithAnimation
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestLayerAddedWithAnimation() {}
virtual void BeginTest() OVERRIDE {
PostSetNeedsCommitToMainThread();
}
virtual void DidCommit() OVERRIDE {
if (layer_tree_host()->source_frame_number() == 1) {
scoped_refptr<Layer> layer = Layer::Create();
layer->set_layer_animation_delegate(this);
// Any valid AnimationCurve will do here.
scoped_ptr<AnimationCurve> curve(EaseTimingFunction::Create());
scoped_ptr<Animation> animation(
Animation::Create(curve.Pass(), 1, 1,
Animation::Opacity));
layer->layer_animation_controller()->AddAnimation(animation.Pass());
// We add the animation *before* attaching the layer to the tree.
layer_tree_host()->root_layer()->AddChild(layer);
}
}
virtual void AnimateLayers(
LayerTreeHostImpl* impl_host,
base::TimeTicks monotonic_time) OVERRIDE {
EndTest();
}
virtual void AfterTest() OVERRIDE {}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestLayerAddedWithAnimation);
class LayerTreeHostAnimationTestContinuousAnimate
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestContinuousAnimate()
: num_commit_complete_(0),
num_draw_layers_(0) {
}
virtual void SetupTree() OVERRIDE {
LayerTreeHostAnimationTest::SetupTree();
// Create a fake content layer so we actually produce new content for every
// animation frame.
content_ = FakeContentLayer::Create(&client_);
content_->set_always_update_resources(true);
layer_tree_host()->root_layer()->AddChild(content_);
}
virtual void BeginTest() OVERRIDE {
PostSetNeedsCommitToMainThread();
}
virtual void Animate(base::TimeTicks) OVERRIDE {
if (num_draw_layers_ == 2)
return;
layer_tree_host()->SetNeedsAnimate();
}
virtual void Layout() OVERRIDE {
layer_tree_host()->root_layer()->SetNeedsDisplay();
}
virtual void CommitCompleteOnThread(LayerTreeHostImpl* tree_impl) OVERRIDE {
if (num_draw_layers_ == 1)
num_commit_complete_++;
}
virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
num_draw_layers_++;
if (num_draw_layers_ == 2)
EndTest();
}
virtual void AfterTest() OVERRIDE {
// Check that we didn't commit twice between first and second draw.
EXPECT_EQ(1, num_commit_complete_);
}
private:
int num_commit_complete_;
int num_draw_layers_;
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> content_;
};
MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestContinuousAnimate);
class LayerTreeHostAnimationTestCancelAnimateCommit
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestCancelAnimateCommit()
: num_animate_calls_(0), num_commit_calls_(0), num_draw_calls_(0) {}
virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
virtual void Animate(base::TimeTicks) OVERRIDE {
num_animate_calls_++;
// No-op animate will cancel the commit.
if (layer_tree_host()->source_frame_number() == 1) {
EndTest();
return;
}
layer_tree_host()->SetNeedsAnimate();
}
virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
num_commit_calls_++;
if (impl->active_tree()->source_frame_number() > 1)
FAIL() << "Commit should have been canceled.";
}
virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
num_draw_calls_++;
if (impl->active_tree()->source_frame_number() > 1)
FAIL() << "Draw should have been canceled.";
}
virtual void AfterTest() OVERRIDE {
EXPECT_EQ(2, num_animate_calls_);
EXPECT_EQ(1, num_commit_calls_);
EXPECT_EQ(1, num_draw_calls_);
}
private:
int num_animate_calls_;
int num_commit_calls_;
int num_draw_calls_;
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> content_;
};
MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestCancelAnimateCommit);
class LayerTreeHostAnimationTestForceRedraw
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestForceRedraw()
: num_animate_(0), num_draw_layers_(0) {}
virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
virtual void Animate(base::TimeTicks) OVERRIDE {
if (++num_animate_ < 2)
layer_tree_host()->SetNeedsAnimate();
}
virtual void Layout() OVERRIDE {
layer_tree_host()->SetNextCommitForcesRedraw();
}
virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
if (++num_draw_layers_ == 2)
EndTest();
}
virtual void AfterTest() OVERRIDE {
// The first commit will always draw; make sure the second draw triggered
// by the animation was not cancelled.
EXPECT_EQ(2, num_draw_layers_);
EXPECT_EQ(2, num_animate_);
}
private:
int num_animate_;
int num_draw_layers_;
};
MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestForceRedraw);
class LayerTreeHostAnimationTestAnimateAfterSetNeedsCommit
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestAnimateAfterSetNeedsCommit()
: num_animate_(0), num_draw_layers_(0) {}
virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
virtual void Animate(base::TimeTicks) OVERRIDE {
if (++num_animate_ <= 2) {
layer_tree_host()->SetNeedsCommit();
layer_tree_host()->SetNeedsAnimate();
}
}
virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
if (++num_draw_layers_ == 2)
EndTest();
}
virtual void AfterTest() OVERRIDE {
// The first commit will always draw; make sure the second draw triggered
// by the SetNeedsCommit was not cancelled.
EXPECT_EQ(2, num_draw_layers_);
EXPECT_GE(num_animate_, 2);
}
private:
int num_animate_;
int num_draw_layers_;
};
MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestAnimateAfterSetNeedsCommit);
// Make sure the main thread can still execute animations when CanDraw() is not
// true.
class LayerTreeHostAnimationTestRunAnimationWhenNotCanDraw
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestRunAnimationWhenNotCanDraw() : started_times_(0) {}
virtual void SetupTree() OVERRIDE {
LayerTreeHostAnimationTest::SetupTree();
content_ = FakeContentLayer::Create(&client_);
content_->SetBounds(gfx::Size(4, 4));
content_->set_layer_animation_delegate(this);
layer_tree_host()->root_layer()->AddChild(content_);
}
virtual void BeginTest() OVERRIDE {
layer_tree_host()->SetViewportSize(gfx::Size());
PostAddAnimationToMainThread(content_.get());
}
virtual void NotifyAnimationStarted(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
started_times_++;
}
virtual void NotifyAnimationFinished(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
EndTest();
}
virtual void AfterTest() OVERRIDE {
EXPECT_EQ(1, started_times_);
}
private:
int started_times_;
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> content_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestRunAnimationWhenNotCanDraw);
// Make sure the main thread can still execute animations when the renderer is
// backgrounded.
class LayerTreeHostAnimationTestRunAnimationWhenNotVisible
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestRunAnimationWhenNotVisible() : started_times_(0) {}
virtual void SetupTree() OVERRIDE {
LayerTreeHostAnimationTest::SetupTree();
content_ = FakeContentLayer::Create(&client_);
content_->SetBounds(gfx::Size(4, 4));
content_->set_layer_animation_delegate(this);
layer_tree_host()->root_layer()->AddChild(content_);
}
virtual void BeginTest() OVERRIDE {
visible_ = true;
PostAddAnimationToMainThread(content_.get());
}
virtual void DidCommit() OVERRIDE {
visible_ = false;
layer_tree_host()->SetVisible(false);
}
virtual void NotifyAnimationStarted(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
EXPECT_FALSE(visible_);
started_times_++;
}
virtual void NotifyAnimationFinished(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
EXPECT_FALSE(visible_);
EXPECT_EQ(1, started_times_);
EndTest();
}
virtual void AfterTest() OVERRIDE {}
private:
bool visible_;
int started_times_;
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> content_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestRunAnimationWhenNotVisible);
// Animations should not be started when frames are being skipped due to
// checkerboard.
class LayerTreeHostAnimationTestCheckerboardDoesntStartAnimations
: public LayerTreeHostAnimationTest {
virtual void SetupTree() OVERRIDE {
LayerTreeHostAnimationTest::SetupTree();
content_ = FakeContentLayer::Create(&client_);
content_->SetBounds(gfx::Size(4, 4));
content_->set_layer_animation_delegate(this);
layer_tree_host()->root_layer()->AddChild(content_);
}
virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
// Make sure that drawing many times doesn't cause a checkerboarded
// animation to start so we avoid flake in this test.
settings->timeout_and_draw_when_animation_checkerboards = false;
}
virtual void BeginTest() OVERRIDE {
prevented_draw_ = 0;
added_animations_ = 0;
started_times_ = 0;
PostSetNeedsCommitToMainThread();
}
virtual DrawResult PrepareToDrawOnThread(
LayerTreeHostImpl* host_impl,
LayerTreeHostImpl::FrameData* frame_data,
DrawResult draw_result) OVERRIDE {
if (added_animations_ < 2)
return draw_result;
if (TestEnded())
return draw_result;
// Act like there is checkerboard when the second animation wants to draw.
++prevented_draw_;
if (prevented_draw_ > 2)
EndTest();
return DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
}
virtual void DidCommitAndDrawFrame() OVERRIDE {
switch (layer_tree_host()->source_frame_number()) {
case 1:
// The animation is longer than 1 BeginFrame interval.
AddOpacityTransitionToLayer(content_.get(), 0.1, 0.2f, 0.8f, false);
added_animations_++;
break;
case 2:
// This second animation will not be drawn so it should not start.
AddAnimatedTransformToLayer(content_.get(), 0.1, 5, 5);
added_animations_++;
break;
}
}
virtual void NotifyAnimationStarted(
base::TimeTicks monotonic_time,
Animation::TargetProperty target_property) OVERRIDE {
if (TestEnded())
return;
started_times_++;
}
virtual void AfterTest() OVERRIDE {
// Make sure we tried to draw the second animation but failed.
EXPECT_LT(0, prevented_draw_);
// The first animation should be started, but the second should not because
// of checkerboard.
EXPECT_EQ(1, started_times_);
}
int prevented_draw_;
int added_animations_;
int started_times_;
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> content_;
};
MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestCheckerboardDoesntStartAnimations);
// Verifies that scroll offset animations are only accepted when impl-scrolling
// is supported, and that when scroll offset animations are accepted,
// scroll offset updates are sent back to the main thread.
class LayerTreeHostAnimationTestScrollOffsetChangesArePropagated
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestScrollOffsetChangesArePropagated() {}
virtual void SetupTree() OVERRIDE {
LayerTreeHostAnimationTest::SetupTree();
scroll_layer_ = FakeContentLayer::Create(&client_);
scroll_layer_->SetScrollClipLayerId(layer_tree_host()->root_layer()->id());
scroll_layer_->SetBounds(gfx::Size(1000, 1000));
scroll_layer_->SetScrollOffset(gfx::Vector2d(10, 20));
layer_tree_host()->root_layer()->AddChild(scroll_layer_);
}
virtual void BeginTest() OVERRIDE {
PostSetNeedsCommitToMainThread();
}
virtual void DidCommit() OVERRIDE {
switch (layer_tree_host()->source_frame_number()) {
case 1: {
scoped_ptr<ScrollOffsetAnimationCurve> curve(
ScrollOffsetAnimationCurve::Create(
gfx::Vector2dF(500.f, 550.f),
EaseInOutTimingFunction::Create()));
scoped_ptr<Animation> animation(Animation::Create(
curve.PassAs<AnimationCurve>(), 1, 0, Animation::ScrollOffset));
animation->set_needs_synchronized_start_time(true);
bool animation_added = scroll_layer_->AddAnimation(animation.Pass());
bool impl_scrolling_supported =
layer_tree_host()->proxy()->SupportsImplScrolling();
EXPECT_EQ(impl_scrolling_supported, animation_added);
if (!impl_scrolling_supported)
EndTest();
break;
}
default:
if (scroll_layer_->scroll_offset().x() > 10 &&
scroll_layer_->scroll_offset().y() > 20)
EndTest();
}
}
virtual void AfterTest() OVERRIDE {}
private:
FakeContentLayerClient client_;
scoped_refptr<FakeContentLayer> scroll_layer_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestScrollOffsetChangesArePropagated);
// Ensure that animation time is correctly updated when animations are frozen
// because of checkerboarding.
class LayerTreeHostAnimationTestFrozenAnimationTickTime
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestFrozenAnimationTickTime()
: started_animating_(false), num_commits_(0), num_draw_attempts_(2) {}
virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
// Make sure that drawing many times doesn't cause a checkerboarded
// animation to start so we avoid flake in this test.
settings->timeout_and_draw_when_animation_checkerboards = false;
}
virtual void BeginTest() OVERRIDE {
PostAddAnimationToMainThread(layer_tree_host()->root_layer());
}
virtual void Animate(base::TimeTicks monotonic_time) OVERRIDE {
last_main_thread_tick_time_ = monotonic_time;
}
virtual void AnimateLayers(LayerTreeHostImpl* host_impl,
base::TimeTicks monotonic_time) OVERRIDE {
if (TestEnded())
return;
if (!started_animating_) {
started_animating_ = true;
expected_impl_tick_time_ = monotonic_time;
} else {
EXPECT_EQ(expected_impl_tick_time_, monotonic_time);
if (num_commits_ > 2)
EndTest();
}
}
virtual DrawResult PrepareToDrawOnThread(LayerTreeHostImpl* host_impl,
LayerTreeHostImpl::FrameData* frame,
DrawResult draw_result) OVERRIDE {
if (TestEnded())
return draw_result;
num_draw_attempts_++;
if (num_draw_attempts_ > 2) {
num_draw_attempts_ = 0;
PostSetNeedsCommitToMainThread();
}
return DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
}
virtual void BeginCommitOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
if (!started_animating_)
return;
expected_impl_tick_time_ =
std::max(expected_impl_tick_time_, last_main_thread_tick_time_);
num_commits_++;
}
virtual void AfterTest() OVERRIDE {}
private:
bool started_animating_;
int num_commits_;
int num_draw_attempts_;
base::TimeTicks last_main_thread_tick_time_;
base::TimeTicks expected_impl_tick_time_;
};
// Only the non-impl-paint multi-threaded compositor freezes animations.
MULTI_THREAD_NOIMPL_TEST_F(LayerTreeHostAnimationTestFrozenAnimationTickTime);
// When animations are simultaneously added to an existing layer and to a new
// layer, they should start at the same time, even when there's already a
// running animation on the existing layer.
class LayerTreeHostAnimationTestAnimationsAddedToNewAndExistingLayers
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestAnimationsAddedToNewAndExistingLayers()
: frame_count_with_pending_tree_(0) {}
virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
virtual void DidCommit() OVERRIDE {
if (layer_tree_host()->source_frame_number() == 1) {
AddAnimatedTransformToLayer(layer_tree_host()->root_layer(), 4, 1, 1);
} else if (layer_tree_host()->source_frame_number() == 2) {
AddOpacityTransitionToLayer(
layer_tree_host()->root_layer(), 1, 0.f, 0.5f, true);
scoped_refptr<Layer> layer = Layer::Create();
layer_tree_host()->root_layer()->AddChild(layer);
layer->set_layer_animation_delegate(this);
layer->SetBounds(gfx::Size(4, 4));
AddOpacityTransitionToLayer(layer, 1, 0.f, 0.5f, true);
}
}
virtual void BeginCommitOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
host_impl->BlockNotifyReadyToActivateForTesting(true);
}
virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
// For the commit that added animations to new and existing layers, keep
// blocking activation. We want to verify that even with activation blocked,
// the animation on the layer that's already in the active tree won't get a
// head start.
if (!host_impl->settings().impl_side_painting ||
host_impl->pending_tree()->source_frame_number() != 2)
host_impl->BlockNotifyReadyToActivateForTesting(false);
}
virtual void WillBeginImplFrameOnThread(LayerTreeHostImpl* host_impl,
const BeginFrameArgs& args) OVERRIDE {
if (!host_impl->pending_tree() ||
host_impl->pending_tree()->source_frame_number() != 2)
return;
frame_count_with_pending_tree_++;
if (frame_count_with_pending_tree_ == 2)
host_impl->BlockNotifyReadyToActivateForTesting(false);
}
virtual void UpdateAnimationState(LayerTreeHostImpl* host_impl,
bool has_unfinished_animation) OVERRIDE {
LayerAnimationController* root_controller_impl =
host_impl->active_tree()->root_layer()->layer_animation_controller();
Animation* root_animation =
root_controller_impl->GetAnimation(Animation::Opacity);
if (!root_animation || root_animation->run_state() != Animation::Running)
return;
LayerAnimationController* child_controller_impl =
host_impl->active_tree()->root_layer()->children()
[0]->layer_animation_controller();
Animation* child_animation =
child_controller_impl->GetAnimation(Animation::Opacity);
EXPECT_EQ(Animation::Running, child_animation->run_state());
EXPECT_EQ(root_animation->start_time(), child_animation->start_time());
root_controller_impl->AbortAnimations(Animation::Opacity);
root_controller_impl->AbortAnimations(Animation::Transform);
child_controller_impl->AbortAnimations(Animation::Opacity);
EndTest();
}
virtual void AfterTest() OVERRIDE {}
private:
int frame_count_with_pending_tree_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestAnimationsAddedToNewAndExistingLayers);
class LayerTreeHostAnimationTestAddAnimationAfterAnimating
: public LayerTreeHostAnimationTest {
public:
LayerTreeHostAnimationTestAddAnimationAfterAnimating()
: num_swap_buffers_(0) {}
virtual void SetupTree() OVERRIDE {
LayerTreeHostAnimationTest::SetupTree();
content_ = Layer::Create();
content_->SetBounds(gfx::Size(4, 4));
layer_tree_host()->root_layer()->AddChild(content_);
}
virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
virtual void DidCommit() OVERRIDE {
switch (layer_tree_host()->source_frame_number()) {
case 1:
// First frame: add an animation to the root layer.
AddAnimatedTransformToLayer(layer_tree_host()->root_layer(), 0.1, 5, 5);
break;
case 2:
// Second frame: add an animation to the content layer. The root layer
// animation has caused us to animate already during this frame.
AddOpacityTransitionToLayer(content_.get(), 0.1, 5, 5, false);
break;
}
}
virtual void SwapBuffersOnThread(LayerTreeHostImpl* host_impl,
bool result) OVERRIDE {
// After both animations have started, verify that they have valid
// start times.
num_swap_buffers_++;
AnimationRegistrar::AnimationControllerMap copy =
host_impl->animation_registrar()->active_animation_controllers();
if (copy.size() == 2u) {
EndTest();
EXPECT_GE(num_swap_buffers_, 3);
for (AnimationRegistrar::AnimationControllerMap::iterator iter =
copy.begin();
iter != copy.end();
++iter) {
int id = ((*iter).second->id());
if (id == host_impl->RootLayer()->id()) {
Animation* anim = (*iter).second->GetAnimation(Animation::Transform);
EXPECT_GT((anim->start_time() - base::TimeTicks()).InSecondsF(), 0);
} else if (id == host_impl->RootLayer()->children()[0]->id()) {
Animation* anim = (*iter).second->GetAnimation(Animation::Opacity);
EXPECT_GT((anim->start_time() - base::TimeTicks()).InSecondsF(), 0);
}
}
}
}
virtual void AfterTest() OVERRIDE {}
private:
scoped_refptr<Layer> content_;
int num_swap_buffers_;
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostAnimationTestAddAnimationAfterAnimating);
} // namespace
} // namespace cc
|
//
// Created by kaiser on 18-11-28.
//
#include <cstdint>
#include <iostream>
std::int32_t fact(std::int32_t val) {
std::int32_t ret{1};
while (val > 1) {
ret *= val;
--val;
}
return ret;
}
int main() { std::cout << fact(5) << '\n'; }
|
/*
* Copyright (c) 2011-2019, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <Eigen/Dense>
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
namespace py = pybind11;
namespace dart {
namespace python {
void Optimizer(py::module& sm);
void IPOptOptimizer(py::module& sm);
void SGDOptimizer(py::module& sm);
void LossFn(py::module& sm);
void Problem(py::module& sm);
void MultiShot(py::module& sm);
void SingleShot(py::module& sm);
void TrajectoryRollout(py::module& sm);
void Solution(py::module& sm);
void dart_trajectory(py::module& m)
{
auto sm = m.def_submodule("trajectory");
sm.doc()
= "This provides a native trajectory optimization framework to DART, "
"transcribing DART trajectory problems into IPOPT for solutions.";
Optimizer(sm);
IPOptOptimizer(sm);
SGDOptimizer(sm);
LossFn(sm);
Problem(sm);
MultiShot(sm);
SingleShot(sm);
TrajectoryRollout(sm);
Solution(sm);
}
} // namespace python
} // namespace dart
|
#include "SamplePlugin.hpp"
SamplePlugin::SamplePlugin():
RobWorkStudioPlugin("SamplePluginUI", QIcon(":/pa_icon.png"))
{
setupUi(this);
_timer = new QTimer(this);
connect(_timer, SIGNAL(timeout()), this, SLOT(timer()));
// now connect stuff from the ui component
connect(_btn_im ,SIGNAL(pressed()), this, SLOT(btnPressed()) );
connect(_btn_scan ,SIGNAL(pressed()), this, SLOT(btnPressed()) );
connect(_btn0 ,SIGNAL(pressed()), this, SLOT(btnPressed()) );
connect(_btn1 ,SIGNAL(pressed()), this, SLOT(btnPressed()) );
connect(_spinBox ,SIGNAL(valueChanged(int)), this, SLOT(btnPressed()) );
_framegrabber = NULL;
_cameras = {"Camera_Right", "Camera_Left"};
_cameras25D = {"Scanner25D"};
}
SamplePlugin::~SamplePlugin()
{
delete _textureRender;
delete _bgRender;
}
void SamplePlugin::initialize() {
log().info() << "INITALIZE" << "\n";
getRobWorkStudio()->stateChangedEvent().add(std::bind(&SamplePlugin::stateChangedListener, this, std::placeholders::_1), this);
// Auto load workcell
WorkCell::Ptr wc = WorkCellLoader::Factory::load("/home/student/Desktop/Project_WorkCell/Scene.wc.xml");
getRobWorkStudio()->setWorkCell(wc);
}
void SamplePlugin::open(WorkCell* workcell)
{
log().info() << "OPEN" << "\n";
_wc = workcell;
_state = _wc->getDefaultState();
log().info() << workcell->getFilename() << "\n";
if (_wc != NULL) {
// Add the texture render to this workcell if there is a frame for texture
Frame* textureFrame = _wc->findFrame("MarkerTexture");
if (textureFrame != NULL) {
getRobWorkStudio()->getWorkCellScene()->addRender("TextureImage",_textureRender,textureFrame);
}
// Add the background render to this workcell if there is a frame for texture
Frame* bgFrame = _wc->findFrame("Background");
if (bgFrame != NULL) {
getRobWorkStudio()->getWorkCellScene()->addRender("BackgroundImage",_bgRender,bgFrame);
}
// Create a GLFrameGrabber if there is a camera frame with a Camera property set
Frame* cameraFrame = _wc->findFrame(_cameras[0]);
if (cameraFrame != NULL) {
if (cameraFrame->getPropertyMap().has("Camera")) {
// Read the dimensions and field of view
double fovy;
int width,height;
std::string camParam = cameraFrame->getPropertyMap().get<std::string>("Camera");
std::istringstream iss (camParam, std::istringstream::in);
iss >> fovy >> width >> height;
// Create a frame grabber
_framegrabber = new GLFrameGrabber(width,height,fovy);
SceneViewer::Ptr gldrawer = getRobWorkStudio()->getView()->getSceneViewer();
_framegrabber->init(gldrawer);
}
}
Frame* cameraFrame25D = _wc->findFrame(_cameras25D[0]);
if (cameraFrame25D != NULL) {
if (cameraFrame25D->getPropertyMap().has("Scanner25D")) {
// Read the dimensions and field of view
double fovy;
int width,height;
std::string camParam = cameraFrame25D->getPropertyMap().get<std::string>("Scanner25D");
std::istringstream iss (camParam, std::istringstream::in);
iss >> fovy >> width >> height;
// Create a frame grabber
_framegrabber25D = new GLFrameGrabber25D(width,height,fovy);
SceneViewer::Ptr gldrawer = getRobWorkStudio()->getView()->getSceneViewer();
_framegrabber25D->init(gldrawer);
}
}
_device = _wc->findDevice("UR-6-85-5-A");
_step = -1;
}
}
void SamplePlugin::close() {
log().info() << "CLOSE" << "\n";
// Stop the timer
_timer->stop();
// Remove the texture render
Frame* textureFrame = _wc->findFrame("MarkerTexture");
if (textureFrame != NULL) {
getRobWorkStudio()->getWorkCellScene()->removeDrawable("TextureImage",textureFrame);
}
// Remove the background render
Frame* bgFrame = _wc->findFrame("Background");
if (bgFrame != NULL) {
getRobWorkStudio()->getWorkCellScene()->removeDrawable("BackgroundImage",bgFrame);
}
// Delete the old framegrabber
if (_framegrabber != NULL) {
delete _framegrabber;
}
_framegrabber = NULL;
_wc = NULL;
}
Mat SamplePlugin::toOpenCVImage(const Image& img) {
Mat res(img.getHeight(),img.getWidth(), CV_8SC3);
res.data = (uchar*)img.getImageData();
return res;
}
void SamplePlugin::btnPressed() {
QObject *obj = sender();
if(obj==_btn0){
// log().info() << "Button 0\n";
// // Toggle the timer on and off
// if (!_timer25D->isActive())
// _timer25D->start(100); // run 10 Hz
// else
// _timer25D->stop();
_timer->stop();
rw::math::Math::seed();
double extend = 0.05;
double maxTime = 60;
Q from(6, 1.571, -1.572, -1.572, -1.572, 1.571, 0);
Q to(6, 1.847, -2.465, -1.602, -0.647, 1.571, 0); //From pose estimation
createPathRRTConnect(from, to, extend, maxTime);
} else if(obj==_btn1){
log().info() << "Button 1\n";
// Toggle the timer on and off
if (!_timer->isActive()){
_timer->start(100); // run 10 Hz
_step = 0;
}
else
_step = 0;
} else if(obj==_spinBox){
log().info() << "spin value:" << _spinBox->value() << "\n";
}
else if( obj==_btn_im ){
getImage();
}
else if( obj==_btn_scan ){
get25DImage();
}
}
void SamplePlugin::get25DImage() {
if (_framegrabber25D != NULL) {
for( int i = 0; i < _cameras25D.size(); i ++)
{
// Get the image as a RW image
Frame* cameraFrame25D = _wc->findFrame(_cameras25D[i]); // "Camera");
_framegrabber25D->grab(cameraFrame25D, _state);
//const Image& image = _framegrabber->getImage();
const rw::geometry::PointCloud* img = &(_framegrabber25D->getImage());
std::ofstream output(_cameras25D[i] + ".pcd");
output << "# .PCD v.5 - Point Cloud Data file format\n";
output << "FIELDS x y z\n";
output << "SIZE 4 4 4\n";
output << "TYPE F F F\n";
output << "WIDTH " << img->getWidth() << "\n";
output << "HEIGHT " << img->getHeight() << "\n";
output << "POINTS " << img->getData().size() << "\n";
output << "DATA ascii\n";
for(const auto &p_tmp : img->getData())
{
rw::math::Vector3D<float> p = p_tmp;
output << p(0) << " " << p(1) << " " << p(2) << "\n";
}
output.close();
}
}
}
void SamplePlugin::getImage() {
if (_framegrabber != NULL) {
for( int i = 0; i < _cameras.size(); i ++)
{
// Get the image as a RW image
Frame* cameraFrame = _wc->findFrame(_cameras[i]); // "Camera");
_framegrabber->grab(cameraFrame, _state);
const rw::sensor::Image* rw_image = &(_framegrabber->getImage());
// Convert to OpenCV matrix.
cv::Mat image = cv::Mat(rw_image->getHeight(), rw_image->getWidth(), CV_8UC3, (rw::sensor::Image*)rw_image->getImageData());
// Convert to OpenCV image
Mat imflip, imflip_mat;
cv::flip(image, imflip, 1);
cv::cvtColor( imflip, imflip_mat, COLOR_RGB2BGR );
cv::imwrite(_cameras[i] + ".png", imflip_mat );
// Show in QLabel
QImage img(imflip.data, imflip.cols, imflip.rows, imflip.step, QImage::Format_RGB888);
QPixmap p = QPixmap::fromImage(img);
unsigned int maxW = 480;
unsigned int maxH = 640;
_label->setPixmap(p.scaled(maxW,maxH,Qt::KeepAspectRatio));
}
}
}
void SamplePlugin::timer() {
if(0 <= _step && _step < _path.size()){
_device->setQ(_path.at(_step),_state);
getRobWorkStudio()->setState(_state);
_step++;
}
}
void SamplePlugin::stateChangedListener(const State& state) {
_state = state;
}
bool SamplePlugin::checkCollisions(Device::Ptr device, const State &state, const CollisionDetector &detector, const Q &q) {
State testState;
CollisionDetector::QueryResult data;
bool colFrom;
testState = state;
device->setQ(q,testState);
colFrom = detector.inCollision(testState,&data);
if (colFrom) {
cerr << "Configuration in collision: " << q << endl;
cerr << "Colliding frames: " << endl;
FramePairSet fps = data.collidingFrames;
for (FramePairSet::iterator it = fps.begin(); it != fps.end(); it++) {
cerr << (*it).first->getName() << " " << (*it).second->getName() << endl;
}
return false;
}
return true;
}
void SamplePlugin::createPathRRTConnect(Q from, Q to, double extend, double maxTime){
_device->setQ(from,_state);
getRobWorkStudio()->setState(_state);
CollisionDetector detector(_wc, ProximityStrategyFactory::makeDefaultCollisionStrategy());
PlannerConstraint constraint = PlannerConstraint::make(&detector,_device,_state);
QSampler::Ptr sampler = QSampler::makeConstrained(QSampler::makeUniform(_device),constraint.getQConstraintPtr());
QMetric::Ptr metric = MetricFactory::makeEuclidean<Q>();
QToQPlanner::Ptr planner = RRTPlanner::makeQToQPlanner(constraint, sampler, metric, extend, RRTPlanner::RRTConnect);
_path.clear();
if (!checkCollisions(_device, _state, detector, from))
cout << from << " is in colission!" << endl;
if (!checkCollisions(_device, _state, detector, to))
cout << to << " is in colission!" << endl;;
Timer t;
t.resetAndResume();
planner->query(from,to,_path,maxTime);
t.pause();
if (t.getTime() >= maxTime) {
cout << "Notice: max time of " << maxTime << " seconds reached." << endl;
}
const int duration = 10;
if(_path.size() == 2){ //The interpolated path between Q start and Q goal is collision free. Set the duration with respect to the desired velocity
LinearInterpolator<Q> linInt(from, to, duration);
QPath tempQ;
for(int i = 0; i < duration+1; i++){
tempQ.push_back(linInt.x(i));
}
_path=tempQ;
}
}
|
#if USE_OPFOR
/***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "Weapons.h"
#include "customentity.h"
#include "Skill.h"
#include "Decals.h"
#include "CShockBeam.h"
BEGIN_DATADESC( CShockBeam )
DEFINE_THINKFUNC( FlyThink ),
DEFINE_THINKFUNC( ExplodeThink ),
DEFINE_THINKFUNC( WaterExplodeThink ),
DEFINE_TOUCHFUNC( BallTouch ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( shock_beam, CShockBeam );
void CShockBeam::Precache()
{
PRECACHE_MODEL( "sprites/flare3.spr" );
PRECACHE_MODEL( "sprites/lgtning.spr" );
PRECACHE_MODEL( "sprites/glow01.spr" );
PRECACHE_MODEL( "models/shock_effect.mdl" );
PRECACHE_SOUND( "weapons/shock_impact.wav" );
}
void CShockBeam::Spawn()
{
Precache();
SetMoveType( MOVETYPE_FLY );
SetSolidType( SOLID_BBOX );
SetModel( "models/shock_effect.mdl" );
SetAbsOrigin( GetAbsOrigin() );
SetSize( Vector( -4, -4, -4 ), Vector( 4, 4, 4 ) );
SetTouch( &CShockBeam::BallTouch );
SetThink( &CShockBeam::FlyThink );
m_pSprite = CSprite::SpriteCreate(
"sprites/flare3.spr",
GetAbsOrigin(),
false );
m_pSprite->SetRenderMode( kRenderTransAdd );
m_pSprite->SetRenderColor( Vector( 255, 255, 255 ) );
m_pSprite->SetRenderAmount( 255 );
m_pSprite->SetRenderFX( kRenderFxDistort );
m_pSprite->SetScale( 0.35 );
m_pSprite->SetAttachment( this, 0 );
m_pBeam1 = CBeam::BeamCreate( "sprites/lgtning.spr", 60 );
if( m_pBeam1 )
{
m_pBeam1->SetAbsOrigin( GetAbsOrigin() );
m_pBeam1->EntsInit( entindex(), entindex() );
m_pBeam1->SetStartAttachment( 1 );
m_pBeam1->SetEndAttachment( 2 );
m_pBeam1->SetRenderColor( Vector( 0, 253, 253 ) );
m_pBeam1->SetBeamFlags( BEAM_FSHADEOUT );
m_pBeam1->SetBrightness( 180 );
m_pBeam1->SetNoise( 0 );
m_pBeam1->SetScrollRate( 10 );
if( bIsMultiplayer() )
{
SetNextThink( gpGlobals->time + 0.01 );
return;
}
m_pBeam2 = CBeam::BeamCreate( "sprites/lgtning.spr", 20 );
if( m_pBeam2 )
{
m_pBeam2->SetAbsOrigin( GetAbsOrigin() );
m_pBeam2->EntsInit( entindex(), entindex() );
m_pBeam2->SetStartAttachment( 1 );
m_pBeam2->SetEndAttachment( 2 );
m_pBeam2->SetRenderColor( Vector( 255, 255, 157 ) );
m_pBeam2->SetBeamFlags( BEAM_FSHADEOUT );
m_pBeam2->SetBrightness( 180 );
m_pBeam2->SetNoise( 30 );
m_pBeam2->SetScrollRate( 30 );
SetNextThink( gpGlobals->time + 0.01 );
}
}
}
EntityClassification_t CShockBeam::GetClassification()
{
return EntityClassifications().GetNoneId();
}
void CShockBeam::FlyThink()
{
if( GetWaterLevel() == WATERLEVEL_HEAD )
{
SetThink( &CShockBeam::WaterExplodeThink );
}
SetNextThink( gpGlobals->time + 0.01 );
}
void CShockBeam::ExplodeThink()
{
Explode();
UTIL_Remove( this );
}
void CShockBeam::WaterExplodeThink()
{
CBaseEntity* pOwner = GetOwner();
Explode();
::RadiusDamage(
GetAbsOrigin(),
CTakeDamageInfo( this, pOwner, 100.0, DMG_ALWAYSGIB | DMG_BLAST ),
150.0, 0 );
UTIL_Remove( this );
}
void CShockBeam::BallTouch( CBaseEntity* pOther )
{
if( pOther->GetTakeDamageMode() != DAMAGE_NO )
{
TraceResult tr = UTIL_GetGlobalTrace();
CBaseEntity* pOwner = GetOwner();
g_MultiDamage.Clear();
int bitsDamageTypes = DMG_ALWAYSGIB | DMG_SHOCK;
if( CBaseMonster* pMonster = pOther->MyMonsterPointer() )
{
bitsDamageTypes = 64;
if( pMonster->m_flShockDuration > 1.0 )
{
bitsDamageTypes = 8192;
}
pMonster->AddShockEffect( 63, 152, 208, 16, 0.5 );
}
pOther->TraceAttack(
CTakeDamageInfo(
pOwner,
bIsMultiplayer() ? gSkillData.GetPlrDmgShockRoachM() : gSkillData.GetPlrDmgShockRoachS(),
bitsDamageTypes ),
GetAbsVelocity().Normalize(),
tr );
g_MultiDamage.ApplyMultiDamage( this, pOwner );
SetAbsVelocity( g_vecZero );
}
SetThink( &CShockBeam::ExplodeThink );
SetNextThink( gpGlobals->time + 0.01 );
if( pOther->GetTakeDamageMode() == DAMAGE_NO )
{
TraceResult tr;
UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + GetAbsVelocity() * 10, dont_ignore_monsters, edict(), &tr );
UTIL_DecalTrace( &tr, DECAL_OFSCORCH1 + UTIL_RandomLong( 0, 2 ) );
MESSAGE_BEGIN( MSG_PAS, SVC_TEMPENTITY, GetAbsOrigin() );
WRITE_BYTE( TE_SPARKS );
WRITE_COORD_VECTOR( GetAbsOrigin() );
MESSAGE_END();
}
}
void CShockBeam::Explode()
{
if( m_pSprite )
{
UTIL_Remove( m_pSprite );
m_pSprite = nullptr;
}
if( m_pBeam1 )
{
UTIL_Remove( m_pBeam1 );
m_pBeam1 = nullptr;
}
if( m_pBeam2 )
{
UTIL_Remove( m_pBeam2 );
m_pBeam2 = nullptr;
}
SetDamage( 40 );
MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, GetAbsOrigin() );
WRITE_BYTE( TE_DLIGHT );
WRITE_COORD_VECTOR( GetAbsOrigin() );
WRITE_BYTE( 8 );
WRITE_BYTE( 0 );
WRITE_BYTE( 253 );
WRITE_BYTE( 253 );
WRITE_BYTE( 5 );
WRITE_BYTE( 10 );
MESSAGE_END();
SetOwner( nullptr );
EMIT_SOUND_DYN(
this, CHAN_WEAPON,
"weapons/shock_impact.wav",
UTIL_RandomFloat( 0.8, 0.9 ), ATTN_NORM, 0, PITCH_NORM );
}
CShockBeam* CShockBeam::CreateShockBeam( const Vector& vecOrigin, const Vector& vecAngles, CBaseEntity* pOwner )
{
Vector vecNewAngles = vecAngles;
vecNewAngles.x = -vecNewAngles.x;
CShockBeam* pBeam = static_cast<CShockBeam*>( Create( "shock_beam", vecOrigin, vecNewAngles, pOwner->edict(), false ) );
pBeam->SetAbsOrigin( vecOrigin );
UTIL_MakeVectors( vecAngles );
pBeam->SetAbsVelocity( gpGlobals->v_forward * 2000.0 );
pBeam->Spawn();
return pBeam;
}
#endif //USE_OPFOR
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h"
#include <memory>
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/Dialect/StandardOps/Ops.h" // TF:local_config_mlir
#include "mlir/IR/Attributes.h" // TF:local_config_mlir
#include "mlir/IR/Function.h" // TF:local_config_mlir
#include "mlir/IR/Location.h" // TF:local_config_mlir
#include "mlir/IR/MLIRContext.h" // TF:local_config_mlir
#include "mlir/IR/Matchers.h" // TF:local_config_mlir
#include "mlir/IR/Module.h" // TF:local_config_mlir
#include "mlir/IR/Operation.h" // TF:local_config_mlir
#include "mlir/IR/TypeUtilities.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h"
#include "tensorflow/compiler/mlir/xla/type_to_shape.h"
#include "tensorflow/compiler/xla/client/lib/matrix.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/comparison_util.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
using ::tensorflow::int16;
using ::tensorflow::int32;
using ::tensorflow::int64;
using ::tensorflow::int8;
using ::tensorflow::uint16;
using ::tensorflow::uint32;
using ::tensorflow::uint64;
using ::tensorflow::uint8;
// Passes through everything except for unique_ptr, on which it calls get().
// This exists to allow the generated code to call XLA functions that take a raw
// pointer. In particular, PrecisionConfig is passed to xla::Dot and xla::Conv
// as a pointer and there is otherwise no way to avoid a memory leak.
template <typename T>
T Unwrap(T t) {
return t;
}
template <typename T>
T* Unwrap(const std::unique_ptr<T>& t) {
return t.get();
}
// Convert APInt into an int.
// TODO(hpucha): This should be consolidated into a general place.
static int ConvertAPInt(llvm::APInt i) { return i.getSExtValue(); }
// Convert APFloat to double.
static double ConvertAPFloat(llvm::APFloat value) {
const auto& semantics = value.getSemantics();
bool losesInfo = false;
if (&semantics != &llvm::APFloat::IEEEdouble())
value.convert(llvm::APFloat::IEEEdouble(),
llvm::APFloat::rmNearestTiesToEven, &losesInfo);
return value.convertToDouble();
}
static absl::string_view ConvertStringRef(mlir::StringRef value) {
return {value.data(), value.size()};
}
static std::vector<int64> ConvertDenseIntAttr(mlir::DenseIntElementsAttr attr) {
auto values = attr.getValues<int64>();
return {values.begin(), values.end()};
}
static std::vector<int64> ConvertDenseIntAttr(
llvm::Optional<mlir::DenseIntElementsAttr> attr) {
if (!attr) return {};
return ConvertDenseIntAttr(*attr);
}
// Converts the broadcast_dimensions attribute into a vector of dimension
// numbers (empty if the attribute is absent).
static std::vector<int64> Convert_broadcast_dimensions(
llvm::Optional<mlir::DenseIntElementsAttr> broadcast_dimensions) {
if (!broadcast_dimensions.hasValue()) return {};
return ConvertDenseIntAttr(*broadcast_dimensions);
}
// Convert a nx2 dense attribute to a list of tuples. This is the way padding
// is defined in hlo.
static std::vector<std::pair<int64, int64>> Convert_padding(
llvm::Optional<mlir::DenseIntElementsAttr> padding_optional) {
if (!padding_optional.hasValue()) return {};
mlir::DenseIntElementsAttr padding = *padding_optional;
auto it = padding.getValues<int64>().begin();
std::vector<std::pair<int64, int64>> out(padding.getNumElements() / 2);
for (auto& item : out) {
int64 left_pad = *it;
++it;
int64 right_pad = *it;
++it;
item = {left_pad, right_pad};
}
return out;
}
static std::vector<xla::ReplicaGroup> Convert_replica_groups(
mlir::DenseIntElementsAttr groups) {
int64_t num_groups = groups.getType().getDimSize(0);
int64_t group_size = groups.getType().getDimSize(1);
std::vector<xla::ReplicaGroup> result;
result.reserve(num_groups);
for (uint64_t i = 0; i < num_groups; ++i) {
xla::ReplicaGroup group;
for (uint64_t j = 0; j < group_size; ++j) {
group.add_replica_ids(groups.getValue<int64_t>({i, j}));
}
result.push_back(group);
}
return result;
}
#define I64_ELEMENTS_ATTR_TO_VECTOR(attribute) \
static std::vector<int64> Convert_##attribute( \
mlir::DenseIntElementsAttr attribute) { \
return ConvertDenseIntAttr(attribute); \
}
I64_ELEMENTS_ATTR_TO_VECTOR(broadcast_sizes);
I64_ELEMENTS_ATTR_TO_VECTOR(permutation);
I64_ELEMENTS_ATTR_TO_VECTOR(start_indices);
I64_ELEMENTS_ATTR_TO_VECTOR(limit_indices);
I64_ELEMENTS_ATTR_TO_VECTOR(strides);
#undef I64_ELEMENTS_ATTR_TO_VECTOR
static std::vector<int64> Convert_ArrayRef(llvm::ArrayRef<int64_t> values) {
return {values.begin(), values.end()};
}
// Converts the precision config array of strings attribute into the
// corresponding XLA proto. All the strings are assumed to be valid names of the
// Precision enum. This should have been checked in the op verify method.
static std::unique_ptr<xla::PrecisionConfig> Convert_precision_config(
llvm::Optional<mlir::ArrayAttr> optional_precision_config_attr) {
if (!optional_precision_config_attr.hasValue()) return nullptr;
auto precision_config = absl::make_unique<xla::PrecisionConfig>();
for (auto attr : optional_precision_config_attr.getValue()) {
xla::PrecisionConfig::Precision p;
auto operand_precision = attr.cast<mlir::StringAttr>().getValue().str();
// TODO(jpienaar): Update this to ensure this is captured by verify.
if (xla::PrecisionConfig::Precision_Parse(operand_precision, &p)) {
precision_config->add_operand_precision(p);
} else {
auto* context = attr.getContext();
mlir::emitError(mlir::UnknownLoc::get(context))
<< "unexpected operand precision " << operand_precision;
return nullptr;
}
}
return precision_config;
}
static xla::DotDimensionNumbers Convert_dot_dimension_numbers(
mlir::xla_hlo::DotDimensionNumbers dot_dimension_numbers_attr) {
xla::DotDimensionNumbers dot_dimension_numbers;
auto rhs_contracting_dimensions =
dot_dimension_numbers_attr.rhs_contracting_dimensions()
.cast<mlir::DenseIntElementsAttr>();
auto lhs_contracting_dimensions =
dot_dimension_numbers_attr.lhs_contracting_dimensions()
.cast<mlir::DenseIntElementsAttr>();
auto rhs_batch_dimensions =
dot_dimension_numbers_attr.rhs_batching_dimensions()
.cast<mlir::DenseIntElementsAttr>();
auto lhs_batch_dimensions =
dot_dimension_numbers_attr.lhs_batching_dimensions()
.cast<mlir::DenseIntElementsAttr>();
for (auto val : rhs_contracting_dimensions) {
dot_dimension_numbers.add_rhs_contracting_dimensions(val.getSExtValue());
}
for (auto val : lhs_contracting_dimensions) {
dot_dimension_numbers.add_lhs_contracting_dimensions(val.getSExtValue());
}
for (auto val : rhs_batch_dimensions) {
dot_dimension_numbers.add_rhs_batch_dimensions(val.getSExtValue());
}
for (auto val : lhs_batch_dimensions) {
dot_dimension_numbers.add_lhs_batch_dimensions(val.getSExtValue());
}
return dot_dimension_numbers;
}
static xla::ConvolutionDimensionNumbers Convert_convolution_dimension_numbers(
mlir::xla_hlo::ConvDimensionNumbers input) {
xla::ConvolutionDimensionNumbers output;
output.set_input_batch_dimension(
input.input_batch_dimension().getValue().getSExtValue());
output.set_input_feature_dimension(
input.input_feature_dimension().getValue().getSExtValue());
for (int64 v : input.input_spatial_dimensions().getValues<int64>()) {
output.add_input_spatial_dimensions(v);
}
output.set_kernel_input_feature_dimension(
input.kernel_input_feature_dimension().getValue().getSExtValue());
output.set_kernel_output_feature_dimension(
input.kernel_output_feature_dimension().getValue().getSExtValue());
for (int64 v : input.kernel_spatial_dimensions().getValues<int64>()) {
output.add_kernel_spatial_dimensions(v);
}
output.set_output_batch_dimension(
input.output_batch_dimension().getValue().getSExtValue());
output.set_output_feature_dimension(
input.output_feature_dimension().getValue().getSExtValue());
for (int64 v : input.output_spatial_dimensions().getValues<int64>()) {
output.add_output_spatial_dimensions(v);
}
return output;
}
xla::ChannelHandle Convert_channel_handle(mlir::xla_hlo::ChannelHandle attr) {
xla::ChannelHandle channel_handle;
channel_handle.set_handle(ConvertAPInt(attr.handle().getValue()));
channel_handle.set_type(static_cast<xla::ChannelHandle::ChannelType>(
ConvertAPInt(attr.type().getValue())));
return channel_handle;
}
// Converts the comparison_direction string attribute into the XLA enum. The
// string is assumed to correspond to exactly one of the allowed strings
// representing the enum. This should have been checked in the op verify method.
static xla::ComparisonDirection Convert_comparison_direction(
llvm::StringRef comparison_direction_string) {
return xla::StringToComparisonDirection(comparison_direction_string.str())
.ValueOrDie();
}
static xla::ScatterDimensionNumbers Convert_scatter_dimension_numbers(
mlir::xla_hlo::ScatterDimensionNumbers input) {
xla::ScatterDimensionNumbers output;
auto update_window_dims = ConvertDenseIntAttr(input.update_window_dims());
std::copy(update_window_dims.begin(), update_window_dims.end(),
tensorflow::protobuf::RepeatedFieldBackInserter(
output.mutable_update_window_dims()));
auto inserted_window_dims = ConvertDenseIntAttr(input.inserted_window_dims());
std::copy(inserted_window_dims.begin(), inserted_window_dims.end(),
tensorflow::protobuf::RepeatedFieldBackInserter(
output.mutable_inserted_window_dims()));
auto scatter_dims_to_operand_dims =
ConvertDenseIntAttr(input.scatter_dims_to_operand_dims());
std::copy(scatter_dims_to_operand_dims.begin(),
scatter_dims_to_operand_dims.end(),
tensorflow::protobuf::RepeatedFieldBackInserter(
output.mutable_scatter_dims_to_operand_dims()));
output.set_index_vector_dim(
ConvertAPInt(input.index_vector_dim().getValue()));
return output;
}
namespace mlir {
namespace {
class ConvertToHloModule {
public:
using ValueLoweringMap = llvm::DenseMap<Value*, xla::XlaOp>;
using FunctionLoweringMap = llvm::DenseMap<mlir::FuncOp, xla::XlaComputation>;
// If use_tuple_args is true, then the entry function's arguments are
// converted to a tuple and passed as a single parameter.
// Similarly, if return tuple is true, then the entry function's return values
// are converted to a tuple even when there is only a single return value.
// Multiple return values are always converted to a tuple and returned as a
// single value.
explicit ConvertToHloModule(mlir::ModuleOp module, bool use_tuple_args,
bool return_tuple)
: module_(module),
module_builder_("main"),
use_tuple_args_(use_tuple_args),
return_tuple_(return_tuple) {}
// Perform the lowering to XLA. This function returns failure if an error was
// encountered.
//
// TODO(hinsu): Check for dynamic shapes and exit instead of crashing.
LogicalResult Run() {
for (auto func : module_.getOps<FuncOp>()) {
if (func.empty()) continue;
if (failed(RunOnFunction(func))) return failure();
}
return success();
}
// Lower a specific function to HLO.
LogicalResult RunOnFunction(mlir::FuncOp f);
// Lower a `mlir::Region` to a `XlaComputation`
LogicalResult LowerRegionAsComputation(mlir::Region* region,
xla::XlaComputation* func);
// Lower a single `Block` to a `XlaComputation`
LogicalResult LowerBasicBlockAsFunction(Block* block,
xla::XlaBuilder* builder,
bool is_entry_function,
xla::XlaComputation* result);
::xla::HloModuleProto ConsumeMainProto() {
return lowered_computation_[module_.lookupSymbol<mlir::FuncOp>("main")]
.proto();
}
// Lower function call to HLO call instruction
LogicalResult LowerFunctionCall(
mlir::CallOp* call_op, xla::XlaBuilder* builder,
ConvertToHloModule::ValueLoweringMap* value_lowering);
private:
LogicalResult Lower(mlir::Operation* inst, bool is_entry_function,
xla::XlaBuilder* builder,
ConvertToHloModule::ValueLoweringMap* value_lowering,
xla::XlaComputation* result);
// The module being lowered.
mlir::ModuleOp module_;
// The top-level XlaBuilder.
xla::XlaBuilder module_builder_;
// Map between function and lowered computation.
FunctionLoweringMap lowered_computation_;
// Whether the entry function should take a single tuple as input.
bool use_tuple_args_;
// Whether to always return a tuple.
bool return_tuple_;
// Unique suffix to give to the name of the next lowered region.
size_t region_id_ = 0;
};
} // namespace
} // namespace mlir
namespace {
struct OpLoweringContext {
llvm::DenseMap<mlir::Value*, xla::XlaOp>* values;
mlir::ConvertToHloModule* converter;
xla::XlaBuilder* builder;
};
llvm::SmallVector<xla::XlaOp, 4> GetTuple(mlir::Operation::operand_range values,
OpLoweringContext ctx) {
llvm::SmallVector<xla::XlaOp, 4> ops;
for (mlir::Value* value : values) {
ops.push_back((*ctx.values)[value]);
}
return ops;
}
} // namespace
namespace mlir {
namespace xla_hlo {
namespace {
LogicalResult ExportXlaOp(AllReduceOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
xla::XlaComputation computation;
if (failed(ctx.converter->LowerRegionAsComputation(&op.computation(),
&computation))) {
return failure();
}
auto replica_groups = Convert_replica_groups(op.replica_groups());
if (!op.channel_id().hasValue()) {
value_map[op] =
xla::AllReduce(value_map[op.operand()], computation, replica_groups,
/*channel_id=*/absl::nullopt);
return success();
}
auto channel_id = Convert_channel_handle(op.channel_id().getValue());
value_map[op] = xla::AllReduce(value_map[op.operand()], computation,
replica_groups, channel_id);
return success();
}
LogicalResult ExportXlaOp(BroadcastInDimOp op, OpLoweringContext ctx) {
auto type = op.getType().dyn_cast<RankedTensorType>();
if (!type) return failure();
auto& value_map = *ctx.values;
value_map[op] =
BroadcastInDim(value_map[op.operand()], Convert_ArrayRef(type.getShape()),
Convert_broadcast_dimensions(op.broadcast_dimensions()));
return success();
}
LogicalResult ExportXlaOp(ConcatenateOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::ConcatInDim(ctx.builder, GetTuple(op.val(), ctx),
op.dimension().getSExtValue());
return success();
}
LogicalResult ExportXlaOp(ConditionalOp op, OpLoweringContext ctx) {
xla::XlaComputation true_branch;
xla::XlaComputation false_branch;
auto& value_map = *ctx.values;
if (failed(ctx.converter->LowerRegionAsComputation(&op.true_branch(),
&true_branch)) ||
failed(ctx.converter->LowerRegionAsComputation(&op.false_branch(),
&false_branch))) {
return failure();
}
value_map[op] =
xla::Conditional(value_map[op.pred()], value_map[op.true_arg()],
true_branch, value_map[op.false_arg()], false_branch);
return success();
}
LogicalResult ExportXlaOp(ConstOp op, OpLoweringContext ctx) {
return failure();
}
LogicalResult ExportXlaOp(ConvOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::ConvGeneralDilated(
value_map[op.lhs()], value_map[op.rhs()],
Convert_broadcast_dimensions(op.window_strides()),
Convert_padding(op.padding()),
Convert_broadcast_dimensions(op.lhs_dilation()),
Convert_broadcast_dimensions(op.rhs_dilation()),
Convert_convolution_dimension_numbers(op.dimension_numbers()),
op.feature_group_count().getSExtValue(),
op.batch_group_count().getSExtValue(),
Convert_precision_config(op.precision_config()).get());
return success();
}
LogicalResult ExportXlaOp(ConvertOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::ConvertElementType(
value_map[op.operand()],
xla::TypeToPrimitiveType(getElementTypeOrSelf(op.getType())));
return success();
}
LogicalResult ExportXlaOp(CopyOp op, OpLoweringContext ctx) {
return failure();
}
LogicalResult ExportXlaOp(DynamicSliceOp op, OpLoweringContext ctx) {
return failure();
}
LogicalResult ExportXlaOp(DynamicUpdateSliceOp op, OpLoweringContext ctx) {
return failure();
}
LogicalResult ExportXlaOp(FftOp op, OpLoweringContext ctx) { return failure(); }
LogicalResult ExportXlaOp(GatherOp op, OpLoweringContext ctx) {
return failure();
}
LogicalResult ExportXlaOp(GetTupleElementOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::GetTupleElement(value_map[op.getOperand()],
op.index().getSExtValue());
return success();
}
LogicalResult ExportXlaOp(IotaOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::Iota(ctx.builder, xla::TypeToShape(op.getType()),
op.iota_dimension().getSExtValue());
return success();
}
LogicalResult ExportXlaOp(PadOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
xla::PaddingConfig padding_config;
auto edge_padding_low = ConvertDenseIntAttr(op.edge_padding_low());
auto edge_padding_high = ConvertDenseIntAttr(op.edge_padding_high());
auto interior_padding = ConvertDenseIntAttr(op.interior_padding());
for (xla::int64 i = 0; i < edge_padding_low.size(); ++i) {
auto* dims = padding_config.add_dimensions();
dims->set_edge_padding_low(edge_padding_low[i]);
dims->set_edge_padding_high(edge_padding_high[i]);
dims->set_interior_padding(interior_padding[i]);
}
value_map[op] = xla::Pad(value_map[op.getOperand(0)],
value_map[op.getOperand(1)], padding_config);
return success();
}
LogicalResult ExportXlaOp(ReduceOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
xla::XlaComputation body;
if (failed(ctx.converter->LowerRegionAsComputation(&op.body(), &body))) {
return failure();
}
xla::XlaOp result =
xla::Reduce(ctx.builder, GetTuple(op.operands(), ctx),
GetTuple(op.init_values(), ctx), body,
Convert_broadcast_dimensions(op.dimensions()));
if (op.getNumResults() == 1) {
value_map[op.getResult(0)] = result;
} else {
for (auto item : llvm::enumerate(op.getResults())) {
value_map[item.value()] = xla::GetTupleElement(result, item.index());
}
}
return success();
}
LogicalResult ExportXlaOp(ReduceWindowOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
xla::XlaComputation body;
if (failed(ctx.converter->LowerRegionAsComputation(&op.body(), &body))) {
return failure();
}
value_map[op] = xla::ReduceWindowWithGeneralPadding(
value_map[op.operand()], value_map[op.init_value()], body,
ConvertDenseIntAttr(op.window_dimensions()),
ConvertDenseIntAttr(op.window_strides()),
ConvertDenseIntAttr(op.base_dilations()),
ConvertDenseIntAttr(op.window_dilations()),
Convert_padding(op.padding()));
return success();
}
LogicalResult ExportXlaOp(ReshapeOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::Reshape(value_map[op.operand()],
xla::TypeToShape(op.getType()).dimensions());
return success();
}
LogicalResult ExportXlaOp(ReturnOp op, OpLoweringContext ctx) {
// Failure on purpose because `xla_hlo::ReturnOp` will be handled by
// special purpose logic in `ConvertToHloModule::Lower`.
return failure();
}
LogicalResult ExportXlaOp(ReverseOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::Rev(value_map[op.operand()],
Convert_broadcast_dimensions(op.dimensions()));
return success();
}
LogicalResult ExportXlaOp(RngUniformOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::RngUniform(value_map[op.a()], value_map[op.b()],
xla::TypeToShape(op.getType()));
return success();
}
LogicalResult ExportXlaOp(ScatterOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
xla::XlaComputation update_computation;
if (failed(ctx.converter->LowerRegionAsComputation(&op.update_computation(),
&update_computation))) {
return failure();
}
xla::ScatterDimensionNumbers dimension_numbers =
Convert_scatter_dimension_numbers(op.scatter_dimension_numbers());
value_map[op] = xla::Scatter(
value_map[op.operand()], value_map[op.scatter_indices()],
value_map[op.updates()], update_computation, dimension_numbers,
op.indices_are_sorted(), op.unique_indices());
return success();
}
LogicalResult ExportXlaOp(SelectAndScatterOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
xla::XlaComputation select;
xla::XlaComputation scatter;
if (failed(ctx.converter->LowerRegionAsComputation(&op.select(), &select)) ||
failed(
ctx.converter->LowerRegionAsComputation(&op.scatter(), &scatter))) {
return failure();
}
value_map[op] = xla::SelectAndScatterWithGeneralPadding(
value_map[op.operand()], select,
ConvertDenseIntAttr(op.window_dimensions()),
ConvertDenseIntAttr(op.window_strides()), Convert_padding(op.padding()),
value_map[op.source()], value_map[op.init_value()], scatter);
return success();
}
LogicalResult ExportXlaOp(SliceOp op, OpLoweringContext ctx) {
return failure();
}
LogicalResult ExportXlaOp(TupleOp op, OpLoweringContext ctx) {
auto& value_map = *ctx.values;
value_map[op] = xla::Tuple(ctx.builder, GetTuple(op.val(), ctx));
return success();
}
LogicalResult ExportXlaOp(UnaryEinsumOp op, OpLoweringContext ctx) {
// Intentional as UnaryEinsumOp is always lowered to the EinsumOp with two
// operands.
return failure();
}
LogicalResult ExportXlaOp(WhileOp op, OpLoweringContext ctx) {
xla::XlaComputation condition;
xla::XlaComputation body;
auto& value_map = *ctx.values;
if (failed(ctx.converter->LowerRegionAsComputation(&op.body(), &body)) ||
failed(ctx.converter->LowerRegionAsComputation(&op.cond(), &condition))) {
return failure();
}
value_map[op] = xla::While(condition, body, value_map[op.getOperand()]);
return success();
}
} // namespace
} // namespace xla_hlo
} // namespace mlir
#include "tensorflow/compiler/mlir/xla/operator_writers.inc"
namespace mlir {
namespace {
StatusOr<xla::Literal> CreateLiteralFromAttr(Type type, ElementsAttr attr) {
xla::Shape shape = xla::TypeToShape(type);
#define ELEMENTS_ATTR_TO_LITERAL(xla_type, cpp_type) \
case xla_type: { \
xla::Array<cpp_type> source_data(shape.dimensions()); \
source_data.SetValues(attr.getValues<cpp_type>()); \
return xla::LiteralUtil::CreateFromArray(source_data); \
}
switch (shape.element_type()) {
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::PRED, bool)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::F32, float)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::F64, double)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::S8, int8)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::S16, int16)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::S32, int32)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::S64, int64)
// TODO(b/130356985): Update once MLIR supports unsigned integers.
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::U8, uint8)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::U16, uint16)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::U32, uint32)
ELEMENTS_ATTR_TO_LITERAL(xla::PrimitiveType::U64, uint64)
default:
return tensorflow::errors::Internal(absl::StrCat(
"Unsupported type: ", xla::PrimitiveType_Name(shape.element_type())));
}
#undef ELEMENTS_ATTR_TO_LITERAL
}
LogicalResult ConvertToHloModule::Lower(
mlir::Operation* inst, bool is_entry_function, xla::XlaBuilder* builder,
ConvertToHloModule::ValueLoweringMap* value_lowering,
xla::XlaComputation* result) {
if (succeeded(ExportXlaOperator(inst, {value_lowering, this, builder}))) {
return success();
}
auto& value_map = *value_lowering;
ElementsAttr const_attr;
if (auto call_op = dyn_cast<mlir::CallOp>(inst)) {
return LowerFunctionCall(&call_op, builder, &value_map);
}
// TODO(jpienaar): This doesn't support layouts yet.
if (matchPattern(inst, m_Constant(&const_attr))) {
auto literal_or =
CreateLiteralFromAttr(*inst->result_type_begin(), const_attr);
if (!literal_or.ok()) return inst->emitError("unsupported elemental type");
value_map[inst->getResult(0)] =
xla::ConstantLiteral(builder, literal_or.ValueOrDie());
return success();
}
if (isa<xla_hlo::ReturnOp>(inst) || isa<mlir::ReturnOp>(inst)) {
// Construct the return value for the function. If there are multiple
// values returned, then create a tuple, else return value directly.
xla::XlaOp return_value;
unsigned num_return_values = inst->getNumOperands();
if ((return_tuple_ && is_entry_function) || num_return_values > 1) {
std::vector<xla::XlaOp> returns(num_return_values);
for (unsigned i = 0, e = inst->getNumOperands(); i != e; ++i) {
returns[i] = value_map[inst->getOperand(i)];
}
return_value = xla::Tuple(builder, returns);
} else if (num_return_values == 1) {
return_value = value_map[inst->getOperand(0)];
}
// Build the XlaComputation and check for failures.
auto computation_or =
return_value.valid() ? builder->Build(return_value) : builder->Build();
if (!computation_or.ok()) {
inst->emitError(llvm::Twine(computation_or.status().error_message()));
return failure();
}
*result = std::move(computation_or.ValueOrDie());
return success();
}
inst->emitError("unable to lower operation of type '" +
inst->getName().getStringRef().str() + '\'');
return failure();
}
LogicalResult ConvertToHloModule::LowerFunctionCall(
mlir::CallOp* call_op, xla::XlaBuilder* builder,
ConvertToHloModule::ValueLoweringMap* value_lowering) {
auto& value_map = *value_lowering;
mlir::FuncOp callee = module_.lookupSymbol<mlir::FuncOp>(call_op->callee());
if (failed(RunOnFunction(callee))) return failure();
std::vector<xla::XlaOp> operands;
for (auto operand : call_op->getOperands()) {
operands.push_back(value_map[operand]);
}
// Each call to xla::Call would insert a copy of the computation to
// the HLO. Thus each callsite would have a unique callee in the
// exported HLO. HLO syntactically does not require all calls to have unique
// callees, but eventually before lowering call graph is "flattened" to
// make that true. This is done before lowering because buffer assignment
// needs this invariant.
xla::XlaOp call_result =
xla::Call(builder, lowered_computation_[callee], operands);
// Use GetTupleElement for multiple outputs
unsigned num_results = call_op->getNumResults();
if (num_results > 1) {
for (unsigned i = 0; i != num_results; ++i) {
value_map[call_op->getResult(i)] = xla::GetTupleElement(call_result, i);
}
} else if (num_results == 1) {
value_map[call_op->getResult(0)] = call_result;
}
return success();
}
LogicalResult ConvertToHloModule::RunOnFunction(mlir::FuncOp f) {
if (lowered_computation_.count(f)) return success();
if (f.getBlocks().size() != 1) {
return f.emitError("only single block Function supported");
}
// Create a sub-builder if this is not the main function.
std::unique_ptr<xla::XlaBuilder> builder_up;
bool entry_function = f.getName().str() == "main";
if (!entry_function)
builder_up = module_builder_.CreateSubBuilder(f.getName().str());
auto& builder = entry_function ? module_builder_ : *builder_up;
xla::XlaComputation computation;
if (failed(LowerBasicBlockAsFunction(&f.front(), &builder, entry_function,
&computation))) {
return failure();
}
lowered_computation_[f] = std::move(computation);
return success();
}
LogicalResult ConvertToHloModule::LowerBasicBlockAsFunction(
Block* block, xla::XlaBuilder* builder, bool is_entry_function,
xla::XlaComputation* result) {
auto& bb = *block;
// Mapping from the Value to lowered XlaOp. The code below lowers in
// program order and will fail if an operand is unseen. This can be improved.
ValueLoweringMap lowering;
// If using tuples as input, then there is only one input parameter that is a
// tuple.
if (is_entry_function && use_tuple_args_) {
std::vector<xla::Shape> arg_shapes;
arg_shapes.reserve(bb.getNumArguments());
for (auto& arg : bb.getArguments())
arg_shapes.push_back(xla::TypeToShape(arg->getType()));
xla::Shape input_shape = xla::ShapeUtil::MakeTupleShape(arg_shapes);
auto tuple = xla::Parameter(builder, 0, input_shape, "arg_tuple");
for (auto& it : llvm::enumerate(bb.getArguments())) {
lowering[it.value()] = xla::GetTupleElement(tuple, it.index());
}
} else {
for (auto& it : llvm::enumerate(bb.getArguments())) {
auto* arg = it.value();
auto num = it.index();
xla::Shape shape = xla::TypeToShape(arg->getType());
lowering[arg] =
xla::Parameter(builder, num, shape, absl::StrCat("Arg_", num));
}
}
for (auto& inst : bb)
if (failed(Lower(&inst, is_entry_function, builder, &lowering, result)))
return failure();
return success();
}
LogicalResult ConvertToHloModule::LowerRegionAsComputation(
mlir::Region* region, xla::XlaComputation* func) {
std::unique_ptr<xla::XlaBuilder> builder =
module_builder_.CreateSubBuilder(absl::StrCat("region_", region_id_++));
return LowerBasicBlockAsFunction(®ion->front(), builder.get(),
/*is_entry_function=*/false, func);
}
} // namespace
Status ConvertMlirHloToHlo(mlir::ModuleOp module, xla::HloProto* hlo_proto,
bool use_tuple_args, bool return_tuple) {
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
ConvertToHloModule converter(module, use_tuple_args, return_tuple);
if (failed(converter.Run())) return diag_handler.ConsumeStatus();
auto hlo_module = converter.ConsumeMainProto();
hlo_proto->mutable_hlo_module()->Swap(&hlo_module);
return Status::OK();
}
} // namespace mlir
|
// Boost.Range library
//
// Copyright Thorsten Ottosen, Neil Groves 2006 - 2008. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ADAPTOR_ADJACENT_FILTER_IMPL_HPP
#define BOOST_RANGE_ADAPTOR_ADJACENT_FILTER_IMPL_HPP
#include <boost/config.hpp>
#ifdef BOOST_MSVC
#pragma warning( push )
#pragma warning( disable : 4355 )
#endif
#include <boost/range/adaptor/argument_fwd.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/next_prior.hpp>
namespace boost
{
namespace range_detail
{
template< class Iter, class Pred, bool default_pass >
class skip_iterator
: public boost::iterator_adaptor<
skip_iterator<Iter,Pred,default_pass>,
Iter,
BOOST_DEDUCED_TYPENAME std::iterator_traits<Iter>::value_type,
boost::forward_traversal_tag,
BOOST_DEDUCED_TYPENAME std::iterator_traits<Iter>::reference,
BOOST_DEDUCED_TYPENAME std::iterator_traits<Iter>::difference_type
>
, private Pred
{
private:
typedef boost::iterator_adaptor<
skip_iterator<Iter,Pred,default_pass>,
Iter,
BOOST_DEDUCED_TYPENAME std::iterator_traits<Iter>::value_type,
boost::forward_traversal_tag,
BOOST_DEDUCED_TYPENAME std::iterator_traits<Iter>::reference,
BOOST_DEDUCED_TYPENAME std::iterator_traits<Iter>::difference_type
> base_t;
public:
typedef Pred pred_t;
typedef Iter iter_t;
skip_iterator() : m_last() {}
skip_iterator(iter_t it, iter_t last, const Pred& pred)
: base_t(it)
, pred_t(pred)
, m_last(last)
{
move_to_next_valid();
}
template<class OtherIter>
skip_iterator( const skip_iterator<OtherIter, pred_t, default_pass>& other )
: base_t(other.base())
, pred_t(other)
, m_last(other.m_last) {}
void move_to_next_valid()
{
iter_t& it = this->base_reference();
pred_t& bi_pred = *this;
if (it != m_last)
{
if (default_pass)
{
iter_t nxt = ::boost::next(it);
while (nxt != m_last && !bi_pred(*it, *nxt))
{
++it;
++nxt;
}
}
else
{
iter_t nxt = ::boost::next(it);
for(; nxt != m_last; ++it, ++nxt)
{
if (bi_pred(*it, *nxt))
{
break;
}
}
if (nxt == m_last)
{
it = m_last;
}
}
}
}
void increment()
{
iter_t& it = this->base_reference();
BOOST_ASSERT( it != m_last );
++it;
move_to_next_valid();
}
iter_t m_last;
};
template< class P, class R, bool default_pass >
struct adjacent_filtered_range
: iterator_range< skip_iterator<
BOOST_DEDUCED_TYPENAME range_iterator<R>::type,
P,
default_pass
>
>
{
private:
typedef skip_iterator<
BOOST_DEDUCED_TYPENAME range_iterator<R>::type,
P,
default_pass
>
skip_iter;
typedef iterator_range<skip_iter>
base_range;
typedef BOOST_DEDUCED_TYPENAME range_iterator<R>::type raw_iterator;
public:
adjacent_filtered_range( const P& p, R& r )
: base_range(skip_iter(boost::begin(r), boost::end(r), p),
skip_iter(boost::end(r), boost::end(r), p))
{
}
};
template< class T >
struct adjacent_holder : holder<T>
{
adjacent_holder( T r ) : holder<T>(r)
{ }
};
template< class T >
struct adjacent_excl_holder : holder<T>
{
adjacent_excl_holder( T r ) : holder<T>(r)
{ }
};
template< class ForwardRng, class BinPredicate >
inline adjacent_filtered_range<BinPredicate, ForwardRng, true>
operator|( ForwardRng& r,
const adjacent_holder<BinPredicate>& f )
{
return adjacent_filtered_range<BinPredicate, ForwardRng, true>( f.val, r );
}
template< class ForwardRng, class BinPredicate >
inline adjacent_filtered_range<BinPredicate, const ForwardRng, true>
operator|( const ForwardRng& r,
const adjacent_holder<BinPredicate>& f )
{
return adjacent_filtered_range<BinPredicate,
const ForwardRng, true>( f.val, r );
}
template< class ForwardRng, class BinPredicate >
inline adjacent_filtered_range<BinPredicate, ForwardRng, false>
operator|( ForwardRng& r,
const adjacent_excl_holder<BinPredicate>& f )
{
return adjacent_filtered_range<BinPredicate, ForwardRng, false>( f.val, r );
}
template< class ForwardRng, class BinPredicate >
inline adjacent_filtered_range<BinPredicate, ForwardRng, false>
operator|( const ForwardRng& r,
const adjacent_excl_holder<BinPredicate>& f )
{
return adjacent_filtered_range<BinPredicate,
const ForwardRng, false>( f.val, r );
}
} // 'range_detail'
// Bring adjacent_filter_range into the boost namespace so that users of
// this library may specify the return type of the '|' operator and
// adjacent_filter()
using range_detail::adjacent_filtered_range;
namespace adaptors
{
namespace
{
const range_detail::forwarder<range_detail::adjacent_holder>
adjacent_filtered =
range_detail::forwarder<range_detail::adjacent_holder>();
const range_detail::forwarder<range_detail::adjacent_excl_holder>
adjacent_filtered_excl =
range_detail::forwarder<range_detail::adjacent_excl_holder>();
}
template<class ForwardRng, class BinPredicate>
inline adjacent_filtered_range<BinPredicate, ForwardRng, true>
adjacent_filter(ForwardRng& rng, BinPredicate filter_pred)
{
return adjacent_filtered_range<BinPredicate, ForwardRng, true>(filter_pred, rng);
}
template<class ForwardRng, class BinPredicate>
inline adjacent_filtered_range<BinPredicate, const ForwardRng, true>
adjacent_filter(const ForwardRng& rng, BinPredicate filter_pred)
{
return adjacent_filtered_range<BinPredicate, const ForwardRng, true>(filter_pred, rng);
}
} // 'adaptors'
}
#ifdef BOOST_MSVC
#pragma warning( pop )
#endif
#endif
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace FabricTest;
using namespace std;
using namespace Naming;
using namespace TestCommon;
using namespace Reliability;
using namespace ServiceModel;
using namespace Reliability::FailoverManagerComponent;
using namespace Management::HealthManager;
using namespace Management;
using namespace Api;
using namespace Query;
using namespace Client;
using namespace Transport;
using namespace ClientServerTransport;
using namespace ReliabilityTestApi;
using namespace ReliabilityTestApi::FailoverManagerComponentTestApi;
const StringLiteral TraceSource("FabricTest.FabricClientHealth");
TestFabricClientHealth::TestFabricClientHealth(FabricTestDispatcher & dispatcher)
: dispatcher_(dispatcher)
, healthTable_(make_shared<TestHealthTable>())
{
}
void AddReport(__in vector<vector<HealthReport>> & reports, EntityHealthInformationSPtr && entityInfo, AttributeList && attributes)
{
wstring property;
Random r;
auto authorityReports = HealthReport::GetAuthoritySources(entityInfo->Kind);
TestSession::FailTestIf(authorityReports.empty(), "Authority reports for entity {0} can't be empty", entityInfo);
auto const & sourceId = authorityReports[0];
if (r.Next(2) == 0)
{
// Generate report with critical priority for some of the entities (the ones that have authority reports with State property)
property = L"State";
}
else
{
// Generate report with Higher priority
property = L"HMLoadTestProperty";
}
HealthReport report(
move(entityInfo),
sourceId,
property,
TimeSpan::MaxValue,
FABRIC_HEALTH_STATE_OK,
L"Report from HMLoadTest",
Common::SequenceNumber::GetNext(),
false,
move(attributes));
if (reports.empty() || (reports.back().size() == static_cast<size_t>(ClientConfig::GetConfig().MaxNumberOfHealthReports)))
{
// Create new bucket, or the reports will be dropped at the health client because max number of queued reports is reached
reports.push_back(vector<HealthReport>());
}
reports.back().push_back(move(report));
}
// Takes a batch of reports and breaks them into chunks that are then reported in parallel on the internal health client.
// Both ReportHealth and InternalReportHealth are used for coverage.
void TestFabricClientHealth::ParallelReportHealthBatch(vector<HealthReport> && reports)
{
Random r;
vector<vector<HealthReport>> chunks;
size_t reportCount = reports.size();
int remainingCount = static_cast<int>(reportCount);
int i = 0;
while (remainingCount > 0)
{
// Force the last batch to have 1 report by generating less than remainingCount
int nextCount = (remainingCount == 1) ? 1 : r.Next(1, remainingCount);
vector<HealthReport> batch;
for (int j = 0; j < nextCount; ++j, ++i)
{
batch.push_back(move(reports[i]));
}
chunks.push_back(move(batch));
remainingCount -= nextCount;
}
size_t chunkCount = chunks.size();
wstring trace;
StringWriter writer(trace);
writer.Write("Break batch of {0} reports in {1} chunks added in parallel :", reportCount, chunkCount);
for (auto const & chunk : chunks)
{
writer.Write(" {0}", chunk.size());
}
TestSession::WriteInfo(TraceSource, "{0}", trace);
// Post all add reports to thread pool and then wait for them to be done
Common::atomic_long parallelBatches(static_cast<long>(chunkCount));
ManualResetEvent allDone(false);
for (size_t idx = 0; idx < chunkCount; ++idx)
{
Threadpool::Post([&chunks, ¶llelBatches, &allDone, this, idx]()
{
auto localChunk = move(chunks[idx]);
for (int retry = 0; retry < FabricTestSessionConfig::GetConfig().QueryOperationRetryCount; ++retry)
{
ErrorCode error;
if (localChunk.size() == 1)
{
// When there is one report, use the overload for 1 report
error = this->internalHealthClient_->ReportHealth(move(localChunk[0]), nullptr);
}
else
{
error = this->internalHealthClient_->InternalReportHealth(move(localChunk), nullptr);
}
if (error.IsSuccess())
{
long previousValue = --parallelBatches;
if (previousValue == 0)
{
allDone.Set();
}
return;
}
else if (error.IsError(ErrorCodeValue::HealthMaxReportsReached))
{
if (retry >= FabricTestSessionConfig::GetConfig().QueryOperationRetryCount - 1)
{
TestSession::FailTest("Report batch {0} failed with error {1} and retry was exhausted", idx, error);
}
else
{
// When multiple reports are passed in to internal report health, some may be accepted. Those must not be passed in again.
auto temp = move(localChunk);
for (auto && ck : temp)
{
if (ck.EntityInformation)
{
localChunk.push_back(move(ck));
}
}
// Sleep and retry
TestSession::WriteInfo(TraceSource, "Report batch {0} with {1} items failed with error {2}, remaining {3}, sleep and retry", idx, temp.size(), error, localChunk.size());
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
continue;
}
}
else
{
TestSession::FailTest("Report batch {0} failed with unexpected error {1}", idx, error);
}
}
});
}
allDone.WaitOne();
TestSession::WriteInfo(TraceSource, "Batch of {0} reports in {1} chunks added", reportCount, chunkCount);
}
bool TestFabricClientHealth::HMLoadTest(Common::StringCollection const & params)
{
// Creates services and performs queries on HM to test how HM is doing under load
CommandLineParser parser(params, 0);
int serviceCount;
parser.TryGetInt(L"serviceCount", serviceCount, 1000);
TestSession::FailTestIf(serviceCount <= 0, "Service count must be positive, not {0}", serviceCount);
int partitionCount;
parser.TryGetInt(L"partitionCount", partitionCount, 3);
TestSession::FailTestIf(partitionCount <= 0, "Partition count must be positive, not {0}", partitionCount);
int replicaCount;
parser.TryGetInt(L"replicaCount", replicaCount, 3);
TestSession::FailTestIf(replicaCount <= 0, "replica count must be positive, not {0}", replicaCount);
// Report through internal health client
CreateInternalFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
NamingUri appUri;
vector<NamingUri> serviceNames = TestFabricClient::GetPerformanceTestNames(serviceCount, parser, appUri);
wstring appName = appUri.ToString();
vector<vector<HealthReport>> reports;
vector<StringCollection> queryArgs;
wstring expectedHealthStateParam(L"expectedhealthstate=ok");
wstring retryServiceTooBusy(L"retryableerror=ServiceTooBusy");
TestSession::WriteInfo(TraceSource, "Create app reports for {0}", appName);
AttributeList appAttribs;
appAttribs.AddAttribute(HealthAttributeNames::ApplicationHealthPolicy, ApplicationHealthPolicy::Default->ToString());
appAttribs.AddAttribute(HealthAttributeNames::ApplicationTypeName, appName + L"Type");
AddReport(reports, EntityHealthInformation::CreateApplicationEntityHealthInformation(appName, 1), move(appAttribs));
StringCollection appParams;
appParams.push_back(L"application");
appParams.push_back(wformatString("appname={0}", appName));
appParams.push_back(expectedHealthStateParam);
appParams.push_back(retryServiceTooBusy);
queryArgs.push_back(move(appParams));
TestSession::WriteInfo(
TraceSource,
"Create reports for {0} services ({1}, ...), {2} partitions and {3} replicas",
serviceCount,
serviceNames[0].ToString(),
partitionCount * serviceCount,
partitionCount * serviceCount * replicaCount);
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
for (size_t ix = 0; ix < serviceNames.size(); ++ix)
{
bool isStateful = ix < (serviceNames.size() / 2);
wstring serviceName = serviceNames[ix].ToString();
// Set up service queries
StringCollection serviceParams;
serviceParams.push_back(L"service");
serviceParams.push_back(wformatString("servicename={0}", serviceName));
serviceParams.push_back(expectedHealthStateParam);
serviceParams.push_back(retryServiceTooBusy);
queryArgs.push_back(move(serviceParams));
AttributeList serviceAttribs;
serviceAttribs.AddAttribute(HealthAttributeNames::ServiceTypeName, L"ServiceTypeName");
serviceAttribs.AddAttribute(HealthAttributeNames::ApplicationName, appName);
AddReport(reports, EntityHealthInformation::CreateServiceEntityHealthInformation(serviceName, 1), move(serviceAttribs));
// Create partitions for each service
FABRIC_REPLICA_ID replicaId = 23;
for (int i = 0; i < partitionCount; ++i)
{
Guid partitionId = Guid::NewGuid();
StringCollection partitionParams;
partitionParams.push_back(L"partition");
partitionParams.push_back(wformatString("partitionguid={0}", partitionId));
partitionParams.push_back(expectedHealthStateParam);
partitionParams.push_back(retryServiceTooBusy);
queryArgs.push_back(move(partitionParams));
AttributeList partitionAttribs;
partitionAttribs.AddAttribute(HealthAttributeNames::ServiceName, serviceName);
AddReport(reports, EntityHealthInformation::CreatePartitionEntityHealthInformation(partitionId), move(partitionAttribs));
// Create replicas for each partition
for (int j = 0; j < replicaCount; ++j)
{
StringCollection replicaParams;
replicaParams.push_back(L"replica");
replicaParams.push_back(wformatString("partitionguid={0}", partitionId));
replicaParams.push_back(wformatString("replica.id={0}", replicaId));
replicaParams.push_back(expectedHealthStateParam);
replicaParams.push_back(retryServiceTooBusy);
queryArgs.push_back(move(replicaParams));
AttributeList replicaAttribs;
replicaAttribs.AddAttribute(HealthAttributeNames::NodeId, wformatString(nodeId));
replicaAttribs.AddAttribute(HealthAttributeNames::NodeInstanceId, wformatString(nodeInstanceId));
auto entityInfo = isStateful
? EntityHealthInformation::CreateStatefulReplicaEntityHealthInformation(partitionId, replicaId, 1)
: EntityHealthInformation::CreateStatelessInstanceEntityHealthInformation(partitionId, replicaId);
AddReport(reports, move(entityInfo), move(replicaAttribs));
++replicaId;
}
}
}
Stopwatch totalDurationStopwatch;
int maxParallelQueries = 50;
Common::atomic_long failedQueries(0);
Common::atomic_long successfulQueries(0);
ManualResetEvent queryBatchDone(false);
int queryIndex = 0;
StringCollection checkClientParams;
checkClientParams.push_back(L"reportcount=0");
totalDurationStopwatch.Start();
for (size_t i = 0; i < reports.size(); ++i)
{
size_t currentBatchSize = reports[i].size();
TestSession::WriteInfo(TraceSource, "Add batch {0} with {1} reports", i, currentBatchSize);
ParallelReportHealthBatch(move(reports[i]));
// Send queries for the current processed reports in parallel with the reports
size_t lastCurrentQueryIndex = queryIndex + currentBatchSize;
for (; queryIndex < lastCurrentQueryIndex; ++queryIndex)
{
TestSession::FailTestIf(queryIndex >= queryArgs.size(), "Query index {0} >= queryArgs.size {1}", queryIndex, queryArgs.size());
Threadpool::Post([&, queryIndex]()
{
if (QueryHealth(queryArgs[queryIndex]))
{
++successfulQueries;
}
else
{
++failedQueries;
}
if (successfulQueries.load() + failedQueries.load() == queryArgs.size())
{
queryBatchDone.Set();
}
});
if (queryIndex % maxParallelQueries == 0)
{
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
}
}
// Wait for the client to drain reports before sending next batch
TestSession::FailTestIfNot(CheckHealthClient(checkClientParams), "CheckHealthClient failed for batch {0}", i);
}
TestSession::FailTestIf(queryIndex != queryArgs.size(), "Query index {0} != queryArgs.size {1}", queryIndex, queryArgs.size());
queryBatchDone.WaitOne();
totalDurationStopwatch.Stop();
TestSession::WriteInfo(
TraceSource,
"TotalEntities={0}, max parallel query={1}, query ok/failed {2}/{3}, total duration={4} msec",
queryArgs.size(),
maxParallelQueries,
successfulQueries.load(),
failedQueries.load(),
totalDurationStopwatch.ElapsedMilliseconds);
TestSession::FailTestIfNot(failedQueries.load() == 0, "Not all entities were created/queried successfully");
TestSession::FailTestIfNot(successfulQueries.load() == queryArgs.size(), "successful queries count {0} doesn't match expected count {1}", successfulQueries.load(), queryArgs.size());
return true;
}
bool TestFabricClientHealth::HealthPreInitialize(StringCollection const & params)
{
if (params.size() < 2)
{
return false;
}
wstring healthKindString = params[0];
FABRIC_HEALTH_REPORT_KIND kind = GetHealthKind(healthKindString);
if (kind == FABRIC_HEALTH_REPORT_KIND_INVALID)
{
return false;
}
CommandLineParser parser(params, 1);
wstring sourceId;
bool sourceIdExists = parser.TryGetString(L"sourceid", sourceId);
if (!sourceIdExists || sourceId.empty())
{
TestSession::WriteError(TraceSource, "Invalid sourceid");
return false;
}
CreateInternalFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
int64 instance;
parser.TryGetInt64(L"instance", instance, 0);
auto error = internalHealthClient_->HealthPreInitialize(sourceId, kind, instance);
TestSession::FailTestIfNot(error.IsSuccess(), "HealthPreInitialize failed with unexpected error = {0}", error);
return true;
}
bool TestFabricClientHealth::RunWatchDog(StringCollection const & params)
{
if (params[0] == L"pause")
{
healthTable_->Pause();
return true;
}
else if (params[0] == L"resume")
{
healthTable_->Resume();
return true;
}
auto it = watchdogs_.find(params[1]);
if (params[0] == L"stop")
{
if (it == watchdogs_.end())
{
TestSession::WriteError(TraceSource, "Watchdog {0} not found", params[1]);
}
else
{
it->second->Stop();
watchdogs_.erase(it);
}
}
else if (params[0] == L"start")
{
if (it == watchdogs_.end())
{
CommandLineParser parser(params, 2);
double interval;
parser.TryGetDouble(L"interval", interval, 1.0);
TestWatchDogSPtr watchDog = make_shared<TestWatchDog>(dispatcher_, params[1], TimeSpan::FromSeconds(interval));
watchDog->Start(watchDog);
watchdogs_[params[1]] = move(watchDog);
}
else
{
TestSession::WriteError(TraceSource, "Watchdog {0} already exists", params[1]);
}
}
return true;
}
bool TestFabricClientHealth::HealthPostInitialize(StringCollection const & params)
{
if (params.size() < 2)
{
return false;
}
wstring healthKindString = params[0];
FABRIC_HEALTH_REPORT_KIND kind = GetHealthKind(healthKindString);
if (kind == FABRIC_HEALTH_REPORT_KIND_INVALID)
{
return false;
}
CommandLineParser parser(params, 1);
wstring sourceId;
bool sourceIdExists = parser.TryGetString(L"sourceid", sourceId);
FABRIC_SEQUENCE_NUMBER sequenceNumber, invalidateSequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, 0);
parser.TryGetInt64(L"invalidatesequencenumber", invalidateSequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
if (!sourceIdExists || sourceId.empty())
{
TestSession::WriteError(TraceSource, "Invalid sourceid");
return false;
}
CreateInternalFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
auto error = internalHealthClient_->HealthPostInitialize(sourceId, kind, sequenceNumber, invalidateSequenceNumber);
TestSession::FailTestIfNot(error.IsSuccess(), "HealthPostInitialize failed with unexpected error = {0}", error);
return true;
}
bool TestFabricClientHealth::HealthGetProgress(StringCollection const & params)
{
if (params.size() < 2)
{
return false;
}
wstring healthKindString = params[0];
FABRIC_HEALTH_REPORT_KIND kind = GetHealthKind(healthKindString);
if (kind == FABRIC_HEALTH_REPORT_KIND_INVALID)
{
return false;
}
CommandLineParser parser(params, 1);
wstring sourceId;
bool sourceIdExists = parser.TryGetString(L"sourceid", sourceId);
if (!sourceIdExists || sourceId.empty())
{
TestSession::WriteError(TraceSource, "Invalid sourceid");
return false;
}
FABRIC_SEQUENCE_NUMBER expectedProgress;
bool expectedProgressExists = parser.TryGetInt64(L"expectedprogress", expectedProgress);
CreateInternalFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
do
{
--remainingRetries;
FABRIC_SEQUENCE_NUMBER actualProgress;
ErrorCode error;
if (sourceId == ServiceModel::Constants::HealthReportFMSource)
{
auto fm = this->dispatcher_.GetFM();
if (!fm)
{
error = ErrorCodeValue::FMNotReadyForUse;
}
error = fm->HealthClient->HealthGetProgress(sourceId, kind, actualProgress);
}
else
{
error = internalHealthClient_->HealthGetProgress(sourceId, kind, actualProgress);
}
if (!error.IsSuccess())
{
TestSession::WriteInfo(TraceSource, "HealthGetProgress failed with error = {0}", error);
}
else if (!expectedProgressExists)
{
TestSession::WriteInfo(TraceSource, "HealthGetProgress result: {0}", actualProgress);
return true;
}
else
{
if (actualProgress != expectedProgress)
{
TestSession::WriteInfo(TraceSource, "HealthGetProgress actualprogress {0} does not match expectedprogress {1}", actualProgress, expectedProgress);
}
else
{
return true;
}
}
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
} while (remainingRetries >= 0);
TestSession::FailTest("HealthGetProgress failed");
}
bool TestFabricClientHealth::HealthSkipSequence(StringCollection const & params)
{
if (params.size() < 2)
{
return false;
}
wstring healthKindString = params[0];
FABRIC_HEALTH_REPORT_KIND kind = GetHealthKind(healthKindString);
if (kind == FABRIC_HEALTH_REPORT_KIND_INVALID)
{
return false;
}
CommandLineParser parser(params, 1);
wstring sourceId;
bool sourceIdExists = parser.TryGetString(L"sourceid", sourceId);
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, 0);
if (!sourceIdExists || sourceId.empty())
{
TestSession::WriteError(TraceSource, "Invalid sourceid");
return false;
}
CreateInternalFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
auto error = internalHealthClient_->HealthSkipSequence(sourceId, kind, sequenceNumber);
TestSession::FailTestIfNot(error.IsSuccess(), "HealthSkipSequence failed with unexpected error = {0}", error);
return true;
}
bool TestFabricClientHealth::ResetHealthClient(StringCollection const & params)
{
UNREFERENCED_PARAMETER(params);
if (healthClient_.GetRawPointer() != nullptr)
{
healthClient_.Release();
}
if (internalHealthClient_.get() != NULL)
{
IHealthClientPtr cleanup;
cleanup = move(internalHealthClient_);
}
return true;
}
bool TestFabricClientHealth::CheckHResult(HRESULT hr, vector<HRESULT> const & expectedErrors)
{
auto actualError = ErrorCode::FromHResult(hr);
for (auto it = expectedErrors.begin(); it != expectedErrors.end(); ++it)
{
if (hr == *it)
{
TestSession::WriteWarning(TraceSource, "Operation failed with expected error: {0}", actualError);
return true;
}
}
TestSession::WriteWarning(TraceSource, "Operation failed with unexpected error: {0}", actualError);
return false;
}
FABRIC_HEALTH_REPORT_KIND TestFabricClientHealth::GetHealthKind(wstring & healthKindString)
{
if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"node"))
{
return FABRIC_HEALTH_REPORT_KIND_NODE;
}
else if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"cluster"))
{
return FABRIC_HEALTH_REPORT_KIND_CLUSTER;
}
else if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"partition"))
{
return FABRIC_HEALTH_REPORT_KIND_PARTITION;
}
else if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"replica"))
{
return FABRIC_HEALTH_REPORT_KIND_STATEFUL_SERVICE_REPLICA;
}
else if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"instance"))
{
return FABRIC_HEALTH_REPORT_KIND_STATELESS_SERVICE_INSTANCE;
}
if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"deployedapplication"))
{
return FABRIC_HEALTH_REPORT_KIND_DEPLOYED_APPLICATION;
}
if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"deployedservicepackage"))
{
return FABRIC_HEALTH_REPORT_KIND_DEPLOYED_SERVICE_PACKAGE;
}
if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"application"))
{
return FABRIC_HEALTH_REPORT_KIND_APPLICATION;
}
if (StringUtility::AreEqualCaseInsensitive(healthKindString, L"service"))
{
return FABRIC_HEALTH_REPORT_KIND_SERVICE;
}
TestSession::WriteError(TraceSource, "Unknown type {0}", healthKindString);
return FABRIC_HEALTH_REPORT_KIND_INVALID;
}
std::wstring TestFabricClientHealth::GetEntityHealthBaseDetails(EntityHealthBase const & entityBase)
{
wstring trace;
StringWriter writer(trace);
writer.WriteLine("{0}", entityBase);
writer.WriteLine("Events:");
for (auto it = entityBase.Events.begin(); it != entityBase.Events.end(); ++it)
{
writer.WriteLine("\t{0}", *it);
}
for (auto it = entityBase.UnhealthyEvaluations.begin(); it != entityBase.UnhealthyEvaluations.end(); ++it)
{
auto evaluation = it->Evaluation;
TestSession::FailTestIfNot(evaluation != nullptr, "evaluation should not be null for {0}", trace);
TestSession::FailTestIf(evaluation->Description == L"", "Reason description should be defined for {0}", trace);
}
return trace;
}
bool TestFabricClientHealth::DeleteHealth(StringCollection const & params)
{
if (params.size() < 2)
{
return false;
}
wstring entityType = params[0];
CommandLineParser parser(params, 1);
ServiceModel::HealthReport healthReport;
if (StringUtility::AreEqualCaseInsensitive(entityType, L"node"))
{
if (!CreateNodeHealthDeleteReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"partition"))
{
if (!CreatePartitionHealthDeleteReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"replica"))
{
if (!CreateReplicaHealthDeleteReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"instance"))
{
if (!CreateInstanceHealthDeleteReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"deployedapplication"))
{
if (!CreateDeployedApplicationHealthDeleteReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"deployedservicepackage"))
{
if (!CreateDeployedServicePackageHealthDeleteReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"service"))
{
if (!CreateServiceHealthDeleteReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"app"))
{
if (!CreateApplicationHealthDeleteReport(parser, healthReport))
{
return false;
}
}
else
{
TestSession::WriteError(TraceSource, "Unknown type {0}", entityType);
return false;
}
CreateInternalFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
vector<HealthReport> healthVector;
healthVector.push_back(move(healthReport));
auto reportError = ReportHealthThroughInternalClientOrHmPrimary(parser, move(healthVector));
std::wstring error;
parser.TryGetString(L"expectederror", error, L"Success");
ErrorCodeValue::Enum errorValue = FABRICSESSION.FabricDispatcher.ParseErrorCode(error);
TestSession::FailTestIfNot(errorValue == reportError.ReadValue(), "InternalReportHealth for delete failed with unexpected reportError = {0}", reportError);
return true;
}
bool TestFabricClientHealth::ReportHealthInternal(StringCollection const & params)
{
if (params.size() < 2)
{
return false;
}
wstring entityType = params[0];
CommandLineParser parser(params, 1);
ServiceModel::HealthReport healthReport;
if (StringUtility::AreEqualCaseInsensitive(entityType, L"node"))
{
if (!CreateInternalNodeHealthReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"partition"))
{
if (!CreateInternalPartitionHealthReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"cluster"))
{
if (!CreateInternalClusterHealthReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"replica"))
{
if (!CreateInternalReplicaHealthReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"instance"))
{
if (!CreateInternalInstanceHealthReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"deployedapplication"))
{
if (!CreateInternalDeployedApplicationHealthReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"deployedservicepackage"))
{
if (!CreateInternalDeployedServicePackageHealthReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"application"))
{
if (!CreateInternalApplicationHealthReport(parser, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"service"))
{
if (!CreateInternalServiceHealthReport(parser, healthReport))
{
return false;
}
}
else
{
TestSession::WriteError(TraceSource, "Unknown type {0}", entityType);
return false;
}
vector<HealthReport> healthVector;
healthVector.push_back(move(healthReport));
std::wstring error;
bool expectedErrorExists = parser.TryGetString(L"expectederror", error, L"Success");
ErrorCodeValue::Enum errorValue = FABRICSESSION.FabricDispatcher.ParseErrorCode(error);
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
ErrorCode reportError(ErrorCodeValue::Success);
do
{
--remainingRetries;
auto healthVectorCopy = healthVector;
reportError = ReportHealthThroughInternalClientOrHmPrimary(parser, move(healthVectorCopy));
if (errorValue == reportError.ReadValue())
{
break;
}
TestSession::FailTestIf(expectedErrorExists, "InternalReportHealth failed with error {0}, expected {1}", reportError, errorValue);
TestSession::WriteWarning(TraceSource, "InternalReportHealth returned unexpected error = {0}, expected {1}", reportError, errorValue);
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
}while (remainingRetries > 0);
TestSession::FailTestIfNot(errorValue == reportError.ReadValue(), "InternalReportHealth failed with unexpected reportError = {0}", reportError);
return true;
}
bool TestFabricClientHealth::ReportHealthStress(StringCollection const & params)
{
int reportCount;
int interval;
int reportsPerMessage;
int criticalReports;
int iterations;
CommandLineParser parser(params, 1);
parser.TryGetInt(L"reports", reportCount, 8192);
parser.TryGetInt(L"interval", interval, 0);
parser.TryGetInt(L"reportsPerMessage", reportsPerMessage, 1);
parser.TryGetInt(L"criticalreports", criticalReports, 0);
parser.TryGetInt(L"iterations", iterations, 1);
auto timeout = ClientConfig::GetConfig().HealthOperationTimeout;
double timeoutSec;
if (parser.TryGetDouble(L"timeout", timeoutSec))
{
timeout = TimeSpan::FromSeconds(timeoutSec);
}
Management::HealthManager::HealthManagerReplicaSPtr hmPrimary;
if (!GetHMPrimaryWithRetries(hmPrimary))
{
return false;
}
// Nodes must have System.FM report to be considered healthy, as that is the authority source
wstring sourceId(L"System.FM");
wstring description(L"stress report");
for (int iteration = 0; iteration < iterations; ++iteration)
{
Common::atomic_long pendingCount(reportCount);
Common::atomic_long successCount(0);
ManualResetEvent event(false);
Stopwatch stopwatch;
stopwatch.Start();
for (int i = 0; i < reportCount; i++)
{
vector<HealthReport> reports;
int criticalGeneratedReports = 0;
for (int j = 0; j < reportsPerMessage; ++j)
{
wstring property(L"stress");
if (criticalGeneratedReports < criticalReports)
{
// Simulate authority report
property = L"State";
++criticalGeneratedReports;
}
LargeInteger nodeId = LargeInteger::RandomLargeInteger_();
wstring nodeName = NodeIdGenerator::GenerateNodeName(NodeId(nodeId));
AttributeList attributes;
attributes.AddAttribute(*HealthAttributeNames::NodeName, nodeName);
HealthReport healthReport(
EntityHealthInformation::CreateNodeEntityHealthInformation(nodeId, nodeName, DateTime::Now().Ticks),
sourceId,
property,
TimeSpan::MaxValue,
FABRIC_HEALTH_STATE_OK,
description,
Common::SequenceNumber::GetNext(),
false,
move(attributes));
reports.push_back(move(healthReport));
}
ActivityId activityId;
auto requestMessage = HealthManagerTcpMessage::GetReportHealth(
activityId,
Common::make_unique<ReportHealthMessageBody>(move(reports), std::vector<SequenceStreamInformation>()))->GetTcpMessage();
hmPrimary->Test_BeginProcessRequest(
move(requestMessage),
activityId,
timeout,
[&hmPrimary, &event, &pendingCount, &successCount](AsyncOperationSPtr const & operation)
{
Transport::MessageUPtr reply;
auto error = hmPrimary->Test_EndProcessRequest(operation, reply);
if (error.IsSuccess())
{
ReportHealthReplyMessageBody body;
reply->GetBody(body);
auto replyResults = body.MoveEntries();
if (replyResults.empty())
{
error = ErrorCodeValue::Timeout;
}
else
{
error = replyResults[0].Error;
}
}
if (error.IsSuccess())
{
++successCount;
}
if (--pendingCount == 0)
{
event.Set();
}
},
AsyncOperationSPtr());
if (interval > 0)
{
Sleep(interval);
}
}
TestSession::WriteInfo(
TraceSource,
"[{0}] Waiting for {1}*{2} reports...",
iteration,
reportCount,
reportsPerMessage);
event.WaitOne();
stopwatch.Stop();
auto throughput = (static_cast<double>(successCount.load()) / stopwatch.Elapsed.TotalPositiveMilliseconds()) * 1000;
auto effectiveThroughput = (static_cast<double>(successCount.load() * reportsPerMessage) / stopwatch.Elapsed.TotalPositiveMilliseconds()) * 1000;
TestSession::WriteInfo(
TraceSource,
"[{0}] {1}*{2} reports created, {3} critical per message, {4} successful, {5} reports/sec, {6} effective reports/sec",
iteration,
reportCount,
reportsPerMessage,
criticalReports,
successCount.load(),
throughput,
effectiveThroughput);
} // for iterations
return true;
}
Common::ErrorCode TestFabricClientHealth::ReportHealthThroughInternalClientOrHmPrimary(CommandLineParser & parser, std::vector<ServiceModel::HealthReport> && reports)
{
if (FabricTestSessionConfig::GetConfig().ReportHealthThroughHMPrimary)
{
auto hmPrimary = FABRICSESSION.FabricDispatcher.GetHM();
if (!hmPrimary)
{
TestSession::WriteInfo(TraceSource, "HM not ready");
return ErrorCode(ErrorCodeValue::NotReady);
}
ActivityId activityId;
Transport::MessageUPtr requestMessage = move(HealthManagerTcpMessage::GetReportHealth(
activityId,
Common::make_unique<ReportHealthMessageBody>(move(reports), std::vector<SequenceStreamInformation>()))->GetTcpMessage());
auto timeout = ClientConfig::GetConfig().HealthOperationTimeout;
double timeoutSec;
if (parser.TryGetDouble(L"timeout", timeoutSec))
{
timeout = TimeSpan::FromSeconds(timeoutSec);
}
ManualResetEvent event(false);
auto operation = hmPrimary->Test_BeginProcessRequest(
move(requestMessage),
activityId,
timeout,
[&event](AsyncOperationSPtr const &) { event.Set(); },
AsyncOperationSPtr());
Transport::MessageUPtr reply;
ErrorCode error(ErrorCodeValue::Success);
if (event.WaitOne(timeout + TimeSpan::FromSeconds(10)))
{
error = hmPrimary->Test_EndProcessRequest(operation, reply);
}
else
{
error = ErrorCodeValue::Timeout;
}
if (!error.IsSuccess())
{
TestSession::WriteInfo(TraceSource, "{0}: HM Test_ProcessRequest returned {1}", activityId, error);
return error;
}
ReportHealthReplyMessageBody body;
reply->GetBody(body);
auto replyResults = body.MoveEntries();
if (replyResults.empty() || replyResults[0].Error == ErrorCodeValue::NotReady)
{
TestSession::WriteInfo(TraceSource, "ReportHealthReplyMessageBody has no reports");
return ErrorCode(ErrorCodeValue::Timeout);
}
if (replyResults[0].Error == ErrorCodeValue::NotReady)
{
// There wasn't enough time to set the result before the async operation timed out
return ErrorCode(ErrorCodeValue::Timeout);
}
return replyResults[0].Error;
}
else
{
// Report through internal health client
CreateInternalFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
bool immediate = parser.GetBool(L"immediate");
HealthReportSendOptionsUPtr options;
Random r;
if (immediate || r.Next() == 0)
{
options = make_unique<HealthReportSendOptions>(immediate);
}
return internalHealthClient_->InternalReportHealth(move(reports), move(options));
}
}
bool TestFabricClientHealth::ReportHealth(StringCollection const & params)
{
if (params.size() < 1)
{
return false;
}
wstring reportType = params[0];
if (reportType == L"stress")
{
return ReportHealthStress(params);
}
if (params.size() < 2)
{
return false;
}
if (FabricTestSessionConfig::GetConfig().UseInternalHealthClient)
{
return ReportHealthInternal(params);
}
CommandLineParser parser(params, 1);
FABRIC_HEALTH_REPORT healthReport;
ScopedHeap heap;
if (StringUtility::AreEqualCaseInsensitive(reportType, L"node"))
{
if (!CreateNodeHealthReport(parser, heap, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"cluster"))
{
if (!CreateClusterHealthReport(parser, heap, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"partition"))
{
if (!CreatePartitionHealthReport(parser, heap, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"replica"))
{
if (!CreateReplicaHealthReport(parser, heap, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"instance"))
{
if (!CreateInstanceHealthReport(parser, heap, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"deployedapplication"))
{
if (!CreateDeployedApplicationHealthReport(parser, heap, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"deployedservicepackage"))
{
if (!CreateDeployedServicePackageHealthReport(parser, heap, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"application"))
{
if (!CreateApplicationHealthReport(parser, heap, healthReport))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"service"))
{
if (!CreateServiceHealthReport(parser, heap, healthReport))
{
return false;
}
}
else
{
TestSession::WriteError(TraceSource, "Unknown type {0}", reportType);
return false;
}
HRESULT hr;
std::wstring error;
bool expectedErrorExists = parser.TryGetString(L"expectederror", error, L"Success");
ErrorCodeValue::Enum errorValue = FABRICSESSION.FabricDispatcher.ParseErrorCode(error);
HRESULT expectedError = ErrorCode(errorValue).ToHResult();
CreateFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
bool immediate = parser.GetBool(L"immediate");
Random r;
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
do
{
--remainingRetries;
if (immediate || r.Next() == 0)
{
FABRIC_HEALTH_REPORT_SEND_OPTIONS sendOptions = { 0 };
sendOptions.Immediate = immediate ? TRUE : FALSE;
hr = healthClient_->ReportHealth2(&healthReport, &sendOptions);
}
else
{
hr = healthClient_->ReportHealth(&healthReport);
}
if (expectedError == hr)
{
break;
}
TestSession::FailTestIf(expectedErrorExists, "ReportHealth failed with unexpected hr = {0}", hr);
TestSession::WriteWarning(TraceSource, "ReportHealth returned unexpected hr = {0}", hr);
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
}while (remainingRetries > 0);
TestSession::FailTestIfNot(expectedError == hr, "ReportHealth failed with unexpected hr = {0}", hr);
return true;
}
bool TestFabricClientHealth::ReportHealthIpc(StringCollection const & params)
{
if (params.size() < 3)
{
return false;
}
wstring reportType = params[0];
CommandLineParser parser(params, 1);
wstring nodeIdString;
if (!parser.TryGetString(L"nodeid", nodeIdString, wstring()))
{
TestSession::WriteInfo(TraceSource, "Could not parse nodeid parameter");
return false;
}
NodeId nodeId = FABRICSESSION.FabricDispatcher.ParseNodeId(nodeIdString);
wstring serviceName;
if (!parser.TryGetString(L"servicename", serviceName))
{
TestSession::WriteInfo(TraceSource, "Could not parse servicename parameter");
return false;
}
ScopedHeap heap;
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInfo = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
if (!CreateCommonHealthInformation(parser, heap, *healthInfo))
{
TestSession::WriteError(TraceSource, "Unable to build HealthInfo");
return false;
}
ReferencePointer<FABRIC_HEALTH_REPORT_SEND_OPTIONS> sendOptions;
bool immediate = parser.GetBool(L"immediate");
Random r;
if (immediate || r.Next() == 0)
{
sendOptions = heap.AddItem<FABRIC_HEALTH_REPORT_SEND_OPTIONS>();
sendOptions->Immediate = immediate ? TRUE : FALSE;
}
CalculatorServiceSPtr calculatorService;
ITestStoreServiceSPtr testStoreService;
bool foundService = false;
if (FABRICSESSION.FabricDispatcher.Federation.TryFindCalculatorService(serviceName, nodeId, calculatorService))
{
foundService = true;
}
else if (FABRICSESSION.FabricDispatcher.Federation.TryFindStoreService(serviceName, nodeId, testStoreService))
{
foundService = true;
}
if (!foundService)
{
TestSession::WriteWarning(TraceSource, "Failed to find service {0} on node {1}.", serviceName, nodeId);
return false;
}
ErrorCode error;
if (StringUtility::AreEqualCaseInsensitive(reportType, L"partition"))
{
if (calculatorService)
{
error = calculatorService->ReportPartitionHealth(healthInfo.GetRawPointer(), sendOptions.GetRawPointer());
}
else
{
TestSession::FailTestIf(testStoreService == nullptr, "reporthealthipc on partition: service is null");
error = testStoreService->ReportPartitionHealth(healthInfo.GetRawPointer(), sendOptions.GetRawPointer());
}
}
else if (StringUtility::AreEqualCaseInsensitive(reportType, L"replica"))
{
if (calculatorService)
{
error = calculatorService->ReportInstanceHealth(healthInfo.GetRawPointer(), sendOptions.GetRawPointer());
}
else
{
TestSession::FailTestIf(testStoreService == nullptr, "reporthealthipc on replica: service is null");
error = testStoreService->ReportReplicaHealth(healthInfo.GetRawPointer(), sendOptions.GetRawPointer());
}
}
else
{
TestSession::WriteError(TraceSource, "Cannot report health via ipc for entity: {0}", reportType);
return false;
}
return true;
}
bool TestFabricClientHealth::CheckHealthClient(Common::StringCollection const & params)
{
if (params.size() < 1)
{
return false;
}
CommandLineParser parser(params, 0);
int reportCount;
if (!parser.TryGetInt(L"reportcount", reportCount))
{
TestSession::WriteInfo(TraceSource, "Could not parse reportcount parameter");
return false;
}
int expectedServiceTooBusyCount;
bool checkServiceTooBusy = parser.TryGetInt(L"servicetoobusycount", expectedServiceTooBusyCount);
CreateInternalFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
FabricClientImpl * fcImpl = static_cast<FabricClientImpl*>(internalHealthClient_.get());
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
do
{
int actualServiceTooBusyCount;
int actualReportCount = fcImpl->Test_GetReportingComponent().Test_GetCurrentReportCount(actualServiceTooBusyCount);
bool needsRetry = false;
if (checkServiceTooBusy)
{
if (expectedServiceTooBusyCount == 0)
{
if (expectedServiceTooBusyCount != actualServiceTooBusyCount)
{
TestSession::WriteWarning(TraceSource, "actualServiceTooBusyCount does not match: expected {0}, actual {1}", expectedServiceTooBusyCount, actualServiceTooBusyCount);
needsRetry = true;
}
}
else if (expectedServiceTooBusyCount > actualServiceTooBusyCount)
{
TestSession::WriteWarning(TraceSource, "actualServiceTooBusyCount does not match: expected {0}, actual {1}", expectedServiceTooBusyCount, actualServiceTooBusyCount);
needsRetry = true;
}
}
if (reportCount != actualReportCount)
{
TestSession::WriteWarning(TraceSource, "reportcount does not match: expected {0}, actual {1}", reportCount, actualReportCount);
needsRetry = true;
}
if (!needsRetry)
{
return true;
}
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
--remainingRetries;
} while (remainingRetries > 0);
// Retries have been exhausted, the check failed
return false;
}
bool TestFabricClientHealth::CheckHMEntity(Common::StringCollection const & params)
{
if (params.size() < 2)
{
return false;
}
auto const & entityType = params[0];
CommandLineParser parser(params, 1);
wstring expectedState;
wstring expectedEntityState;
if (!parser.TryGetString(L"state", expectedState) && !parser.TryGetString(L"expectedentitystate", expectedEntityState))
{
TestSession::WriteInfo(TraceSource, "Please specify either \"state\" or \"expectedentitystate\" for validation");
return false;
}
// Changing the entity state can depend on the cleanup logic.
// Since cleanup runs every HealthStoreCleanupInterval and respects grace periods HealthStoreCleanupGraceInterval and HealthStoreEntityWithoutSystemReportKeptInterval,
// compute max number of retries depending on these.
int maxRetryCapTimeInSeconds = 300;
auto maxRetryTimeInSeconds =
Management::ManagementConfig::GetConfig().HealthStoreCleanupInterval.TotalSeconds() +
Management::ManagementConfig::GetConfig().HealthStoreCleanupGraceInterval.TotalSeconds() +
Management::ManagementConfig::GetConfig().HealthStoreEntityWithoutSystemReportKeptInterval.TotalSeconds();
if (maxRetryTimeInSeconds > maxRetryCapTimeInSeconds)
{
maxRetryTimeInSeconds = maxRetryCapTimeInSeconds;
}
auto remainingRetries = maxRetryTimeInSeconds / FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalSeconds();
bool success = false;
do
{
--remainingRetries;
// Get the HM primary before retrying as it may have moved
auto hmPrimary = FABRICSESSION.FabricDispatcher.GetHM();
if (!hmPrimary)
{
TestSession::WriteWarning(TraceSource, "CheckHMEntity: HM not ready");
success = false;
}
else if (!hmPrimary->Test_IsOpened())
{
TestSession::WriteWarning(TraceSource, "CheckHMEntity: HM created, but acceptRequests is false");
success = false;
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"node"))
{
if (!CheckNodeEntityState(parser, hmPrimary, success))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"partition"))
{
if (!CheckPartitionEntityState(parser, hmPrimary, success))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"replica"))
{
if (!CheckReplicaEntityState(parser, hmPrimary, success))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"service"))
{
if (!CheckServiceEntityState(parser, hmPrimary, success))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"application"))
{
if (!CheckApplicationEntityState(parser, hmPrimary, success))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"deployedapplication"))
{
if (!CheckDeployedApplicationEntityState(parser, hmPrimary, success))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"deployedservicepackage"))
{
if (!CheckDeployedServicePackageEntityState(parser, hmPrimary, success))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"cluster"))
{
if (!CheckClusterEntityState(parser, hmPrimary, success))
{
return false;
}
}
else
{
TestSession::WriteError(TraceSource, "Unknown type {0}", entityType);
return false;
}
if (!success)
{
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
TestSession::WriteInfo(TraceSource, "CheckHMEntity failed, remaining retries {0}", remainingRetries);
}
} while (!success && remainingRetries >= 0);
if (!success)
{
TestSession::WriteWarning(TraceSource, "CheckHMEntity failed and retry time exhausted");
}
return success;
}
bool TestFabricClientHealth::CorruptHMEntity(Common::StringCollection const & params)
{
if (params.size() < 2)
{
return false;
}
Management::HealthManager::HealthManagerReplicaSPtr hmPrimary;
if (!GetHMPrimaryWithRetries(hmPrimary))
{
return false;
}
wstring const & entityType = params[0];
ActivityId activityId;
CommandLineParser parser(params, 1);
HealthEntitySPtr entity;
if (StringUtility::AreEqualCaseInsensitive(entityType, L"cluster"))
{
entity = hmPrimary->EntityManager->Cluster.GetEntity(*Management::HealthManager::Constants::StoreType_ClusterTypeString);
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"node"))
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
entity = hmPrimary->EntityManager->Nodes.GetEntity(nodeId.IdValue);
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"partition"))
{
PartitionHealthId partitionId;
if (!ParsePartitionId(parser, partitionId))
{
return false;
}
entity = hmPrimary->EntityManager->Partitions.GetEntity(partitionId);
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"replica"))
{
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionId;
if (!ParseReplicaId(parser, partitionId, replicaId, replicaInstanceId))
{
return false;
}
entity = hmPrimary->EntityManager->Replicas.GetEntity(ReplicaHealthId(partitionId, replicaId));
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"service"))
{
wstring serviceName;
if (!parser.TryGetString(L"servicename", serviceName))
{
return false;
}
entity = hmPrimary->EntityManager->Services.GetEntity(ServiceHealthId(serviceName));
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"application"))
{
wstring applicationName;
if (!parser.TryGetString(L"appname", applicationName))
{
return false;
}
entity = hmPrimary->EntityManager->Applications.GetEntity(ApplicationHealthId(applicationName));
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"deployedapplication"))
{
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
return false;
}
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
entity = hmPrimary->EntityManager->DeployedApplications.GetEntity(DeployedApplicationHealthId(appName, nodeId.IdValue));
}
else if (StringUtility::AreEqualCaseInsensitive(entityType, L"deployedservicepackage"))
{
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
return false;
}
wstring serviceManifestName;
if (!parser.TryGetString(L"servicemanifestname", serviceManifestName))
{
return false;
}
wstring servicePackageActivationId;
if (!ParseServicePackageActivationId(parser, servicePackageActivationId))
{
return false;
}
TestSession::WriteInfo(TraceSource, "CorruptHMEntity(): Using ServicePackageActivationId=[{0}] for deployedservicepackage.", servicePackageActivationId);
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
entity = hmPrimary->EntityManager->DeployedServicePackages.GetEntity(
DeployedServicePackageHealthId(appName, serviceManifestName, servicePackageActivationId, nodeId.IdValue));
}
else
{
TestSession::WriteError(TraceSource, "Unknown type {0}", entityType);
return false;
}
bool changeEntityState = parser.GetBool(L"changeentitystate");
bool changeHasSystemReport = parser.GetBool(L"changeHasSystemReport");
bool changeSystemErrorCount = parser.GetBool(L"changeSystemErrorCount");
vector<HealthInformation> addReports;
wstring eventsString;
if (parser.TryGetString(L"addevents", eventsString))
{
map<wstring, vector<wstring>> addEvents;
if (!ParseEvents(eventsString, addEvents))
{
return false;
}
Random r;
for (auto const & entry : addEvents)
{
addReports.push_back(HealthInformation(
entry.second[0], // source
entry.second[1], // property
TimeSpan::MaxValue,
r.Next(3) == 1 ? FABRIC_HEALTH_STATE_WARNING : FABRIC_HEALTH_STATE_ERROR,
L"Corrupted report",
Common::SequenceNumber::GetNext(),
DateTime::Now(),
false));
}
}
vector<pair<wstring, wstring>> removeEventKeys;
if (parser.TryGetString(L"removeevents", eventsString))
{
map<wstring, vector<wstring>> removeEvents;
if (!ParseEvents(eventsString, removeEvents))
{
return false;
}
for (auto const & entry : removeEvents)
{
removeEventKeys.push_back(make_pair(entry.second[0], entry.second[1]));
}
}
vector<tuple<wstring, wstring, FABRIC_HEALTH_STATE>> scrambleEventKeys;
if (parser.TryGetString(L"scrambleevents", eventsString))
{
map<wstring, vector<wstring>> scrambleEvents;
if (!ParseEvents(eventsString, scrambleEvents))
{
return false;
}
for (auto const & entry : scrambleEvents)
{
scrambleEventKeys.push_back(make_tuple(entry.second[0], entry.second[1], GetHealthState(entry.second[2])));
}
}
HealthEntityState::Enum entityState;
size_t eventCount;
if (!entity->Test_CorruptEntity(
activityId,
changeEntityState,
changeHasSystemReport,
changeSystemErrorCount,
move(addReports),
removeEventKeys,
scrambleEventKeys,
entityState,
eventCount))
{
TestSession::WriteError(TraceSource, "{0}: Corrupt entity failed", activityId);
return false;
}
int expectedEventCount;
if (parser.TryGetInt(L"expectedeventcount", expectedEventCount))
{
if (static_cast<int>(eventCount) != expectedEventCount)
{
TestSession::WriteInfo(TraceSource, "Unexpected event count: expected {0}, actual {1}.", expectedEventCount, eventCount);
return false;
}
}
wstring expectedEntityStateString;
if (parser.TryGetString(L"expectedentitystate", expectedEntityStateString))
{
wstring actualEntityState = wformatString(entityState);
if (!StringUtility::AreEqualCaseInsensitive(expectedEntityStateString, actualEntityState))
{
TestSession::WriteInfo(TraceSource, "Unexpected entity health state: expected {0}, actual {1}.", expectedEntityStateString, actualEntityState);
return false;
}
}
return true;
}
bool TestFabricClientHealth::QueryHealthStateChunk(StringCollection const & params)
{
CreateFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
CommandLineParser parser(params, 0);
bool requiresValidation = false;
wstring expectedHealthStateString;
wstring expectedHealthStatesString;
wstring expectedApplicationsString;
requiresValidation |= parser.TryGetString(L"expectedhealthstate", expectedHealthStateString);
requiresValidation |= parser.TryGetString(L"expectedstates", expectedHealthStatesString);
requiresValidation |= parser.TryGetString(L"expectedapps", expectedApplicationsString);
vector<HRESULT> expectedErrors;
std::wstring error;
if (parser.TryGetString(L"expectederror", error, L"Success"))
{
ErrorCodeValue::Enum errorValue = FABRICSESSION.FabricDispatcher.ParseErrorCode(error);
expectedErrors.push_back(ErrorCode(errorValue).ToHResult());
}
else
{
expectedErrors.push_back(S_OK);
}
if (!requiresValidation)
{
expectedErrors.push_back(FABRIC_E_HEALTH_ENTITY_NOT_FOUND);
}
vector<HRESULT> allowedErrorsOnRetry;
allowedErrorsOnRetry.push_back(S_OK);
vector<HRESULT> retryableErrors;
retryableErrors.push_back(FABRIC_E_NOT_READY);
retryableErrors.push_back(FABRIC_E_HEALTH_ENTITY_NOT_FOUND);
if (!requiresValidation)
{
retryableErrors.push_back(FABRIC_E_SERVICE_TOO_BUSY);
}
else
{
std::wstring retryableError;
if (parser.TryGetString(L"retryableerror", retryableError, L"Success"))
{
ErrorCodeValue::Enum errorValue = FABRICSESSION.FabricDispatcher.ParseErrorCode(retryableError);
retryableErrors.push_back(ErrorCode(errorValue).ToHResult());
}
}
CreateFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
wstring queryType = params[0];
bool result;
if (StringUtility::AreEqualCaseInsensitive(queryType, L"cluster"))
{
result = GetClusterHealthChunk(params, requiresValidation, expectedErrors, allowedErrorsOnRetry, retryableErrors);
}
else
{
TestSession::WriteError(TraceSource, "Unsupported type {0}", queryType);
return false;
}
if (!result)
{
TestSession::FailTest("GetHealthStateChunk failed");
}
return true;
}
bool TestFabricClientHealth::QueryHealth(StringCollection const & params)
{
CreateFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
if (params.size() == 0)
{
return healthTable_->TestQuery(healthClient_);
}
bool result;
wstring const & queryType = params[0];
if (StringUtility::AreEqualCaseInsensitive(queryType, L"node"))
{
result = GetNodeHealth(params);
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"partition"))
{
result = GetPartitionHealth(params);
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"replica"))
{
result = GetReplicaHealth(params);
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"service"))
{
result = GetServiceHealth(params);
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"application"))
{
result = GetApplicationHealth(params);
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"deployedapplication"))
{
result = GetDeployedApplicationHealth(params);
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"deployedservicepackage"))
{
result = GetDeployedServicePackageHealth(params);
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"cluster"))
{
result = GetClusterHealth(params);
}
else
{
TestSession::WriteError(TraceSource, "Unknown type {0}", queryType);
return false;
}
if (!result)
{
TestSession::WriteError(TraceSource,"GetHealth failed");
return false;
}
return true;
}
bool CheckQueryHResult(HRESULT hr, vector<HRESULT> const & expectedErrors, bool requiresValidation)
{
bool isExpected = false;
for (auto it = expectedErrors.begin(); it != expectedErrors.end(); ++it)
{
if (hr == *it)
{
isExpected = true;
break;
}
}
if (FAILED(hr))
{
ErrorCode error = ErrorCode::FromHResult(hr);
if (isExpected)
{
TestSession::WriteInfo(TraceSource, "Query returned expected error {0}", error);
}
else if (requiresValidation)
{
TestSession::WriteWarning(TraceSource, "Query failed with error {0}", error);
return false;
}
else
{
TestSession::WriteInfo(TraceSource, "Query returned {0}", error);
}
}
else if (!isExpected)
{
TestSession::WriteWarning(TraceSource, "Query returned success. Expected: {0}", expectedErrors);
return false;
}
return true;
}
bool TestFabricClientHealth::GetClusterHealthChunk(StringCollection const & params, bool requiresValidation, vector<HRESULT> const & expectedErrors, vector<HRESULT> const & allowedErrorsOnRetry, vector<HRESULT> const & retryableErrors)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_CLUSTER_HEALTH_CHUNK_QUERY_DESCRIPTION>();
wstring nodeFiltersString;
if (parser.TryGetString(L"nodefilters", nodeFiltersString))
{
NodeHealthStateFilterListWrapper nodeFilters;
auto error = nodeFilters.FromJsonString(nodeFiltersString, nodeFilters);
TestSession::FailTestIfNot(error.IsSuccess(), "Failed to parse node filters string {0} with {1}", nodeFiltersString, error);
auto nodeFiltersPublic = heap.AddItem<FABRIC_NODE_HEALTH_STATE_FILTER_LIST>();
error = nodeFilters.ToPublicApi(heap, *nodeFiltersPublic);
queryDescription->NodeFilters = nodeFiltersPublic.GetRawPointer();
}
wstring applicationFiltersString;
if (parser.TryGetString(L"applicationfilters", applicationFiltersString))
{
ApplicationHealthStateFilterListWrapper applicationFilters;
auto error = applicationFilters.FromJsonString(applicationFiltersString, applicationFilters);
TestSession::FailTestIfNot(error.IsSuccess(), "Failed to parse application filters string {0} with {1}", applicationFiltersString, error);
auto applicationFiltersPublic = heap.AddItem<FABRIC_APPLICATION_HEALTH_STATE_FILTER_LIST>();
error = applicationFilters.ToPublicApi(heap, *applicationFiltersPublic);
queryDescription->ApplicationFilters = applicationFiltersPublic.GetRawPointer();
}
std::unique_ptr<ClusterHealthPolicy> healthPolicy;
if (!ParseClusterHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto clusterHealthPolicy = heap.AddItem<FABRIC_CLUSTER_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *clusterHealthPolicy);
queryDescription->ClusterHealthPolicy = clusterHealthPolicy.GetRawPointer();
}
// Parse application health policy map passed as a Json string
ApplicationHealthPolicyMapSPtr applicationHealthPolicies;
if (!GetApplicationHealthPolicies(parser, applicationHealthPolicies))
{
return false;
}
if (applicationHealthPolicies)
{
auto applicationHealthPolicyMap = heap.AddItem<FABRIC_APPLICATION_HEALTH_POLICY_MAP>();
applicationHealthPolicies->ToPublicApi(heap, *applicationHealthPolicyMap);
queryDescription->ApplicationHealthPolicyMap = applicationHealthPolicyMap.GetRawPointer();
}
wstring expectedErrorMessage;
parser.TryGetString(L"expectederrormessage", expectedErrorMessage);
CreateFabricHealthClient(FABRICSESSION.FabricDispatcher.Federation);
bool success = false;
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
do
{
--remainingRetries;
ComPointer<IFabricGetClusterHealthChunkResult> clusterHealthChunkResult;
HRESULT hr = TestFabricClient::PerformFabricClientOperation(
L"GetClusterHealthChunk",
FabricTestSessionConfig::GetConfig().NamingOperationTimeout,
[&](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetClusterHealthChunk(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[&](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetClusterHealthChunk(context.GetRawPointer(), clusterHealthChunkResult.InitializationAddress());
},
expectedErrors,
allowedErrorsOnRetry,
retryableErrors,
true /*failOnError*/,
expectedErrorMessage);
success = CheckQueryHResult(hr, expectedErrors, requiresValidation);
if (success && SUCCEEDED(hr))
{
success = ValidateClusterHealthChunk(parser, *clusterHealthChunkResult->get_ClusterHealthChunk(), requiresValidation);
}
if (!success)
{
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
}
} while (!success && remainingRetries >= 0);
return success;
}
bool TestFabricClientHealth::PerformHealthQueryClientOperation(
__in CommandLineParser & parser,
std::wstring const & operationName,
TestFabricClient::BeginFabricClientOperationCallback const & beginCallback,
TestFabricClient::EndFabricClientOperationCallback const & endCallback,
ValidateHealthCallback const & validateCallback)
{
bool expectEmpty = parser.GetBool(L"expectempty") | parser.GetBool(L"expectedempty");
bool requiresValidation = expectEmpty;
wstring expectedHealthStateString;
wstring expectedHealthDescString;
wstring expectedHealthStatesString;
wstring expectedHealthDescStringLength;
wstring expectedEvaluation;
wstring expectedStatsString;
int expectedEventCount;
requiresValidation |= parser.TryGetString(L"expectedhealthstate", expectedHealthStateString);
requiresValidation |= parser.TryGetString(L"expecteddesc", expectedHealthDescString);
requiresValidation |= parser.TryGetString(L"expecteddesclength", expectedHealthDescStringLength);
requiresValidation |= parser.TryGetString(L"expectedstates", expectedHealthStatesString);
requiresValidation |= parser.TryGetInt(L"expectedeventcount", expectedEventCount, -1);
requiresValidation |= parser.TryGetString(L"expectedreason", expectedEvaluation);
requiresValidation |= parser.TryGetString(L"stats", expectedStatsString);
vector<HRESULT> expectedErrors;
std::wstring error;
if (parser.TryGetString(L"expectederror", error, L"Success"))
{
ErrorCodeValue::Enum errorValue = FABRICSESSION.FabricDispatcher.ParseErrorCode(error);
expectedErrors.push_back(ErrorCode(errorValue).ToHResult());
}
else
{
expectedErrors.push_back(S_OK);
}
if (expectEmpty || (expectedEventCount == 0) || !requiresValidation)
{
expectedErrors.push_back(FABRIC_E_HEALTH_ENTITY_NOT_FOUND);
}
vector<HRESULT> allowedErrorsOnRetry;
allowedErrorsOnRetry.push_back(S_OK);
vector<HRESULT> retryableErrors;
retryableErrors.push_back(FABRIC_E_NOT_READY);
if (!expectEmpty)
{
retryableErrors.push_back(FABRIC_E_HEALTH_ENTITY_NOT_FOUND);
}
else
{
retryableErrors.push_back(FABRIC_E_VALUE_TOO_LARGE);
}
if (!requiresValidation)
{
retryableErrors.push_back(FABRIC_E_SERVICE_TOO_BUSY);
}
else
{
std::wstring retryableError;
if (parser.TryGetString(L"retryableerror", retryableError, L"Success"))
{
ErrorCodeValue::Enum errorValue = FABRICSESSION.FabricDispatcher.ParseErrorCode(retryableError);
retryableErrors.push_back(ErrorCode(errorValue).ToHResult());
}
}
wstring expectedErrorMessage;
parser.TryGetString(L"expectederrormessage", expectedErrorMessage);
bool success = false;
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
do
{
--remainingRetries;
HRESULT hr = TestFabricClient::PerformFabricClientOperation(
operationName,
FabricTestSessionConfig::GetConfig().NamingOperationTimeout,
beginCallback,
endCallback,
expectedErrors,
allowedErrorsOnRetry,
retryableErrors,
true /*failOnError*/,
expectedErrorMessage);
success = CheckQueryHResult(hr, expectedErrors, requiresValidation);
if (success && SUCCEEDED(hr))
{
success = validateCallback(expectEmpty, requiresValidation);
}
if (!success)
{
TestSession::WriteInfo(TraceSource, "PerformHealthQueryClientOperation {0}: !success, remainingRetries {1}...", operationName, remainingRetries);
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
}
} while (!success && remainingRetries >= 0);
return success;
}
bool TestFabricClientHealth::GetClusterHealth(StringCollection const & params)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_CLUSTER_HEALTH_QUERY_DESCRIPTION>();
wstring eventsFilterString;
if (parser.TryGetString(L"eventsfilter", eventsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(eventsFilterString, filter))
{
return false;
}
auto eventsFilter = heap.AddItem<FABRIC_HEALTH_EVENTS_FILTER>();
eventsFilter->HealthStateFilter = filter;
queryDescription->EventsFilter = eventsFilter.GetRawPointer();
}
wstring nodesFilterString;
if (parser.TryGetString(L"nodesfilter", nodesFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(nodesFilterString, filter))
{
return false;
}
auto nodesFilter = heap.AddItem<FABRIC_NODE_HEALTH_STATES_FILTER>();
nodesFilter->HealthStateFilter = filter;
queryDescription->NodesFilter = nodesFilter.GetRawPointer();
}
wstring applicationsFilterString;
if (parser.TryGetString(L"applicationsfilter", applicationsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(applicationsFilterString, filter))
{
return false;
}
auto applicationsFilter = heap.AddItem<FABRIC_APPLICATION_HEALTH_STATES_FILTER>();
applicationsFilter->HealthStateFilter = filter;
queryDescription->ApplicationsFilter = applicationsFilter.GetRawPointer();
}
std::unique_ptr<ClusterHealthPolicy> healthPolicy;
if (!ParseClusterHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto clusterHealthPolicy = heap.AddItem<FABRIC_CLUSTER_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *clusterHealthPolicy);
queryDescription->HealthPolicy = clusterHealthPolicy.GetRawPointer();
}
// Parse application health policy map passed as a Json string
ApplicationHealthPolicyMapSPtr applicationHealthPolicies;
if (!GetApplicationHealthPolicies(parser, applicationHealthPolicies))
{
return false;
}
if (applicationHealthPolicies)
{
auto applicationHealthPolicyMap = heap.AddItem<FABRIC_APPLICATION_HEALTH_POLICY_MAP>();
applicationHealthPolicies->ToPublicApi(heap, *applicationHealthPolicyMap);
queryDescription->ApplicationHealthPolicyMap = applicationHealthPolicyMap.GetRawPointer();
}
wstring excludeHealthStatsString;
wstring includeSystemAppStatsString;
if (parser.TryGetString(L"excludeHealthStats", excludeHealthStatsString) ||
parser.TryGetString(L"includeSystemAppStats", includeSystemAppStatsString))
{
auto statsFilter = heap.AddItem<FABRIC_CLUSTER_HEALTH_STATISTICS_FILTER>();
if (!excludeHealthStatsString.empty())
{
bool excludeHealthStats = parser.GetBool(L"excludeHealthStats");
statsFilter->ExcludeHealthStatistics = excludeHealthStats ? TRUE : FALSE;
}
if (!includeSystemAppStatsString.empty())
{
bool includeSystemAppStats = parser.GetBool(L"includeSystemAppStats");
statsFilter->IncludeSystemApplicationHealthStatistics = includeSystemAppStats ? TRUE : FALSE;
}
auto ex1 = heap.AddItem<FABRIC_CLUSTER_HEALTH_QUERY_DESCRIPTION_EX1>();
ex1->HealthStatisticsFilter = statsFilter.GetRawPointer();
queryDescription->Reserved = ex1.GetRawPointer();
}
ComPointer<IFabricClusterHealthResult> clusterHealthResult;
return PerformHealthQueryClientOperation(
parser,
L"GetClusterHealth",
[this, &queryDescription](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetClusterHealth2(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[this, &clusterHealthResult](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetClusterHealth2(context.GetRawPointer(), clusterHealthResult.InitializationAddress());
},
[this, &parser, &clusterHealthResult](bool expectEmpty, bool requiresValidation)
{
bool result = ValidateClusterHealth(parser, *clusterHealthResult->get_ClusterHealth(), expectEmpty, requiresValidation);
clusterHealthResult.Release();
return result;
});
}
bool TestFabricClientHealth::GetNodeHealth(StringCollection const & params)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_NODE_HEALTH_QUERY_DESCRIPTION>();
wstring eventsFilterString;
if (parser.TryGetString(L"eventsfilter", eventsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(eventsFilterString, filter))
{
return false;
}
auto eventsFilter = heap.AddItem<FABRIC_HEALTH_EVENTS_FILTER>();
eventsFilter->HealthStateFilter = filter;
queryDescription->EventsFilter = eventsFilter.GetRawPointer();
}
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
queryDescription->NodeName = heap.AddString(nodeName);
std::unique_ptr<ClusterHealthPolicy> healthPolicy;
if (!ParseClusterHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto nodeHealthPolicy = heap.AddItem<FABRIC_CLUSTER_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *nodeHealthPolicy);
queryDescription->HealthPolicy = nodeHealthPolicy.GetRawPointer();
}
ComPointer<IFabricNodeHealthResult> nodeHealthResult;
return PerformHealthQueryClientOperation(
parser,
L"GetNodeHealth",
[this, &queryDescription](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetNodeHealth2(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[this, &nodeHealthResult](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetNodeHealth2(context.GetRawPointer(), nodeHealthResult.InitializationAddress());
},
[this, &parser, &nodeHealthResult, &nodeName](bool expectEmpty, bool requiresValidation)
{
bool result = this->ValidateNodeHealth(parser, *nodeHealthResult->get_NodeHealth(), nodeName, expectEmpty, requiresValidation);
nodeHealthResult.Release();
return result;
});
}
bool TestFabricClientHealth::GetReplicaHealth(StringCollection const & params)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_REPLICA_HEALTH_QUERY_DESCRIPTION>();
wstring eventsFilterString;
if (parser.TryGetString(L"eventsfilter", eventsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(eventsFilterString, filter))
{
return false;
}
auto eventsFilter = heap.AddItem<FABRIC_HEALTH_EVENTS_FILTER>();
eventsFilter->HealthStateFilter = filter;
queryDescription->EventsFilter = eventsFilter.GetRawPointer();
}
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionGuid;
if (!ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
return false;
}
queryDescription->PartitionId = partitionGuid.AsGUID();
queryDescription->ReplicaOrInstanceId = replicaId;
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto replicaHealthPolicy = heap.AddItem<FABRIC_APPLICATION_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *replicaHealthPolicy);
queryDescription->HealthPolicy = replicaHealthPolicy.GetRawPointer();
}
ComPointer<IFabricReplicaHealthResult> replicaHealthResult;
return PerformHealthQueryClientOperation(
parser,
L"GetReplicaHealth",
[this, &queryDescription](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetReplicaHealth2(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[this, &replicaHealthResult](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetReplicaHealth2(context.GetRawPointer(), replicaHealthResult.InitializationAddress());
},
[this, &parser, &replicaHealthResult, partitionGuid, replicaId](bool expectEmpty, bool requiresValidation)
{
bool result = ValidateReplicaHealth(parser, *replicaHealthResult->get_ReplicaHealth(), partitionGuid, replicaId, expectEmpty, requiresValidation);
replicaHealthResult.Release();
return result;
});
}
bool TestFabricClientHealth::GetPartitionHealth(StringCollection const & params)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_PARTITION_HEALTH_QUERY_DESCRIPTION>();
wstring eventsFilterString;
if (parser.TryGetString(L"eventsfilter", eventsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(eventsFilterString, filter))
{
return false;
}
auto eventsFilter = heap.AddItem<FABRIC_HEALTH_EVENTS_FILTER>();
eventsFilter->HealthStateFilter = filter;
queryDescription->EventsFilter = eventsFilter.GetRawPointer();
}
wstring replicasFilterString;
if (parser.TryGetString(L"replicasfilter", replicasFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(replicasFilterString, filter))
{
return false;
}
auto replicasFilter = heap.AddItem<FABRIC_REPLICA_HEALTH_STATES_FILTER>();
replicasFilter->HealthStateFilter = filter;
queryDescription->ReplicasFilter = replicasFilter.GetRawPointer();
}
wstring excludeHealthStatsString;
if (parser.TryGetString(L"excludeHealthStats", excludeHealthStatsString))
{
bool excludeHealthStats = parser.GetBool(L"excludeHealthStats");
auto statsFilter = heap.AddItem<FABRIC_PARTITION_HEALTH_STATISTICS_FILTER>();
statsFilter->ExcludeHealthStatistics = excludeHealthStats ? TRUE : FALSE;
auto ex1 = heap.AddItem<FABRIC_PARTITION_HEALTH_QUERY_DESCRIPTION_EX1>();
ex1->HealthStatisticsFilter = statsFilter.GetRawPointer();
queryDescription->Reserved = ex1.GetRawPointer();
}
Common::Guid partitionGuid;
if (!ParsePartitionId(parser, partitionGuid))
{
return false;
}
queryDescription->PartitionId = partitionGuid.AsGUID();
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto partitionHealthPolicy = heap.AddItem<FABRIC_APPLICATION_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *partitionHealthPolicy);
queryDescription->HealthPolicy = partitionHealthPolicy.GetRawPointer();
}
ComPointer<IFabricPartitionHealthResult> partitionHealthResult;
return PerformHealthQueryClientOperation(
parser,
L"GetPartitionHealth",
[this, &queryDescription](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetPartitionHealth2(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[this, &partitionHealthResult](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetPartitionHealth2(context.GetRawPointer(), partitionHealthResult.InitializationAddress());
},
[this, &parser, &partitionHealthResult, partitionGuid](bool expectEmpty, bool requiresValidation)
{
bool result = ValidatePartitionHealth(parser, *partitionHealthResult->get_PartitionHealth(), partitionGuid, expectEmpty, requiresValidation);
partitionHealthResult.Release();
return result;
});
}
bool TestFabricClientHealth::GetServiceHealth(StringCollection const & params)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_SERVICE_HEALTH_QUERY_DESCRIPTION>();
wstring eventsFilterString;
if (parser.TryGetString(L"eventsfilter", eventsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(eventsFilterString, filter))
{
return false;
}
auto eventsFilter = heap.AddItem<FABRIC_HEALTH_EVENTS_FILTER>();
eventsFilter->HealthStateFilter = filter;
queryDescription->EventsFilter = eventsFilter.GetRawPointer();
}
wstring partitionsFilterString;
if (parser.TryGetString(L"partitionsfilter", partitionsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(partitionsFilterString, filter))
{
return false;
}
auto partitionsFilter = heap.AddItem<FABRIC_PARTITION_HEALTH_STATES_FILTER>();
partitionsFilter->HealthStateFilter = filter;
queryDescription->PartitionsFilter = partitionsFilter.GetRawPointer();
}
wstring serviceNameString;
if (!parser.TryGetString(L"servicename", serviceNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse servicename parameter");
return false;
}
queryDescription->ServiceName = heap.AddString(serviceNameString);
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto serviceHealthPolicy = heap.AddItem<FABRIC_APPLICATION_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *serviceHealthPolicy);
queryDescription->HealthPolicy = serviceHealthPolicy.GetRawPointer();
}
wstring excludeHealthStatsString;
if (parser.TryGetString(L"excludeHealthStats", excludeHealthStatsString))
{
bool excludeHealthStats = parser.GetBool(L"excludeHealthStats");
auto statsFilter = heap.AddItem<FABRIC_SERVICE_HEALTH_STATISTICS_FILTER>();
statsFilter->ExcludeHealthStatistics = excludeHealthStats ? TRUE : FALSE;
auto ex1 = heap.AddItem<FABRIC_SERVICE_HEALTH_QUERY_DESCRIPTION_EX1>();
ex1->HealthStatisticsFilter = statsFilter.GetRawPointer();
queryDescription->Reserved = ex1.GetRawPointer();
}
ComPointer<IFabricServiceHealthResult> serviceHealthResult;
return PerformHealthQueryClientOperation(
parser,
L"GetServiceHealth",
[this, &queryDescription](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetServiceHealth2(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[this, &serviceHealthResult](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetServiceHealth2(context.GetRawPointer(), serviceHealthResult.InitializationAddress());
},
[this, &parser, &serviceHealthResult, &serviceNameString](bool expectEmpty, bool requiresValidation)
{
bool result = ValidateServiceHealth(parser, *serviceHealthResult->get_ServiceHealth(), serviceNameString, expectEmpty, requiresValidation);
serviceHealthResult.Release();
return result;
});
}
bool TestFabricClientHealth::GetDeployedApplicationHealth(StringCollection const & params)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_DEPLOYED_APPLICATION_HEALTH_QUERY_DESCRIPTION>();
wstring eventsFilterString;
if (parser.TryGetString(L"eventsfilter", eventsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(eventsFilterString, filter))
{
return false;
}
auto eventsFilter = heap.AddItem<FABRIC_HEALTH_EVENTS_FILTER>();
eventsFilter->HealthStateFilter = filter;
queryDescription->EventsFilter = eventsFilter.GetRawPointer();
}
wstring deployedServicePackagesFilterString;
if (parser.TryGetString(L"deployedservicepackagesfilter", deployedServicePackagesFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(deployedServicePackagesFilterString, filter))
{
return false;
}
auto deployedServicePackagesFilter = heap.AddItem<FABRIC_DEPLOYED_SERVICE_PACKAGE_HEALTH_STATES_FILTER>();
deployedServicePackagesFilter->HealthStateFilter = filter;
queryDescription->DeployedServicePackagesFilter = deployedServicePackagesFilter.GetRawPointer();
}
wstring applicationNameString;
if (!parser.TryGetString(L"appname", applicationNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
queryDescription->ApplicationName = heap.AddString(applicationNameString);
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
queryDescription->NodeName = heap.AddString(nodeName);
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto deployedApplicationHealthPolicy = heap.AddItem<FABRIC_APPLICATION_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *deployedApplicationHealthPolicy);
queryDescription->HealthPolicy = deployedApplicationHealthPolicy.GetRawPointer();
}
wstring excludeHealthStatsString;
if (parser.TryGetString(L"excludeHealthStats", excludeHealthStatsString))
{
bool excludeHealthStats = parser.GetBool(L"excludeHealthStats");
auto statsFilter = heap.AddItem<FABRIC_DEPLOYED_APPLICATION_HEALTH_STATISTICS_FILTER>();
statsFilter->ExcludeHealthStatistics = excludeHealthStats ? TRUE : FALSE;
auto ex1 = heap.AddItem<FABRIC_DEPLOYED_APPLICATION_HEALTH_QUERY_DESCRIPTION_EX1>();
ex1->HealthStatisticsFilter = statsFilter.GetRawPointer();
queryDescription->Reserved = ex1.GetRawPointer();
}
ComPointer<IFabricDeployedApplicationHealthResult> deployedApplicationHealthResult;
return PerformHealthQueryClientOperation(
parser,
L"GetDeployedApplicationHealth",
[this, &queryDescription](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetDeployedApplicationHealth2(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[this, &deployedApplicationHealthResult](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetDeployedApplicationHealth2(context.GetRawPointer(), deployedApplicationHealthResult.InitializationAddress());
},
[this, &parser, &deployedApplicationHealthResult, &applicationNameString, &nodeName](bool expectEmpty, bool requiresValidation)
{
bool result = ValidateDeployedApplicationHealth(parser, *deployedApplicationHealthResult->get_DeployedApplicationHealth(), applicationNameString, nodeName, expectEmpty, requiresValidation);
deployedApplicationHealthResult.Release();
return result;
});
}
bool TestFabricClientHealth::GetDeployedServicePackageHealth(StringCollection const & params)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_DEPLOYED_SERVICE_PACKAGE_HEALTH_QUERY_DESCRIPTION>();
wstring eventsFilterString;
if (parser.TryGetString(L"eventsfilter", eventsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(eventsFilterString, filter))
{
return false;
}
auto eventsFilter = heap.AddItem<FABRIC_HEALTH_EVENTS_FILTER>();
eventsFilter->HealthStateFilter = filter;
queryDescription->EventsFilter = eventsFilter.GetRawPointer();
}
wstring applicationNameString;
if (!parser.TryGetString(L"appname", applicationNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
queryDescription->ApplicationName = heap.AddString(applicationNameString);
wstring serviceManifestNameString;
if (!parser.TryGetString(L"servicemanifestname", serviceManifestNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse servicemanifestname parameter");
return false;
}
queryDescription->ServiceManifestName = heap.AddString(serviceManifestNameString);
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
queryDescription->NodeName = heap.AddString(nodeName);
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto deployedServicePackageHealthPolicy = heap.AddItem<FABRIC_APPLICATION_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *deployedServicePackageHealthPolicy);
queryDescription->HealthPolicy = deployedServicePackageHealthPolicy.GetRawPointer();
}
wstring servicePackageActivationId;
if (!ParseServicePackageActivationId(parser, servicePackageActivationId))
{
return false;
}
TestSession::WriteInfo(
TraceSource,
"GetDeployedServicePackageHealth(): applicationNameString:{0}, serviceManifestNameString={1}, servicePackageActivationId={2}.",
applicationNameString,
serviceManifestNameString,
servicePackageActivationId);
auto queryDescriptionEx1 = heap.AddItem<FABRIC_DEPLOYED_SERVICE_PACKAGE_HEALTH_QUERY_DESCRIPTION_EX1>();
queryDescriptionEx1->ServicePackageActivationId = heap.AddString(servicePackageActivationId);
queryDescription->Reserved = queryDescriptionEx1.GetRawPointer();
ComPointer<IFabricDeployedServicePackageHealthResult> deployedServicePackageHealthResult;
return PerformHealthQueryClientOperation(
parser,
L"GetDeployedServicePackageHealth",
[this, &queryDescription](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetDeployedServicePackageHealth2(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[this, &deployedServicePackageHealthResult](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetDeployedServicePackageHealth2(context.GetRawPointer(), deployedServicePackageHealthResult.InitializationAddress());
},
[this, &parser, &deployedServicePackageHealthResult, &applicationNameString, &nodeName, &serviceManifestNameString, &servicePackageActivationId](bool expectEmpty, bool requiresValidation)
{
bool result = ValidateDeployedServicePackageHealth(
parser,
*deployedServicePackageHealthResult->get_DeployedServicePackageHealth(),
applicationNameString,
serviceManifestNameString,
servicePackageActivationId,
nodeName,
expectEmpty,
requiresValidation);
deployedServicePackageHealthResult.Release();
return result;
});
}
bool TestFabricClientHealth::GetApplicationHealth(StringCollection const & params)
{
CommandLineParser parser(params, 0);
ScopedHeap heap;
auto queryDescription = heap.AddItem<FABRIC_APPLICATION_HEALTH_QUERY_DESCRIPTION>();
wstring eventsFilterString;
if (parser.TryGetString(L"eventsfilter", eventsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(eventsFilterString, filter))
{
return false;
}
auto eventsFilter = heap.AddItem<FABRIC_HEALTH_EVENTS_FILTER>();
eventsFilter->HealthStateFilter = filter;
queryDescription->EventsFilter = eventsFilter.GetRawPointer();
}
wstring servicesFilterString;
if (parser.TryGetString(L"servicesfilter", servicesFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(servicesFilterString, filter))
{
return false;
}
auto servicesFilter = heap.AddItem<FABRIC_SERVICE_HEALTH_STATES_FILTER>();
servicesFilter->HealthStateFilter = filter;
queryDescription->ServicesFilter = servicesFilter.GetRawPointer();
}
wstring deployedApplicationsFilterString;
if (parser.TryGetString(L"deployedapplicationsfilter", deployedApplicationsFilterString))
{
DWORD filter;
if (!GetHealthStateFilter(deployedApplicationsFilterString, filter))
{
return false;
}
auto deployedApplicationsFilter = heap.AddItem<FABRIC_DEPLOYED_APPLICATION_HEALTH_STATES_FILTER>();
deployedApplicationsFilter->HealthStateFilter = filter;
queryDescription->DeployedApplicationsFilter = deployedApplicationsFilter.GetRawPointer();
}
wstring applicationNameString;
if (!parser.TryGetString(L"appname", applicationNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
queryDescription->ApplicationName = heap.AddString(applicationNameString);
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
auto applicationHealthPolicy = heap.AddItem<FABRIC_APPLICATION_HEALTH_POLICY>();
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
healthPolicy->ToPublicApi(heap, *applicationHealthPolicy);
queryDescription->HealthPolicy = applicationHealthPolicy.GetRawPointer();
}
wstring excludeHealthStatsString;
if (parser.TryGetString(L"excludeHealthStats", excludeHealthStatsString))
{
bool excludeHealthStats = parser.GetBool(L"excludeHealthStats");
auto statsFilter = heap.AddItem<FABRIC_APPLICATION_HEALTH_STATISTICS_FILTER>();
statsFilter->ExcludeHealthStatistics = excludeHealthStats ? TRUE : FALSE;
auto ex1 = heap.AddItem<FABRIC_APPLICATION_HEALTH_QUERY_DESCRIPTION_EX1>();
ex1->HealthStatisticsFilter = statsFilter.GetRawPointer();
queryDescription->Reserved = ex1.GetRawPointer();
}
ComPointer<IFabricApplicationHealthResult> applicationHealthResult;
return PerformHealthQueryClientOperation(
parser,
L"GetApplicationHealth",
[this, &queryDescription](DWORD const timeout, ComPointer<ComCallbackWaiter> const & callback, ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->BeginGetApplicationHealth2(
queryDescription.GetRawPointer(),
timeout,
callback.GetRawPointer(),
context.InitializationAddress());
},
[this, &applicationHealthResult](ComPointer<IFabricAsyncOperationContext> & context) -> HRESULT
{
return healthClient_->EndGetApplicationHealth2(context.GetRawPointer(), applicationHealthResult.InitializationAddress());
},
[this, &parser, &applicationHealthResult, &applicationNameString](bool expectEmpty, bool requiresValidation)
{
bool result = ValidateApplicationHealth(parser, *applicationHealthResult->get_ApplicationHealth(), applicationNameString, expectEmpty, requiresValidation);
applicationHealthResult.Release();
return result;
});
}
bool TestFabricClientHealth::QueryHealthList(StringCollection const & params)
{
if (params.size() < 1)
{
return false;
}
wstring queryType = params[0];
CommandLineParser parser(params, 0);
QueryArgumentMap queryArgs;
Query::QueryNames::Enum queryName;
if (StringUtility::AreEqualCaseInsensitive(queryType, L"nodes"))
{
queryName = Query::QueryNames::GetAggregatedNodeHealthList;
if (!CreateNodeHealthQueryList(parser, queryArgs))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"partitions"))
{
queryName = Query::QueryNames::GetAggregatedServicePartitionHealthList;
if (!CreatePartitionHealthQueryList(parser, queryArgs))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"replicas"))
{
queryName = Query::QueryNames::GetAggregatedServicePartitionReplicaHealthList;
if (!CreateReplicaHealthQueryList(parser, queryArgs))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"services"))
{
queryName = Query::QueryNames::GetAggregatedServiceHealthList;
if (!CreateServiceHealthQueryList(parser, queryArgs))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"applications"))
{
queryName = Query::QueryNames::GetAggregatedApplicationHealthList;
if (!CreateApplicationHealthQueryList(parser, queryArgs))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"deployedapplications"))
{
queryName = Query::QueryNames::GetAggregatedDeployedApplicationHealthList;
if (!CreateDeployedApplicationHealthQueryList(parser, queryArgs))
{
return false;
}
}
else if (StringUtility::AreEqualCaseInsensitive(queryType, L"deployedservicepackages"))
{
queryName = Query::QueryNames::GetAggregatedDeployedServicePackageHealthList;
if (!CreateDeployedServicePackageHealthQueryList(parser, queryArgs))
{
return false;
}
}
else
{
TestSession::WriteError(TraceSource, "Unknown type {0}", queryType);
return false;
}
wstring continuationToken;
if (parser.TryGetString(L"continuationtoken", continuationToken))
{
queryArgs.Insert(QueryResourceProperties::QueryMetadata::ContinuationToken, continuationToken);
}
auto internalQueryClient = TestFabricClientQuery::CreateInternalFabricQueryClient(FABRICSESSION.FabricDispatcher.Federation);
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
bool success = false;
wstring queryNameString = wformatString(queryName);
AutoResetEvent waitEvent;
auto defaultNamingOperationTimeoutBuffer = TimeSpan::FromSeconds(10);
do
{
--remainingRetries;
auto asyncOperation = internalQueryClient->BeginInternalQuery(
queryNameString,
queryArgs,
FabricTestSessionConfig::GetConfig().NamingOperationTimeout,
[&waitEvent](Common::AsyncOperationSPtr const &) { waitEvent.Set(); },
internalQueryClient.get_Root()->CreateAsyncOperationRoot());
TimeSpan timeToWait = FabricTestSessionConfig::GetConfig().NamingOperationTimeout + defaultNamingOperationTimeoutBuffer;
if (!waitEvent.WaitOne(timeToWait))
{
TestSession::FailTest(
"BeginInternalQuery did not complete in {0} secs although a timeout of {1} was provided",
timeToWait,
FabricTestSessionConfig::GetConfig().NamingOperationTimeout);
}
QueryResult queryResult;
auto error = internalQueryClient->EndInternalQuery(asyncOperation, queryResult);
if (!error.IsSuccess())
{
TestSession::WriteWarning(TraceSource, "Query failed with error = {0}", error);
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
continue;
}
else
{
if (!VerifyHealthQueryListResult(parser, queryName, queryResult))
{
TestSession::WriteWarning(TraceSource, "Health query list result verification failed");
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
continue;
}
success = true;
}
} while (!success && remainingRetries >= 0);
if (!success)
{
TestSession::FailTest("QueryHealthList failed");
}
return true;
}
Management::HealthManager::EntityKind::Enum GetEntityKind(FABRIC_HEALTH_REPORT_KIND kind)
{
switch (kind)
{
case FABRIC_HEALTH_REPORT_KIND_NODE:
return EntityKind::Node;
case FABRIC_HEALTH_REPORT_KIND_STATEFUL_SERVICE_REPLICA:
case FABRIC_HEALTH_REPORT_KIND_STATELESS_SERVICE_INSTANCE:
return EntityKind::Replica;
case FABRIC_HEALTH_REPORT_KIND_PARTITION:
return EntityKind::Partition;
case FABRIC_HEALTH_REPORT_KIND_SERVICE:
return EntityKind::Service;
case FABRIC_HEALTH_REPORT_KIND_APPLICATION:
return EntityKind::Application;
case FABRIC_HEALTH_REPORT_KIND_DEPLOYED_APPLICATION:
return EntityKind::DeployedApplication;
case FABRIC_HEALTH_REPORT_KIND_DEPLOYED_SERVICE_PACKAGE:
return EntityKind::DeployedServicePackage;
case FABRIC_HEALTH_REPORT_KIND_CLUSTER:
return EntityKind::Cluster;
default:
TestSession::FailTest("{0}: Unsupported entity kind", static_cast<int>(kind));
}
}
template<class TResultType>
bool CheckAggregatedHealthQueryResult(__in CommandLineParser & parser, FABRIC_HEALTH_REPORT_KIND kind, __in QueryResult & queryResult)
{
bool requiresValidation = false;
wstring expectedHealthStateString;
wstring expectedHealthStatesString;
wstring expectedContinuationToken;
wstring expectedPagingStatusString;
requiresValidation |= parser.TryGetString(L"expectedhealthstate", expectedHealthStateString);
requiresValidation |= parser.TryGetString(L"expectedstates", expectedHealthStatesString);
requiresValidation |= parser.TryGetString(L"expectedcontinuationtoken", expectedContinuationToken);
requiresValidation |= parser.TryGetString(L"expectedpagingstatus", expectedPagingStatusString);
bool expectEmpty = parser.GetBool(L"expectempty") | parser.GetBool(L"expectedempty");
vector<TResultType> aggregatedHealthList;
auto error = queryResult.MoveList<TResultType>(aggregatedHealthList);
TestSession::FailTestIfNot(error.IsSuccess(), "QueryHealthList: MoveList returned error {0}", error);
if (expectEmpty)
{
if (aggregatedHealthList.size() != 0u)
{
TestSession::WriteWarning(TraceSource, "Unexpected health query result count {0}.", aggregatedHealthList.size());
return false;
}
TestSession::WriteInfo(TraceSource, "QueryHealthList: Received empty list...");
return true;
}
wstring resultString;
StringWriter writer(resultString);
HealthStateCount counts;
for (auto it = aggregatedHealthList.begin(); it != aggregatedHealthList.end(); ++it)
{
counts.Add(it->AggregatedHealthState);
writer.WriteLine("{0}", it->ToString());
}
HealthStateCountMap results;
results.insert(make_pair(GetEntityKind(kind), move(counts)));
bool success = TestFabricClientHealth::VerifyAggregatedHealthStates(parser, results);
auto pagingStatus = queryResult.MovePagingStatus();
bool expectedPagingStatus = parser.GetBool(L"expectedpagingstatus");
if (expectedContinuationToken.empty())
{
// Check that no continuation token is received
if (pagingStatus && !pagingStatus->ContinuationToken.empty())
{
if (requiresValidation && !expectedPagingStatus)
{
TestSession::WriteWarning(TraceSource, "Unexpected continuation token {0}, expected none.", pagingStatus->ContinuationToken);
return false;
}
else
{
writer.WriteLine("ContinuationToken: {0}", pagingStatus->ContinuationToken);
}
}
else if (expectedPagingStatus)
{
TestSession::WriteWarning(TraceSource, "Expected paging status not received.");
return false;
}
}
else
{
// Check expected continuation token
if (!pagingStatus)
{
TestSession::WriteWarning(TraceSource, "Expected continuation token {0} not received.", expectedContinuationToken);
return false;
}
if (expectedContinuationToken != pagingStatus->ContinuationToken)
{
TestSession::WriteWarning(TraceSource, "Continuation token mismatch: expected {0}, actual {1}.", expectedContinuationToken, pagingStatus->ContinuationToken);
return false;
}
}
if (!requiresValidation || !success)
{
TestSession::WriteInfo(TraceSource, "{0}", resultString);
}
else
{
TestSession::WriteNoise(TraceSource, "{0}", resultString);
}
return success;
}
bool TestFabricClientHealth::VerifyHealthQueryListResult(CommandLineParser & parser, Query::QueryNames::Enum queryName, QueryResult & queryResult)
{
TestSession::FailTestIf(
queryResult.ResultKind != FABRIC_QUERY_RESULT_KIND_LIST,
"Query result null or invalid.");
bool success;
switch (queryName)
{
case QueryNames::GetAggregatedNodeHealthList:
success = CheckAggregatedHealthQueryResult<NodeAggregatedHealthState>(parser, FABRIC_HEALTH_REPORT_KIND_NODE, queryResult);
break;
case QueryNames::GetAggregatedServicePartitionReplicaHealthList:
success = CheckAggregatedHealthQueryResult<ReplicaAggregatedHealthState>(parser, FABRIC_HEALTH_REPORT_KIND_STATEFUL_SERVICE_REPLICA, queryResult);
break;
case QueryNames::GetAggregatedServicePartitionHealthList:
success = CheckAggregatedHealthQueryResult<PartitionAggregatedHealthState>(parser, FABRIC_HEALTH_REPORT_KIND_PARTITION, queryResult);
break;
case QueryNames::GetAggregatedServiceHealthList:
success = CheckAggregatedHealthQueryResult<ServiceAggregatedHealthState>(parser, FABRIC_HEALTH_REPORT_KIND_SERVICE, queryResult);
break;
case QueryNames::GetAggregatedDeployedServicePackageHealthList:
success = CheckAggregatedHealthQueryResult<DeployedServicePackageAggregatedHealthState>(parser, FABRIC_HEALTH_REPORT_KIND_DEPLOYED_SERVICE_PACKAGE, queryResult);
break;
case QueryNames::GetAggregatedDeployedApplicationHealthList:
success = CheckAggregatedHealthQueryResult<DeployedApplicationAggregatedHealthState>(parser, FABRIC_HEALTH_REPORT_KIND_DEPLOYED_APPLICATION, queryResult);
break;
case QueryNames::GetAggregatedApplicationHealthList:
success = CheckAggregatedHealthQueryResult<ApplicationAggregatedHealthState>(parser, FABRIC_HEALTH_REPORT_KIND_APPLICATION, queryResult);
break;
default:
TestSession::FailTest("Invalid query name {0}", queryName);
}
return success;
}
bool TestFabricClientHealth::CreateNodeHealthQueryList(CommandLineParser & parser, ServiceModel::QueryArgumentMap & queryArgs)
{
std::unique_ptr<ClusterHealthPolicy> healthPolicy;
if (!ParseClusterHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
queryArgs.Insert(Query::QueryResourceProperties::Health::ClusterHealthPolicy, healthPolicyString);
}
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
queryArgs.Insert(Query::QueryResourceProperties::Node::Name, nodeName);
}
// No required paramters
return true;
}
bool TestFabricClientHealth::CreateReplicaHealthQueryList(CommandLineParser & parser, ServiceModel::QueryArgumentMap & queryArgs)
{
Common::Guid partitionGuid;
if (!ParsePartitionId(parser, partitionGuid))
{
return false;
}
queryArgs.Insert(Query::QueryResourceProperties::Partition::PartitionId, partitionGuid.ToString());
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
if (ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
queryArgs.Insert(QueryResourceProperties::Replica::ReplicaId, wformatString(replicaId));
}
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
queryArgs.Insert(Query::QueryResourceProperties::Health::ApplicationHealthPolicy, healthPolicyString);
}
return true;
}
bool TestFabricClientHealth::CreatePartitionHealthQueryList(CommandLineParser & parser, ServiceModel::QueryArgumentMap & queryArgs)
{
bool found = false;
wstring serviceNameArg;
if (parser.TryGetString(L"servicename", serviceNameArg, wstring()))
{
queryArgs.Insert(Query::QueryResourceProperties::Service::ServiceName, serviceNameArg);
found = true;
}
Guid partitionGuid;
if (ParsePartitionId(parser, partitionGuid))
{
queryArgs.Insert(QueryResourceProperties::Partition::PartitionId, wformatString(partitionGuid));
found = true;
}
if (!found)
{
TestSession::WriteError(TraceSource, "Did not find any of the servicename or partitionId parameters. At least one of them must be present.");
return false;
}
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
queryArgs.Insert(Query::QueryResourceProperties::Health::ApplicationHealthPolicy, healthPolicyString);
}
return true;
}
bool TestFabricClientHealth::CreateDeployedServicePackageHealthQueryList(CommandLineParser & parser, ServiceModel::QueryArgumentMap & queryArgs)
{
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
queryArgs.Insert(Query::QueryResourceProperties::Node::Name, nodeName);
queryArgs.Insert(Query::QueryResourceProperties::Application::ApplicationName, appName);
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
queryArgs.Insert(Query::QueryResourceProperties::Health::ApplicationHealthPolicy, healthPolicyString);
}
return true;
}
bool TestFabricClientHealth::CreateDeployedApplicationHealthQueryList(CommandLineParser & parser, ServiceModel::QueryArgumentMap & queryArgs)
{
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
queryArgs.Insert(Query::QueryResourceProperties::Application::ApplicationName, appName);
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
queryArgs.Insert(Query::QueryResourceProperties::Health::ApplicationHealthPolicy, healthPolicyString);
}
return true;
}
bool TestFabricClientHealth::CreateServiceHealthQueryList(CommandLineParser & parser, ServiceModel::QueryArgumentMap & queryArgs)
{
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
queryArgs.Insert(Query::QueryResourceProperties::Application::ApplicationName, move(appName));
wstring serviceName;
if (parser.TryGetString(L"servicename", serviceName, wstring()))
{
queryArgs.Insert(Query::QueryResourceProperties::Service::ServiceName, move(serviceName));
}
wstring serviceTypeName;
if (parser.TryGetString(L"servicetypename", serviceTypeName, wstring()))
{
queryArgs.Insert(Query::QueryResourceProperties::ServiceType::ServiceTypeName, move(serviceTypeName));
}
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
queryArgs.Insert(Query::QueryResourceProperties::Health::ApplicationHealthPolicy, healthPolicyString);
}
return true;
}
bool TestFabricClientHealth::CreateApplicationHealthQueryList(CommandLineParser & parser, ServiceModel::QueryArgumentMap & queryArgs)
{
std::unique_ptr<ApplicationHealthPolicy> healthPolicy;
if (!ParseApplicationHealthPolicy(parser, healthPolicy))
{
return false;
}
if (healthPolicy)
{
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Use policy {0}", healthPolicyString);
queryArgs.Insert(Query::QueryResourceProperties::Health::ApplicationHealthPolicy, healthPolicyString);
}
wstring appName(L"");
if (parser.TryGetString(L"appname", appName))
{
queryArgs.Insert(Query::QueryResourceProperties::Application::ApplicationName, move(appName));
}
wstring appTypeName(L"");
if (parser.TryGetString(L"apptypename", appTypeName))
{
queryArgs.Insert(Query::QueryResourceProperties::ApplicationType::ApplicationTypeName, move(appTypeName));
}
wstring applicationDefinitionKindFilter(L"");
if (parser.TryGetString(L"applicationdefinitionkindfilter", applicationDefinitionKindFilter))
{
queryArgs.Insert(Query::QueryResourceProperties::Deployment::ApplicationDefinitionKindFilter, move(applicationDefinitionKindFilter));
}
// No required paramters
return true;
}
bool TestFabricClientHealth::GetHealthStateFilter(std::wstring const & healthStateFilterString, __out DWORD & filter)
{
filter = FABRIC_HEALTH_STATE_FILTER_DEFAULT;
vector<wstring> tokens;
StringUtility::Split<wstring>(healthStateFilterString, tokens, L"|");
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
DWORD filterValueToken = FABRIC_HEALTH_STATE_FILTER_DEFAULT;
FABRIC_HEALTH_STATE healthState = GetHealthState(*it);
switch (healthState)
{
case FABRIC_HEALTH_STATE_OK: filterValueToken = FABRIC_HEALTH_STATE_FILTER_OK;
break;
case FABRIC_HEALTH_STATE_WARNING: filterValueToken = FABRIC_HEALTH_STATE_FILTER_WARNING; break;
case FABRIC_HEALTH_STATE_ERROR: filterValueToken = FABRIC_HEALTH_STATE_FILTER_ERROR; break;
case FABRIC_HEALTH_STATE_INVALID:
if (*it == L"all")
{
filterValueToken = FABRIC_HEALTH_STATE_FILTER_ALL;
}
else if (*it == L"none")
{
filterValueToken = FABRIC_HEALTH_STATE_FILTER_NONE;
}
else
{
TestSession::WriteInfo(TraceSource, "GetHealthStateFilter token {0} not supported in {1}", *it, healthStateFilterString);
}
break;
default:
TestSession::WriteInfo(TraceSource, "GetHealthStateFilter token {0} not supported in {1}", *it, healthStateFilterString);
return false;
}
if (filter == FABRIC_HEALTH_STATE_FILTER_DEFAULT)
{
filter = filterValueToken;
}
else
{
filter |= filterValueToken;
}
}
TestSession::WriteNoise(TraceSource, "GetHealthStateFilter: {0} = {1}", healthStateFilterString, filter);
return true;
}
FABRIC_HEALTH_STATE TestFabricClientHealth::GetHealthState(std::wstring const & healthStateString)
{
FABRIC_HEALTH_STATE healthState = FABRIC_HEALTH_STATE_INVALID;
if (StringUtility::AreEqualCaseInsensitive(healthStateString, L"ok"))
{
healthState = FABRIC_HEALTH_STATE_OK;
}
else if (StringUtility::AreEqualCaseInsensitive(healthStateString, L"warning"))
{
healthState = FABRIC_HEALTH_STATE_WARNING;
}
else if (StringUtility::AreEqualCaseInsensitive(healthStateString, L"error"))
{
healthState = FABRIC_HEALTH_STATE_ERROR;
}
else if (StringUtility::AreEqualCaseInsensitive(healthStateString, L"unknown"))
{
healthState = FABRIC_HEALTH_STATE_UNKNOWN;
}
return healthState;
}
std::wstring TestFabricClientHealth::GetHealthStateString(FABRIC_HEALTH_STATE healthState)
{
switch(healthState)
{
case FABRIC_HEALTH_STATE::FABRIC_HEALTH_STATE_OK:
return L"ok";
case FABRIC_HEALTH_STATE::FABRIC_HEALTH_STATE_WARNING:
return L"warning";
case FABRIC_HEALTH_STATE::FABRIC_HEALTH_STATE_ERROR:
return L"error";
case FABRIC_HEALTH_STATE::FABRIC_HEALTH_STATE_UNKNOWN:
return L"unknown";
default:
return L"invalid";
}
}
bool TestFabricClientHealth::ParseCommonHealthInformation(CommandLineParser & parser, FABRIC_SEQUENCE_NUMBER & sequenceNumber, std::wstring & sourceId, FABRIC_HEALTH_STATE & healthState, std::wstring & property, int64 & timeToLiveSeconds, std::wstring & description, bool & removeWhenExpired)
{
parser.TryGetString(L"property", property, L"FabricTest_Property");
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
int64 descriptionLength;
if (parser.TryGetInt64(L"descriptionlength", descriptionLength))
{
// Set description as a string with required length
description = wstring(descriptionLength, L'a');
TestSession::WriteInfo(TraceSource, "Generate description based on descriptionLength, with {0} characters", description.size());
}
else
{
parser.TryGetString(L"description", description, L"FabricTest_Description");
}
// Use Auto as default so the system generates a sequence number
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_AUTO_SEQUENCE_NUMBER);
// Use default ttl large enough for events not to expire before validation in general case
parser.TryGetInt64(L"timetoliveseconds", timeToLiveSeconds, 60 * 60);
wstring healthStateString;
if (!parser.TryGetString(L"healthstate", healthStateString, L""))
{
TestSession::WriteError(TraceSource, "Could not parse healthstate parameter");
return false;
}
healthState = GetHealthState(healthStateString);
if (healthState == FABRIC_HEALTH_STATE_INVALID)
{
TestSession::WriteError(TraceSource, "Unknown healthstate {0}", healthStateString);
return false;
}
removeWhenExpired = parser.GetBool(L"transient");
return true;
}
bool TestFabricClientHealth::ParsePartitionId(CommandLineParser & parser, __inout Common::Guid & partitionGuid)
{
wstring partitionGuidString;
wstring partitionIdString;
if (parser.TryGetString(L"partitionguid", partitionGuidString, wstring()))
{
partitionGuid = Guid(partitionGuidString);
}
else
{
if (!parser.TryGetString(L"partitionid", partitionIdString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse partitionid parameter");
return false;
}
auto failoverUnit = FABRICSESSION.FabricDispatcher.GetFMFailoverUnitFromParam(partitionIdString);
if (failoverUnit == nullptr)
{
TestSession::WriteError(TraceSource, "Could not find the partition");
return false;
}
partitionGuid = failoverUnit->Id.Guid;
}
TestSession::WriteInfo(TraceSource, "Partition guid: {0}", partitionGuid.ToString());
return true;
}
bool TestFabricClientHealth::ParseReplicaId(CommandLineParser & parser, __inout Common::Guid & partitionGuid, __inout FABRIC_REPLICA_ID & replicaId, __inout FABRIC_INSTANCE_ID & replicaInstanceId)
{
wstring replicaIdString;
if (parser.TryGetString(L"replicaid", replicaIdString, wstring()) ||
parser.TryGetString(L"instanceid", replicaIdString, wstring()))
{
FailoverUnitSnapshotUPtr failoverUnit;
auto replicaPtr = FABRICSESSION.FabricDispatcher.GetReplicaFromParam(replicaIdString, failoverUnit);
if (replicaPtr == nullptr)
{
TestSession::WriteError(TraceSource, "Could not find the replica");
return false;
}
auto & replica = *replicaPtr;
partitionGuid = failoverUnit->Id.Guid;
replicaId = replica.ReplicaId;
// Replace the instance id with the test passed one
wstring replicaInstanceIdString;
if (parser.TryGetString(L"replica.instanceid", replicaInstanceIdString, wstring()))
{
if (!TryParseInt64(replicaInstanceIdString, replicaInstanceId))
{
return false;
}
}
else
{
replicaInstanceId = replica.InstanceId;
}
}
else if (parser.TryGetString(L"replica.id", replicaIdString, wstring()) ||
parser.TryGetString(L"instance.id", replicaIdString, wstring()))
{
if (!TryParseInt64(replicaIdString, replicaId))
{
return false;
}
if (!ParsePartitionId(parser, partitionGuid))
{
return false;
}
wstring replicaInstanceIdString;
if (parser.TryGetString(L"replica.instanceid", replicaInstanceIdString, wstring()))
{
if (!TryParseInt64(replicaInstanceIdString, replicaInstanceId))
{
return false;
}
}
else
{
replicaInstanceId = FABRIC_INVALID_INSTANCE_ID;
}
}
else
{
TestSession::WriteError(TraceSource, "Could not parse replicaid or replica.id parameter");
return false;
}
TestSession::WriteInfo(TraceSource, "Partition Id = {0} Replica Id = {1} replicainstanceId = {2}", partitionGuid.ToString(), replicaId, replicaInstanceId);
return true;
}
bool TestFabricClientHealth::ParseNodeHealthInformation(CommandLineParser & parser, NodeId & nodeId, FABRIC_NODE_INSTANCE_ID & nodeInstanceId, std::wstring & nodeName)
{
wstring nodeIdString;
if (!parser.TryGetString(L"nodeid", nodeIdString, wstring()))
{
TestSession::WriteInfo(TraceSource, "Could not parse nodeid parameter");
return false;
}
nodeId = FABRICSESSION.FabricDispatcher.ParseNodeId(nodeIdString);
if (!parser.TryGetString(L"nodename", nodeName))
{
nodeName = Federation::NodeIdGenerator::GenerateNodeName(nodeId);
}
nodeInstanceId = FABRIC_INVALID_NODE_INSTANCE_ID;
int64 instance;
if (parser.TryGetInt64(L"node.instanceid", instance))
{
nodeInstanceId = static_cast<FABRIC_NODE_INSTANCE_ID>(instance);
}
else
{
auto node = FabricTest::FabricTestSession::GetFabricTestSession().FabricDispatcher.Federation.GetNode(nodeId);
if (node)
{
nodeInstanceId = node->Node->Instance.InstanceId;
}
if (nodeInstanceId == FABRIC_INVALID_NODE_INSTANCE_ID)
{
nodeInstanceId = static_cast<FABRIC_NODE_INSTANCE_ID>(DateTime::Now().Ticks);
}
}
TestSession::WriteInfo(TraceSource, "Node Id = {0} instanceId = {1}", nodeId, nodeInstanceId);
return true;
}
bool TestFabricClientHealth::CreateCommonHealthInformation(
CommandLineParser & parser,
ScopedHeap & heap,
FABRIC_HEALTH_INFORMATION & healthInformation)
{
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
healthInformation.Description = heap.AddString(description);
healthInformation.SourceId = heap.AddString(sourceId);
healthInformation.Property = heap.AddString(property);
healthInformation.TimeToLiveSeconds = static_cast<DWORD>(timeToLiveSeconds);
healthInformation.SequenceNumber = sequenceNumber;
healthInformation.State = healthState;
healthInformation.RemoveWhenExpired = removeWhenExpired;
return true;
}
bool TestFabricClientHealth::CreateClusterHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
auto clusterHealthReport = heap.AddItem<FABRIC_CLUSTER_HEALTH_REPORT>();
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
clusterHealthReport->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = clusterHealthReport.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_CLUSTER;
return success;
}
bool TestFabricClientHealth::CreateReplicaHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionGuid;
if (!ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
return false;
}
auto replicaHealthReport = heap.AddItem<FABRIC_STATEFUL_SERVICE_REPLICA_HEALTH_REPORT>();
replicaHealthReport->PartitionId = partitionGuid.AsGUID();
replicaHealthReport->ReplicaId = replicaId;
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
replicaHealthReport->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = replicaHealthReport.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_STATEFUL_SERVICE_REPLICA;
return success;
}
bool TestFabricClientHealth::CreateInstanceHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionGuid;
if (!ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
return false;
}
auto replicaHealthReport = heap.AddItem<FABRIC_STATELESS_SERVICE_INSTANCE_HEALTH_REPORT>();
replicaHealthReport->PartitionId = partitionGuid.AsGUID();
replicaHealthReport->InstanceId = replicaId;
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
replicaHealthReport->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = replicaHealthReport.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_STATELESS_SERVICE_INSTANCE;
return success;
}
bool TestFabricClientHealth::CreatePartitionHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
Common::Guid partitionGuid;
if (!ParsePartitionId(parser, partitionGuid))
{
return false;
}
TestSession::WriteInfo(TraceSource, "Partition Id = {0}", partitionGuid.ToString());
auto partitionHealthReport = heap.AddItem<FABRIC_PARTITION_HEALTH_REPORT>();
partitionHealthReport->PartitionId = partitionGuid.AsGUID();
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
partitionHealthReport->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = partitionHealthReport.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_PARTITION;
return success;
}
bool TestFabricClientHealth::CreateNodeHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
auto nodeHealthInformation = heap.AddItem<FABRIC_NODE_HEALTH_REPORT>();
nodeHealthInformation->NodeName = heap.AddString(nodeName);
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
nodeHealthInformation->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = nodeHealthInformation.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_NODE;
return success;
}
bool TestFabricClientHealth::CreateDeployedApplicationHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
wstring applicationNameString;
if (!parser.TryGetString(L"appname", applicationNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
auto applicationName = heap.AddString(applicationNameString);
auto deployedApplicationHealthInformation = heap.AddItem<FABRIC_DEPLOYED_APPLICATION_HEALTH_REPORT>();
deployedApplicationHealthInformation->ApplicationName = heap.AddString(applicationName);
deployedApplicationHealthInformation->NodeName = heap.AddString(nodeName);
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
deployedApplicationHealthInformation->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = deployedApplicationHealthInformation.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_DEPLOYED_APPLICATION;
return success;
}
bool TestFabricClientHealth::CreateDeployedServicePackageHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
wstring applicationNameString;
if (!parser.TryGetString(L"appname", applicationNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
wstring serviceManifestNameString;
if (!parser.TryGetString(L"servicemanifestname", serviceManifestNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse servicemanifestname parameter");
return false;
}
auto deployedServicePackageHealthInformation = heap.AddItem<FABRIC_DEPLOYED_SERVICE_PACKAGE_HEALTH_REPORT>();
deployedServicePackageHealthInformation->ApplicationName = heap.AddString(applicationNameString);
deployedServicePackageHealthInformation->ServiceManifestName = heap.AddString(serviceManifestNameString);
deployedServicePackageHealthInformation->NodeName = heap.AddString(nodeName);
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
deployedServicePackageHealthInformation->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = deployedServicePackageHealthInformation.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_DEPLOYED_SERVICE_PACKAGE;
return success;
}
bool TestFabricClientHealth::CreateApplicationHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
wstring applicationNameString;
if (!parser.TryGetString(L"appname", applicationNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
auto applicationHealthInformation = heap.AddItem<FABRIC_APPLICATION_HEALTH_REPORT>();
applicationHealthInformation->ApplicationName = heap.AddString(applicationNameString);
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
applicationHealthInformation->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = applicationHealthInformation.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_APPLICATION;
return success;
}
bool TestFabricClientHealth::CreateServiceHealthReport(CommandLineParser & parser, ScopedHeap & heap, FABRIC_HEALTH_REPORT & healthReport)
{
wstring serviceNameString;
if (!parser.TryGetString(L"servicename", serviceNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse servicename parameter");
return false;
}
auto serviceHealthInformation = heap.AddItem<FABRIC_SERVICE_HEALTH_REPORT>();
serviceHealthInformation->ServiceName = heap.AddString(serviceNameString);
ReferencePointer<FABRIC_HEALTH_INFORMATION> healthInformation = heap.AddItem<FABRIC_HEALTH_INFORMATION>();
bool success = CreateCommonHealthInformation(parser, heap, *healthInformation);
if (!success)
{
return success;
}
serviceHealthInformation->HealthInformation = healthInformation.GetRawPointer();
healthReport.Value = serviceHealthInformation.GetRawPointer();
healthReport.Kind = FABRIC_HEALTH_REPORT_KIND_SERVICE;
return success;
}
bool TestFabricClientHealth::CreateApplicationHealthDeleteReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
wstring appNameString;
if (!parser.TryGetString(L"appname", appNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
FABRIC_INSTANCE_ID instanceId;
if (!parser.TryGetInt64(L"appinstanceid", instanceId, 1))
{
TestSession::WriteError(TraceSource, "Could not parse appinstanceid parameter");
return false;
}
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
wstring sourceId;
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
healthReport = ServiceModel::HealthReport::CreateHealthInformationForDelete(
EntityHealthInformation::CreateApplicationEntityHealthInformation(appNameString, instanceId),
move(sourceId),
sequenceNumber);
return true;
}
bool TestFabricClientHealth::CreateServiceHealthDeleteReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
wstring serviceNameString;
if (!parser.TryGetString(L"servicename", serviceNameString, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse servicename parameter");
return false;
}
FABRIC_INSTANCE_ID instanceId;
if (!parser.TryGetInt64(L"serviceinstanceid", instanceId, 1))
{
TestSession::WriteError(TraceSource, "Could not parse serviceinstanceid parameter");
return false;
}
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
wstring sourceId;
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
healthReport = ServiceModel::HealthReport::CreateHealthInformationForDelete(
EntityHealthInformation::CreateServiceEntityHealthInformation(serviceNameString, instanceId),
move(sourceId),
sequenceNumber);
return true;
}
bool TestFabricClientHealth::CreateReplicaHealthDeleteReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionGuid;
if (!ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
return false;
}
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
wstring sourceId;
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
healthReport = ServiceModel::HealthReport::CreateHealthInformationForDelete(
EntityHealthInformation::CreateStatefulReplicaEntityHealthInformation(partitionGuid, replicaId, replicaInstanceId),
move(sourceId),
sequenceNumber);
return true;
}
bool TestFabricClientHealth::CreateInstanceHealthDeleteReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionGuid;
if (!ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
return false;
}
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
wstring sourceId;
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
healthReport = ServiceModel::HealthReport::CreateHealthInformationForDelete(
EntityHealthInformation::CreateStatelessInstanceEntityHealthInformation(partitionGuid, replicaId),
move(sourceId),
sequenceNumber);
return true;
}
bool TestFabricClientHealth::CreatePartitionHealthDeleteReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
Common::Guid partitionGuid;
if (!ParsePartitionId(parser, partitionGuid))
{
return false;
}
TestSession::WriteInfo(TraceSource, "Partition Id = {0}", partitionGuid.ToString());
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
wstring sourceId;
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
healthReport = ServiceModel::HealthReport::CreateHealthInformationForDelete(
EntityHealthInformation::CreatePartitionEntityHealthInformation(partitionGuid),
move(sourceId),
sequenceNumber);
return true;
}
bool TestFabricClientHealth::CreateNodeHealthDeleteReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
wstring sourceId;
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
healthReport = ServiceModel::HealthReport::CreateHealthInformationForDelete(
EntityHealthInformation::CreateNodeEntityHealthInformation(nodeId.IdValue, nodeName, nodeInstanceId),
move(sourceId),
sequenceNumber);
return true;
}
bool TestFabricClientHealth::CreateDeployedApplicationHealthDeleteReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
FABRIC_INSTANCE_ID appInstanceId;
parser.TryGetInt64(L"appinstanceid", appInstanceId, FABRIC_INVALID_INSTANCE_ID);
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
wstring sourceId;
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
healthReport = ServiceModel::HealthReport::CreateHealthInformationForDelete(
EntityHealthInformation::CreateDeployedApplicationEntityHealthInformation(appName, nodeId.IdValue, nodeName, appInstanceId),
move(sourceId),
sequenceNumber);
return true;
}
bool TestFabricClientHealth::CreateDeployedServicePackageHealthDeleteReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
wstring serviceManifestName;
if (!parser.TryGetString(L"servicemanifestname", serviceManifestName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse servicemanifestname parameter");
return false;
}
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
FABRIC_INSTANCE_ID servicePackageInstanceId;
parser.TryGetInt64(L"servicepackageinstanceid", servicePackageInstanceId, FABRIC_INVALID_INSTANCE_ID);
FABRIC_SEQUENCE_NUMBER sequenceNumber;
parser.TryGetInt64(L"sequencenumber", sequenceNumber, FABRIC_INVALID_SEQUENCE_NUMBER);
wstring sourceId;
parser.TryGetString(L"sourceid", sourceId, L"FabricTest_Source");
wstring servicePackageActivationId;
if (!ParseServicePackageActivationId(parser, servicePackageActivationId))
{
return false;
}
TestSession::WriteInfo(TraceSource, "CreateDeployedServicePackageHealthDeleteReport(): Using servicePackageActivationId=[{0}].", servicePackageActivationId);
healthReport = ServiceModel::HealthReport::CreateHealthInformationForDelete(
EntityHealthInformation::CreateDeployedServicePackageEntityHealthInformation(appName, serviceManifestName, servicePackageActivationId, nodeId.IdValue, nodeName, servicePackageInstanceId),
move(sourceId),
sequenceNumber);
return true;
}
// Internal HealthReport - with attributes
bool TestFabricClientHealth::CreateInternalClusterHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
AttributeList attributeList;
healthReport = HealthReport(
EntityHealthInformation::CreateClusterEntityHealthInformation(),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
bool TestFabricClientHealth::CreateInternalReplicaHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionGuid;
if (!ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
return false;
}
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
AttributeList attributeList;
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
attributeList.AddAttribute(HealthAttributeNames::NodeId, wformatString(nodeId));
attributeList.AddAttribute(HealthAttributeNames::NodeInstanceId, wformatString(nodeInstanceId));
}
healthReport = HealthReport(
EntityHealthInformation::CreateStatefulReplicaEntityHealthInformation(partitionGuid, replicaId, replicaInstanceId),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
bool TestFabricClientHealth::CreateInternalInstanceHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionGuid;
if (!ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
return false;
}
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
AttributeList attributeList;
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
attributeList.AddAttribute(HealthAttributeNames::NodeId, wformatString(nodeId));
attributeList.AddAttribute(HealthAttributeNames::NodeInstanceId, wformatString(nodeInstanceId));
}
healthReport = HealthReport(
EntityHealthInformation::CreateStatelessInstanceEntityHealthInformation(partitionGuid, replicaId),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
bool TestFabricClientHealth::CreateInternalPartitionHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
Common::Guid partitionGuid;
if (!ParsePartitionId(parser, partitionGuid))
{
return false;
}
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
AttributeList attributeList;
wstring serviceName;
if (parser.TryGetString(L"servicename", serviceName, wstring()))
{
attributeList.AddAttribute(HealthAttributeNames::ServiceName, serviceName);
}
healthReport = HealthReport(
EntityHealthInformation::CreatePartitionEntityHealthInformation(partitionGuid),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
bool TestFabricClientHealth::CreateInternalNodeHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
AttributeList attributeList;
wstring ipAddressOrFqdn;
if (parser.TryGetString(L"ipaddressorfqdn", ipAddressOrFqdn, wstring()))
{
attributeList.AddAttribute(HealthAttributeNames::IpAddressOrFqdn, ipAddressOrFqdn);
}
wstring upgradeDomain;
if (parser.TryGetString(L"ud", upgradeDomain))
{
attributeList.AddAttribute(HealthAttributeNames::UpgradeDomain, upgradeDomain);
}
wstring faultDomain;
if (parser.TryGetString(L"fd", faultDomain))
{
attributeList.AddAttribute(HealthAttributeNames::FaultDomain, faultDomain);
}
if (!nodeName.empty())
{
attributeList.AddAttribute(*HealthAttributeNames::NodeName, nodeName);
}
healthReport = HealthReport(
EntityHealthInformation::CreateNodeEntityHealthInformation(nodeId.IdValue, nodeName, nodeInstanceId),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
bool TestFabricClientHealth::CreateInternalDeployedServicePackageHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
wstring serviceManifestName;
if (!parser.TryGetString(L"servicemanifestname", serviceManifestName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse servicemanifestname parameter");
return false;
}
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
FABRIC_INSTANCE_ID servicePackageInstanceId;
parser.TryGetInt64(L"servicepackageinstanceid", servicePackageInstanceId, FABRIC_INVALID_INSTANCE_ID);
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
AttributeList attributeList;
if (!nodeName.empty())
{
attributeList.AddAttribute(*HealthAttributeNames::NodeName, nodeName);
}
if (nodeInstanceId != FABRIC_INVALID_NODE_INSTANCE_ID)
{
attributeList.AddAttribute(*HealthAttributeNames::NodeInstanceId, wformatString(nodeInstanceId));
}
wstring servicePackageActivationId;
if (!ParseServicePackageActivationId(parser, servicePackageActivationId))
{
return false;
}
TestSession::WriteInfo(TraceSource, "CreateInternalDeployedServicePackageHealthReport(): Using servicePackageActivationId=[{0}].", servicePackageActivationId);
healthReport = HealthReport(
EntityHealthInformation::CreateDeployedServicePackageEntityHealthInformation(appName, serviceManifestName, servicePackageActivationId, nodeId.IdValue, nodeName, servicePackageInstanceId),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
bool TestFabricClientHealth::CreateInternalDeployedApplicationHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
FABRIC_INSTANCE_ID applicationInstanceId;
parser.TryGetInt64(L"appinstanceid", applicationInstanceId, FABRIC_INVALID_INSTANCE_ID);
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
AttributeList attributeList;
if (!nodeName.empty())
{
attributeList.AddAttribute(*HealthAttributeNames::NodeName, nodeName);
}
if (nodeInstanceId != FABRIC_INVALID_NODE_INSTANCE_ID)
{
attributeList.AddAttribute(*HealthAttributeNames::NodeInstanceId, wformatString(nodeInstanceId));
}
healthReport = HealthReport(
EntityHealthInformation::CreateDeployedApplicationEntityHealthInformation(appName, nodeId.IdValue, nodeName, applicationInstanceId),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
bool TestFabricClientHealth::CreateInternalApplicationHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse appname parameter");
return false;
}
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
FABRIC_INSTANCE_ID applicationInstanceId;
parser.TryGetInt64(L"appinstanceid", applicationInstanceId, FABRIC_INVALID_INSTANCE_ID);
AttributeList attributeList;
wstring appTypeName;
if (parser.TryGetString(L"apptype", appTypeName, wstring()))
{
attributeList.AddAttribute(HealthAttributeNames::ApplicationTypeName, move(appTypeName));
}
wstring applicationDefinitionKind;
if (parser.TryGetString(L"applicationdefinitionkind", applicationDefinitionKind, wstring()))
{
attributeList.AddAttribute(HealthAttributeNames::ApplicationDefinitionKind, move(applicationDefinitionKind));
}
std::unique_ptr<ApplicationHealthPolicy> healthPolicy = nullptr;
if (ParseApplicationHealthPolicy(parser, healthPolicy) && (healthPolicy != nullptr))
{
wstring healthPolicyString = healthPolicy->ToString();
TestSession::WriteNoise(TraceSource, "Add app policy {0}", healthPolicyString);
attributeList.AddAttribute(HealthAttributeNames::ApplicationHealthPolicy, healthPolicyString);
}
healthReport = HealthReport(
EntityHealthInformation::CreateApplicationEntityHealthInformation(appName, applicationInstanceId),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
bool TestFabricClientHealth::CreateInternalServiceHealthReport(CommandLineParser & parser, __inout ServiceModel::HealthReport & healthReport)
{
wstring serviceName;
if (!parser.TryGetString(L"servicename", serviceName, wstring()))
{
TestSession::WriteError(TraceSource, "Could not parse servicename parameter");
return false;
}
FABRIC_INSTANCE_ID instanceId;
parser.TryGetInt64(L"serviceinstanceid", instanceId, 1);
wstring sourceId;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
FABRIC_HEALTH_STATE healthState;
wstring property;
int64 timeToLiveSeconds;
wstring description;
bool removeWhenExpired;
if (!ParseCommonHealthInformation(parser, sequenceNumber, sourceId, healthState, property, timeToLiveSeconds, description, removeWhenExpired))
{
return false;
}
AttributeList attributeList;
wstring serviceTypeName;
if (parser.TryGetString(L"servicetypename", serviceTypeName, wstring()))
{
attributeList.AddAttribute(HealthAttributeNames::ServiceTypeName, serviceTypeName);
}
wstring appName;
if (parser.TryGetString(L"appname", appName, wstring()))
{
attributeList.AddAttribute(HealthAttributeNames::ApplicationName, appName);
}
healthReport = HealthReport(
EntityHealthInformation::CreateServiceEntityHealthInformation(serviceName, instanceId),
sourceId,
property,
TimeSpan::FromSeconds(static_cast<double>(timeToLiveSeconds)),
healthState,
description,
sequenceNumber,
removeWhenExpired,
move(attributeList));
return true;
}
// Parse health policies
bool TestFabricClientHealth::ParseClusterHealthPolicy(CommandLineParser & parser, __inout std::unique_ptr<ClusterHealthPolicy> & clusterHealthPolicy)
{
wstring healthPolicy;
if (!parser.TryGetString(L"clusterpolicy", healthPolicy, wstring()))
{
if (parser.TryGetString(L"jsonpolicy", healthPolicy))
{
clusterHealthPolicy = make_unique<ClusterHealthPolicy>();
auto error = ClusterHealthPolicy::FromString(healthPolicy, *clusterHealthPolicy);
TestSession::FailTestIfNot(error.IsSuccess(), "Failed to parse cluster health policy string {0} with {1}", healthPolicy, error);
}
return true;
}
vector<wstring> tokens;
StringUtility::Split<wstring>(healthPolicy, tokens, L",");
if (tokens.size() == 0 || tokens.size() > 4)
{
TestSession::WriteError(TraceSource, "Could not parse nodepolicy parameter - too many arguments {0}", healthPolicy);
return false;
}
bool considerWarningAsError = false;
int maxUnhealthyNodes = 0;
int maxUnhealthyApplications = 0;
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
if (StringUtility::AreEqualCaseInsensitive(*it, L"warningaserror"))
{
considerWarningAsError = true;
}
else if (StringUtility::StartsWithCaseInsensitive<wstring>(*it, L"maxunhealthynodespercent"))
{
vector<wstring> innerTokens;
StringUtility::Split<wstring>(*it, innerTokens, L":");
if (innerTokens.size() != 2u)
{
TestSession::WriteError(TraceSource, "Could not parse maxunhealthynodespercent in nodepolicy parameter - {0}", healthPolicy);
return false;
}
maxUnhealthyNodes = Int32_Parse(innerTokens[1]);
}
else if (StringUtility::StartsWithCaseInsensitive<wstring>(*it, L"maxunhealthyappspercent"))
{
vector<wstring> innerTokens;
StringUtility::Split<wstring>(*it, innerTokens, L":");
if (innerTokens.size() != 2u)
{
TestSession::WriteError(TraceSource, "Could not parse maxunhealthyappspercent in nodepolicy parameter - {0}", healthPolicy);
return false;
}
maxUnhealthyApplications = Int32_Parse(innerTokens[1]);
}
else
{
TestSession::WriteError(TraceSource, "Unrecognized input {0} in {1}", *it, healthPolicy);
return false;
}
}
BYTE maxPercentUnhealthyNodes = static_cast<BYTE>(maxUnhealthyNodes);
BYTE maxPercentUnhealthyApplications = static_cast<BYTE>(maxUnhealthyApplications);
clusterHealthPolicy = make_unique<ClusterHealthPolicy>(considerWarningAsError, maxPercentUnhealthyNodes, maxPercentUnhealthyApplications);
return true;
}
bool TestFabricClientHealth::ParseApplicationHealthPolicy(CommandLineParser & parser, __inout std::unique_ptr<ApplicationHealthPolicy> & applicationHealthPolicy)
{
wstring healthPolicy;
if (!parser.TryGetString(L"apppolicy", healthPolicy, wstring()))
{
return true;
}
return ParseApplicationHealthPolicy(healthPolicy, applicationHealthPolicy);
}
bool TestFabricClientHealth::ParseApplicationHealthPolicy(std::wstring const & healthPolicy, __inout std::unique_ptr<ApplicationHealthPolicy> & applicationHealthPolicy)
{
if (healthPolicy == L"default")
{
// Use default policy
applicationHealthPolicy = make_unique<ApplicationHealthPolicy>();
return true;
}
vector<wstring> tokens;
StringUtility::Split<wstring>(healthPolicy, tokens, L",");
if (tokens.size() == 0 || tokens.size() > 5)
{
TestSession::WriteError(TraceSource, "Could not parse apppolicy parameter - invalid argument count {0}", healthPolicy);
return false;
}
bool considerWarningAsError = false;
int maxUnhealthyPartitions = 0;
int maxUnhealthyReplicas = 0;
int maxUnhealthyServices = 0;
int maxUnhealthyDeployedApps = 0;
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
if (StringUtility::AreEqualCaseInsensitive(*it, L"warningaserror"))
{
considerWarningAsError = true;
}
else if (StringUtility::StartsWithCaseInsensitive<wstring>(*it, L"maxunhealthyreplicaspercent"))
{
vector<wstring> innerTokens;
StringUtility::Split<wstring>(*it, innerTokens, L":");
if (innerTokens.size() != 2u)
{
TestSession::WriteError(TraceSource, "Could not parse maxunhealthyreplicaspercent in apppolicy parameter - {0}", healthPolicy);
return false;
}
maxUnhealthyReplicas = Int32_Parse(innerTokens[1]);
}
else if (StringUtility::StartsWithCaseInsensitive<wstring>(*it, L"maxunhealthypartitionspercent"))
{
vector<wstring> innerTokens;
StringUtility::Split<wstring>(*it, innerTokens, L":");
if (innerTokens.size() != 2u)
{
TestSession::WriteError(TraceSource, "Could not parse maxunhealthypartitionspercent in apppolicy parameter - {0}", healthPolicy);
return false;
}
maxUnhealthyPartitions = Int32_Parse(innerTokens[1]);
}
else if (StringUtility::StartsWithCaseInsensitive<wstring>(*it, L"maxunhealthyservicespercent"))
{
vector<wstring> innerTokens;
StringUtility::Split<wstring>(*it, innerTokens, L":");
if (innerTokens.size() != 2u)
{
TestSession::WriteError(TraceSource, "Could not parse maxunhealthyservicespercent in apppolicy parameter - {0}", healthPolicy);
return false;
}
maxUnhealthyServices = Int32_Parse(innerTokens[1]);
}
else if (StringUtility::StartsWithCaseInsensitive<wstring>(*it, L"maxunhealthydeployedapplicationspercent"))
{
vector<wstring> innerTokens;
StringUtility::Split<wstring>(*it, innerTokens, L":");
if (innerTokens.size() != 2u)
{
TestSession::WriteError(TraceSource, "Could not parse maxunhealthydeployedapplicationspercent in applicationpolicy parameter - {0}", healthPolicy);
return false;
}
maxUnhealthyDeployedApps = Int32_Parse(innerTokens[1]);
}
else
{
TestSession::WriteError(TraceSource, "Unrecognized input {0} in {1}", *it, healthPolicy);
return false;
}
}
BYTE maxPercentUnhealthyServices = static_cast<BYTE>(maxUnhealthyServices);
BYTE maxPercentUnhealthyPartitionsPerService = static_cast<BYTE>(maxUnhealthyPartitions);
BYTE maxPercentUnhealthyDeployedApplications = static_cast<BYTE>(maxUnhealthyDeployedApps);
BYTE maxPercentUnhealthyReplicasPerPartition = static_cast<BYTE>(maxUnhealthyReplicas);
ServiceTypeHealthPolicy defaultServiceType(maxPercentUnhealthyServices, maxPercentUnhealthyPartitionsPerService, maxPercentUnhealthyReplicasPerPartition);
applicationHealthPolicy = make_unique<ApplicationHealthPolicy>(
considerWarningAsError, maxPercentUnhealthyDeployedApplications, defaultServiceType, ServiceTypeHealthPolicyMap());
return true;
}
bool TestFabricClientHealth::ValidateClusterHealthChunk(CommandLineParser & parser, FABRIC_CLUSTER_HEALTH_CHUNK const & publicClusterStateChunk, bool requiresValidation)
{
ClusterHealthChunk clusterHealthChunk;
auto error = clusterHealthChunk.FromPublicApi(publicClusterStateChunk);
TestSession::FailTestIfNot(error.IsSuccess(), "GetClusterHealthChunk: ClusterHealthChunk.FromPublicApi failed with unexpected error = {0}", error);
bool success = true;
TestSession::WriteInfo(TraceSource, "GetClusterHealthChunk returned {0}", clusterHealthChunk);
wstring expectedHealthStateString;
if (parser.TryGetString(L"expectedhealthstate", expectedHealthStateString))
{
FABRIC_HEALTH_STATE expectedHealthState = GetHealthState(expectedHealthStateString);
if (expectedHealthState != clusterHealthChunk.HealthState)
{
TestSession::WriteInfo(
TraceSource,
"Aggregated health state does not match expected:{0} actual:{1}",
expectedHealthStateString,
GetHealthStateString(clusterHealthChunk.HealthState));
return false;
}
}
wstring expectedAppsString;
map<wstring, vector<wstring>> expectedAppChunks;
if (parser.TryGetString(L"expectedapps", expectedAppsString))
{
vector<wstring> appInfos;
StringUtility::Split<wstring>(expectedAppsString, appInfos, L";");
for (auto const & appInfo : appInfos)
{
vector<wstring> appTokens;
StringUtility::Split<wstring>(appInfo, appTokens, L",", false /*skipEmptyItems*/);
TestSession::FailTestIf(appTokens.size() != 3, "Error parsing expectedapps {0}: {1} should contain app name, app type and health state", expectedAppsString, appInfo);
expectedAppChunks.insert(pair<wstring, vector<wstring>>(appTokens[0], appTokens));
}
}
HealthStateCountMap resultsPerChildrenType;
HealthStateCount nodeResults;
for (auto const & node : clusterHealthChunk.NodeHealthStateChunks.Items)
{
TestSession::FailTestIf(node.NodeName.empty(), "Node name should be set in node health state chunk");
nodeResults.Add(node.HealthState);
}
ULONG nodeTotal = nodeResults.GetTotal();
TestSession::FailTestIf(clusterHealthChunk.NodeHealthStateChunks.TotalCount < nodeTotal, "Node TotalCount {0} should be >= included item count {1}", clusterHealthChunk.NodeHealthStateChunks.TotalCount, nodeTotal);
TestSession::FailTestIfNot(clusterHealthChunk.NodeHealthStateChunks.Count == nodeTotal, "Node Count {0} should be == included item count {1}", clusterHealthChunk.NodeHealthStateChunks.TotalCount, nodeTotal);
HealthStateCount appResults;
HealthStateCount serviceResults;
HealthStateCount partitionResults;
HealthStateCount replicaResults;
HealthStateCount deployedAppResults;
HealthStateCount deployedServicePackageResults;
size_t verifiedAppChunks = 0;
for (auto const & app : clusterHealthChunk.ApplicationHealthStateChunks.Items)
{
TestSession::FailTestIf(app.ApplicationName.empty(), "Application name should be set in app health state chunk {0}", app);
auto itApp = expectedAppChunks.find(app.ApplicationName);
if (itApp != expectedAppChunks.cend())
{
if (app.ApplicationTypeName != itApp->second[1])
{
TestSession::WriteInfo(TraceSource, "App type name mismatch: received {0}, expected {1}", app, itApp->second[1]);
return false;
}
if (app.HealthState != GetHealthState(itApp->second[2]))
{
TestSession::WriteInfo(TraceSource, "App health state mismatch: received {0}, expected {1}", app, itApp->second[2]);
return false;
}
++verifiedAppChunks;
}
else if (!app.ApplicationName.empty() && app.ApplicationName != SystemServiceApplicationNameHelper::SystemServiceApplicationName)
{
TestSession::FailTestIf(app.ApplicationTypeName.empty(), "Application type name should be set in app health state chunk {0}", app);
}
appResults.Add(app.HealthState);
size_t serviceCount = 0;
for (auto const & service : app.ServiceHealthStateChunks.Items)
{
TestSession::FailTestIf(service.ServiceName.empty(), "Service name should be set in service health state chunk {0}", service);
serviceResults.Add(service.HealthState);
serviceCount++;
size_t partitionCount = 0;
for (auto const & partition : service.PartitionHealthStateChunks.Items)
{
TestSession::FailTestIf(partition.PartitionId == Guid::Empty(), "Partition id should be set in partition health state chunk {0}", partition);
partitionResults.Add(partition.HealthState);
++partitionCount;
size_t replicaCount = 0;
for (auto const & replica : partition.ReplicaHealthStateChunks.Items)
{
TestSession::FailTestIf(replica.ReplicaOrInstanceId == FABRIC_INVALID_REPLICA_ID, "Replica id should be set in replica health state chunk {0}", replica);
replicaResults.Add(replica.HealthState);
++replicaCount;
}
TestSession::FailTestIfNot(
partition.ReplicaHealthStateChunks.Count == replicaCount && partition.ReplicaHealthStateChunks.TotalCount >= replicaCount,
"Partition {0}: Count={1}, TotalCount={2}, included items {3}",
partition.PartitionId,
partition.ReplicaHealthStateChunks.Count,
partition.ReplicaHealthStateChunks.TotalCount,
replicaCount);
}
TestSession::FailTestIfNot(
service.PartitionHealthStateChunks.Count == partitionCount && service.PartitionHealthStateChunks.TotalCount >= partitionCount,
"Service {0}: Count={1}, TotalCount={2}, included items {3}",
service.ServiceName,
service.PartitionHealthStateChunks.Count,
service.PartitionHealthStateChunks.TotalCount,
partitionCount);
}
TestSession::FailTestIfNot(
app.ServiceHealthStateChunks.Count == serviceCount && app.ServiceHealthStateChunks.TotalCount >= serviceCount,
"App services {0}: Count={1}, TotalCount={2}, included items {3}",
app.ApplicationName,
app.ServiceHealthStateChunks.Count,
app.ServiceHealthStateChunks.TotalCount,
serviceCount);
size_t daCount = 0;
for (auto const & deployedApp : app.DeployedApplicationHealthStateChunks.Items)
{
TestSession::FailTestIf(deployedApp.NodeName.empty(), "Node name should be set in deployed app health state chunk {0}", deployedApp);
deployedAppResults.Add(deployedApp.HealthState);
daCount++;
size_t dspCount = 0;
for (auto const & dsp : deployedApp.DeployedServicePackageHealthStateChunks.Items)
{
TestSession::FailTestIf(dsp.ServiceManifestName.empty(), "Service manifest name should be set in deployed service package health state chunk {0}", dsp);
deployedServicePackageResults.Add(dsp.HealthState);
++dspCount;
}
if (deployedApp.DeployedServicePackageHealthStateChunks.Count != dspCount || deployedApp.DeployedServicePackageHealthStateChunks.TotalCount < dspCount)
{
TestSession::FailTest(
"{0}+{1}: Count={2}, TotalCount={3}, included items {4}",
app.ApplicationName,
deployedApp.NodeName,
deployedApp.DeployedServicePackageHealthStateChunks.Count,
deployedApp.DeployedServicePackageHealthStateChunks.TotalCount,
dspCount);
}
}
TestSession::FailTestIfNot(
app.DeployedApplicationHealthStateChunks.Count == daCount && app.DeployedApplicationHealthStateChunks.TotalCount >= daCount,
"App deployed apps {0}: Count={1}, TotalCount={2}, included items {3}",
app.ApplicationName,
app.DeployedApplicationHealthStateChunks.Count,
app.DeployedApplicationHealthStateChunks.TotalCount,
daCount);
}
if (verifiedAppChunks != expectedAppChunks.size())
{
TestSession::WriteInfo(TraceSource, "Not all app chunks were verified against expectedApps: verified {0}, expected {1}", verifiedAppChunks, expectedAppsString);
return false;
}
ULONG appTotal = appResults.GetTotal();
TestSession::FailTestIfNot(clusterHealthChunk.ApplicationHealthStateChunks.TotalCount >= appTotal, "Application TotalCount {0} should be >= included item count {1}", clusterHealthChunk.ApplicationHealthStateChunks.TotalCount, appTotal);
TestSession::FailTestIfNot(clusterHealthChunk.ApplicationHealthStateChunks.Count == appTotal, "Application Count {0} should be == included item count {1}", clusterHealthChunk.ApplicationHealthStateChunks.TotalCount, appTotal);
resultsPerChildrenType.insert(make_pair(EntityKind::Node, move(nodeResults)));
resultsPerChildrenType.insert(make_pair(EntityKind::Application, move(appResults)));
resultsPerChildrenType.insert(make_pair(EntityKind::Service, move(serviceResults)));
resultsPerChildrenType.insert(make_pair(EntityKind::Partition, move(partitionResults)));
resultsPerChildrenType.insert(make_pair(EntityKind::Replica, move(replicaResults)));
resultsPerChildrenType.insert(make_pair(EntityKind::DeployedApplication, move(deployedAppResults)));
resultsPerChildrenType.insert(make_pair(EntityKind::DeployedServicePackage, move(deployedServicePackageResults)));
if (!VerifyAggregatedHealthStates(parser, resultsPerChildrenType))
{
success = false;
}
if (!success || !requiresValidation)
{
wstring trace(L"Cluster: ");
StringWriter writer(trace);
writer.WriteLine(GetHealthStateString(clusterHealthChunk.HealthState));
if (!clusterHealthChunk.ApplicationHealthStateChunks.Items.empty())
{
writer.WriteLine("Application Children:");
for (auto const & app : clusterHealthChunk.ApplicationHealthStateChunks.Items)
{
writer.WriteLine("\t{0}", app);
for (auto const & service : app.ServiceHealthStateChunks.Items)
{
writer.WriteLine("\t\t{0}", service);
for (auto const & partition : service.PartitionHealthStateChunks.Items)
{
writer.WriteLine("\t\t\t{0}", partition);
for (auto const & replica : partition.ReplicaHealthStateChunks.Items)
{
writer.WriteLine("\t\t\t\t{0}", replica);
}
}
}
for (auto const & deployedApp : app.DeployedApplicationHealthStateChunks.Items)
{
writer.WriteLine("\t\t{0}", deployedApp);
for (auto const & dsp : deployedApp.DeployedServicePackageHealthStateChunks.Items)
{
writer.WriteLine("\t\t\t\t{0}", dsp);
}
}
}
}
if (!clusterHealthChunk.NodeHealthStateChunks.Items.empty())
{
writer.WriteLine("Node Children:");
for (auto const & node : clusterHealthChunk.NodeHealthStateChunks.Items)
{
writer.WriteLine("\t{0}", node);
}
}
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ValidateClusterHealth(CommandLineParser & parser, FABRIC_CLUSTER_HEALTH const & publicClusterHealth, bool expectEmpty, bool requiresValidation)
{
ClusterHealth clusterHealth;
auto error = clusterHealth.FromPublicApi(publicClusterHealth);
TestSession::FailTestIfNot(error.IsSuccess(), "GetClusterHealth: ClusterHealth.FromPublicApi failed with unexpected error = {0}", error);
bool success = true;
wstring expectedHealthStateString;
if (requiresValidation)
{
TestSession::WriteInfo(TraceSource, "GetClusterHealth returned {0}", clusterHealth);
if (!VerifyEntityEventsAndHealthState(parser, false, clusterHealth.Events, clusterHealth.AggregatedHealthState, clusterHealth.UnhealthyEvaluations, expectEmpty))
{
TestSession::WriteWarning(TraceSource, "GetClusterHealth events and health state verification failed");
success = false;
}
HealthStateCountMap resultsPerChildrenType;
HealthStateCount appResults;
for (auto it = clusterHealth.ApplicationsAggregatedHealthStates.begin(); it != clusterHealth.ApplicationsAggregatedHealthStates.end(); ++it)
{
appResults.Add(it->AggregatedHealthState);
}
resultsPerChildrenType.insert(make_pair(EntityKind::Application, move(appResults)));
HealthStateCount nodeResults;
for (auto it = clusterHealth.NodesAggregatedHealthStates.begin(); it != clusterHealth.NodesAggregatedHealthStates.end(); ++it)
{
nodeResults.Add(it->AggregatedHealthState);
}
resultsPerChildrenType.insert(make_pair(EntityKind::Node, move(nodeResults)));
if (!VerifyAggregatedHealthStates(parser, resultsPerChildrenType))
{
success = false;
}
if (!CheckHealthStats(parser, clusterHealth.HealthStats))
{
success = false;
}
}
if (!success || !requiresValidation)
{
wstring trace = GetEntityHealthBaseDetails(clusterHealth);
StringWriter writer(trace);
writer.WriteLine("Application Children:");
for (auto it = clusterHealth.ApplicationsAggregatedHealthStates.begin(); it != clusterHealth.ApplicationsAggregatedHealthStates.end(); ++it)
{
writer.WriteLine("\t{0}", *it);
}
writer.WriteLine("Node Children:");
for (auto it = clusterHealth.NodesAggregatedHealthStates.begin(); it != clusterHealth.NodesAggregatedHealthStates.end(); ++it)
{
writer.WriteLine("\t{0}", *it);
}
if (clusterHealth.HealthStats)
{
writer.WriteLine("\nStats:{0}", *clusterHealth.HealthStats);
}
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ValidateNodeHealth(CommandLineParser & parser, FABRIC_NODE_HEALTH const & publicNodeHealth, std::wstring const & nodeName, bool expectEmpty, bool requiresValidation)
{
NodeHealth nodeHealth;
auto error = nodeHealth.FromPublicApi(publicNodeHealth);
TestSession::FailTestIfNot(error.IsSuccess(), "GetNodeHealth: NodeHealth.FromPublicApi failed with unexpected error = {0}", error);
if (nodeHealth.NodeName.empty())
{
TestSession::WriteInfo(TraceSource, "GetNodeHealth returned empty node name: {0}", nodeHealth);
// FM health report is not yet received, so node name is not populated
return false;
}
TestSession::FailTestIf(nodeHealth.NodeName != nodeName, "GetNodeHealth entity information verification failed: expected nodeName {0}, received {1}", nodeName, nodeHealth.NodeName);
bool success = true;
if (requiresValidation)
{
TestSession::WriteInfo(TraceSource, "GetNodeHealth {0} returned {1}", nodeHealth.NodeName, nodeHealth);
if (!VerifyEntityEventsAndHealthState(parser, true, nodeHealth.Events, nodeHealth.AggregatedHealthState, nodeHealth.UnhealthyEvaluations, expectEmpty))
{
TestSession::WriteWarning(TraceSource, "GetNodeHealth events and health state verification failed");
success = false;
}
}
if (!success || !requiresValidation)
{
wstring trace = GetEntityHealthBaseDetails(nodeHealth);
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ValidateReplicaHealth(CommandLineParser & parser, FABRIC_REPLICA_HEALTH const & publicReplicaHealth, Common::Guid const & partitionGuid, FABRIC_REPLICA_ID replicaId, bool expectEmpty, bool requiresValidation)
{
ReplicaHealth replicaHealth;
auto error = replicaHealth.FromPublicApi(publicReplicaHealth);
TestSession::FailTestIfNot(error.IsSuccess(), "GetReplicaHealth: ReplicaHealth.FromPublicApi failed with unexpected error = {0}", error);
TestSession::FailTestIf(replicaHealth.ReplicaId != replicaId, "GetReplicaHealth entity information verification failed: expected replicaId {0}, received {1}", replicaId, replicaHealth.ReplicaId);
TestSession::FailTestIf(replicaHealth.PartitionId != partitionGuid, "GetPartitionHealth entity information verification failed: expected partitionId {0}, received {1}", partitionGuid, replicaHealth.PartitionId);
bool success = true;
if (requiresValidation)
{
TestSession::WriteNoise(TraceSource, "GetReplicaHealth {0}+{1} returned {2}", replicaHealth.PartitionId, replicaHealth.ReplicaId, replicaHealth);
if (!VerifyEntityEventsAndHealthState(parser, true, replicaHealth.Events, replicaHealth.AggregatedHealthState, replicaHealth.UnhealthyEvaluations, expectEmpty))
{
TestSession::WriteWarning(TraceSource, "GetReplicaHealth events and health state verification failed");
success = false;
}
}
if (!success || !requiresValidation)
{
wstring trace = GetEntityHealthBaseDetails(replicaHealth);
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ValidatePartitionHealth(CommandLineParser & parser, FABRIC_PARTITION_HEALTH const & publicPartitionHealth, Common::Guid const & partitionGuid, bool expectEmpty, bool requiresValidation)
{
PartitionHealth partitionHealth;
auto error = partitionHealth.FromPublicApi(publicPartitionHealth);
TestSession::FailTestIfNot(error.IsSuccess(), "GetPartitionHealth: PartitionHealth.FromPublicApi failed with unexpected error = {0}", error);
TestSession::FailTestIf(partitionHealth.PartitionId != partitionGuid, "GetPartitionHealth entity information verification failed: expected partitionId {0}, received {1}", partitionGuid, partitionHealth.PartitionId);
bool success = true;
if (requiresValidation)
{
TestSession::WriteNoise(TraceSource, "GetPartitionHealth {0} returned {1}", partitionHealth.PartitionId, partitionHealth);
if (!VerifyEntityEventsAndHealthState(parser, true, partitionHealth.Events, partitionHealth.AggregatedHealthState, partitionHealth.UnhealthyEvaluations, expectEmpty))
{
TestSession::WriteWarning(TraceSource, "GetPartitionHealth events and health state verification failed");
success = false;
}
HealthStateCount results;
for (auto it = partitionHealth.ReplicasAggregatedHealthStates.begin(); it != partitionHealth.ReplicasAggregatedHealthStates.end(); ++it)
{
results.Add(it->AggregatedHealthState);
}
HealthStateCountMap resultsMap;
resultsMap.insert(make_pair(EntityKind::Replica, move(results)));
if (!VerifyAggregatedHealthStates(parser, resultsMap))
{
success = false;
}
if (!CheckHealthStats(parser, partitionHealth.HealthStats))
{
success = false;
}
}
if (!success || !requiresValidation)
{
wstring trace = GetEntityHealthBaseDetails(partitionHealth);
StringWriter writer(trace);
writer.WriteLine("Children:");
for (auto it = partitionHealth.ReplicasAggregatedHealthStates.begin(); it != partitionHealth.ReplicasAggregatedHealthStates.end(); ++it)
{
writer.WriteLine("\t{0}", *it);
}
if (partitionHealth.HealthStats)
{
writer.WriteLine("\nStats:{0}", *partitionHealth.HealthStats);
}
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ValidateDeployedServicePackageHealth(
CommandLineParser & parser,
FABRIC_DEPLOYED_SERVICE_PACKAGE_HEALTH const & publicDeployedServicePackageHealth,
std::wstring const & appName,
std::wstring const & serviceManifestName,
std::wstring const & servicePackageActivationId,
std::wstring const & nodeName,
bool expectEmpty,
bool requiresValidation)
{
DeployedServicePackageHealth deployedServicePackageHealth;
auto error = deployedServicePackageHealth.FromPublicApi(publicDeployedServicePackageHealth);
TestSession::FailTestIfNot(error.IsSuccess(), "GetDeployedServicePackageHealth: DeployedServicePackageHealth.FromPublicApi failed with unexpected error = {0}", error);
TestSession::FailTestIf(deployedServicePackageHealth.ApplicationName != appName, "GetDeployedServicePackageHealth entity information verification failed: expected appName {0}, received {1}", appName, deployedServicePackageHealth.ApplicationName);
TestSession::FailTestIf(deployedServicePackageHealth.ServiceManifestName != serviceManifestName, "GetDeployedServicePackageHealth entity information verification failed: expected deployedServiceManifestName {0}, received {1}", serviceManifestName, deployedServicePackageHealth.ServiceManifestName);
TestSession::FailTestIf(
deployedServicePackageHealth.ServicePackageActivationId != servicePackageActivationId,
"GetDeployedServicePackageHealth entity information verification failed: expected ServicePackageActivationId={0}, received={1}.",
servicePackageActivationId,
deployedServicePackageHealth.ServicePackageActivationId);
if (deployedServicePackageHealth.NodeName.empty())
{
TestSession::WriteInfo(TraceSource, "GetDeployedServicePackageHealth returned empty node name: {0}", deployedServicePackageHealth);
// FM health report is not yet received, so node name is not populated
return false;
}
TestSession::FailTestIf(deployedServicePackageHealth.NodeName != nodeName, "GetDeployedServicePackageHealth entity information verification failed: expected nodeName {0}, received {1}", nodeName, deployedServicePackageHealth.NodeName);
bool success = true;
if (requiresValidation)
{
TestSession::WriteInfo(TraceSource, "GetDeployedServicePackageHealth on node {0} returned {1}", deployedServicePackageHealth.NodeName, deployedServicePackageHealth);
if (!VerifyEntityEventsAndHealthState(parser, true, deployedServicePackageHealth.Events, deployedServicePackageHealth.AggregatedHealthState, deployedServicePackageHealth.UnhealthyEvaluations, expectEmpty))
{
TestSession::WriteWarning(TraceSource, "GetDeployedServicePackageHealth events and health state verification failed");
success = false;
}
}
if (!success || !requiresValidation)
{
wstring trace = GetEntityHealthBaseDetails(deployedServicePackageHealth);
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ValidateDeployedApplicationHealth(CommandLineParser & parser, FABRIC_DEPLOYED_APPLICATION_HEALTH const & publicDeployedApplicationHealth, std::wstring const & appName, std::wstring const & nodeName, bool expectEmpty, bool requiresValidation)
{
DeployedApplicationHealth deployedApplicationHealth;
auto error = deployedApplicationHealth.FromPublicApi(publicDeployedApplicationHealth);
TestSession::FailTestIfNot(error.IsSuccess(), "GetDeployedApplicationHealth: DeployedApplicationHealth.FromPublicApi failed with unexpected error = {0}", error);
TestSession::FailTestIf(deployedApplicationHealth.ApplicationName != appName, "GetDeployedApplicationHealth entity information verification failed: expected appName {0}, received {1}", appName, deployedApplicationHealth.ApplicationName);
if (deployedApplicationHealth.NodeName.empty())
{
TestSession::WriteInfo(TraceSource, "GetDeployedApplicationHealth returned empty node name: {0}", deployedApplicationHealth);
return false;
}
TestSession::FailTestIf(deployedApplicationHealth.NodeName != nodeName, "GetDeployedApplicationHealth entity information verification failed: expected nodeName {0}, received {1}", nodeName, deployedApplicationHealth.NodeName);
bool success = true;
if (requiresValidation)
{
TestSession::WriteInfo(TraceSource, "GetDeployedApplicationHealth on node {0} returned {1}", deployedApplicationHealth.NodeName, deployedApplicationHealth);
if (!VerifyEntityEventsAndHealthState(parser, false, deployedApplicationHealth.Events, deployedApplicationHealth.AggregatedHealthState, deployedApplicationHealth.UnhealthyEvaluations, expectEmpty))
{
TestSession::WriteWarning(TraceSource, "GetDeployedApplicationHealth events and health state verification failed");
success = false;
}
HealthStateCount results;
for (auto it = deployedApplicationHealth.DeployedServicePackagesAggregatedHealthStates.begin(); it != deployedApplicationHealth.DeployedServicePackagesAggregatedHealthStates.end(); ++it)
{
results.Add(it->AggregatedHealthState);
}
HealthStateCountMap resultsMap;
resultsMap.insert(make_pair(EntityKind::DeployedServicePackage, move(results)));
if (!VerifyAggregatedHealthStates(parser, resultsMap))
{
success = false;
}
if (!CheckHealthStats(parser, deployedApplicationHealth.HealthStats))
{
success = false;
}
}
if (!success || !requiresValidation)
{
wstring trace = GetEntityHealthBaseDetails(deployedApplicationHealth);
StringWriter writer(trace);
writer.WriteLine("Children:");
for (auto it = deployedApplicationHealth.DeployedServicePackagesAggregatedHealthStates.begin(); it != deployedApplicationHealth.DeployedServicePackagesAggregatedHealthStates.end(); ++it)
{
writer.WriteLine("\t{0}", *it);
}
if (deployedApplicationHealth.HealthStats)
{
writer.WriteLine("\nStats:{0}", deployedApplicationHealth.HealthStats);
}
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ValidateServiceHealth(CommandLineParser & parser, FABRIC_SERVICE_HEALTH const & publicServiceHealth, std::wstring const & serviceName, bool expectEmpty, bool requiresValidation)
{
ServiceHealth serviceHealth;
auto error = serviceHealth.FromPublicApi(publicServiceHealth);
TestSession::FailTestIfNot(error.IsSuccess(), "GetServiceHealth: ServiceHealth.FromPublicApi failed with unexpected error = {0}", error);
TestSession::FailTestIf(serviceHealth.ServiceName != serviceName, "GetServiceHealth entity information verification failed: expected serviceName {0}, received {1}", serviceName, serviceHealth.ServiceName);
bool success = true;
if (requiresValidation)
{
TestSession::WriteInfo(TraceSource, "GetServiceHealth {0} returned {1}", serviceHealth.ServiceName, serviceHealth);
if (!VerifyEntityEventsAndHealthState(parser, false, serviceHealth.Events, serviceHealth.AggregatedHealthState, serviceHealth.UnhealthyEvaluations, expectEmpty))
{
TestSession::WriteWarning(TraceSource, "GetServiceHealth events and health state verification failed");
success = false;
}
HealthStateCount results;
for (auto it = serviceHealth.PartitionsAggregatedHealthStates.begin(); it != serviceHealth.PartitionsAggregatedHealthStates.end(); ++it)
{
results.Add(it->AggregatedHealthState);
}
HealthStateCountMap resultsMap;
resultsMap.insert(make_pair(EntityKind::Partition, move(results)));
if (!VerifyAggregatedHealthStates(parser, resultsMap))
{
success = false;
}
if (!CheckHealthStats(parser, serviceHealth.HealthStats))
{
success = false;
}
}
if (!success || !requiresValidation)
{
wstring trace = GetEntityHealthBaseDetails(serviceHealth);
StringWriter writer(trace);
writer.WriteLine("Children:");
for (auto it = serviceHealth.PartitionsAggregatedHealthStates.begin(); it != serviceHealth.PartitionsAggregatedHealthStates.end(); ++it)
{
writer.WriteLine("\t{0}", *it);
}
if (serviceHealth.HealthStats)
{
writer.WriteLine("\nStats:{0}", serviceHealth.HealthStats);
}
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ValidateApplicationHealth(CommandLineParser & parser, FABRIC_APPLICATION_HEALTH const & publicApplicationHealth, std::wstring const & applicationName, bool expectEmpty, bool requiresValidation)
{
ApplicationHealth applicationHealth;
auto error = applicationHealth.FromPublicApi(publicApplicationHealth);
TestSession::FailTestIfNot(error.IsSuccess(), "GetApplicationHealth: ApplicationHealth.FromPublicApi failed with unexpected error = {0}", error);
TestSession::FailTestIf(applicationHealth.ApplicationName != applicationName, "GetApplicationHealth entity information verification failed: expected applicationName {0}, received {1}", applicationName, applicationHealth.ApplicationName);
bool success = true;
if (requiresValidation)
{
TestSession::WriteInfo(TraceSource, "GetApplicationHealth for {0} returned {1}", applicationHealth.ApplicationName, applicationHealth);
if (!VerifyEntityEventsAndHealthState(parser, false, applicationHealth.Events, applicationHealth.AggregatedHealthState, applicationHealth.UnhealthyEvaluations, expectEmpty))
{
TestSession::WriteWarning(TraceSource, "GetApplicationHealth events and health state verification failed");
success = false;
}
HealthStateCountMap resultsMap;
HealthStateCount serviceResults;
for (auto it = applicationHealth.ServicesAggregatedHealthStates.begin(); it != applicationHealth.ServicesAggregatedHealthStates.end(); ++it)
{
serviceResults.Add(it->AggregatedHealthState);
}
resultsMap.insert(make_pair(EntityKind::Service, move(serviceResults)));
HealthStateCount daResults;
for (auto it = applicationHealth.DeployedApplicationsAggregatedHealthStates.begin(); it != applicationHealth.DeployedApplicationsAggregatedHealthStates.end(); ++it)
{
daResults.Add(it->AggregatedHealthState);
}
resultsMap.insert(make_pair(EntityKind::DeployedApplication, move(daResults)));
if (!VerifyAggregatedHealthStates(parser, resultsMap))
{
success = false;
}
if (!CheckHealthStats(parser, applicationHealth.HealthStats))
{
success = false;
}
}
if (!success || !requiresValidation)
{
wstring trace = GetEntityHealthBaseDetails(applicationHealth);
StringWriter writer(trace);
writer.WriteLine("Service Children:");
for (auto it = applicationHealth.ServicesAggregatedHealthStates.begin(); it != applicationHealth.ServicesAggregatedHealthStates.end(); ++it)
{
writer.WriteLine("\t{0}", *it);
}
writer.WriteLine("DeployedApplication Children:");
for (auto it = applicationHealth.DeployedApplicationsAggregatedHealthStates.begin(); it != applicationHealth.DeployedApplicationsAggregatedHealthStates.end(); ++it)
{
writer.WriteLine("\t{0}", *it);
}
if (applicationHealth.HealthStats)
{
writer.WriteLine("\nStats:{0}", applicationHealth.HealthStats);
}
TestSession::WriteInfo(TraceSource, "{0}\n", trace);
}
return success;
}
bool TestFabricClientHealth::ParseEvents(std::wstring const & eventsString, __out map<wstring, StringCollection> & events)
{
vector<wstring> eventsSegments;
StringUtility::Split<wstring>(eventsString, eventsSegments, L";");
for (auto it = eventsSegments.begin(); it != eventsSegments.end(); ++it)
{
vector<wstring> expectedEventTokens;
StringUtility::Split<wstring>(*it, expectedEventTokens, L",");
if (expectedEventTokens.size() < 3 || expectedEventTokens.size() > 5)
{
TestSession::WriteInfo(TraceSource, "Invalid expectedevents format for {0}. Expected 3 to 5 tokens", *it);
return false;
}
wstring const & source = expectedEventTokens[0];
wstring const & property = expectedEventTokens[1];
events.insert(make_pair(source + property, move(expectedEventTokens)));
}
return true;
}
// Parse strings like key:value;key:value
void ParseKeyValueTestArray(wstring const & input, __out map<wstring, wstring> & values)
{
vector<wstring> segments;
StringUtility::Split<wstring>(input, segments, L";");
for (auto it = segments.begin(); it != segments.end(); ++it)
{
size_t index = it->find_first_of(L":");
if (index != it->npos)
{
values[it->substr(0, index)] = it->substr(index + 1);
}
}
}
bool TestFabricClientHealth::ParseServicePackageActivationId(CommandLineParser & parser, __inout std::wstring & servicePackageActivationId)
{
if (parser.TryGetString(L"servicePackageActivationId", servicePackageActivationId))
{
ServicePackageActivationContext activationContext;
auto error = ServicePackageActivationContext::FromString(servicePackageActivationId, activationContext);
if (!error.IsSuccess())
{
TestSession::WriteError(
TraceSource,
"Invalid servicePackageActivationId={0} specified. Parsing Error={2}.",
servicePackageActivationId,
error);
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyEntityEventsAndHealthState(
CommandLineParser & parser,
bool isEntityPersisted,
vector<ServiceModel::HealthEvent> const & events,
FABRIC_HEALTH_STATE resultAggregatedHealthState,
std::vector<HealthEvaluation> const & unhealthyEvaluations,
bool isEmptyExpected)
{
size_t receivedEventsCount = events.size();
if (isEmptyExpected)
{
if (receivedEventsCount != 0)
{
TestSession::WriteWarning(TraceSource, "Unexpected health query result count {0}.", events.size());
return false;
}
return true;
}
int expectedEventCount = -1;
if (parser.TryGetInt(L"expectedeventcount", expectedEventCount))
{
if (receivedEventsCount != expectedEventCount)
{
TestSession::WriteWarning(TraceSource, "Unexpected health query event count: expected {0}, actual {1}.", expectedEventCount, receivedEventsCount);
return false;
}
}
wstring expectedHealthStateString;
bool checkHealthState = parser.TryGetString(L"expectedhealthstate", expectedHealthStateString);
wstring expectedHealthDescString;
map<wstring, wstring> expectedDescriptions;
size_t expectedDescriptionsChecked = 0;
if (parser.TryGetString(L"expecteddesc", expectedHealthDescString))
{
ParseKeyValueTestArray(expectedHealthDescString, expectedDescriptions);
expectedDescriptionsChecked = expectedDescriptions.size();
}
wstring expectedHealthDescStringLength;
map<wstring, wstring> expectedDescriptionsLength;
size_t expectedDescriptionsLengthChecked = 0;
if (parser.TryGetString(L"expecteddesclength", expectedHealthDescStringLength))
{
ParseKeyValueTestArray(expectedHealthDescStringLength, expectedDescriptionsLength);
expectedDescriptionsLengthChecked = expectedDescriptionsLength.size();
}
map<wstring, vector<wstring>> expectedEvents;
wstring expectedEventsString;
if (parser.TryGetString(L"expectedevents", expectedEventsString))
{
if (!ParseEvents(expectedEventsString, expectedEvents))
{
return false;
}
}
if (expectedHealthDescString.empty() && expectedHealthStateString.empty() && expectedHealthDescStringLength.empty())
{
return true;
}
if (receivedEventsCount == 0 && isEntityPersisted && expectedEventCount != 0)
{
TestSession::WriteInfo(TraceSource, "Invalid health query result count {0}.", receivedEventsCount);
return false;
}
FABRIC_HEALTH_STATE expectedHealthState = FABRIC_HEALTH_STATE_INVALID;
if (checkHealthState)
{
expectedHealthState = GetHealthState(expectedHealthStateString);
if (expectedHealthState != resultAggregatedHealthState)
{
TestSession::WriteInfo(TraceSource, "Aggregated health state does not match expected:{0} actual:{1}",
expectedHealthStateString, GetHealthStateString(resultAggregatedHealthState));
return false;
}
}
if (resultAggregatedHealthState == FABRIC_HEALTH_STATE_OK)
{
// No evaluation should be generated in this case
TestSession::FailTestIfNot(unhealthyEvaluations.empty(), "Aggregated health state {0} and {1} evaluation reasons. There should be 0 reasons.", resultAggregatedHealthState, unhealthyEvaluations.size());
}
else if (unhealthyEvaluations.empty())
{
TestSession::FailTest("Aggregated health state {0}: invalid evaluation reasons count {1}.", resultAggregatedHealthState, unhealthyEvaluations.size());
}
for (size_t i = 0; i < receivedEventsCount; ++i)
{
if (checkHealthState && (events[i].State > expectedHealthState) && !events[i].IsExpired)
{
TestSession::WriteInfo(TraceSource, "Event health state does not match expected aggregated health:{0} actual:{1}, event not expired ({2})",
expectedHealthStateString, GetHealthStateString(events[i].State), events[i]);
return false;
}
wstring const & eventSource = events[i].SourceId;
wstring const & eventProperty = events[i].Property;
wstring const & eventDesc = events[i].Description;
auto it = expectedDescriptions.find(eventProperty);
if (it != expectedDescriptions.end())
{
--expectedDescriptionsChecked;
if (!StringUtility::Contains<wstring>(eventDesc, it->second))
{
TestSession::WriteInfo(TraceSource, "Health description does not match expected:\"{0}\" actual:\"{1}\"",
it->second, eventDesc);
return false;
}
}
auto it2 = expectedDescriptionsLength.find(eventProperty);
if (it2 != expectedDescriptionsLength.end())
{
--expectedDescriptionsLengthChecked;
if (wformatString("{0}", eventDesc.size()) != it2->second)
{
TestSession::WriteInfo(TraceSource, "Health description length does not match expected: actual \"{0}\", length {1} expected:{2}",
eventDesc, eventDesc.size(), it2->second);
return false;
}
}
vector<pair<FABRIC_HEALTH_STATE, DateTime>> healthStateTransitions;
healthStateTransitions.push_back(make_pair(FABRIC_HEALTH_STATE_OK, events[i].LastOkTransitionAt));
healthStateTransitions.push_back(make_pair(FABRIC_HEALTH_STATE_WARNING, events[i].LastWarningTransitionAt));
healthStateTransitions.push_back(make_pair(FABRIC_HEALTH_STATE_ERROR, events[i].LastErrorTransitionAt));
// Sort DESC
sort(healthStateTransitions.begin(), healthStateTransitions.end(), [](pair<FABRIC_HEALTH_STATE, DateTime> const & l, pair<FABRIC_HEALTH_STATE, DateTime> const & r) { return l.second > r.second; });
auto & currentStateTransitionTime = healthStateTransitions[0].second;
TestSession::FailTestIf(currentStateTransitionTime == DateTime::Zero, "Validate event {0} failed: Current state transition time should be set", events[i]);
auto previousState = FABRIC_HEALTH_STATE_INVALID;
if (healthStateTransitions[1].second != DateTime::Zero)
{
previousState = (healthStateTransitions[1].first == events[i].State) ? healthStateTransitions[0].first : healthStateTransitions[1].first;
TestSession::FailTestIfNot(
currentStateTransitionTime == healthStateTransitions[1].second,
"Validate event {0} failed: previous state {1} time should be = current state transition time {2}",
events[i],
previousState,
currentStateTransitionTime);
}
auto oldestState = FABRIC_HEALTH_STATE_INVALID;
if (healthStateTransitions[2].second != DateTime::Zero)
{
oldestState = healthStateTransitions[2].first;
TestSession::FailTestIfNot(
currentStateTransitionTime > healthStateTransitions[2].second,
"Validate event {0} failed: Current state transition time {1} should be > Last{2}",
events[i],
currentStateTransitionTime,
oldestState);
}
auto itExpectedEvents = expectedEvents.find(eventSource + eventProperty);
if (itExpectedEvents != expectedEvents.end())
{
// Check the event against desired event
FABRIC_HEALTH_STATE desiredHealthState = GetHealthState(itExpectedEvents->second[2]);
if (events[i].State != desiredHealthState)
{
TestSession::WriteInfo(TraceSource, "Validate event {0} current health state failed. Expected {1}", events[i], expectedEventsString);
return false;
}
if (itExpectedEvents->second.size() > 3)
{
// Check against transition times
FABRIC_HEALTH_STATE previousDesiredHealthState = GetHealthState(itExpectedEvents->second[3]);
if (previousDesiredHealthState != previousState)
{
TestSession::WriteInfo(TraceSource, "Validate event {0}: previous health state failed. Expected {1} ({2}), actual previous state = {3}", events[i], expectedEventsString, previousDesiredHealthState, previousState);
return false;
}
if (itExpectedEvents->second.size() > 4)
{
FABRIC_HEALTH_STATE oldestDesiredHealthState = GetHealthState(itExpectedEvents->second[4]);
if (oldestDesiredHealthState != oldestState)
{
TestSession::WriteInfo(TraceSource, "Validate event {0}: oldest health state failed. Expected {1} ({2}), actual oldest state = {3}", events[i], expectedEventsString, oldestDesiredHealthState, oldestState);
return false;
}
}
}
// Event validation succeeded
expectedEvents.erase(itExpectedEvents);
}
}
if (expectedDescriptionsChecked > 0)
{
TestSession::WriteInfo(TraceSource, "Event description match failed: Some expected properties were not found. Expected: {0}", expectedHealthDescString);
return false;
}
if (expectedDescriptionsLengthChecked > 0)
{
TestSession::WriteInfo(TraceSource, "Event description length match failed: Some expected properties were not found. Expected: {0}", expectedHealthDescStringLength);
return false;
}
if (!expectedEvents.empty())
{
TestSession::WriteInfo(TraceSource, "{0} events required for validation were not returned. Expected {1}", expectedEvents.size(), expectedEventsString);
return false;
}
wstring expectedEvaluation;
if (parser.TryGetString(L"expectedreason", expectedEvaluation))
{
return VerifyExpectedHealthEvaluations(expectedEvaluation, unhealthyEvaluations);
}
else
{
PrintUnhealthyEvaluations(unhealthyEvaluations);
}
return true;
}
bool TestFabricClientHealth::VerifyExpectedHealthEvaluations(FABRIC_HEALTH_EVALUATION_LIST const * publicHealthEvaluations, std::wstring const & expectedEvaluation)
{
TestSession::FailTestIf(publicHealthEvaluations == NULL, "ExpectedHealthEvaluation evaluation {0}, but no reasons returned", expectedEvaluation);
vector<HealthEvaluation> unhealthyEvaluations;
auto error = PublicApiHelper::FromPublicApiList<HealthEvaluation, FABRIC_HEALTH_EVALUATION_LIST>(
publicHealthEvaluations,
unhealthyEvaluations);
TestSession::FailTestIfNot(
error.IsSuccess(),
"UnhealthyEvaluations FromPublicApiList error={0}",
error);
return VerifyExpectedHealthEvaluations(expectedEvaluation, unhealthyEvaluations);
}
bool TestFabricClientHealth::VerifyExpectedHealthEvaluations(std::wstring const & expectedEvaluation, vector<HealthEvaluation> const & unhealthyEvaluations)
{
TestSession::FailTestIf(unhealthyEvaluations.size() != 1, "Evaluation reasons count is not valid: {0}, expected evaluation: {1}", unhealthyEvaluations.size(), expectedEvaluation);
HealthEvaluationBaseSPtr evaluation = unhealthyEvaluations[0].Evaluation;
TestSession::FailTestIf(!evaluation, "EvaluationWrapper contains null evaluation evaluation");
TestSession::FailTestIf(evaluation->Description.empty(), "Description is empty for {0}. Expected {1}", evaluation, expectedEvaluation);
vector<wstring> tokens;
StringUtility::Split<wstring>(expectedEvaluation, tokens, L",");
if (tokens.size() == 0)
{
TestSession::WriteError(TraceSource, "Could not parse evaluationreason parameter - too few arguments {0}", expectedEvaluation);
return false;
}
if (tokens[0] == L"event")
{
if (!VerifyEventEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"replicas")
{
if (!VerifyReplicasEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"nodes")
{
if (!VerifyNodesEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"partitions")
{
if (!VerifyPartitionsEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"deployedapplications")
{
if (!VerifyDeployedApplicationsEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"deployedservicepackages")
{
if (!VerifyDeployedServicePackagesEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"applications")
{
if (!VerifyApplicationsEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"apptypeapplications")
{
if (!VerifyApplicationTypeApplicationsEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"services")
{
if (!VerifyServicesEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"systemapp")
{
if (!VerifySystemAppEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"deployedapplicationsperud")
{
if (!VerifyDeployedApplicationsPerUdEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"nodesperud")
{
if (!VerifyNodesPerUdEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"delta")
{
if (!VerifyDeltaEvaluation(tokens, evaluation))
{
return false;
}
}
else if (tokens[0] == L"uddelta")
{
if (!VerifyDeltaPerUdEvaluation(tokens, evaluation))
{
return false;
}
}
else
{
TestSession::FailTest("Can't parse evaluationReason {0}: can't identify the type", expectedEvaluation);
}
return true;
}
void TestFabricClientHealth::PrintUnhealthyEvaluations(std::vector<HealthEvaluation> const & unhealthyEvaluations)
{
if (unhealthyEvaluations.empty())
{
return;
}
for (auto it = unhealthyEvaluations.begin(); it != unhealthyEvaluations.end(); ++it)
{
auto & evaluation = it->Evaluation;
// Check expected reasons
switch(evaluation->Kind)
{
case FABRIC_HEALTH_EVALUATION_KIND_NODES:
TestSession::FailTestIfNot(VerifyNodesEvaluation(evaluation), "Verify nodes failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_REPLICAS:
TestSession::FailTestIfNot(VerifyReplicasEvaluation(evaluation), "Verify replicas failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_PARTITIONS:
TestSession::FailTestIfNot(VerifyPartitionsEvaluation(evaluation), "Verify partitions failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_SERVICES:
TestSession::FailTestIfNot(VerifyServicesEvaluation(evaluation), "Verify services failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_APPLICATIONS:
TestSession::FailTestIfNot(VerifyApplicationsEvaluation(evaluation), "Verify apps failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_APPLICATION_TYPE_APPLICATIONS:
TestSession::FailTestIfNot(VerifyApplicationTypeApplicationsEvaluation(evaluation), "Verify app type apps failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_SYSTEM_APPLICATION:
TestSession::FailTestIfNot(VerifySystemApplicationEvaluation(evaluation), "Verify system app failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS:
TestSession::FailTestIfNot(VerifyDeployedApplicationsEvaluation(evaluation), "Verify deployed app failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGES:
TestSession::FailTestIfNot(VerifyDeployedServicePackagesEvaluation(evaluation), "Verify deployed service packages failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_EVENT:
TestSession::FailTestIfNot(VerifyEventEvaluation(evaluation), "Verify event failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DEPLOYED_APPLICATIONS:
TestSession::FailTestIfNot(VerifyUDDeployedApplicationsEvaluation(evaluation), "Verify deployed app failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_NODES:
TestSession::FailTestIfNot(VerifyUDNodesEvaluation(evaluation), "Verify nodes failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_DELTA_NODES_CHECK:
TestSession::FailTestIfNot(VerifyDeltaNodesEvaluation(evaluation), "Verify delta nodes failed for {0}", evaluation);
break;
case FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DELTA_NODES_CHECK:
TestSession::FailTestIfNot(VerifyUDDeltaNodesEvaluation(evaluation), "Verify upgrade domain delta nodes failed for {0}", evaluation);
break;
default:
TestSession::FailTest("Unexpected health evaluation evaluation {0}: {1}", evaluation->Kind, evaluation->Description);
break;
}
}
}
void TestFabricClientHealth::PrintHealthEvaluations(FABRIC_HEALTH_EVALUATION_LIST const * publicHealthEvaluations, vector<FABRIC_HEALTH_EVALUATION_KIND> const & possibleReasons)
{
if (publicHealthEvaluations == NULL)
{
return;
}
vector<HealthEvaluation> unhealthyEvaluations;
auto error = PublicApiHelper::FromPublicApiList<HealthEvaluation, FABRIC_HEALTH_EVALUATION_LIST>(
publicHealthEvaluations,
unhealthyEvaluations);
TestSession::FailTestIfNot(
error.IsSuccess(),
"UnhealthyEvaluations FromPublicApiList error={0}",
error);
return PrintHealthEvaluations(unhealthyEvaluations, possibleReasons);
}
void TestFabricClientHealth::PrintHealthEvaluations(vector<HealthEvaluation> const & unhealthyEvaluations, vector<FABRIC_HEALTH_EVALUATION_KIND> const & possibleReasons)
{
if (unhealthyEvaluations.empty())
{
return;
}
TestSession::FailTestIfNot(unhealthyEvaluations.size() == 1, "Evaluation reasons count is not valid: {0}", unhealthyEvaluations.size());
HealthEvaluationBaseSPtr evaluation = unhealthyEvaluations[0].Evaluation;
TestSession::FailTestIfNot(evaluation != nullptr, "EvaluationWrapper contains null evaluation evaluation");
TestSession::FailTestIf(evaluation->Description.empty(), "Description is empty for {0}.", evaluation);
TestSession::WriteInfo(TraceSource, "HealthEvaluation: {0}", evaluation->Description);
bool isExpected = false;
for (auto it = possibleReasons.begin(); it != possibleReasons.end(); ++it)
{
if (evaluation->Kind != *it)
{
continue;
}
isExpected = true;
}
TestSession::FailTestIfNot(isExpected, "Unexpected health evaluation kind");
PrintUnhealthyEvaluations(unhealthyEvaluations);
}
bool TestFabricClientHealth::VerifyEventEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedReason = dynamic_cast<EventHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedReason->Description.empty(), "Description is empty for {0}.", evaluation);
return true;
}
bool TestFabricClientHealth::VerifyNodesEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<NodesHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
if (!VerifyNodeEvaluation(itInner->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyNodeEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_NODE)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_NODE, evaluation->Kind);
return false;
}
auto typedEvaluation = dynamic_cast<NodeHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for child {0}", evaluation->Description);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->NodeName.empty(), "Node name is empty for {0}", evaluation);
// The children may be trimmed, so the number of children can be 0 or 1.
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
TestSession::FailTestIf(typedEvaluation->UnhealthyEvaluations.size() != 1, "There should be one event unhealthy for {0}", evaluation);
return VerifyEventEvaluation(typedEvaluation->UnhealthyEvaluations[0].Evaluation);
}
bool TestFabricClientHealth::VerifyUDNodesEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<UDNodesHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->UpgradeDomainName.empty(), "UpgradeDomainName should be set for {0}", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
if (!VerifyNodeEvaluation(itInner->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyUDDeltaNodesEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<UpgradeDomainDeltaNodesCheckHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->MaxPercentUpgradeDomainDeltaUnhealthyNodes >= 100, "Delta can't be greater than 100 for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->UpgradeDomainName.empty(), "UpgradeDomainName should be set for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->BaselineTotalCount < typedEvaluation->BaselineErrorCount, "baseline error can't be greater than baseline total for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "current total count can't be 0 for {0}.", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
if (!VerifyNodeEvaluation(itInner->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyReplicasEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<ReplicasHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
if (!VerifyReplicaEvaluation(itInner->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyReplicaEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_REPLICA)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_REPLICA, evaluation->Kind);
return false;
}
auto typedEvaluation = dynamic_cast<ReplicaHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for child {0}", evaluation);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
TestSession::FailTestIf(typedEvaluation->UnhealthyEvaluations.size() != 1, "There should be at 1 event unhealthy entry for {0}", evaluation);
return VerifyEventEvaluation(typedEvaluation->UnhealthyEvaluations[0].Evaluation);
}
bool TestFabricClientHealth::VerifyPartitionsEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<PartitionsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
if (!VerifyPartitionEvaluation(itInner->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyPartitionEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_PARTITION)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_PARTITION, evaluation->Kind);
return false;
}
auto typedEvaluation = dynamic_cast<PartitionHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for child {0}", evaluation);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
TestSession::FailTestIf(typedEvaluation->UnhealthyEvaluations.size() != 1, "There should be at 1 event unhealthy entry for {0}", evaluation);
// Children can be either event or replicas
auto const & eval = typedEvaluation->UnhealthyEvaluations[0].Evaluation;
switch(eval->Kind)
{
case FABRIC_HEALTH_EVALUATION_KIND_EVENT:
return VerifyEventEvaluation(eval);
case FABRIC_HEALTH_EVALUATION_KIND_REPLICAS:
return VerifyReplicasEvaluation(eval);
default:
return false;
}
}
bool TestFabricClientHealth::VerifyServicesEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<ServicesHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->ServiceTypeName.empty(), "ServiceTypeName should be set for {0}", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
if (!VerifyServiceEvaluation(itInner->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyServiceEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_SERVICE)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_SERVICE, evaluation->Kind);
return false;
}
auto typedEvaluation = dynamic_cast<ServiceHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for child {0}", evaluation);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->ServiceName.empty(), "Service name shouldn't be empty for {0}", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
TestSession::FailTestIf(typedEvaluation->UnhealthyEvaluations.size() != 1, "There should be at 1 event unhealthy entry for {0}", evaluation);
// Children can be either event or partitions
auto const & eval = typedEvaluation->UnhealthyEvaluations[0].Evaluation;
switch(eval->Kind)
{
case FABRIC_HEALTH_EVALUATION_KIND_EVENT:
return VerifyEventEvaluation(eval);
case FABRIC_HEALTH_EVALUATION_KIND_PARTITIONS:
return VerifyPartitionsEvaluation(eval);
default:
return false;
}
}
bool TestFabricClientHealth::VerifyDeployedServicePackagesEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<DeployedServicePackagesHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
TestSession::FailTestIfNot(VerifyDeployedServicePackageEvaluation(itInner->Evaluation), "VerifyDeployedServicesPackageEvaluation failed");
}
return true;
}
bool TestFabricClientHealth::VerifyDeployedServicePackageEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGE)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGE, evaluation->Kind);
return false;
}
auto typedEvaluation = dynamic_cast<DeployedServicePackageHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for child {0}", evaluation);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->NodeName.empty(), "Node name is empty for {0}", evaluation);
// The children may be trimmed
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
TestSession::FailTestIf(typedEvaluation->UnhealthyEvaluations.size() != 1, "There should be at 1 event unhealthy entry for {0}", evaluation);
return VerifyEventEvaluation(typedEvaluation->UnhealthyEvaluations[0].Evaluation);
}
bool TestFabricClientHealth::VerifyDeployedApplicationsEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<DeployedApplicationsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
TestSession::FailTestIfNot(VerifyDeployedApplicationEvaluation(itInner->Evaluation), "VerifyDeployedApplicationEvaluation failed");
}
return true;
}
bool TestFabricClientHealth::VerifyUDDeployedApplicationsEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<UDDeployedApplicationsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->UpgradeDomainName.empty(), "UpgradeDomainName should be set for {0}", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
TestSession::FailTestIfNot(VerifyDeployedApplicationEvaluation(itInner->Evaluation), "VerifyDeployedApplicationEvaluation failed");
}
return true;
}
bool TestFabricClientHealth::VerifyDeployedApplicationEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATION)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATION, evaluation->Kind);
return false;
}
auto typedEvaluation = dynamic_cast<DeployedApplicationHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for child {0}", evaluation);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->NodeName.empty(), "Node name shouldn't be empty for {0}", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
TestSession::FailTestIf(typedEvaluation->UnhealthyEvaluations.size() != 1, "There should be at 1 event unhealthy entry for {0}", evaluation);
// Children can be either event, services or deployed apps
auto const & eval = typedEvaluation->UnhealthyEvaluations[0].Evaluation;
switch(eval->Kind)
{
case FABRIC_HEALTH_EVALUATION_KIND_EVENT:
return VerifyEventEvaluation(eval);
case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGES:
return VerifyDeployedServicePackagesEvaluation(eval);
default:
return false;
}
}
bool TestFabricClientHealth::VerifySystemApplicationEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<SystemApplicationHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
auto const & eval = typedEvaluation->UnhealthyEvaluations[0].Evaluation;
switch(eval->Kind)
{
case FABRIC_HEALTH_EVALUATION_KIND_EVENT:
return VerifyEventEvaluation(eval);
case FABRIC_HEALTH_EVALUATION_KIND_SERVICES:
return VerifyServicesEvaluation(eval);
case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS:
return VerifyDeployedApplicationsEvaluation(eval);
default:
return false;
}
}
bool TestFabricClientHealth::VerifyApplicationsEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<ApplicationsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
TestSession::FailTestIfNot(VerifyApplicationEvaluation(itInner->Evaluation), "VerifyApplicationEvaluation failed");
}
return true;
}
bool TestFabricClientHealth::VerifyApplicationTypeApplicationsEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<ApplicationTypeApplicationsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "There should be at least one child for {0}", evaluation);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->ApplicationTypeName.empty(), "Application type name should be set for {0}", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
TestSession::FailTestIfNot(VerifyApplicationEvaluation(itInner->Evaluation), "VerifyApplicationEvaluation failed");
}
return true;
}
bool TestFabricClientHealth::VerifyApplicationEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_APPLICATION)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_APPLICATION, evaluation->Kind);
return false;
}
auto typedEvaluation = dynamic_cast<ApplicationHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for child {0}", evaluation);
TestSession::FailTestIfNot(typedEvaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_WARNING || evaluation->AggregatedHealthState == FABRIC_HEALTH_STATE_ERROR, "Child should be at warning or error not {0}", evaluation->AggregatedHealthState);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
TestSession::FailTestIf(typedEvaluation->UnhealthyEvaluations.size() != 1, "There should be at 1 event unhealthy entry for {0}", evaluation);
// Children can be either event, services or deployed apps
auto const & eval = typedEvaluation->UnhealthyEvaluations[0].Evaluation;
switch(eval->Kind)
{
case FABRIC_HEALTH_EVALUATION_KIND_EVENT:
return VerifyEventEvaluation(eval);
case FABRIC_HEALTH_EVALUATION_KIND_SERVICES:
return VerifyServicesEvaluation(eval);
case FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS:
return VerifyDeployedApplicationsEvaluation(eval);
default:
return false;
}
}
bool TestFabricClientHealth::VerifyDeltaNodesEvaluation(HealthEvaluationBaseSPtr const & evaluation)
{
auto typedEvaluation = dynamic_cast<DeltaNodesCheckHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedEvaluation == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedEvaluation->Description.empty(), "Description is empty for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->MaxPercentDeltaUnhealthyNodes >= 100, "Delta can't be greater than 100 for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->BaselineTotalCount < typedEvaluation->BaselineErrorCount, "baseline error can't be greater than baseline total for {0}.", evaluation);
TestSession::FailTestIf(typedEvaluation->TotalCount == 0, "current total count can't be 0 for {0}.", evaluation);
if (typedEvaluation->UnhealthyEvaluations.empty())
{
TestSession::WriteInfo(TraceSource, "Verify evaluations: children are trimmed: {0}", typedEvaluation->Description);
return true;
}
TestSession::FailTestIf(typedEvaluation->UnhealthyEvaluations.empty(), "There should be at least one unhealthy entry for {0}", evaluation);
for (auto itInner = typedEvaluation->UnhealthyEvaluations.begin(); itInner != typedEvaluation->UnhealthyEvaluations.end(); ++itInner)
{
if (!VerifyNodeEvaluation(itInner->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyChildrenEvaluation(
std::vector<std::wstring> const & expectedEvaluationTokens,
std::vector<ServiceModel::HealthEvaluation> const & unhealthyEvaluations,
FABRIC_HEALTH_EVALUATION_KIND expectedChildrenKind,
ULONG totalCount,
BYTE maxUnhealthy,
std::wstring const & description)
{
TestSession::FailTestIf(totalCount == 0, "There should be at least one child for {0}", description);
size_t childrenCount = unhealthyEvaluations.size();
BYTE invalid = static_cast<BYTE>(-1);
if (expectedEvaluationTokens.size() > 1)
{
int expectedUnhealthy = Int32_Parse(expectedEvaluationTokens[1]);
if (childrenCount != static_cast<size_t>(expectedUnhealthy))
{
TestSession::WriteInfo(TraceSource, "Expected children count doesn't match: expected {0}, actual {1}", expectedUnhealthy, childrenCount);
return false;
}
for (auto it = unhealthyEvaluations.begin(); it != unhealthyEvaluations.end(); ++it)
{
TestSession::FailTestIfNot(it->Evaluation != nullptr, "Child evaluation is null. Expected unhealthy: {0}", expectedUnhealthy);
TestSession::FailTestIfNot(it->Evaluation->Description.size() > 0, "Child evaluation has empty description. Expected unhealthy: {0}", expectedUnhealthy);
TestSession::FailTestIfNot(it->Evaluation->Kind == expectedChildrenKind, "Child evaluation doesn't have expected type. Expected unhealthy: {0}, child {1}", expectedUnhealthy, it->Evaluation);
}
if (expectedEvaluationTokens.size() > 2)
{
if (maxUnhealthy == invalid)
{
TestSession::FailTest("Invalid evaluationreason, request for maxUnhealthy when maxUnhealthy shouldn't exist");
}
int expectedMaxUnhealthy = Int32_Parse(expectedEvaluationTokens[2]);
if (maxUnhealthy != expectedMaxUnhealthy)
{
TestSession::WriteInfo(TraceSource, "Expected maxUnhealthyPercent doesn't match: expected {0}, actual {1}", expectedMaxUnhealthy, maxUnhealthy);
return false;
}
}
if (expectedEvaluationTokens.size() > 3)
{
int expectedTotal = Int32_Parse(expectedEvaluationTokens[3]);
if (totalCount != static_cast<ULONG>(expectedTotal))
{
TestSession::WriteInfo(TraceSource, "Expected total children count doesn't match: expected {0}, actual {1}", expectedTotal, totalCount);
return false;
}
}
}
if (maxUnhealthy != invalid)
{
wstring maxUnhealthyString = wformatString("{0}", maxUnhealthy);
if (!StringUtility::Contains<wstring>(description, maxUnhealthyString))
{
TestSession::WriteInfo(TraceSource, "Reason doesn't contain the maxUnhealthy percent: \"{0}\", maxUnhealthy {1}", description, maxUnhealthy);
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyNodesEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_NODES)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_NODES, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<NodesHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
if (!VerifyChildrenEvaluation(expectedEvaluationTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_NODE, typedReason->TotalCount, typedReason->MaxPercentUnhealthyNodes, evaluation->Description))
{
return false;
}
// Children of nodes should be of type node
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyNodeEvaluation(it->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyApplicationsEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_APPLICATIONS)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_APPLICATIONS, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<ApplicationsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
if (!VerifyChildrenEvaluation(expectedEvaluationTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_APPLICATION, typedReason->TotalCount, typedReason->MaxPercentUnhealthyApplications, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyApplicationEvaluation(it->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyApplicationTypeApplicationsEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_APPLICATION_TYPE_APPLICATIONS)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_APPLICATION_TYPE_APPLICATIONS, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<ApplicationTypeApplicationsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
if (expectedEvaluationTokens.size() > 1)
{
if (typedReason->ApplicationTypeName != expectedEvaluationTokens[1])
{
TestSession::WriteInfo(TraceSource, "Upgrade domain name mismatch: expected {0}, actual {1}", expectedEvaluationTokens[1], typedReason->ApplicationTypeName);
return false;
}
// Check the rest (common parameters);
vector<wstring> commonTokens;
for (size_t i = 1; i < expectedEvaluationTokens.size(); ++i)
{
commonTokens.push_back(expectedEvaluationTokens[i]);
}
if (!VerifyChildrenEvaluation(commonTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_APPLICATION, typedReason->TotalCount, typedReason->MaxPercentUnhealthyApplications, evaluation->Description))
{
return false;
}
}
else if (!VerifyChildrenEvaluation(expectedEvaluationTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_APPLICATION, typedReason->TotalCount, typedReason->MaxPercentUnhealthyApplications, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyApplicationEvaluation(it->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyDeployedApplicationsEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATIONS, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<DeployedApplicationsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
if (!VerifyChildrenEvaluation(expectedEvaluationTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATION, typedReason->TotalCount, typedReason->MaxPercentUnhealthyDeployedApplications, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyDeployedApplicationEvaluation(it->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyDeployedServicePackagesEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGES)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGES, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<DeployedServicePackagesHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
BYTE invalid = static_cast<BYTE>(-1);
if (!VerifyChildrenEvaluation(expectedEvaluationTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_SERVICE_PACKAGE, typedReason->TotalCount, invalid, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyDeployedServicePackageEvaluation(it->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyReplicasEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_REPLICAS)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_REPLICAS, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<ReplicasHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
if (!VerifyChildrenEvaluation(expectedEvaluationTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_REPLICA, typedReason->TotalCount, typedReason->MaxPercentUnhealthyReplicasPerPartition, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyReplicaEvaluation(it->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyPartitionsEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_PARTITIONS)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_PARTITIONS, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<PartitionsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
if (!VerifyChildrenEvaluation(expectedEvaluationTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_PARTITION, typedReason->TotalCount, typedReason->MaxPercentUnhealthyPartitionsPerService, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyPartitionEvaluation(it->Evaluation))
{
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyServicesEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_SERVICES)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_SERVICES, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<ServicesHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
// Check service type name
if (expectedEvaluationTokens.size() > 1)
{
if (typedReason->ServiceTypeName != expectedEvaluationTokens[1])
{
TestSession::WriteInfo(TraceSource, "Service type name mismatch: expected {0}, actual {1}", expectedEvaluationTokens[1], typedReason->ServiceTypeName);
return false;
}
// Check the rest (common parameters);
vector<wstring> commonTokens;
for (size_t i = 1; i < expectedEvaluationTokens.size(); ++i)
{
commonTokens.push_back(expectedEvaluationTokens[i]);
}
if (!VerifyChildrenEvaluation(commonTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_SERVICE, typedReason->TotalCount, typedReason->MaxPercentUnhealthyServices, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyServiceEvaluation(it->Evaluation))
{
return false;
}
}
}
return true;
}
bool TestFabricClientHealth::VerifySystemAppEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (expectedEvaluationTokens.size() != 1)
{
TestSession::FailTest("Invalid expectedEvalutionReasons: nothing should be passed in for systemapp");
}
if (!VerifySystemApplicationEvaluation(evaluation))
{
return false;
}
return true;
}
bool TestFabricClientHealth::VerifyNodesPerUdEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_NODES)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_NODES, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<UDNodesHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
// Check upgrade domain name
if (expectedEvaluationTokens.size() > 1)
{
if (typedReason->UpgradeDomainName != expectedEvaluationTokens[1])
{
TestSession::WriteInfo(TraceSource, "Upgrade domain name mismatch: expected {0}, actual {1}", expectedEvaluationTokens[1], typedReason->UpgradeDomainName);
return false;
}
// Check the rest (common parameters);
vector<wstring> commonTokens;
for (size_t i = 1; i < expectedEvaluationTokens.size(); ++i)
{
commonTokens.push_back(expectedEvaluationTokens[i]);
}
if (!VerifyChildrenEvaluation(commonTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_NODE, typedReason->TotalCount, typedReason->MaxPercentUnhealthyNodes, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyNodeEvaluation(it->Evaluation))
{
return false;
}
}
}
return true;
}
bool TestFabricClientHealth::VerifyDeltaEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_DELTA_NODES_CHECK)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_DELTA_NODES_CHECK, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<DeltaNodesCheckHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
TestSession::FailTestIf(typedReason->Description.empty(), "unexpected empty description for {0}", evaluation);
if (expectedEvaluationTokens.size() != 6)
{
TestSession::WriteInfo(TraceSource, "expectedreason: invalid number of tokesn {0}", expectedEvaluationTokens);
return false;
}
ULONG baseError, baseTotal, error, total, delta;
if (!StringUtility::TryFromWString(expectedEvaluationTokens[1], baseError) ||
!StringUtility::TryFromWString(expectedEvaluationTokens[2], baseTotal) ||
!StringUtility::TryFromWString(expectedEvaluationTokens[3], error) ||
!StringUtility::TryFromWString(expectedEvaluationTokens[4], total) ||
!StringUtility::TryFromWString(expectedEvaluationTokens[5], delta))
{
TestSession::WriteError(TraceSource, "expectedreason: Unable to parse {0}", expectedEvaluationTokens);
return false;
}
if (baseError != typedReason->BaselineErrorCount)
{
TestSession::WriteInfo(TraceSource, "BaselineError mismatch: expected {0}, actual {1}", baseError, typedReason->BaselineErrorCount);
return false;
}
if (baseTotal != typedReason->BaselineTotalCount)
{
TestSession::WriteInfo(TraceSource, "BaselineTotal mismatch: expected {0}, actual {1}", baseTotal, typedReason->BaselineTotalCount);
return false;
}
if (error != static_cast<ULONG>(typedReason->UnhealthyEvaluations.size()))
{
TestSession::WriteInfo(TraceSource, "Error mismatch: expected {0}, actual {1}", error, typedReason->UnhealthyEvaluations.size());
return false;
}
if (total != typedReason->TotalCount)
{
TestSession::WriteInfo(TraceSource, "Total mismatch: expected {0}, actual {1}", total, typedReason->TotalCount);
return false;
}
if (delta != typedReason->MaxPercentDeltaUnhealthyNodes)
{
TestSession::WriteInfo(TraceSource, "MaxPercentDeltaUnhealthyNodes mismatch: expected {0}, actual {1}", delta, typedReason->MaxPercentDeltaUnhealthyNodes);
return false;
}
if (typedReason->UnhealthyEvaluations.size() != static_cast<size_t>(error))
{
TestSession::WriteInfo(TraceSource, "nhealthy evaluations size mismatch: expected {0}, actual {1}", error, typedReason->UnhealthyEvaluations.size());
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyNodeEvaluation(it->Evaluation))
{
return false;
}
}
wstring totalString = wformatString("{0}", total);
if (!StringUtility::Contains<wstring>(typedReason->Description, totalString))
{
TestSession::WriteInfo(TraceSource, "Reason doesn't contain the total count: \"{0}\", total {1}", typedReason->Description, total);
return false;
}
wstring baseErrorString = wformatString("{0}", baseError);
if (!StringUtility::Contains<wstring>(typedReason->Description, baseErrorString))
{
TestSession::WriteInfo(TraceSource, "Reason doesn't contain the baseline error count: \"{0}\", baseerror {1}", typedReason->Description, baseError);
return false;
}
wstring baseTotalString = wformatString("{0}", baseTotal);
if (!StringUtility::Contains<wstring>(typedReason->Description, baseTotalString))
{
TestSession::WriteInfo(TraceSource, "Reason doesn't contain the baseline total count: \"{0}\", basetotal {1}", typedReason->Description, baseTotal);
return false;
}
return true;
}
bool TestFabricClientHealth::VerifyDeltaPerUdEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DELTA_NODES_CHECK)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DELTA_NODES_CHECK, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<UpgradeDomainDeltaNodesCheckHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
if (expectedEvaluationTokens.size() != 7)
{
TestSession::WriteInfo(TraceSource, "expectedreason: invalid number of tokesn {0}", expectedEvaluationTokens);
return false;
}
if (typedReason->UpgradeDomainName != expectedEvaluationTokens[1])
{
TestSession::WriteInfo(TraceSource, "Upgrade domain name mismatch: expected {0}, actual {1}", expectedEvaluationTokens[1], typedReason->UpgradeDomainName);
return false;
}
ULONG baseError, baseTotal, error, total, delta;
if (!StringUtility::TryFromWString(expectedEvaluationTokens[2], baseError) ||
!StringUtility::TryFromWString(expectedEvaluationTokens[3], baseTotal) ||
!StringUtility::TryFromWString(expectedEvaluationTokens[4], error) ||
!StringUtility::TryFromWString(expectedEvaluationTokens[5], total) ||
!StringUtility::TryFromWString(expectedEvaluationTokens[6], delta))
{
TestSession::WriteError(TraceSource, "expectedreason: Unable to parse {0}", expectedEvaluationTokens);
return false;
}
if (baseError != typedReason->BaselineErrorCount)
{
TestSession::WriteInfo(TraceSource, "BaselineError mismatch: expected {0}, actual {1}", baseError, typedReason->BaselineErrorCount);
return false;
}
if (baseTotal != typedReason->BaselineTotalCount)
{
TestSession::WriteInfo(TraceSource, "BaselineTotal mismatch: expected {0}, actual {1}", baseTotal, typedReason->BaselineTotalCount);
return false;
}
if (error != static_cast<ULONG>(typedReason->UnhealthyEvaluations.size()))
{
TestSession::WriteInfo(TraceSource, "Error mismatch: expected {0}, actual {1}", error, typedReason->UnhealthyEvaluations.size());
return false;
}
if (total != typedReason->TotalCount)
{
TestSession::WriteInfo(TraceSource, "Total mismatch: expected {0}, actual {1}", total, typedReason->TotalCount);
return false;
}
if (delta != typedReason->MaxPercentUpgradeDomainDeltaUnhealthyNodes)
{
TestSession::WriteInfo(TraceSource, "MaxPercentUpgradeDomainDeltaUnhealthyNodes mismatch: expected {0}, actual {1}", delta, typedReason->MaxPercentUpgradeDomainDeltaUnhealthyNodes);
return false;
}
if (typedReason->UnhealthyEvaluations.size() != static_cast<size_t>(error))
{
TestSession::WriteInfo(TraceSource, "Healthy evaluations size mismatch: expected {0}, actual {1}", error, typedReason->UnhealthyEvaluations.size());
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyNodeEvaluation(it->Evaluation))
{
return false;
}
}
wstring baseErrorString = wformatString("{0}", baseError);
if (!StringUtility::Contains<wstring>(typedReason->Description, baseErrorString))
{
TestSession::WriteInfo(TraceSource, "Reason doesn't contain the baseline error count: \"{0}\", baseerror {1}", typedReason->Description, baseError);
return false;
}
wstring baseTotalString = wformatString("{0}", baseTotal);
if (!StringUtility::Contains<wstring>(typedReason->Description, baseTotalString))
{
TestSession::WriteInfo(TraceSource, "Reason doesn't contain the baseline total count: \"{0}\", basetotal {1}", typedReason->Description, baseTotal);
return false;
}
wstring totalString = wformatString("{0}", total);
if (!StringUtility::Contains<wstring>(typedReason->Description, totalString))
{
TestSession::WriteInfo(TraceSource, "Reason doesn't contain the total count: \"{0}\", total {1}", typedReason->Description, total);
return false;
}
return true;
}
bool TestFabricClientHealth::VerifyDeployedApplicationsPerUdEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DEPLOYED_APPLICATIONS)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_UPGRADE_DOMAIN_DEPLOYED_APPLICATIONS, evaluation->Kind);
return false;
}
auto typedReason = dynamic_cast<UDDeployedApplicationsHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(typedReason == NULL, "Conversion to type returned null for {0}", evaluation);
// Check service type name
if (expectedEvaluationTokens.size() > 1)
{
if (typedReason->UpgradeDomainName != expectedEvaluationTokens[1])
{
TestSession::WriteInfo(TraceSource, "Upgrade domain name mismatch: expected {0}, actual {1}", expectedEvaluationTokens[1], typedReason->UpgradeDomainName);
return false;
}
// Check the rest (common parameters);
vector<wstring> commonTokens;
for (size_t i = 1; i < expectedEvaluationTokens.size(); ++i)
{
commonTokens.push_back(expectedEvaluationTokens[i]);
}
if (!VerifyChildrenEvaluation(commonTokens, typedReason->UnhealthyEvaluations, FABRIC_HEALTH_EVALUATION_KIND_DEPLOYED_APPLICATION, typedReason->TotalCount, typedReason->MaxPercentUnhealthyDeployedApplications, evaluation->Description))
{
return false;
}
for (auto it = typedReason->UnhealthyEvaluations.begin(); it != typedReason->UnhealthyEvaluations.end(); ++it)
{
if (!VerifyDeployedApplicationEvaluation(it->Evaluation))
{
return false;
}
}
}
return true;
}
bool TestFabricClientHealth::VerifyEventEvaluation(std::vector<std::wstring> const & expectedEvaluationTokens, HealthEvaluationBaseSPtr const & evaluation)
{
if (evaluation->Kind != FABRIC_HEALTH_EVALUATION_KIND_EVENT)
{
TestSession::WriteInfo(TraceSource, "HealthEvaluationBase kind mismatch: Expected {0}, received {1}", FABRIC_HEALTH_EVALUATION_KIND_EVENT, evaluation->Kind);
return false;
}
auto eventReason = dynamic_cast<EventHealthEvaluation *>(evaluation.get());
TestSession::FailTestIf(eventReason == NULL, "Conversion to type returned null for {0}", evaluation);
if (expectedEvaluationTokens.size() > 1)
{
if (eventReason->UnhealthyEvent.SourceId != expectedEvaluationTokens[1])
{
TestSession::WriteInfo(TraceSource, "EventEvaluation: Source mismatch: expected {0}, received {1}", expectedEvaluationTokens[1], eventReason->UnhealthyEvent.SourceId);
return false;
}
if (expectedEvaluationTokens.size() > 2)
{
if (eventReason->UnhealthyEvent.Property != expectedEvaluationTokens[2])
{
TestSession::WriteInfo(TraceSource, "EventEvaluation: Property mismatch: expected {0}, received {1}", expectedEvaluationTokens[2], eventReason->UnhealthyEvent.Property);
return false;
}
if (expectedEvaluationTokens.size() > 3)
{
int64 sn;
if (!Common::TryParseInt64(expectedEvaluationTokens[3], sn))
{
TestSession::WriteInfo(TraceSource, "EventEvaluation: error reading sn from expected: expected {0}, received {1}", expectedEvaluationTokens[3], eventReason->UnhealthyEvent.SequenceNumber);
return false;
}
if (eventReason->UnhealthyEvent.SequenceNumber != sn)
{
TestSession::WriteInfo(TraceSource, "EventEvaluation: sequence number mismatch: expected {0}, received {1}", expectedEvaluationTokens[3], eventReason->UnhealthyEvent.SequenceNumber);
return false;
}
}
}
}
return true;
}
bool TestFabricClientHealth::VerifyHealthStateCount(
std::wstring const & expectedHealthStatesString,
HealthStateCount const & counts)
{
// Expected format: ok:<number>,warning:<number>,error:<number>
vector<wstring> tokens;
StringUtility::Split<wstring>(expectedHealthStatesString, tokens, L",");
int expectedTotalCount = -1;
int expectedOkCount = 0;
int expectedWarningCount = 0;
int expectedErrorCount = 0;
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
vector<wstring> innerTokens;
StringUtility::Split<wstring>(*it, innerTokens, L":");
if (innerTokens.size() == 1u)
{
expectedTotalCount = Int32_Parse(innerTokens[0]);
// If total is requested, no per states information will be checked
TestSession::FailTestIfNot(tokens.size() == 1u, "Invalid health state check command: global count requested with other tokens in {0}", expectedHealthStatesString);
}
else if (innerTokens.size() > 2u)
{
TestSession::WriteError(TraceSource, "Could not parse expectedHealthStates inner token {0} in {1}", *it, expectedHealthStatesString);
return false;
}
else
{
int expectedStateCount = Int32_Parse(innerTokens[1]);
switch(GetHealthState(innerTokens[0]))
{
case FABRIC_HEALTH_STATE_OK: expectedOkCount = expectedStateCount; break;
case FABRIC_HEALTH_STATE_WARNING: expectedWarningCount = expectedStateCount; break;
case FABRIC_HEALTH_STATE_ERROR: expectedErrorCount = expectedStateCount; break;
default: TestSession::FailTest("Unknown health state {0}", innerTokens[0]);
}
}
}
int receivedOkCount = static_cast<int>(counts.OkCount);
int receivedWarningCount = static_cast<int>(counts.WarningCount);
int receivedErrorCount = static_cast<int>(counts.ErrorCount);
int receivedTotalCount = receivedErrorCount + receivedOkCount + receivedWarningCount;
if (expectedTotalCount != -1)
{
if (expectedTotalCount != receivedTotalCount)
{
TestSession::WriteInfo(TraceSource, "Invalid health query total state count: expected {0}, actual {1}/{2}/{3} (total {4}).", expectedTotalCount, receivedOkCount, receivedWarningCount, receivedErrorCount, receivedTotalCount);
return false;
}
}
else if (expectedOkCount != receivedOkCount ||
expectedWarningCount != receivedWarningCount ||
expectedErrorCount != receivedErrorCount)
{
TestSession::WriteInfo(TraceSource, "Invalid health query state count: expected {0}/{1}/{2}, actual {3}/{4}/{5}.", expectedOkCount, expectedWarningCount, expectedErrorCount, receivedOkCount, receivedWarningCount, receivedErrorCount);
return false;
}
return true;
}
bool TestFabricClientHealth::VerifyHealthStateCountMap(
std::wstring const & expectedHealthStatesString,
HealthStateCountMap const & results)
{
TestSession::WriteInfo(TraceSource, "VerifyHealthStateCountMap: Received health state map: {0}", results);
// Parameter format:
// expectedstates=<type>+
// Where per type info can be either the total count, total count per states (ok/warning/error) or count and count per states for each type (nodes, apps etc)
// Example:
// expectedstates=10
// expectedstates=ok:4,warning:6
// expectedstates=nodes-4;apps-ok:5,warning:2,error:1
vector<wstring> typeInfo;
StringUtility::Split<wstring>(expectedHealthStatesString, typeInfo, L";");
for (auto itTypeInfo = typeInfo.begin(); itTypeInfo != typeInfo.end(); ++itTypeInfo)
{
vector<wstring> typeTokens;
StringUtility::Split<wstring>(*itTypeInfo, typeTokens, L"-");
if (typeTokens.size() > 2)
{
TestSession::WriteInfo(TraceSource, "Invalid command format: type info has too many separators for {0}.", *itTypeInfo);
return false;
}
if (typeTokens.size() == 2)
{
// First token represents the type
auto itActualResults = results.end();
if (typeTokens[0] == L"nodes")
{
itActualResults = results.find(EntityKind::Node);
}
else if (typeTokens[0] == L"replicas")
{
itActualResults = results.find(EntityKind::Replica);
}
else if (typeTokens[0] == L"partitions")
{
itActualResults = results.find(EntityKind::Partition);
}
else if (typeTokens[0] == L"services")
{
itActualResults = results.find(EntityKind::Service);
}
else if (typeTokens[0] == L"apps")
{
itActualResults = results.find(EntityKind::Application);
}
else if (typeTokens[0] == L"deployedservicepackages")
{
itActualResults = results.find(EntityKind::DeployedServicePackage);
}
else if (typeTokens[0] == L"deployedapps")
{
itActualResults = results.find(EntityKind::DeployedApplication);
}
else
{
TestSession::WriteInfo(TraceSource, "Invalid type {0} for {1}", typeTokens[0], *itTypeInfo);
return false;
}
TestSession::FailTestIf(itActualResults == results.end(), "Expected {0} not returned by GetHealth. Expected children: {1}", typeTokens[0], expectedHealthStatesString);
if (!VerifyHealthStateCount(typeTokens[1], itActualResults->second))
{
TestSession::WriteInfo(TraceSource, "Verify HealthStateCount for {0} failed, expected {1}", typeTokens[0], typeTokens[1]);
return false;
}
}
else
{
// Check total count/health states
HealthStateCount globalResults;
for (auto itResults = results.begin(); itResults != results.end(); ++itResults)
{
globalResults.AppendCount(itResults->second);
}
if (!VerifyHealthStateCount(typeTokens[0], globalResults))
{
return false;
}
}
}
return true;
}
bool TestFabricClientHealth::VerifyAggregatedHealthStates(CommandLineParser & parser, HealthStateCountMap const & results)
{
wstring expectedHealthStatesString;
if (parser.TryGetString(L"expectedchildrenhealthstates", expectedHealthStatesString) ||
parser.TryGetString(L"expectedhealthstates", expectedHealthStatesString) ||
parser.TryGetString(L"expectedchildrencount", expectedHealthStatesString))
{
TestSession::WriteWarning(TraceSource, "{0} parameter is no longer supported", expectedHealthStatesString);
return false;
}
wstring expectedChildrenString;
if (!parser.TryGetString(L"expectedstates", expectedChildrenString))
{
// No validation needed
return true;
}
return VerifyHealthStateCountMap(expectedChildrenString, results);
}
void TestFabricClientHealth::CreateFabricHealthClient(__in FabricTestFederation & testFederation)
{
if (healthClient_.GetRawPointer() == nullptr)
{
ComPointer<IFabricHealthClient4> result;
HRESULT hr = TestFabricClient::FabricCreateComFabricClient(testFederation)->QueryInterface(
IID_IFabricHealthClient4,
(void **)result.InitializationAddress());
TestSession::FailTestIfNot(SUCCEEDED(hr), "ComFabricClient does not support IFabricHealthClient");
healthClient_ = result;
}
}
void TestFabricClientHealth::CreateInternalFabricHealthClient(__in FabricTestFederation & testFederation)
{
if (internalHealthClient_.get() == NULL)
{
auto factoryPtr = TestFabricClient::FabricCreateNativeClientFactory(testFederation);
auto error = factoryPtr->CreateHealthClient(internalHealthClient_);
TestSession::FailTestIfNot(error.IsSuccess(), "InternalClientFactory does not support IHealthClient");
}
}
bool TestFabricClientHealth::CheckClusterEntityState(CommandLineParser & parser, Management::HealthManager::HealthManagerReplicaSPtr const & hmPrimary, bool & success)
{
auto entity = hmPrimary->EntityManager->Cluster.GetEntity(*Management::HealthManager::Constants::StoreType_ClusterTypeString);
AttributesStoreDataSPtr baseAttributes;
success = CheckHealthEntityCommonParameters(parser, entity, baseAttributes);
return true;
}
bool TestFabricClientHealth::CheckNodeEntityState(CommandLineParser & parser, Management::HealthManager::HealthManagerReplicaSPtr const & hmPrimary, bool & success)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
auto entity = hmPrimary->EntityManager->Nodes.GetEntity(nodeId.IdValue);
AttributesStoreDataSPtr baseAttributes;
success = CheckHealthEntityCommonParameters(parser, entity, baseAttributes);
if (!success)
{
return true;
}
if (baseAttributes)
{
auto attributes = static_cast<NodeAttributesStoreData*>(baseAttributes.get());
if (attributes->HasSystemReport && nodeName != attributes->NodeName)
{
TestSession::WriteInfo(TraceSource, "CheckNodeEntityState: nodeName mismatch: expected '{0}'/ actual '{1}'", nodeName, attributes->NodeName);
success = false;
return true;
}
if (nodeInstanceId != attributes->NodeInstanceId)
{
TestSession::WriteInfo(TraceSource, "CheckNodeEntityState: nodeInstanceId mismatch: expected '{0}'/ actual '{1}'", nodeInstanceId, attributes->InstanceId);
success = false;
return true;
}
if (!attributes->IsMarkedForDeletion && !attributes->IsCleanedUp && attributes->HasSystemReport)
{
wstring ipAddressOrFqdn;
if (parser.TryGetString(L"ipaddressorfqdn", ipAddressOrFqdn))
{
if (!attributes->AttributeSetFlags.IsIpAddressOrFqdnSet() ||
attributes->IpAddressOrFqdn != ipAddressOrFqdn)
{
TestSession::WriteInfo(TraceSource, "CheckNodeEntityState: ipaddressorfqdn mismatch: expected '{0}'/ actual '{1}'", ipAddressOrFqdn, attributes->IpAddressOrFqdn);
success = false;
return true;
}
}
wstring upgradeDomain;
if (parser.TryGetString(L"ud", upgradeDomain))
{
if (!attributes->AttributeSetFlags.IsUpgradeDomainSet() ||
attributes->UpgradeDomain != upgradeDomain)
{
TestSession::WriteInfo(TraceSource, "CheckNodeEntityState: ud mismatch expected: '{0}'/ actual '{1}'", upgradeDomain, attributes->UpgradeDomain);
success = false;
return true;
}
}
wstring faultDomain;
if (parser.TryGetString(L"fd", faultDomain))
{
if (!attributes->AttributeSetFlags.IsFaultDomainSet() ||
attributes->FaultDomain != faultDomain)
{
TestSession::WriteInfo(TraceSource, "CheckNodeEntityState: fd mismatch expected: '{0}'/ actual '{1}'", faultDomain, attributes->FaultDomain);
success = false;
return true;
}
}
}
}
return true;
}
bool TestFabricClientHealth::CheckReplicaEntityState(CommandLineParser & parser, Management::HealthManager::HealthManagerReplicaSPtr const & hmPrimary, bool & success)
{
FABRIC_REPLICA_ID replicaId;
FABRIC_INSTANCE_ID replicaInstanceId;
Common::Guid partitionGuid;
if (!ParseReplicaId(parser, partitionGuid, replicaId, replicaInstanceId))
{
return false;
}
AttributesStoreDataSPtr baseAttributes;
auto entity = hmPrimary->EntityManager->Replicas.GetEntity(ReplicaHealthId(partitionGuid, replicaId));
success = CheckHealthEntityCommonParameters(parser, entity, baseAttributes);
if (!success)
{
return true;
}
if (baseAttributes)
{
auto attributes = static_cast<ReplicaAttributesStoreData*>(baseAttributes.get());
if (replicaInstanceId != FABRIC_INVALID_INSTANCE_ID && replicaInstanceId != attributes->InstanceId)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: replicaInstanceId mismatch: expected '{0}'/ actual '{1}'", replicaInstanceId, attributes->InstanceId);
success = false;
return true;
}
if (!attributes->IsMarkedForDeletion && !attributes->IsCleanedUp)
{
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
if (!attributes->AttributeSetFlags.IsNodeIdSet() ||
attributes->NodeId != nodeId.IdValue)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: nodeid mismatch expected: '{0}'/ actual '{1}'", nodeId, attributes->NodeId);
success = false;
return true;
}
if (!attributes->AttributeSetFlags.IsNodeInstanceIdSet() ||
attributes->NodeInstanceId != nodeInstanceId)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: nodeInstanceId mismatch expected: '{0}'/ actual '{1}'", nodeInstanceId, attributes->NodeInstanceId);
success = false;
return true;
}
}
}
}
return true;
}
bool TestFabricClientHealth::CheckPartitionEntityState(CommandLineParser & parser, Management::HealthManager::HealthManagerReplicaSPtr const & hmPrimary, bool & success)
{
PartitionHealthId partitionId;
if (!ParsePartitionId(parser, partitionId))
{
return false;
}
auto entity = hmPrimary->EntityManager->Partitions.GetEntity(partitionId);
AttributesStoreDataSPtr baseAttributes;
success = CheckHealthEntityCommonParameters(parser, entity, baseAttributes);
if (!success)
{
return true;
}
if (baseAttributes)
{
auto attributes = static_cast<PartitionAttributesStoreData*>(baseAttributes.get());
if (!attributes->IsMarkedForDeletion && !attributes->IsCleanedUp)
{
wstring serviceName;
if (parser.TryGetString(L"servicename", serviceName, wstring()))
{
if (!attributes->AttributeSetFlags.IsServiceNameSet() ||
attributes->ServiceName != serviceName)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: servicename mismatch expected: '{0}'/ actual '{1}'", serviceName, attributes->ServiceName);
success = false;
return true;
}
}
}
}
return true;
}
bool TestFabricClientHealth::CheckServiceEntityState(CommandLineParser & parser, Management::HealthManager::HealthManagerReplicaSPtr const & hmPrimary, bool & success)
{
wstring serviceName;
if (!parser.TryGetString(L"servicename", serviceName))
{
return false;
}
auto entity = hmPrimary->EntityManager->Services.GetEntity(ServiceHealthId(serviceName));
AttributesStoreDataSPtr baseAttributes;
success = CheckHealthEntityCommonParameters(parser, entity, baseAttributes);
if (!success)
{
return true;
}
if (baseAttributes)
{
auto attributes = static_cast<ServiceAttributesStoreData*>(baseAttributes.get());
if (!attributes->IsMarkedForDeletion && !attributes->IsCleanedUp)
{
wstring serviceTypeName;
if (parser.TryGetString(L"servicetypename", serviceTypeName, wstring()))
{
if (!attributes->AttributeSetFlags.IsServiceTypeNameSet() ||
attributes->ServiceTypeName != serviceTypeName)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: servicetypename mismatch expected: '{0}'/ actual '{1}'", serviceTypeName, attributes->ServiceTypeName);
success = false;
return true;
}
}
wstring appName;
if (parser.TryGetString(L"appname", appName, wstring()))
{
if (!attributes->AttributeSetFlags.IsApplicationNameSet() ||
attributes->ApplicationName != appName)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: appName mismatch expected: '{0}'/ actual '{1}'", appName, attributes->ApplicationName);
success = false;
return true;
}
}
}
}
return true;
}
bool TestFabricClientHealth::CheckDeployedServicePackageEntityState(CommandLineParser & parser, Management::HealthManager::HealthManagerReplicaSPtr const & hmPrimary, bool & success)
{
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
return false;
}
wstring serviceManifestName;
if (!parser.TryGetString(L"servicemanifestname", serviceManifestName))
{
return false;
}
wstring servicePackageActivationId;
if (!ParseServicePackageActivationId(parser, servicePackageActivationId))
{
return false;
}
TestSession::WriteInfo(TraceSource, "CheckDeployedServicePackageEntityState(): Using servicePackageActivationId=[{0}].", servicePackageActivationId);
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
auto entity = hmPrimary->EntityManager->DeployedServicePackages.GetEntity(
DeployedServicePackageHealthId(appName, serviceManifestName, servicePackageActivationId, nodeId.IdValue));
AttributesStoreDataSPtr baseAttributes;
success = CheckHealthEntityCommonParameters(parser, entity, baseAttributes);
if (!success)
{
return true;
}
if (baseAttributes)
{
auto attributes = static_cast<DeployedServicePackageAttributesStoreData*>(baseAttributes.get());
FABRIC_INSTANCE_ID servicePackageInstanceId;
parser.TryGetInt64(L"servicepackageinstanceid", servicePackageInstanceId, FABRIC_INVALID_INSTANCE_ID);
if (servicePackageInstanceId != FABRIC_INVALID_INSTANCE_ID && servicePackageInstanceId != attributes->InstanceId)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: servicePackageInstanceId mismatch: expected '{0}'/ actual '{1}'", servicePackageInstanceId, attributes->InstanceId);
success = false;
return true;
}
if (!attributes->IsMarkedForDeletion && !attributes->IsCleanedUp)
{
if (nodeInstanceId != FABRIC_INVALID_NODE_INSTANCE_ID &&
(!attributes->AttributeSetFlags.IsNodeInstanceIdSet() || attributes->NodeInstanceId != nodeInstanceId))
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: nodeInstanceId mismatch expected: '{0}'/ actual '{1}'", nodeInstanceId, attributes->NodeInstanceId);
success = false;
return true;
}
}
}
return true;
}
bool TestFabricClientHealth::CheckDeployedApplicationEntityState(CommandLineParser & parser, Management::HealthManager::HealthManagerReplicaSPtr const & hmPrimary, bool & success)
{
wstring appName;
if (!parser.TryGetString(L"appname", appName, wstring()))
{
return false;
}
NodeId nodeId;
FABRIC_NODE_INSTANCE_ID nodeInstanceId;
std::wstring nodeName;
if (!ParseNodeHealthInformation(parser, nodeId, nodeInstanceId, nodeName))
{
return false;
}
auto entity = hmPrimary->EntityManager->DeployedApplications.GetEntity(DeployedApplicationHealthId(appName, nodeId.IdValue));
AttributesStoreDataSPtr baseAttributes;
success = CheckHealthEntityCommonParameters(parser, entity, baseAttributes);
if (!success)
{
return true;
}
if (baseAttributes)
{
auto attributes = static_cast<DeployedApplicationAttributesStoreData*>(baseAttributes.get());
FABRIC_INSTANCE_ID applicationInstanceId;
parser.TryGetInt64(L"appinstanceid", applicationInstanceId, FABRIC_INVALID_INSTANCE_ID);
if (applicationInstanceId != FABRIC_INVALID_INSTANCE_ID && applicationInstanceId != attributes->InstanceId)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: applicationInstanceId mismatch: expected '{0}'/ actual '{1}'", applicationInstanceId, attributes->InstanceId);
success = false;
return true;
}
if (!attributes->IsMarkedForDeletion && !attributes->IsCleanedUp)
{
if (nodeInstanceId != FABRIC_INVALID_NODE_INSTANCE_ID &&
(!attributes->AttributeSetFlags.IsNodeInstanceIdSet() || attributes->NodeInstanceId != nodeInstanceId))
{
TestSession::WriteInfo(TraceSource, "CheckEntityState: nodeInstanceId mismatch: expected '{0}'/ actual '{1}'", nodeInstanceId, attributes->NodeInstanceId);
success = false;
return true;
}
}
}
return true;
}
bool TestFabricClientHealth::CheckApplicationEntityState(CommandLineParser & parser, Management::HealthManager::HealthManagerReplicaSPtr const & hmPrimary, bool & success)
{
wstring applicationName;
if (!parser.TryGetString(L"appname", applicationName))
{
return false;
}
auto entity = hmPrimary->EntityManager->Applications.GetEntity(ApplicationHealthId(applicationName));
AttributesStoreDataSPtr baseAttributes;
success = CheckHealthEntityCommonParameters(parser, entity, baseAttributes);
if (!success)
{
return true;
}
if (baseAttributes)
{
auto attributes = static_cast<ApplicationAttributesStoreData*>(baseAttributes.get());
if (success && !attributes->IsMarkedForDeletion && !attributes->IsCleanedUp && attributes->HasSystemReport)
{
wstring applicationTypeName;
if (parser.TryGetString(L"apptype", applicationTypeName))
{
if (!attributes->AttributeSetFlags.IsApplicationTypeNameSet() ||
attributes->ApplicationTypeName != applicationTypeName)
{
TestSession::WriteInfo(TraceSource, "CheckApplicationEntityState: apptypeName mismatch: expected '{0}'/ actual '{1}'", applicationTypeName, attributes->ApplicationTypeName);
success = false;
return true;
}
}
}
}
return true;
}
bool TestFabricClientHealth::CheckHealthEntityCommonParameters(
__in CommandLineParser & parser,
HealthEntitySPtr const & entity,
__inout AttributesStoreDataSPtr & baseAttributes)
{
if (entity)
{
HealthEntityState::Enum entityState;
vector<HealthEvent> events;
if (!entity->Test_GetData(entityState, baseAttributes, events))
{
return false;
}
int expectedEventCount;
if (parser.TryGetInt(L"expectedeventcount", expectedEventCount))
{
if (static_cast<int>(events.size()) != expectedEventCount)
{
TestSession::WriteInfo(TraceSource, "Unexpected event count: expected {0}, actual {1}.", expectedEventCount, events.size());
return false;
}
}
wstring expectedEntityStateString;
if (parser.TryGetString(L"expectedentitystate", expectedEntityStateString))
{
wstring actualEntityState = wformatString(entityState);
if (!StringUtility::AreEqualCaseInsensitive(expectedEntityStateString, actualEntityState))
{
TestSession::WriteInfo(TraceSource, "Unexpected entity health state: expected {0}, actual {1}.", expectedEntityStateString, actualEntityState);
return false;
}
}
wstring expectedState;
if (parser.TryGetString(L"state", expectedState))
{
return CheckEntityState(expectedState, *baseAttributes);
}
return true;
}
else
{
wstring expectedState;
if (!parser.TryGetString(L"state", expectedState))
{
TestSession::WriteInfo(TraceSource, "Entity not found and \"state\" parameter not provided");
return false;
}
return CheckCleanedUpEntityState(expectedState);
}
}
bool TestFabricClientHealth::CheckCleanedUpEntityState(std::wstring const & expectedState)
{
TestSession::WriteNoise(TraceSource, "CheckCleanedUpEntityState: expectedState={0}", expectedState);
return (expectedState == L"cleanedup") || (expectedState == L"deleted") || (expectedState == L"notfound");
}
bool TestFabricClientHealth::CheckEntityState(std::wstring const & expectedState, AttributesStoreData const & attributes)
{
TestSession::WriteNoise(TraceSource, "CheckEntityState: {0}, expectedState={1}", attributes, expectedState);
bool success;
if (expectedState == L"notfound")
{
success = false;
}
if (expectedState == L"cleanedup")
{
success = attributes.IsCleanedUp;
}
else if (expectedState == L"deleted")
{
success = attributes.IsCleanedUp || attributes.IsMarkedForDeletion;
}
else if (expectedState == L"nosystemreport")
{
success = attributes.ExpectSystemReports && (!attributes.HasSystemReport);
}
else if (expectedState == L"systemerror")
{
success = attributes.HasSystemError;
}
else if (expectedState == L"ok")
{
success = attributes.HasSystemReport && (!attributes.IsMarkedForDeletion) && (!attributes.IsCleanedUp);
}
else
{
TestSession::WriteInfo(TraceSource, "CheckEntityState failed: unknown expectedState={0}, actual: {1}", expectedState, attributes);
success = false;
}
if (!success)
{
TestSession::WriteInfo(TraceSource, "CheckEntityState failed: expectedState={0}, actual: {1}", expectedState, attributes);
}
return success;
}
wstring TestFabricClientHealth::ConvertHealthOutput(wstring const & input)
{
size_t i = input.find_first_of(L'(');
if (i != wstring::npos && input.back() == L')')
{
return input.substr(i + 1, input.size() - i - 2);
}
return input;
}
bool TestFabricClientHealth::ParseUnhealthyState(std::wstring const & input, __inout ULONG & error, __inout ULONG & total)
{
vector<wstring> unhealthyState;
StringUtility::Split<wstring>(input, unhealthyState, L"/");
if (unhealthyState.size() != 2)
{
TestSession::WriteError(TraceSource, "Unable to parse unhealthy state {0}: expected error/total format", input);
return false;
}
if (!StringUtility::TryFromWString(unhealthyState[0], error))
{
TestSession::WriteError(TraceSource, "Unable to parse error count from {0}", input);
return false;
}
if (!StringUtility::TryFromWString(unhealthyState[1], total))
{
TestSession::WriteError(TraceSource, "Unable to parse total count from {0}", input);
return false;
}
return true;
}
bool TestFabricClientHealth::ParseSnapshot(std::wstring const & input, Management::HealthManager::ClusterUpgradeStateSnapshot & snapshot)
{
vector<wstring> tokens;
StringUtility::Split<wstring>(input, tokens, L",");
for (wstring const & entry : tokens)
{
vector<wstring> uds;
StringUtility::Split<wstring>(entry, uds, L":");
if (uds.size() == 1)
{
// global
ULONG error;
ULONG total;
if (!ParseUnhealthyState(uds[0], error, total))
{
return false;
}
snapshot.SetGlobalState(error, total);
}
else if (uds.size() == 2)
{
ULONG error;
ULONG total;
if (!ParseUnhealthyState(uds[1], error, total))
{
return false;
}
snapshot.AddUpgradeDomainEntry(uds[0], error, total);
}
else
{
TestSession::WriteError(TraceSource, "Unable to parse snapshot {0}: {1} is not global or ud entry", input, entry);
return false;
}
}
return true;
}
bool TestFabricClientHealth::TakeClusterHealthSnapshot(StringCollection const & params)
{
CommandLineParser parser(params);
bool requiresValidation = false;
wstring snapshotString;
ClusterUpgradeStateSnapshot expectedSnapshot;
if (parser.TryGetString(L"expected", snapshotString))
{
requiresValidation = true;
if (!ParseSnapshot(snapshotString, expectedSnapshot))
{
return false;
}
}
Management::HealthManager::HealthManagerReplicaSPtr hmPrimary;
if (!GetHMPrimaryWithRetries(hmPrimary))
{
return false;
}
ActivityId activityId;
ClusterUpgradeStateSnapshot actualSnapshot;
auto error = hmPrimary->GetClusterUpgradeSnapshot(activityId, actualSnapshot);
TestSession::FailTestIfNot(error.IsSuccess(), "hm->GetClusterUpgradeSnapshot returned {0}", error);
// Print snapshot
wstring actualSnapshotString;
StringWriter writer(actualSnapshotString);
writer.Write("Global={0}/{1}, Uds=[", actualSnapshot.GlobalUnhealthyState.ErrorCount, actualSnapshot.GlobalUnhealthyState.TotalCount);
for (auto const & entry : actualSnapshot.UpgradeDomainUnhealthyStates)
{
writer.Write("{0}:{1}/{2} ", entry.first, entry.second.ErrorCount, entry.second.TotalCount);
}
writer.Write("]");
TestSession::WriteInfo(TraceSource, "Snapshot: {0}", actualSnapshotString);
if (requiresValidation)
{
if (expectedSnapshot.GlobalUnhealthyState != actualSnapshot.GlobalUnhealthyState)
{
TestSession::WriteInfo(
TraceSource,
"Snapshot global mismatch: expected {0}/{1}, actual {2}/{3}",
expectedSnapshot.GlobalUnhealthyState.ErrorCount,
expectedSnapshot.GlobalUnhealthyState.TotalCount,
actualSnapshot.GlobalUnhealthyState.ErrorCount,
actualSnapshot.GlobalUnhealthyState.TotalCount);
return false;
}
if (expectedSnapshot.UpgradeDomainUnhealthyStates.size() != actualSnapshot.UpgradeDomainUnhealthyStates.size())
{
TestSession::WriteInfo(TraceSource, "Snapshot ud count mismatch: expected {0}, actual {1}", expectedSnapshot.UpgradeDomainUnhealthyStates.size(), actualSnapshot.UpgradeDomainUnhealthyStates.size());
return false;
}
for (auto const & entry : actualSnapshot.UpgradeDomainUnhealthyStates)
{
ULONG err;
ULONG total;
if (!expectedSnapshot.TryGetUpgradeDomainEntry(entry.first, err, total).IsSuccess())
{
TestSession::WriteInfo(TraceSource, "Returned UD is not expected {0}", entry.first);
return false;
}
UnhealthyState expectedState(err, total);
if (entry.second != expectedState)
{
TestSession::WriteInfo(
TraceSource,
"Snapshot UD mismatch for {0}: expected {1}/{2}, actual {3}/{4}",
entry.first,
expectedState.ErrorCount,
expectedState.TotalCount,
entry.second.ErrorCount,
entry.second.TotalCount);
return false;
}
}
}
return true;
}
bool TestFabricClientHealth::GetApplicationHealthPolicies(__in CommandLineParser & parser, __inout ApplicationHealthPolicyMapSPtr & applicationHealthPolicies)
{
wstring jsonApplicationHealthPolicies;
if (parser.TryGetString(L"apphealthpolicies", jsonApplicationHealthPolicies))
{
applicationHealthPolicies = make_shared<ApplicationHealthPolicyMap>();
auto error = ApplicationHealthPolicyMap::FromString(jsonApplicationHealthPolicies, *applicationHealthPolicies);
if (!error.IsSuccess())
{
TestSession::WriteWarning(TraceSource, "Failed to parse application health policies string {0} with {1}", jsonApplicationHealthPolicies, error);
return false;
}
}
return true;
}
bool TestFabricClientHealth::GetHMPrimaryWithRetries(__inout Management::HealthManager::HealthManagerReplicaSPtr & hm)
{
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
DWORD retryDelay = static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds());
do
{
--remainingRetries;
hm = FABRICSESSION.FabricDispatcher.GetHM();
if (hm)
{
return true;
}
TestSession::WriteInfo(TraceSource, "GetHMPrimaryWithRetries: HM not ready, remaining retries {0}, sleep {1} msec", remainingRetries, retryDelay);
Sleep(retryDelay);
} while (remainingRetries >= 0);
TestSession::WriteWarning(TraceSource, "GetHMPrimaryWithRetries: Could not get HM and retries are exhausted.");
return false;
}
bool TestFabricClientHealth::CheckIsClusterHealthy(StringCollection const & params)
{
CommandLineParser parser(params);
wstring snapshotString;
ClusterUpgradeStateSnapshot baseline;
if (parser.TryGetString(L"baseline", snapshotString))
{
if (!ParseSnapshot(snapshotString, baseline))
{
return false;
}
}
wstring jsonPolicy;
shared_ptr<ClusterHealthPolicy> clusterPolicy;
if (parser.TryGetString(L"jsonpolicy", jsonPolicy))
{
clusterPolicy = make_shared<ClusterHealthPolicy>();
auto error = ClusterHealthPolicy::FromString(jsonPolicy, *clusterPolicy);
if (!error.IsSuccess())
{
TestSession::WriteWarning(TraceSource, "Failed to parse cluster health policy string {0} with {1}", jsonPolicy, error);
return false;
}
}
wstring jsonUpgradePolicy;
shared_ptr<ClusterUpgradeHealthPolicy> clusterUpgradePolicy;
if (parser.TryGetString(L"jsonupgradepolicy", jsonUpgradePolicy))
{
clusterUpgradePolicy = make_shared<ClusterUpgradeHealthPolicy>();
auto error = ClusterUpgradeHealthPolicy::FromString(jsonUpgradePolicy, *clusterUpgradePolicy);
if (!error.IsSuccess())
{
TestSession::WriteWarning(TraceSource, "Failed to parse cluster upgrade health policy string {0} with {1}", jsonUpgradePolicy, error);
return false;
}
}
vector<wstring> upgradeDomains;
wstring upgradeDomainList;
if (!parser.TryGetString(L"upgradedomains", upgradeDomainList))
{
TestSession::WriteWarning(TraceSource, "Required parameter upgradedomains is missing");
return false;
}
StringUtility::Split<wstring>(upgradeDomainList, upgradeDomains, L",");
size_t expectedAppsWithoutAppTypeCount;
int expectedAppsWithoutAppTypeCountInt;
parser.TryGetInt(L"expectedappswithoutapptypecount", expectedAppsWithoutAppTypeCountInt, 0);
expectedAppsWithoutAppTypeCount = static_cast<size_t>(expectedAppsWithoutAppTypeCountInt);
vector<wstring> expectedAppsWithoutAppType;
wstring appsWithoutAppTypeList;
if (parser.TryGetString(L"expectedappswithoutapptype", appsWithoutAppTypeList))
{
StringUtility::Split<wstring>(appsWithoutAppTypeList, expectedAppsWithoutAppType, L",");
if (expectedAppsWithoutAppTypeCount == 0u)
{
expectedAppsWithoutAppTypeCount = expectedAppsWithoutAppType.size();
}
}
bool expectedIsHealthy = false;
wstring expectedHealthyString;
if (parser.TryGetString(L"expectedhealthy", expectedHealthyString))
{
expectedIsHealthy = parser.GetBool(L"expectedhealthy");
}
else if (expectedAppsWithoutAppTypeCount == 0)
{
TestSession::WriteWarning(TraceSource, "Required parameter expectedhealthy is missing");
return false;
}
ApplicationHealthPolicyMapSPtr applicationHealthPolicies;
if (!GetApplicationHealthPolicies(parser, applicationHealthPolicies))
{
return false;
}
Management::HealthManager::HealthManagerReplicaSPtr hmPrimary;
if (!GetHMPrimaryWithRetries(hmPrimary))
{
return false;
}
ActivityId activityId;
bool actualIsHealthy;
vector<HealthEvaluation> unhealthyEvaluations;
vector<wstring> actualAppsWithoutAppType;
auto error = hmPrimary->Test_IsClusterHealthy(
activityId,
upgradeDomains,
clusterPolicy,
clusterUpgradePolicy,
applicationHealthPolicies,
baseline,
actualIsHealthy,
unhealthyEvaluations,
actualAppsWithoutAppType);
if (expectedAppsWithoutAppTypeCount > 0)
{
// Expect to receive error
TestSession::FailTestIfNot(error.IsError(ErrorCodeValue::ApplicationTypeNotFound), "{0}: Test_IsClusterHealthy returned {1}, but expected {2} apps without app types {3}", activityId, error, expectedAppsWithoutAppTypeCount, expectedAppsWithoutAppType);
if (actualAppsWithoutAppType.size() != expectedAppsWithoutAppTypeCount)
{
TestSession::WriteInfo(TraceSource, "{0}: mismatch for apps without app types count: expected {1}, actual {2}", activityId, expectedAppsWithoutAppTypeCount, actualAppsWithoutAppType.size());
return false;
}
if (!expectedAppsWithoutAppType.empty())
{
// Sort the vectors
sort(expectedAppsWithoutAppType.begin(), expectedAppsWithoutAppType.end());
sort(actualAppsWithoutAppType.begin(), actualAppsWithoutAppType.end());
for (size_t i = 0; i < expectedAppsWithoutAppType.size(); ++i)
{
if (actualAppsWithoutAppType[i] != expectedAppsWithoutAppType[i])
{
TestSession::WriteInfo(TraceSource, "{0}: mismatch for apps without app types at position {1}: expected {2}, actual {3}", activityId, i, expectedAppsWithoutAppType[i], actualAppsWithoutAppType[i]);
return false;
}
}
}
return true;
}
TestSession::FailTestIfNot(error.IsSuccess(), "{0}: Error executing Test_IsClusterHealthy: {1}", activityId, error);
if (actualIsHealthy)
{
if (!unhealthyEvaluations.empty())
{
TestSession::FailTest("{0}: IsClusterHealthy returned healthy and {1} evaluation results: {1}", activityId, unhealthyEvaluations.size(), unhealthyEvaluations[0].Evaluation->Description);
}
}
else
{
TestSession::FailTestIf(unhealthyEvaluations.empty(), "{0}: IsClusterHealthy returned unhealthy and 0 evaluations", activityId);
}
if (expectedIsHealthy != actualIsHealthy)
{
TestSession::WriteInfo(TraceSource, "{0}: mismatch for isHealthy result: expected {1}, actual {2}", activityId, expectedIsHealthy, actualIsHealthy);
return false;
}
wstring expectedEvaluation;
if (parser.TryGetString(L"expectedreason", expectedEvaluation))
{
return VerifyExpectedHealthEvaluations(expectedEvaluation, unhealthyEvaluations);
}
else
{
PrintUnhealthyEvaluations(unhealthyEvaluations);
}
return true;
}
bool TestFabricClientHealth::SetHMThrottle(StringCollection const & params)
{
if (params.size() == 0)
{
return false;
}
Management::HealthManager::HealthManagerReplicaSPtr hm;
if (!GetHMPrimaryWithRetries(hm))
{
return false;
}
CommandLineParser parser(params);
bool shouldThrottle = parser.GetBool(L"throttle");
hm->JobQueueManager.Test_SetThrottle(shouldThrottle);
return true;
}
bool TestFabricClientHealth::CheckHealthStats(__in CommandLineParser & parser, HealthStatisticsUPtr const & healthStats)
{
wstring excludeHealthStatsString;
bool excludeHealthStats = parser.GetBool(L"excludeHealthStats");
if (excludeHealthStats)
{
if (healthStats != nullptr)
{
TestSession::WriteInfo(TraceSource, "CheckHealthStats: excludeHealthStates=true but received health stats {0}", *healthStats);
return false;
}
else
{
return true;
}
}
else if (healthStats == nullptr)
{
TestSession::WriteInfo(TraceSource, "CheckHealthStats: excludeHealthStates=false but no health stats received");
return false;
}
wstring expectedHealthStatesString;
if (!parser.TryGetString(L"stats", expectedHealthStatesString))
{
// No need to validate
return true;
}
HealthStateCountMap results;
if (healthStats)
{
results = healthStats->GetHealthCountMap();
}
wstring expectedStats;
if (!parser.TryGetString(L"stats", expectedStats))
{
// No validation needed
return true;
}
return VerifyHealthStateCountMap(expectedStats, results);
}
bool TestFabricClientHealth::CheckHM(StringCollection const & params)
{
if (params.size() == 0)
{
return false;
}
Management::HealthManager::HealthManagerReplicaSPtr hm;
if (!GetHMPrimaryWithRetries(hm))
{
return false;
}
CommandLineParser parser(params);
int expectedCount = -1;
parser.TryGetInt(L"expectedcount", expectedCount);
ErrorCode error;
size_t actualCount;
int remainingRetries = FabricTestSessionConfig::GetConfig().QueryOperationRetryCount;
ActivityId activityId;
do
{
--remainingRetries;
vector<HealthEntitySPtr> entities;
if (params[0] == L"nodes")
{
error = hm->EntityManager->Nodes.GetEntities(activityId, entities);
}
else if (params[0] == L"partitions")
{
error = hm->EntityManager->Partitions.GetEntities(activityId, entities);
}
else if (params[0] == L"replicas")
{
error = hm->EntityManager->Replicas.GetEntities(activityId, entities);
}
else if (params[0] == L"applications")
{
error = hm->EntityManager->Applications.GetEntities(activityId, entities);
}
else if (params[0] == L"services")
{
error = hm->EntityManager->Services.GetEntities(activityId, entities);
}
else if (params[0] == L"deployedapplications")
{
error = hm->EntityManager->DeployedApplications.GetEntities(activityId, entities);
}
else if (params[0] == L"deployedservicepackages")
{
error = hm->EntityManager->DeployedServicePackages.GetEntities(activityId, entities);
}
else
{
return false;
}
actualCount = entities.size();
if (error.IsSuccess() && expectedCount == static_cast<int>(actualCount))
{
return true;
}
TestSession::WriteInfo(TraceSource, "CheckHM failed: expectedCount={0}, actualCount={1}, remaining retries {2}", expectedCount, actualCount, remainingRetries);
Sleep(static_cast<DWORD>(FabricTestSessionConfig::GetConfig().QueryOperationRetryDelay.TotalMilliseconds()));
}
while (remainingRetries > 0);
TestSession::WriteWarning(TraceSource, "CheckHM failed: expectedCount={0}, timeout expired", expectedCount);
return false;
}
bool TestFabricClientHealth::ShowHM(HealthManagerReplicaSPtr const & hm, StringCollection const & params)
{
if (params.size() == 0)
{
return false;
}
ErrorCode error;
ActivityId activityId;
vector<HealthEntitySPtr> entities;
if (params[0] == L"nodes")
{
error = hm->EntityManager->Nodes.GetEntities(activityId, entities);
}
else if (params[0] == L"partitions")
{
error = hm->EntityManager->Partitions.GetEntities(activityId, entities);
}
else if (params[0] == L"replicas")
{
error = hm->EntityManager->Replicas.GetEntities(activityId, entities);
}
else if (params[0] == L"applications")
{
error = hm->EntityManager->Applications.GetEntities(activityId, entities);
}
else if (params[0] == L"services")
{
error = hm->EntityManager->Services.GetEntities(activityId, entities);
}
else if (params[0] == L"deployedapplications")
{
error = hm->EntityManager->DeployedApplications.GetEntities(activityId, entities);
}
else if (params[0] == L"deployedservicepackages")
{
error = hm->EntityManager->DeployedServicePackages.GetEntities(activityId, entities);
}
else
{
TestSession::WriteInfo(TraceSource, "ShowHM: Unknown entity type {0}", params[0]);
return false;
}
if (!error.IsSuccess())
{
TestSession::WriteInfo(TraceSource, "Error getting {0} from HM cache: {1}", params[0], error);
return false;
}
wstring pattern;
bool countOnly = false;
if (params.size() > 1)
{
if (params[1] == L"count")
{
countOnly = true;
}
else
{
pattern = params[1];
}
}
int count = 0;
bool showReplicas = (params[0] == L"partitions");
for (auto const & entity : entities)
{
if (pattern.empty() || StringUtility::Contains<wstring>(entity->EntityIdString, pattern))
{
HealthEntityState::Enum entityState;
AttributesStoreDataSPtr baseAttributes;
vector<HealthEvent> events;
if (entity->Test_GetData(entityState, baseAttributes, events))
{
if (!countOnly)
{
TestSession::WriteInfo(TraceSource, "\n{0}, entityState {1}", TestFabricClientHealth::ConvertHealthOutput(wformatString(*baseAttributes)), entityState);
for (auto it = events.begin(); it != events.end(); ++it)
{
TestSession::WriteInfo(TraceSource, "\t{0}", ConvertHealthOutput(wformatString(*it)));
}
if (showReplicas)
{
auto partition = PartitionsCache::GetCastedEntityPtr(entity);
TestSession::WriteInfo(TraceSource, "Replicas:");
set<ReplicaEntitySPtr> replicas = partition->GetReplicas();
for (ReplicaEntitySPtr const & replica : replicas)
{
TestSession::WriteInfo(TraceSource, "\t{0}", replica->EntityIdString);
}
}
}
++count;
}
else
{
TestSession::WriteInfo(TraceSource, "\nNot loaded, entity state {0}", entityState);
}
}
}
TestSession::WriteInfo(TraceSource, "{0} {1} entities", count, params[0]);
return true;
}
bool TestFabricClientHealth::VerifyNodeHealthReports(HealthManagerReplicaSPtr const & hm, vector<NodeSnapshot> const & nodes, size_t expectedUpCount)
{
vector<NodeEntitySPtr> hmNodes;
if (!healthTable_->Update(hm, hmNodes))
{
return false;
}
FABRIC_SEQUENCE_NUMBER invalidatedSequence = hm->EntityManager->Nodes.Test_GetInvalidatedLsn(*ServiceModel::Constants::HealthReportFMSource);
size_t hmUpCount = 0;
for (NodeEntitySPtr const & node : hmNodes)
{
bool isInvalidated = false;
HealthEntityState::Enum entityState;
shared_ptr<AttributesStoreData> entityBase;
vector<HealthEvent> events;
if (!node->Test_GetData(entityState, entityBase, events))
{
TestSession::WriteInfo(TraceSource, "HM get node failed for {0}, entity state {1}", node->EntityId, entityState);
return false;
}
auto entity = dynamic_cast<NodeAttributesStoreData*>(entityBase.get());
bool found = false;
for (auto it = events.begin(); it != events.end(); ++it)
{
if (it->SourceId == *ServiceModel::Constants::HealthReportFMSource)
{
found = true;
TestSession::FailTestIfNot(
(it->Property == *ServiceModel::Constants::HealthStateProperty) && (it->TimeToLive == TimeSpan::MaxValue),
"{0}: Unexpected health event: {1}",
node->EntityIdString,
*it);
if (it->State == FABRIC_HEALTH_STATE_OK)
{
++hmUpCount;
auto itNode = find_if(nodes.begin(), nodes.end(),
[node](NodeSnapshot const & fmNode) { return fmNode.Id == node->EntityId; });
if (itNode == nodes.end())
{
TestSession::WriteInfo(TraceSource, "Up node {0} in HM not found in FM", node->EntityId);
return false;
}
else if (!itNode->IsUp)
{
TestSession::WriteInfo(TraceSource, "Up node {0} in HM is down in FM", node->EntityId);
return false;
}
else if (itNode->HealthSequence != it->SequenceNumber)
{
TestSession::WriteInfo(TraceSource, "HM node {0} sequence number {1} does not match FM {2}", node->EntityId, it->SequenceNumber, itNode->HealthSequence);
return false;
}
else if ((itNode->NodeInstance.InstanceId != entity->NodeInstanceId) ||
(itNode->NodeName != entity->NodeName) ||
(itNode->FaultDomainId != entity->FaultDomain) ||
(itNode->ActualUpgradeDomainId != entity->UpgradeDomain) ||
(itNode->IpAddressOrFQDN != entity->IpAddressOrFqdn))
{
TestSession::WriteInfo(TraceSource, "HM node property {0} does not match FM {1}", *entity, *itNode);
return false;
}
}
isInvalidated = (it->SequenceNumber < invalidatedSequence);
}
}
if (!found)
{
TestSession::WriteInfo(TraceSource, "Node {0} did not find FM report", node->EntityIdString);
return false;
}
if (!healthTable_->Verify(node, events, isInvalidated))
{
return false;
}
}
if (hmUpCount != expectedUpCount)
{
TestSession::WriteInfo(TraceSource, "HM up node count {0} does not match FM {1}", hmUpCount, expectedUpCount);
return false;
}
return true;
}
bool TestFabricClientHealth::VerifyParititionHealthReports(HealthManagerReplicaSPtr const & hm, map<FailoverUnitId, FailoverUnitSnapshot> const & failoverUnits)
{
set<FailoverUnitId> fmFailoverUnits;
for (auto it = failoverUnits.begin(); it != failoverUnits.end(); ++it)
{
if (!it->second.IsOrphaned)
{
fmFailoverUnits.insert(it->first);
}
}
vector<PartitionEntitySPtr> hmPartitions;
if (!healthTable_->Update(hm, hmPartitions))
{
return false;
}
FABRIC_SEQUENCE_NUMBER invalidatedSequence = hm->EntityManager->Partitions.Test_GetInvalidatedLsn(*ServiceModel::Constants::HealthReportFMSource);
for (PartitionEntitySPtr const & partition : hmPartitions)
{
bool isInvalidated = false;
HealthEntityState::Enum entityState;
shared_ptr<AttributesStoreData> entityBase;
vector<HealthEvent> events;
if (!partition->Test_GetData(entityState, entityBase, events))
{
TestSession::WriteInfo(TraceSource, "HM get partition failed for {0}, entity state {1}", partition->EntityId, entityState);
return false;
}
auto entity = static_cast<PartitionAttributesStoreData*>(entityBase.get());
bool found = false;
for (auto it = events.begin(); it != events.end(); ++it)
{
if (it->SourceId == *ServiceModel::Constants::HealthReportFMSource)
{
found = true;
isInvalidated = (it->SequenceNumber < invalidatedSequence);
TestSession::FailTestIf(
it->Property != *ServiceModel::Constants::HealthStateProperty ||
it->TimeToLive != TimeSpan::MaxValue,
"Unexpected health event: {0}", *it);
auto itFailoverUnit = failoverUnits.find(FailoverUnitId(entity->EntityId));
if (itFailoverUnit == failoverUnits.end() || itFailoverUnit->second.IsOrphaned)
{
if (dispatcher_.IsRebuildLostFU(entity->EntityId))
{
continue;
}
TestSession::WriteInfo(TraceSource, "HM Partition {0}\n{1} not found in FM", *entity, *it);
return false;
}
fmFailoverUnits.erase(itFailoverUnit->first);
FailoverUnitSnapshot const * failoverUnit = &(itFailoverUnit->second);
if (failoverUnit->HealthSequence != it->SequenceNumber)
{
TestSession::WriteInfo(TraceSource, "HM partition {0}\n{1} sequence number does not match FM {2}", *entity, *it, failoverUnit->HealthSequence);
return false;
}
else if (SystemServiceApplicationNameHelper::GetPublicServiceName(failoverUnit->ServiceName) != entity->ServiceName)
{
TestSession::WriteInfo(TraceSource, "HM partition {0}\n{1} attributes do not match FM {2}", *entity, *it, failoverUnit->GetServiceInfo().ServiceDescription);
return false;
}
else if (failoverUnit->IsQuorumLost())
{
if (failoverUnit->CurrentHealthState != FailoverUnitHealthState::QuorumLost)
{
TestSession::WriteInfo(TraceSource, "FM partition state {0} expected to be in quorum loss: {1}", failoverUnit->CurrentHealthState, *failoverUnit);
return false;
}
if (it->State != FABRIC_HEALTH_STATE_ERROR || !StringUtility::Contains(it->Description, HMResource::GetResources().PartitionQuorumLoss))
{
TestSession::WriteInfo(TraceSource, "HM Partition {0}\n{1} does not match FM quorum loss state", *entity, *it);
return false;
}
}
else if (failoverUnit->IsInReconfiguration)
{
if (failoverUnit->CurrentHealthState != FailoverUnitHealthState::ReconfigurationStuck)
{
TestSession::WriteInfo(TraceSource, "FM partition state {0} expected to be in reconfiguration stuck: {1}: {1}", failoverUnit->CurrentHealthState, *failoverUnit);
return false;
}
if (it->State != FABRIC_HEALTH_STATE_WARNING || !StringUtility::Contains(it->Description, HMResource::GetResources().PartitionReconfigurationStuck))
{
TestSession::WriteInfo(TraceSource, "HM Partition {0}\n{1} does not match FM reconfiguration state", *entity, *it);
return false;
}
}
else if ((failoverUnit->IsStateful && static_cast<int>(failoverUnit->GetCurrentConfigurationReplicas().size()) < failoverUnit->TargetReplicaSetSize) ||
(!failoverUnit->IsStateful && static_cast<int>(failoverUnit->ReplicaCount) < failoverUnit->TargetReplicaSetSize))
{
if (failoverUnit->CurrentHealthState != FailoverUnitHealthState::PlacementStuck)
{
TestSession::WriteInfo(TraceSource, "FM partition state {0} expected to be in placement stuck: {1}", failoverUnit->CurrentHealthState, *failoverUnit);
return false;
}
if (it->State != FABRIC_HEALTH_STATE_WARNING || !StringUtility::Contains(it->Description, HMResource::GetResources().PartitionPlacementStuck))
{
TestSession::WriteInfo(TraceSource, "HM Partition {0}\n{1} does not match FM below replica count state", *entity, *it);
return false;
}
}
else
{
bool inBuild = false;
auto replicas = failoverUnit->GetReplicas();
for (auto replica = replicas.begin(); replica != replicas.end(); ++replica)
{
if (replica->IsUp && replica->IsInBuild)
{
inBuild = true;
if (failoverUnit->CurrentHealthState != FailoverUnitHealthState::BuildStuck)
{
TestSession::WriteInfo(TraceSource, "FM partition state {0} expected to be in placement stuck for replica {1}: {2}", failoverUnit->CurrentHealthState, replica->FederationNodeId, *failoverUnit);
return false;
}
if (it->State != FABRIC_HEALTH_STATE_WARNING || !StringUtility::StartsWith(it->Description, HMResource::GetResources().PartitionPlacementStuck) || !StringUtility::Contains(it->Description, replica->GetNode().NodeName))
{
TestSession::WriteInfo(TraceSource, "HM Partition {0}\n{1} does not match FM below replica inbuild state", *entity, *it);
return false;
}
}
}
if (!inBuild)
{
if (failoverUnit->CurrentHealthState != FailoverUnitHealthState::Healthy)
{
TestSession::WriteInfo(TraceSource, "FM partition state {0} expected to be healthy: {1}", failoverUnit->CurrentHealthState, *failoverUnit);
return false;
}
if (it->State != FABRIC_HEALTH_STATE_OK || !StringUtility::Contains(it->Description, HMResource::GetResources().PartitionHealthy))
{
TestSession::WriteInfo(TraceSource, "HM Partition {0}\n{1} does not match FM healthy state", *entity, *it);
return false;
}
}
}
}
}
if (!found && partition->EntityId != Reliability::Constants::FMServiceGuid)
{
TestSession::WriteInfo(TraceSource, "Partition {0} did not find FM report", partition->EntityId);
return false;
}
if (!healthTable_->Verify(partition, events, isInvalidated))
{
return false;
}
}
if (fmFailoverUnits.size() > 0)
{
TestSession::WriteInfo(TraceSource, "{0} FM partitions not found in HM: {1}", fmFailoverUnits.size(), *fmFailoverUnits.begin());
return false;
}
return true;
}
bool TestFabricClientHealth::VerifyReplicaHealthReports(
HealthManagerReplicaSPtr const & hm,
map<FailoverUnitId, FailoverUnitSnapshot> const & failoverUnits)
{
map<wstring, bool> fmReplicas;
for (auto it = failoverUnits.begin(); it != failoverUnits.end(); ++it)
{
auto replicas = it->second.GetReplicas();
for (auto replica = replicas.begin(); replica != replicas.end(); ++replica)
{
if (replica->IsUp && !replica->IsCreating &&
(!it->second.IsStateful || (replica->CurrentConfigurationRole != ReplicaRole::None && !replica->IsStandBy)))
{
wstring id = wformatString("{0}+{1}", it->second.Id, replica->ReplicaId);
fmReplicas.insert(make_pair(move(id), it->second.IsQuorumLost()));
}
}
}
TestSession::WriteNoise(TraceSource, "FM up replicas :{0}", fmReplicas.size());
vector<ReplicaEntitySPtr> hmReplicas;
if (!healthTable_->Update(hm, hmReplicas))
{
return false;
}
for (ReplicaEntitySPtr const & replica : hmReplicas)
{
HealthEntityState::Enum entityState;
shared_ptr<AttributesStoreData> entityBase;
vector<HealthEvent> events;
if (!replica->Test_GetData(entityState, entityBase, events))
{
TestSession::WriteInfo(TraceSource, "HM get replica failed: {0}, entity state {1}", replica->EntityId, entityState);
return false;
}
auto entity = static_cast<ReplicaAttributesStoreData*>(entityBase.get());
bool found = false;
for (auto it = events.begin(); it != events.end(); ++it)
{
if (it->SourceId == *ServiceModel::Constants::HealthReportRASource)
{
found = true;
if (it->Property == *ServiceModel::Constants::HealthStateProperty)
{
TestSession::FailTestIf(
it->TimeToLive != TimeSpan::MaxValue,
"Unexpected health event (TTL not infinite for EventProperty: {0}, EventState: {1}): {2}", it->Property, it->State, *it);
}
if (replica->EntityId.PartitionId == Reliability::Constants::FMServiceGuid ||
dispatcher_.IsRebuildLostFailoverUnit(replica->EntityId.PartitionId))
{
continue;
}
auto itFailoverUnit = failoverUnits.find(FailoverUnitId(entity->EntityId.PartitionId));
if (itFailoverUnit == failoverUnits.end() || itFailoverUnit->second.IsOrphaned)
{
TestSession::WriteInfo(TraceSource, "Replica {0} in HM not found in FM partition", *entity);
return false;
}
auto fmReplica = itFailoverUnit->second.GetReplica(entity->NodeId);
if (!fmReplica)
{
TestSession::WriteInfo(TraceSource, "Replica {0} in HM not found in FM", *entity);
return false;
}
if (entity->EntityId.ReplicaId != fmReplica->ReplicaId ||
entity->InstanceId != (itFailoverUnit->second.IsStateful ? fmReplica->InstanceId : -2) ||
entity->NodeInstanceId != fmReplica->GetNode().NodeInstance.InstanceId)
{
TestSession::WriteInfo(TraceSource, "Replica attributes {0} in HM does not match FM {1}", *entity, *fmReplica);
return false;
}
if (it->State != FABRIC_HEALTH_STATE_OK)
{
TestSession::WriteInfo(TraceSource, "Replica {0} in HM is not healthy", *it);
// This is a special check because ClearError health report may not be propertly generated due to bug 7188617.
// This will be removed after that bug is fixed.
if (it->State == FABRIC_HEALTH_STATE_ERROR &&
it->Property == *ServiceModel::Constants::HealthReplicaChangeRoleStatusProperty &&
itFailoverUnit->second.IsInReconfiguration)
{
TestSession::WriteInfo(TraceSource, "Ignore health verification for replica {0} event {1} because ClearError health report may not be generated properly.", replica->EntityIdString, *it);
}
else if (it->State == FABRIC_HEALTH_STATE_WARNING &&
it->Property == *ServiceModel::Constants::ReconfigurationProperty &&
itFailoverUnit->second.IsInReconfiguration)
{
TestSession::WriteInfo(TraceSource, "Ignore health verification for replica {0} event {1} because ReconfigurationStuck warning is expected.", replica->EntityIdString, *it);
}
else
{
return false;
}
}
if (!fmReplica->IsUp)
{
TestSession::WriteInfo(TraceSource, "Replica {0} is down in FM", replica->EntityId);
return false;
}
fmReplicas.erase(replica->EntityId.ToString());
}
}
if (!found)
{
TestSession::WriteInfo(TraceSource, "Replica {0} did not find RA report", replica->EntityId);
return false;
}
if (!healthTable_->Verify(replica, events))
{
return false;
}
}
for (auto it = fmReplicas.begin(); it != fmReplicas.end(); ++it)
{
if (!it->second)
{
TestSession::WriteInfo(TraceSource, "{0} replicas on FM not found in HM: {1}", fmReplicas.size(), it->first);
return false;
}
}
return true;
}
bool TestFabricClientHealth::VerifyServiceHealthReports(HealthManagerReplicaSPtr const & hm, vector<ServiceSnapshot> const & services)
{
map<wstring, ServiceSnapshot> fmServices;
for (auto it = services.begin(); it != services.end(); ++it)
{
if (!it->IsDeleted && it->ServiceDescription.Name != Reliability::Constants::TombstoneServiceName)
{
fmServices.insert(make_pair(SystemServiceApplicationNameHelper::GetPublicServiceName(it->ServiceDescription.Name), *it));
}
}
vector<ServiceEntitySPtr> hmServices;
if (!healthTable_->Update(hm, hmServices))
{
return false;
}
FABRIC_SEQUENCE_NUMBER invalidatedSequence = hm->EntityManager->Services.Test_GetInvalidatedLsn(*ServiceModel::Constants::HealthReportFMSource);
for (ServiceEntitySPtr const & service : hmServices)
{
if (service->EntityId.ServiceName == ServiceModel::SystemServiceApplicationNameHelper::PublicFMServiceName)
{
continue;
}
bool isInvalidated = false;
HealthEntityState::Enum entityState;
shared_ptr<AttributesStoreData> entityBase;
vector<HealthEvent> events;
if (!service->Test_GetData(entityState, entityBase, events))
{
TestSession::WriteInfo(TraceSource, "HM get service failed: {0}, entity state {1}", service->EntityId, entityState);
return false;
}
auto entity = static_cast<ServiceAttributesStoreData*>(entityBase.get());
bool found = false;
for (auto it = events.begin(); it != events.end(); ++it)
{
if (it->SourceId == *ServiceModel::Constants::HealthReportFMSource)
{
found = true;
TestSession::FailTestIf(
it->Property != *ServiceModel::Constants::HealthStateProperty ||
it->TimeToLive != TimeSpan::MaxValue ||
it->State != FABRIC_HEALTH_STATE_OK,
"Unexpected health event: {0}", *it);
auto itService = fmServices.find(service->EntityId.ServiceName);
if (itService == fmServices.end())
{
auto partitions = service->GetPartitions();
wstring partitionOutput;
for (PartitionEntitySPtr const & partition : partitions)
{
if (!dispatcher_.IsRebuildLostFailoverUnit(partition->EntityId))
{
partitionOutput = partition->EntityIdString;
break;
}
}
if (partitionOutput.size() > 0)
{
TestSession::WriteInfo(TraceSource, "Service {0} with {1} partitions {2} in HM not found in FM",
*entity, partitions.size(), partitionOutput);
return false;
}
}
else
{
if (itService->second.HealthSequence != it->SequenceNumber)
{
TestSession::WriteInfo(TraceSource, "HM service {0} sequence number {1} does not match FM {2}", service->EntityId, entity->SequenceNumber, itService->second.HealthSequence);
return false;
}
fmServices.erase(itService);
}
isInvalidated = (it->SequenceNumber < invalidatedSequence);
}
}
if (!found)
{
TestSession::WriteInfo(TraceSource, "Service {0} did not find FM report", service->EntityId);
return false;
}
if (!healthTable_->Verify(service, events, isInvalidated))
{
return false;
}
}
if (fmServices.size() > 0)
{
TestSession::WriteInfo(TraceSource, "{0} services on FM not found in HM: {1}", fmServices.size(), *fmServices.begin());
return false;
}
return true;
}
bool TestFabricClientHealth::VerifyApplicationHealthReports(HealthManagerReplicaSPtr const & hm, vector<ServiceSnapshot> const & services)
{
map<wstring, ApplicationSnapshot> fmApplications;
for (auto it = services.begin(); it != services.end(); ++it)
{
if (it->ServiceDescription.ApplicationName.size() > 0 && !it->IsDeleted && it->ServiceDescription.Name != Reliability::Constants::TombstoneServiceName)
{
auto app = it->GetServiceType().GetApplication();
fmApplications.insert(make_pair(it->ServiceDescription.ApplicationName, app));
}
}
vector<ApplicationEntitySPtr> hmApplications;
if (!healthTable_->Update(hm, hmApplications))
{
return false;
}
for (ApplicationEntitySPtr const & application : hmApplications)
{
HealthEntityState::Enum entityState;
shared_ptr<AttributesStoreData> entityBase;
vector<HealthEvent> events;
if (!application->Test_GetData(entityState, entityBase, events))
{
TestSession::WriteInfo(TraceSource, "HM get application failed: {0}, entity state {1}", application->EntityId, entityState);
return false;
}
auto entity = static_cast<ApplicationAttributesStoreData*>(entityBase.get());
if (!application->IsAdHocApp() && !application->IsSystemApp)
{
auto it = fmApplications.find(application->EntityId.ApplicationName);
if (it == fmApplications.end())
{
auto hmAppServices = application->GetServices();
if (hmAppServices.empty())
{
// If an application has no services, it will not appear in FM view, skip validation here
TestSession::WriteNoise(TraceSource, "Application {0} with 0 services in HM not found in FM", *entity);
}
else
{
// Check whether the services are deleted. The CleanupGraceInterval is by default 1 hour, so the entities may not have been cleaned up yet
int upChildren = 0;
wstring details;
StringWriter writer(details);
writer.WriteLine("{0} total services, up:", hmAppServices.size());
for (auto hmAppServicesIt = hmAppServices.begin(); hmAppServicesIt != hmAppServices.end(); ++hmAppServicesIt)
{
auto attrib = (*hmAppServicesIt)->GetAttributesCopy();
if (!attrib->IsCleanedUp && !attrib->IsMarkedForDeletion)
{
++upChildren;
wstring partitions;
StringWriter partitionsDetail(partitions);
auto hmPartitions = (*hmAppServicesIt)->GetPartitions();
for (auto itPartitions = hmPartitions.begin(); itPartitions != hmPartitions.end(); ++itPartitions)
{
partitionsDetail.Write("{0};", (*itPartitions)->EntityIdString);
}
writer.WriteLine("{0}, {1}, partitions: {2}", *attrib, (*hmAppServicesIt)->State.State, partitions);
}
}
if (upChildren > 0)
{
TestSession::WriteInfo(TraceSource, "Application {0} in HM not found in FM. {1}", *entity, details);
return false;
}
}
// If the FM application is not found, the CM report may or may not be received on HM.
// Do not do any validation in this case.
continue;
}
bool found = false;
for (auto itEvents = events.begin(); itEvents != events.end(); ++itEvents)
{
if (itEvents->SourceId == L"System.CM")
{
found = true;
TestSession::FailTestIf(
itEvents->Property != *ServiceModel::Constants::HealthStateProperty ||
itEvents->TimeToLive != TimeSpan::MaxValue,
"Unexpected health event: {0}", *it);
}
}
if (!found)
{
TestSession::WriteInfo(TraceSource, "Application {0} did not find CM report", application->EntityIdString);
return false;
}
if (entity->AttributeSetFlags.IsApplicationTypeNameSet())
{
if (entity->ApplicationTypeName != it->second.AppId.ApplicationTypeName)
{
TestSession::WriteInfo(TraceSource, "Application {0}: HM app type name {1} doesn't match FM {2}", application->EntityIdString, entity->ApplicationTypeName, it->second.AppId.ApplicationTypeName);
return false;
}
}
else
{
TestSession::WriteInfo(TraceSource, "Application {0}: app type name not set", application->EntityIdString);
return false;
}
fmApplications.erase(it);
}
if (!healthTable_->Verify(application, events))
{
return false;
}
}
if (fmApplications.size() > 0)
{
TestSession::WriteInfo(TraceSource, "{0} applications on FM not found in HM: {1}", fmApplications.size(), fmApplications.begin()->first);
return false;
}
return true;
}
bool TestFabricClientHealth::VerifyDeployedServicePackageAndApplicationHealthReports(HealthManagerReplicaSPtr const & hm, map<DeployedServicePackageHealthId, FailoverUnitId> && packages)
{
vector<DeployedServicePackageEntitySPtr> hmDeployedServicePackages;
if (!healthTable_->Update(hm, hmDeployedServicePackages))
{
return false;
}
TestSession::WriteInfo(TraceSource, "DeployedServicePckageCount - HM={0}, RA={1}.", hmDeployedServicePackages.size(), packages.size());
map<DeployedApplicationHealthId, FABRIC_NODE_INSTANCE_ID> applications;
for (DeployedServicePackageEntitySPtr const & package : hmDeployedServicePackages)
{
// For debugging only
TestSession::WriteInfo(TraceSource, "HM DeployedServicePackageEntityId: {0}.", package->EntityId);
HealthEntityState::Enum entityState;
shared_ptr<AttributesStoreData> entityBase;
vector<HealthEvent> events;
if (!package->Test_GetData(entityState, entityBase, events))
{
TestSession::WriteInfo(TraceSource, "HM get deployed service package failed: {0}, entity state {1}", package->EntityId, entityState);
return false;
}
auto entity = static_cast<DeployedServicePackageAttributesStoreData*>(entityBase.get());
auto it = packages.find(package->EntityId);
if (it == packages.end())
{
TestSession::WriteInfo(TraceSource, "Deployed service package {0} in HM not found on RA", *entity);
return false;
}
else
{
bool found = false;
for (auto const & event : events)
{
if (event.SourceId == L"System.Hosting")
{
found = true;
break;
}
}
if (!found)
{
TestSession::WriteInfo(TraceSource, "Deployed service package {0} did not find Hosting report", *entity);
return false;
}
packages.erase(it);
}
if (!healthTable_->Verify(package, events))
{
return false;
}
DeployedApplicationHealthId appId(package->EntityId.ApplicationName, package->EntityId.NodeId);
applications[appId] = entity->NodeInstanceId;
}
if (packages.size() > 0)
{
TestSession::WriteInfo(TraceSource, "{0} deployed service packages on RA not found in HM: {1} with Failover unit {2}", packages.size(), packages.begin()->first, packages.begin()->second);
return false;
}
vector<DeployedApplicationEntitySPtr> hmDeployedApplications;
if (!healthTable_->Update(hm, hmDeployedApplications))
{
return false;
}
for (DeployedApplicationEntitySPtr const & application : hmDeployedApplications)
{
HealthEntityState::Enum entityState;
shared_ptr<AttributesStoreData> entityBase;
vector<HealthEvent> events;
if (!application->Test_GetData(entityState, entityBase, events))
{
TestSession::WriteInfo(TraceSource, "HM get deployed application failed: {0}, entity state {1}", application->EntityId, entityState);
return false;
}
auto entity = static_cast<DeployedApplicationAttributesStoreData*>(entityBase.get());
auto it = applications.find(application->EntityId);
if (it == applications.end())
{
TestSession::WriteInfo(TraceSource, "Deployed application {0} in HM not found in FM", *entity);
return false;
}
else
{
if (entity->NodeInstanceId != it->second)
{
TestSession::WriteInfo(TraceSource, "Deployed application {0} in HM node instance does not match FM {1}",
*entity, it->second);
return false;
}
bool found = false;
for (auto const & event : events)
{
if (event.SourceId == L"System.Hosting")
{
found = true;
break;
}
}
if (!found)
{
TestSession::WriteInfo(TraceSource, "Deployed application {0} did not find Hosting report", *entity);
return false;
}
applications.erase(it);
}
if (!healthTable_->Verify(application, events))
{
return false;
}
}
return true;
}
|
// Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018 The SLATE developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "scheduler.h"
#include "reverselock.h"
#include <assert.h>
#include <boost/bind.hpp>
#include <utility>
CScheduler::CScheduler() : nThreadsServicingQueue(0), stopRequested(false), stopWhenEmpty(false)
{
}
CScheduler::~CScheduler()
{
assert(nThreadsServicingQueue == 0);
}
#if BOOST_VERSION < 105000
static boost::system_time toPosixTime(const boost::chrono::system_clock::time_point& t)
{
return boost::posix_time::from_time_t(boost::chrono::system_clock::to_time_t(t));
}
#endif
void CScheduler::serviceQueue()
{
boost::unique_lock<boost::mutex> lock(newTaskMutex);
++nThreadsServicingQueue;
// newTaskMutex is locked throughout this loop EXCEPT
// when the thread is waiting or when the user's function
// is called.
while (!shouldStop()) {
try {
while (!shouldStop() && taskQueue.empty()) {
// Wait until there is something to do.
newTaskScheduled.wait(lock);
}
// Wait until either there is a new task, or until
// the time of the first item on the queue:
// wait_until needs boost 1.50 or later; older versions have timed_wait:
#if BOOST_VERSION < 105000
while (!shouldStop() && !taskQueue.empty() &&
newTaskScheduled.timed_wait(lock, toPosixTime(taskQueue.begin()->first))) {
// Keep waiting until timeout
}
#else
// Some boost versions have a conflicting overload of wait_until that returns void.
// Explicitly use a template here to avoid hitting that overload.
while (!shouldStop() && !taskQueue.empty() &&
newTaskScheduled.wait_until<>(lock, taskQueue.begin()->first) != boost::cv_status::timeout) {
// Keep waiting until timeout
}
#endif
// If there are multiple threads, the queue can empty while we're waiting (another
// thread may service the task we were waiting on).
if (shouldStop() || taskQueue.empty())
continue;
Function f = taskQueue.begin()->second;
taskQueue.erase(taskQueue.begin());
{
// Unlock before calling f, so it can reschedule itself or another task
// without deadlocking:
reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
f();
}
} catch (...) {
--nThreadsServicingQueue;
throw;
}
}
--nThreadsServicingQueue;
newTaskScheduled.notify_one();
}
void CScheduler::stop(bool drain)
{
{
boost::unique_lock<boost::mutex> lock(newTaskMutex);
if (drain)
stopWhenEmpty = true;
else
stopRequested = true;
}
newTaskScheduled.notify_all();
}
void CScheduler::schedule(CScheduler::Function f, boost::chrono::system_clock::time_point t)
{
{
boost::unique_lock<boost::mutex> lock(newTaskMutex);
taskQueue.insert(std::make_pair(t, f));
}
newTaskScheduled.notify_one();
}
void CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaSeconds)
{
schedule(f, boost::chrono::system_clock::now() + boost::chrono::seconds(deltaSeconds));
}
static void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaSeconds)
{
f();
s->scheduleFromNow(boost::bind(&Repeat, s, f, deltaSeconds), deltaSeconds);
}
void CScheduler::scheduleEvery(CScheduler::Function f, int64_t deltaSeconds)
{
scheduleFromNow(boost::bind(&Repeat, this, f, deltaSeconds), deltaSeconds);
}
size_t CScheduler::getQueueInfo(boost::chrono::system_clock::time_point &first,
boost::chrono::system_clock::time_point &last) const
{
boost::unique_lock<boost::mutex> lock(newTaskMutex);
size_t result = taskQueue.size();
if (!taskQueue.empty()) {
first = taskQueue.begin()->first;
last = taskQueue.rbegin()->first;
}
return result;
}
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/secure_channel/secure_channel.h"
#include <memory>
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "chromeos/components/multidevice/logging/logging.h"
#include "chromeos/components/multidevice/secure_message_delegate_impl.h"
#include "chromeos/services/secure_channel/wire_message.h"
namespace chromeos {
namespace secure_channel {
// static
SecureChannel::Factory* SecureChannel::Factory::factory_instance_ = nullptr;
// static
std::unique_ptr<SecureChannel> SecureChannel::Factory::Create(
std::unique_ptr<Connection> connection) {
if (factory_instance_)
return factory_instance_->CreateInstance(std::move(connection));
return base::WrapUnique(new SecureChannel(std::move(connection)));
}
// static
void SecureChannel::Factory::SetFactoryForTesting(Factory* factory) {
factory_instance_ = factory;
}
// static
std::string SecureChannel::StatusToString(const Status& status) {
switch (status) {
case Status::DISCONNECTED:
return "[disconnected]";
case Status::CONNECTING:
return "[connecting]";
case Status::CONNECTED:
return "[connected]";
case Status::AUTHENTICATING:
return "[authenticating]";
case Status::AUTHENTICATED:
return "[authenticated]";
case Status::DISCONNECTING:
return "[disconnecting]";
default:
return "[unknown status]";
}
}
SecureChannel::PendingMessage::PendingMessage(const std::string& feature,
const std::string& payload,
int sequence_number)
: feature(feature), payload(payload), sequence_number(sequence_number) {}
SecureChannel::PendingMessage::~PendingMessage() {}
SecureChannel::SecureChannel(std::unique_ptr<Connection> connection)
: status_(Status::DISCONNECTED), connection_(std::move(connection)) {
connection_->AddObserver(this);
}
SecureChannel::~SecureChannel() {
connection_->RemoveObserver(this);
}
void SecureChannel::Initialize() {
DCHECK(status_ == Status::DISCONNECTED);
connection_->Connect();
TransitionToStatus(Status::CONNECTING);
}
int SecureChannel::SendMessage(const std::string& feature,
const std::string& payload) {
DCHECK(status_ == Status::AUTHENTICATED);
int sequence_number = next_sequence_number_;
next_sequence_number_++;
queued_messages_.emplace(
std::make_unique<PendingMessage>(feature, payload, sequence_number));
ProcessMessageQueue();
return sequence_number;
}
void SecureChannel::Disconnect() {
if (connection_->IsConnected()) {
TransitionToStatus(Status::DISCONNECTING);
// If |connection_| is active, calling Disconnect() will eventually cause
// its status to transition to DISCONNECTED, which will in turn cause this
// class to transition to DISCONNECTED.
connection_->Disconnect();
return;
}
TransitionToStatus(Status::DISCONNECTED);
}
void SecureChannel::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void SecureChannel::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
void SecureChannel::GetConnectionRssi(
base::OnceCallback<void(absl::optional<int32_t>)> callback) {
if (!connection_) {
std::move(callback).Run(absl::nullopt);
return;
}
connection_->GetConnectionRssi(std::move(callback));
}
absl::optional<std::string> SecureChannel::GetChannelBindingData() {
if (secure_context_)
return secure_context_->GetChannelBindingData();
return absl::nullopt;
}
void SecureChannel::OnConnectionStatusChanged(Connection* connection,
Connection::Status old_status,
Connection::Status new_status) {
DCHECK(connection == connection_.get());
if (new_status == Connection::Status::CONNECTED) {
TransitionToStatus(Status::CONNECTED);
// Once the connection has succeeded, authenticate the connection by
// initiating the security handshake.
Authenticate();
return;
}
if (new_status == Connection::Status::DISCONNECTED) {
// If the connection is no longer active, disconnect.
Disconnect();
return;
}
}
void SecureChannel::OnMessageReceived(const Connection& connection,
const WireMessage& wire_message) {
DCHECK(&connection == const_cast<const Connection*>(connection_.get()));
if (wire_message.feature() == Authenticator::kAuthenticationFeature) {
// If the message received was part of the authentication handshake, it
// is a low-level message and should not be forwarded to observers.
return;
}
if (!secure_context_) {
PA_LOG(WARNING) << "Received unexpected message before authentication "
<< "was complete. Feature: " << wire_message.feature()
<< ", Payload size: " << wire_message.payload().size()
<< " byte(s)";
return;
}
secure_context_->Decode(
wire_message.payload(),
base::BindOnce(&SecureChannel::OnMessageDecoded,
weak_ptr_factory_.GetWeakPtr(), wire_message.feature()));
}
void SecureChannel::OnSendCompleted(const Connection& connection,
const WireMessage& wire_message,
bool success) {
if (wire_message.feature() == Authenticator::kAuthenticationFeature) {
// No need to process authentication messages; these are handled by
// |authenticator_|.
return;
}
if (!pending_message_) {
PA_LOG(ERROR) << "OnSendCompleted(), but a send was not expected to be in "
<< "progress. Disconnecting from "
<< connection_->GetDeviceAddress();
Disconnect();
return;
}
if (success && status_ != Status::DISCONNECTED) {
pending_message_.reset();
// Create a WeakPtr to |this| before invoking observer callbacks. It is
// possible that an Observer will respond to the OnMessageSent() call by
// destroying the connection (e.g., if the client only wanted to send one
// message and destroyed the connection after the message was sent).
base::WeakPtr<SecureChannel> weak_this = weak_ptr_factory_.GetWeakPtr();
if (wire_message.sequence_number() != -1) {
for (auto& observer : observer_list_)
observer.OnMessageSent(this, wire_message.sequence_number());
}
// Process the next message if possible. Note that if the SecureChannel was
// deleted by the OnMessageSent() callback, this will be a no-op since
// |weak_this| will have been invalidated in that case.
if (weak_this.get())
weak_this->ProcessMessageQueue();
return;
}
PA_LOG(ERROR) << "Could not send message: {"
<< "payload size: " << pending_message_->payload.size()
<< " byte(s), feature: \"" << pending_message_->feature << "\""
<< "}";
pending_message_.reset();
// The connection automatically retries failed messges, so if |success| is
// |false| here, a fatal error has occurred. Thus, there is no need to retry
// the message; instead, disconnect.
Disconnect();
}
void SecureChannel::TransitionToStatus(const Status& new_status) {
if (new_status == status_) {
// Only report changes to state.
return;
}
Status old_status = status_;
status_ = new_status;
for (auto& observer : observer_list_)
observer.OnSecureChannelStatusChanged(this, old_status, status_);
}
void SecureChannel::Authenticate() {
DCHECK(status_ == Status::CONNECTED);
DCHECK(!authenticator_);
authenticator_ = DeviceToDeviceAuthenticator::Factory::Create(
connection_.get(),
multidevice::SecureMessageDelegateImpl::Factory::Create());
authenticator_->Authenticate(base::BindOnce(
&SecureChannel::OnAuthenticationResult, weak_ptr_factory_.GetWeakPtr()));
TransitionToStatus(Status::AUTHENTICATING);
}
void SecureChannel::ProcessMessageQueue() {
if (pending_message_ || queued_messages_.empty()) {
return;
}
DCHECK(!connection_->is_sending_message());
pending_message_ = std::move(queued_messages_.front());
queued_messages_.pop();
PA_LOG(INFO) << "Sending message to " << connection_->GetDeviceAddress()
<< ": {"
<< "feature: \"" << pending_message_->feature << "\", "
<< "payload size: " << pending_message_->payload.size()
<< " byte(s)"
<< "}";
secure_context_->Encode(
pending_message_->payload,
base::BindOnce(&SecureChannel::OnMessageEncoded,
weak_ptr_factory_.GetWeakPtr(), pending_message_->feature,
pending_message_->sequence_number));
}
void SecureChannel::OnMessageEncoded(const std::string& feature,
int sequence_number,
const std::string& encoded_message) {
connection_->SendMessage(
std::make_unique<WireMessage>(encoded_message, feature, sequence_number));
}
void SecureChannel::OnMessageDecoded(const std::string& feature,
const std::string& decoded_message) {
PA_LOG(VERBOSE) << "Received message from " << connection_->GetDeviceAddress()
<< ": {"
<< "feature: \"" << feature << "\", "
<< "payload size: " << decoded_message.size() << " byte(s)"
<< "}";
for (auto& observer : observer_list_)
observer.OnMessageReceived(this, feature, decoded_message);
}
void SecureChannel::OnAuthenticationResult(
Authenticator::Result result,
std::unique_ptr<SecureContext> secure_context) {
DCHECK(status_ == Status::AUTHENTICATING);
// The authenticator is no longer needed, so release it.
authenticator_.reset();
if (result != Authenticator::Result::SUCCESS) {
PA_LOG(WARNING)
<< "Failed to authenticate connection to device with ID "
<< connection_->remote_device().GetTruncatedDeviceIdForLogs();
Disconnect();
return;
}
secure_context_ = std::move(secure_context);
TransitionToStatus(Status::AUTHENTICATED);
}
} // namespace secure_channel
} // namespace chromeos
|
// Copyright (c) 2019
// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
// ABN 41 687 119 230
//
// Author: Kazys Stepanas
#include "VoxelBuffer.h"
namespace ohm
{
template <typename VoxelBlock>
VoxelBuffer<VoxelBlock>::VoxelBuffer(ohm::VoxelBlock *block)
: voxel_block_(block)
{
if (block)
{
block->retain();
voxel_memory_size_ = block->uncompressedByteSize();
voxel_memory_ = block->voxelBytes();
}
}
template <typename VoxelBlock>
VoxelBuffer<VoxelBlock>::VoxelBuffer(VoxelBuffer<VoxelBlock> &&other) noexcept
: voxel_memory_(std::exchange(other.voxel_memory_, nullptr))
, voxel_memory_size_(std::exchange(other.voxel_memory_size_, 0))
, voxel_block_(std::exchange(other.voxel_block_, nullptr))
{}
template <typename VoxelBlock>
VoxelBuffer<VoxelBlock>::VoxelBuffer(const VoxelBuffer<VoxelBlock> &other)
: voxel_memory_(other.voxel_memory_)
, voxel_memory_size_(other.voxel_memory_size_)
, voxel_block_(other.voxel_block_)
{
if (voxel_block_)
{
voxel_block_->retain();
}
}
template <typename VoxelBlock>
VoxelBuffer<VoxelBlock>::~VoxelBuffer()
{
release();
}
template <typename VoxelBlock>
VoxelBuffer<VoxelBlock> &VoxelBuffer<VoxelBlock>::operator=(VoxelBuffer<VoxelBlock> &&other) noexcept
{
std::swap(voxel_block_, other.voxel_block_);
std::swap(voxel_memory_size_, other.voxel_memory_size_);
std::swap(voxel_memory_, other.voxel_memory_);
return *this;
}
template <typename VoxelBlock>
VoxelBuffer<VoxelBlock> &VoxelBuffer<VoxelBlock>::operator=(const VoxelBuffer<VoxelBlock> &other)
{
if (this != &other)
{
release();
voxel_block_ = other.voxel_block_;
if (voxel_block_)
{
voxel_block_->retain();
voxel_memory_size_ = voxel_block_->uncompressedByteSize();
voxel_memory_ = voxel_block_->voxelBytes();
}
}
return *this;
}
template <typename VoxelBlock>
void VoxelBuffer<VoxelBlock>::release()
{
if (voxel_block_)
{
voxel_block_->release();
voxel_block_ = nullptr;
voxel_memory_ = nullptr;
voxel_memory_size_ = 0;
}
}
// Export explicit template instantiations
#ifdef _MSC_VER
// Need to export the template instantiations for the Microsoft compiler only.
template class ohm_API VoxelBuffer<VoxelBlock>;
template class ohm_API VoxelBuffer<const VoxelBlock>;
#else // _MSC_VER
template class VoxelBuffer<VoxelBlock>;
template class VoxelBuffer<const VoxelBlock>;
#endif // _MSC_VER
} // namespace ohm
|
//
// Copyright (C) 2010 Aleksandar Zlateski <zlateski@mit.edu>
// ----------------------------------------------------------
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#ifndef ZI_NET_UDP_HPP
#define ZI_NET_UDP_HPP 1
#include <zi/net/config.hpp>
#include <zi/net/detail/socket_types.hpp>
namespace zi {
namespace net {
namespace ip {
class udp
{
private:
int family_;
explicit udp( int family ): family_( family )
{
}
public:
static udp v4()
{
return udp( PF_INET );
}
static udp v6()
{
return udp( PF_INET6 );
}
int type() const
{
return SOCK_STREAM;
}
int protocol() const
{
return IPPROTO_UDP;
}
int family() const
{
return family_;
}
friend bool operator==( const udp& udp1, const udp& udp2 )
{
return udp1.family_ == udp2.family_;
}
friend bool operator!=( const udp& udp1, const udp& udp2 )
{
return udp1.family_ != udp2.family_;
}
};
} // namespace ip
} // namespace net
} // namespace zi
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
//Copyright (c) 2015-2019 The PIVX developers
//Copyright (c) 2020 The ogcnode developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "script/standard.h"
#include "script/sign.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "util.h"
uint256 CBlockHeader::GetHash() const
{
if (nVersion < 4) {
#if defined(WORDS_BIGENDIAN)
uint8_t data[80];
WriteLE32(&data[0], nVersion);
memcpy(&data[4], hashPrevBlock.begin(), hashPrevBlock.size());
memcpy(&data[36], hashMerkleRoot.begin(), hashMerkleRoot.size());
WriteLE32(&data[68], nTime);
WriteLE32(&data[72], nBits);
WriteLE32(&data[76], nNonce);
return HashQuark(data, data + 80);
#else // Can take shortcut for little endian
return HashQuark(BEGIN(nVersion), END(nNonce));
#endif
}
// version >= 4
return SerializeHash(*this);
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
return s.str();
}
void CBlock::print() const
{
LogPrintf("%s", ToString());
}
|
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "init.h"
#include "instantx.h"
#include "key.h"
#include "validation.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "messagesigner.h"
#include "net.h"
#include "netmessagemaker.h"
#include "protocol.h"
#include "spork.h"
#include "sync.h"
#include "txmempool.h"
#include "util.h"
#include "consensus/validation.h"
#include "validationinterface.h"
#include "warnings.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif // ENABLE_WALLET
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
#ifdef ENABLE_WALLET
extern CWallet* pwalletMain;
#endif // ENABLE_WALLET
extern CTxMemPool mempool;
bool fEnableInstantSend = true;
int nCompleteTXLocks;
std::atomic<bool> CInstantSend::isAutoLockBip9Active{false};
const double CInstantSend::AUTO_IX_MEMPOOL_THRESHOLD = 0.1;
CInstantSend instantsend;
const std::string CInstantSend::SERIALIZATION_VERSION_STRING = "CInstantSend-Version-1";
// Transaction Locks
//
// step 1) Some node announces intention to lock transaction inputs via "txlockrequest" message (ix)
// step 2) Top COutPointLock::SIGNATURES_TOTAL masternodes per each spent outpoint push "txlockvote" message (txlvote)
// step 3) Once there are COutPointLock::SIGNATURES_REQUIRED valid "txlockvote" messages (txlvote) per each spent outpoint
// for a corresponding "txlockrequest" message (ix), all outpoints from that tx are treated as locked
//
// CInstantSend
//
void CInstantSend::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
if(fLiteMode) return; // disable all Sparks specific functionality
if(!sporkManager.IsSporkActive(SPORK_2_INSTANTSEND_ENABLED)) return;
// NOTE: NetMsgType::TXLOCKREQUEST is handled via ProcessMessage() in net_processing.cpp
if (strCommand == NetMsgType::TXLOCKVOTE) { // InstantSend Transaction Lock Consensus Votes
if(pfrom->nVersion < MIN_INSTANTSEND_PROTO_VERSION) {
LogPrint("instantsend", "TXLOCKVOTE -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion);
connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
strprintf("Version must be %d or greater", MIN_INSTANTSEND_PROTO_VERSION)));
return;
}
CTxLockVote vote;
vRecv >> vote;
uint256 nVoteHash = vote.GetHash();
{
LOCK(cs_main);
connman.RemoveAskFor(nVoteHash);
}
// Ignore any InstantSend messages until masternode list is synced
if (!masternodeSync.IsMasternodeListSynced()) return;
{
LOCK(cs_instantsend);
auto ret = mapTxLockVotes.emplace(nVoteHash, vote);
if (!ret.second) return;
}
ProcessNewTxLockVote(pfrom, vote, connman);
return;
}
}
bool CInstantSend::ProcessTxLockRequest(const CTxLockRequest& txLockRequest, CConnman& connman)
{
LOCK(cs_main);
#ifdef ENABLE_WALLET
LOCK(pwalletMain ? &pwalletMain->cs_wallet : NULL);
#endif
LOCK2(mempool.cs, cs_instantsend);
uint256 txHash = txLockRequest.GetHash();
// Check to see if we conflict with existing completed lock
for (const auto& txin : txLockRequest.tx->vin) {
std::map<COutPoint, uint256>::iterator it = mapLockedOutpoints.find(txin.prevout);
if (it != mapLockedOutpoints.end() && it->second != txLockRequest.GetHash()) {
// Conflicting with complete lock, proceed to see if we should cancel them both
LogPrintf("CInstantSend::ProcessTxLockRequest -- WARNING: Found conflicting completed Transaction Lock, txid=%s, completed lock txid=%s\n",
txLockRequest.GetHash().ToString(), it->second.ToString());
}
}
// Check to see if there are votes for conflicting request,
// if so - do not fail, just warn user
for (const auto& txin : txLockRequest.tx->vin) {
std::map<COutPoint, std::set<uint256> >::iterator it = mapVotedOutpoints.find(txin.prevout);
if (it != mapVotedOutpoints.end()) {
for (const auto& hash : it->second) {
if (hash != txLockRequest.GetHash()) {
LogPrint("instantsend", "CInstantSend::ProcessTxLockRequest -- Double spend attempt! %s\n", txin.prevout.ToStringShort());
// do not fail here, let it go and see which one will get the votes to be locked
// NOTIFY ZMQ
CTransaction txCurrent = *txLockRequest.tx; // currently processed tx
auto itPrevious = mapTxLockCandidates.find(hash);
if (itPrevious != mapTxLockCandidates.end() && itPrevious->second.txLockRequest) {
CTransaction txPrevious = *itPrevious->second.txLockRequest.tx; // previously locked one
GetMainSignals().NotifyInstantSendDoubleSpendAttempt(txCurrent, txPrevious);
}
}
}
}
}
if (!CreateTxLockCandidate(txLockRequest)) {
// smth is not right
LogPrintf("CInstantSend::ProcessTxLockRequest -- CreateTxLockCandidate failed, txid=%s\n", txHash.ToString());
return false;
}
LogPrintf("CInstantSend::ProcessTxLockRequest -- accepted, txid=%s\n", txHash.ToString());
// Masternodes will sometimes propagate votes before the transaction is known to the client.
// If this just happened - process orphan votes, lock inputs, resolve conflicting locks,
// update transaction status forcing external script/zmq notifications.
ProcessOrphanTxLockVotes();
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
TryToFinalizeLockCandidate(itLockCandidate->second);
return true;
}
bool CInstantSend::CreateTxLockCandidate(const CTxLockRequest& txLockRequest)
{
if (!txLockRequest.IsValid()) return false;
LOCK(cs_instantsend);
uint256 txHash = txLockRequest.GetHash();
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate == mapTxLockCandidates.end()) {
LogPrintf("CInstantSend::CreateTxLockCandidate -- new, txid=%s\n", txHash.ToString());
CTxLockCandidate txLockCandidate(txLockRequest);
// all inputs should already be checked by txLockRequest.IsValid() above, just use them now
for (const auto& txin : txLockRequest.tx->vin) {
txLockCandidate.AddOutPointLock(txin.prevout);
}
mapTxLockCandidates.insert(std::make_pair(txHash, txLockCandidate));
} else if (!itLockCandidate->second.txLockRequest) {
// i.e. empty Transaction Lock Candidate was created earlier, let's update it with actual data
itLockCandidate->second.txLockRequest = txLockRequest;
if (itLockCandidate->second.IsTimedOut()) {
LogPrintf("CInstantSend::CreateTxLockCandidate -- timed out, txid=%s\n", txHash.ToString());
return false;
}
LogPrintf("CInstantSend::CreateTxLockCandidate -- update empty, txid=%s\n", txHash.ToString());
// all inputs should already be checked by txLockRequest.IsValid() above, just use them now
for (const auto& txin : txLockRequest.tx->vin) {
itLockCandidate->second.AddOutPointLock(txin.prevout);
}
} else {
LogPrint("instantsend", "CInstantSend::CreateTxLockCandidate -- seen, txid=%s\n", txHash.ToString());
}
return true;
}
void CInstantSend::CreateEmptyTxLockCandidate(const uint256& txHash)
{
if (mapTxLockCandidates.find(txHash) != mapTxLockCandidates.end())
return;
LogPrintf("CInstantSend::CreateEmptyTxLockCandidate -- new, txid=%s\n", txHash.ToString());
const CTxLockRequest txLockRequest = CTxLockRequest();
mapTxLockCandidates.insert(std::make_pair(txHash, CTxLockCandidate(txLockRequest)));
}
void CInstantSend::Vote(const uint256& txHash, CConnman& connman)
{
AssertLockHeld(cs_main);
#ifdef ENABLE_WALLET
LOCK(pwalletMain ? &pwalletMain->cs_wallet : NULL);
#endif
CTxLockRequest dummyRequest;
CTxLockCandidate txLockCandidate(dummyRequest);
{
LOCK(cs_instantsend);
auto itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate == mapTxLockCandidates.end()) return;
txLockCandidate = itLockCandidate->second;
Vote(txLockCandidate, connman);
}
// Let's see if our vote changed smth
LOCK2(mempool.cs, cs_instantsend);
TryToFinalizeLockCandidate(txLockCandidate);
}
void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman)
{
if (!fMasternodeMode) return;
if (!sporkManager.IsSporkActive(SPORK_2_INSTANTSEND_ENABLED)) return;
AssertLockHeld(cs_main);
AssertLockHeld(cs_instantsend);
uint256 txHash = txLockCandidate.GetHash();
// We should never vote on a Transaction Lock Request that was not (yet) accepted by the mempool
if (mapLockRequestAccepted.find(txHash) == mapLockRequestAccepted.end()) return;
// check if we need to vote on this candidate's outpoints,
// it's possible that we need to vote for several of them
for (auto& outpointLockPair : txLockCandidate.mapOutPointLocks) {
int nPrevoutHeight = GetUTXOHeight(outpointLockPair.first);
if (nPrevoutHeight == -1) {
LogPrint("instantsend", "CInstantSend::Vote -- Failed to find UTXO %s\n", outpointLockPair.first.ToStringShort());
return;
}
int nLockInputHeight = nPrevoutHeight + Params().GetConsensus().nInstantSendConfirmationsRequired - 2;
int nRank;
uint256 quorumModifierHash;
int nMinRequiredProtocol = std::max(MIN_INSTANTSEND_PROTO_VERSION, mnpayments.GetMinMasternodePaymentsProto());
if (!mnodeman.GetMasternodeRank(activeMasternodeInfo.outpoint, nRank, quorumModifierHash, nLockInputHeight, nMinRequiredProtocol)) {
LogPrint("instantsend", "CInstantSend::Vote -- Can't calculate rank for masternode %s\n", activeMasternodeInfo.outpoint.ToStringShort());
continue;
}
if (!deterministicMNManager->IsDeterministicMNsSporkActive()) {
// not used until spork16 activation
quorumModifierHash = uint256();
}
int nSignaturesTotal = COutPointLock::SIGNATURES_TOTAL;
if (nRank > nSignaturesTotal) {
LogPrint("instantsend", "CInstantSend::Vote -- Masternode not in the top %d (%d)\n", nSignaturesTotal, nRank);
continue;
}
LogPrint("instantsend", "CInstantSend::Vote -- In the top %d (%d)\n", nSignaturesTotal, nRank);
std::map<COutPoint, std::set<uint256> >::iterator itVoted = mapVotedOutpoints.find(outpointLockPair.first);
// Check to see if we already voted for this outpoint,
// refuse to vote twice or to include the same outpoint in another tx
bool fAlreadyVoted = false;
if (itVoted != mapVotedOutpoints.end()) {
for (const auto& hash : itVoted->second) {
std::map<uint256, CTxLockCandidate>::iterator it2 = mapTxLockCandidates.find(hash);
if (it2->second.HasMasternodeVoted(outpointLockPair.first, activeMasternodeInfo.outpoint)) {
// we already voted for this outpoint to be included either in the same tx or in a competing one,
// skip it anyway
fAlreadyVoted = true;
LogPrintf("CInstantSend::Vote -- WARNING: We already voted for this outpoint, skipping: txHash=%s, outpoint=%s\n",
txHash.ToString(), outpointLockPair.first.ToStringShort());
break;
}
}
}
if (fAlreadyVoted) {
continue; // skip to the next outpoint
}
// we haven't voted for this outpoint yet, let's try to do this now
// Please note that activeMasternodeInfo.proTxHash is only valid after spork16 activation
CTxLockVote vote(txHash, outpointLockPair.first, activeMasternodeInfo.outpoint, quorumModifierHash, activeMasternodeInfo.proTxHash);
if (!vote.Sign()) {
LogPrintf("CInstantSend::Vote -- Failed to sign consensus vote\n");
return;
}
if (!vote.CheckSignature()) {
LogPrintf("CInstantSend::Vote -- Signature invalid\n");
return;
}
// vote constructed sucessfully, let's store and relay it
uint256 nVoteHash = vote.GetHash();
mapTxLockVotes.insert(std::make_pair(nVoteHash, vote));
if (outpointLockPair.second.AddVote(vote)) {
LogPrintf("CInstantSend::Vote -- Vote created successfully, relaying: txHash=%s, outpoint=%s, vote=%s\n",
txHash.ToString(), outpointLockPair.first.ToStringShort(), nVoteHash.ToString());
if (itVoted == mapVotedOutpoints.end()) {
std::set<uint256> setHashes;
setHashes.insert(txHash);
mapVotedOutpoints.insert(std::make_pair(outpointLockPair.first, setHashes));
} else {
mapVotedOutpoints[outpointLockPair.first].insert(txHash);
if (mapVotedOutpoints[outpointLockPair.first].size() > 1) {
// it's ok to continue, just warn user
LogPrintf("CInstantSend::Vote -- WARNING: Vote conflicts with some existing votes: txHash=%s, outpoint=%s, vote=%s\n",
txHash.ToString(), outpointLockPair.first.ToStringShort(), nVoteHash.ToString());
}
}
vote.Relay(connman);
}
}
}
bool CInstantSend::ProcessNewTxLockVote(CNode* pfrom, const CTxLockVote& vote, CConnman& connman)
{
uint256 txHash = vote.GetTxHash();
uint256 nVoteHash = vote.GetHash();
if (!vote.IsValid(pfrom, connman)) {
// could be because of missing MN
LogPrint("instantsend", "CInstantSend::%s -- Vote is invalid, txid=%s\n", __func__, txHash.ToString());
return false;
}
// relay valid vote asap
vote.Relay(connman);
LOCK(cs_main);
#ifdef ENABLE_WALLET
LOCK(pwalletMain ? &pwalletMain->cs_wallet : NULL);
#endif
LOCK2(mempool.cs, cs_instantsend);
// Masternodes will sometimes propagate votes before the transaction is known to the client,
// will actually process only after the lock request itself has arrived
std::map<uint256, CTxLockCandidate>::iterator it = mapTxLockCandidates.find(txHash);
if (it == mapTxLockCandidates.end() || !it->second.txLockRequest) {
// no or empty tx lock candidate
if (it == mapTxLockCandidates.end()) {
// start timeout countdown after the very first vote
CreateEmptyTxLockCandidate(txHash);
}
bool fInserted = mapTxLockVotesOrphan.emplace(nVoteHash, vote).second;
LogPrint("instantsend", "CInstantSend::%s -- Orphan vote: txid=%s masternode=%s %s\n",
__func__, txHash.ToString(), vote.GetMasternodeOutpoint().ToStringShort(), fInserted ? "new" : "seen");
// This tracks those messages and allows only the same rate as of the rest of the network
// TODO: make sure this works good enough for multi-quorum
int nMasternodeOrphanExpireTime = GetTime() + 60*10; // keep time data for 10 minutes
auto itMnOV = mapMasternodeOrphanVotes.find(vote.GetMasternodeOutpoint());
if (itMnOV == mapMasternodeOrphanVotes.end()) {
mapMasternodeOrphanVotes.emplace(vote.GetMasternodeOutpoint(), nMasternodeOrphanExpireTime);
} else {
if (itMnOV->second > GetTime() && itMnOV->second > GetAverageMasternodeOrphanVoteTime()) {
LogPrint("instantsend", "CInstantSend::%s -- masternode is spamming orphan Transaction Lock Votes: txid=%s masternode=%s\n",
__func__, txHash.ToString(), vote.GetMasternodeOutpoint().ToStringShort());
// Misbehaving(pfrom->id, 1);
return false;
}
// not spamming, refresh
itMnOV->second = nMasternodeOrphanExpireTime;
}
return true;
}
// We have a valid (non-empty) tx lock candidate
CTxLockCandidate& txLockCandidate = it->second;
if (txLockCandidate.IsTimedOut()) {
LogPrint("instantsend", "CInstantSend::%s -- too late, Transaction Lock timed out, txid=%s\n", __func__, txHash.ToString());
return false;
}
LogPrint("instantsend", "CInstantSend::%s -- Transaction Lock Vote, txid=%s\n", __func__, txHash.ToString());
UpdateVotedOutpoints(vote, txLockCandidate);
if (!txLockCandidate.AddVote(vote)) {
// this should never happen
return false;
}
int nSignatures = txLockCandidate.CountVotes();
int nSignaturesMax = txLockCandidate.txLockRequest.GetMaxSignatures();
LogPrint("instantsend", "CInstantSend::%s -- Transaction Lock signatures count: %d/%d, vote hash=%s\n", __func__,
nSignatures, nSignaturesMax, nVoteHash.ToString());
TryToFinalizeLockCandidate(txLockCandidate);
return true;
}
bool CInstantSend::ProcessOrphanTxLockVote(const CTxLockVote& vote)
{
// cs_main, cs_wallet and cs_instantsend should be already locked
AssertLockHeld(cs_main);
#ifdef ENABLE_WALLET
if (pwalletMain)
AssertLockHeld(pwalletMain->cs_wallet);
#endif
AssertLockHeld(cs_instantsend);
uint256 txHash = vote.GetTxHash();
// We shouldn't process orphan votes without a valid tx lock candidate
std::map<uint256, CTxLockCandidate>::iterator it = mapTxLockCandidates.find(txHash);
if (it == mapTxLockCandidates.end() || !it->second.txLockRequest)
return false; // this shouldn never happen
CTxLockCandidate& txLockCandidate = it->second;
if (txLockCandidate.IsTimedOut()) {
LogPrint("instantsend", "CInstantSend::%s -- too late, Transaction Lock timed out, txid=%s\n", __func__, txHash.ToString());
return false;
}
LogPrint("instantsend", "CInstantSend::%s -- Transaction Lock Vote, txid=%s\n", __func__, txHash.ToString());
UpdateVotedOutpoints(vote, txLockCandidate);
if (!txLockCandidate.AddVote(vote)) {
// this should never happen
return false;
}
int nSignatures = txLockCandidate.CountVotes();
int nSignaturesMax = txLockCandidate.txLockRequest.GetMaxSignatures();
LogPrint("instantsend", "CInstantSend::%s -- Transaction Lock signatures count: %d/%d, vote hash=%s\n",
__func__, nSignatures, nSignaturesMax, vote.GetHash().ToString());
return true;
}
void CInstantSend::UpdateVotedOutpoints(const CTxLockVote& vote, CTxLockCandidate& txLockCandidate)
{
AssertLockHeld(cs_instantsend);
uint256 txHash = vote.GetTxHash();
std::map<COutPoint, std::set<uint256> >::iterator it1 = mapVotedOutpoints.find(vote.GetOutpoint());
if (it1 != mapVotedOutpoints.end()) {
for (const auto& hash : it1->second) {
if (hash != txHash) {
// same outpoint was already voted to be locked by another tx lock request,
// let's see if it was the same masternode who voted on this outpoint
// for another tx lock request
std::map<uint256, CTxLockCandidate>::iterator it2 = mapTxLockCandidates.find(hash);
if (it2 !=mapTxLockCandidates.end() && it2->second.HasMasternodeVoted(vote.GetOutpoint(), vote.GetMasternodeOutpoint())) {
// yes, it was the same masternode
LogPrintf("CInstantSend::%s -- masternode sent conflicting votes! %s\n", __func__, vote.GetMasternodeOutpoint().ToStringShort());
// mark both Lock Candidates as attacked, none of them should complete,
// or at least the new (current) one shouldn't even
// if the second one was already completed earlier
txLockCandidate.MarkOutpointAsAttacked(vote.GetOutpoint());
it2->second.MarkOutpointAsAttacked(vote.GetOutpoint());
// apply maximum PoSe ban score to this masternode i.e. PoSe-ban it instantly
mnodeman.PoSeBan(vote.GetMasternodeOutpoint());
// NOTE: This vote must be relayed further to let all other nodes know about such
// misbehaviour of this masternode. This way they should also be able to construct
// conflicting lock and PoSe-ban this masternode.
}
}
}
// store all votes, regardless of them being sent by malicious masternode or not
it1->second.insert(txHash);
} else {
mapVotedOutpoints.emplace(vote.GetOutpoint(), std::set<uint256>({txHash}));
}
}
void CInstantSend::ProcessOrphanTxLockVotes()
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_instantsend);
std::map<uint256, CTxLockVote>::iterator it = mapTxLockVotesOrphan.begin();
while (it != mapTxLockVotesOrphan.end()) {
if (ProcessOrphanTxLockVote(it->second)) {
mapTxLockVotesOrphan.erase(it++);
} else {
++it;
}
}
}
void CInstantSend::TryToFinalizeLockCandidate(const CTxLockCandidate& txLockCandidate)
{
if (!sporkManager.IsSporkActive(SPORK_2_INSTANTSEND_ENABLED)) return;
AssertLockHeld(cs_main);
AssertLockHeld(cs_instantsend);
uint256 txHash = txLockCandidate.txLockRequest.tx->GetHash();
if (txLockCandidate.IsAllOutPointsReady() && !IsLockedInstantSendTransaction(txHash)) {
// we have enough votes now
LogPrint("instantsend", "CInstantSend::TryToFinalizeLockCandidate -- Transaction Lock is ready to complete, txid=%s\n", txHash.ToString());
if (ResolveConflicts(txLockCandidate)) {
LockTransactionInputs(txLockCandidate);
UpdateLockedTransaction(txLockCandidate);
}
}
}
void CInstantSend::UpdateLockedTransaction(const CTxLockCandidate& txLockCandidate)
{
// cs_main, cs_wallet and cs_instantsend should be already locked
AssertLockHeld(cs_main);
#ifdef ENABLE_WALLET
if (pwalletMain) {
AssertLockHeld(pwalletMain->cs_wallet);
}
#endif
AssertLockHeld(cs_instantsend);
uint256 txHash = txLockCandidate.GetHash();
if (!IsLockedInstantSendTransaction(txHash)) return; // not a locked tx, do not update/notify
#ifdef ENABLE_WALLET
if (pwalletMain && pwalletMain->UpdatedTransaction(txHash)) {
// bumping this to update UI
nCompleteTXLocks++;
// notify an external script once threshold is reached
std::string strCmd = GetArg("-instantsendnotify", "");
if (!strCmd.empty()) {
boost::replace_all(strCmd, "%s", txHash.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
}
#endif
GetMainSignals().NotifyTransactionLock(*txLockCandidate.txLockRequest.tx);
LogPrint("instantsend", "CInstantSend::UpdateLockedTransaction -- done, txid=%s\n", txHash.ToString());
}
void CInstantSend::LockTransactionInputs(const CTxLockCandidate& txLockCandidate)
{
if (!sporkManager.IsSporkActive(SPORK_2_INSTANTSEND_ENABLED)) return;
LOCK(cs_instantsend);
uint256 txHash = txLockCandidate.GetHash();
if (!txLockCandidate.IsAllOutPointsReady()) return;
for (const auto& pair : txLockCandidate.mapOutPointLocks) {
mapLockedOutpoints.insert(std::make_pair(pair.first, txHash));
}
LogPrint("instantsend", "CInstantSend::LockTransactionInputs -- done, txid=%s\n", txHash.ToString());
}
bool CInstantSend::GetLockedOutPointTxHash(const COutPoint& outpoint, uint256& hashRet)
{
LOCK(cs_instantsend);
std::map<COutPoint, uint256>::iterator it = mapLockedOutpoints.find(outpoint);
if (it == mapLockedOutpoints.end()) return false;
hashRet = it->second;
return true;
}
bool CInstantSend::ResolveConflicts(const CTxLockCandidate& txLockCandidate)
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_instantsend);
uint256 txHash = txLockCandidate.GetHash();
// make sure the lock is ready
if (!txLockCandidate.IsAllOutPointsReady()) return false;
AssertLockHeld(mempool.cs); // protect mempool.mapNextTx
for (const auto& txin : txLockCandidate.txLockRequest.tx->vin) {
uint256 hashConflicting;
if (GetLockedOutPointTxHash(txin.prevout, hashConflicting) && txHash != hashConflicting) {
// completed lock which conflicts with another completed one?
// this means that majority of MNs in the quorum for this specific tx input are malicious!
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
std::map<uint256, CTxLockCandidate>::iterator itLockCandidateConflicting = mapTxLockCandidates.find(hashConflicting);
if (itLockCandidate == mapTxLockCandidates.end() || itLockCandidateConflicting == mapTxLockCandidates.end()) {
// safety check, should never really happen
LogPrintf("CInstantSend::ResolveConflicts -- ERROR: Found conflicting completed Transaction Lock, but one of txLockCandidate-s is missing, txid=%s, conflicting txid=%s\n",
txHash.ToString(), hashConflicting.ToString());
return false;
}
LogPrintf("CInstantSend::ResolveConflicts -- WARNING: Found conflicting completed Transaction Lock, dropping both, txid=%s, conflicting txid=%s\n",
txHash.ToString(), hashConflicting.ToString());
CTxLockRequest txLockRequest = itLockCandidate->second.txLockRequest;
CTxLockRequest txLockRequestConflicting = itLockCandidateConflicting->second.txLockRequest;
itLockCandidate->second.SetConfirmedHeight(0); // expired
itLockCandidateConflicting->second.SetConfirmedHeight(0); // expired
CheckAndRemove(); // clean up
// AlreadyHave should still return "true" for both of them
mapLockRequestRejected.insert(std::make_pair(txHash, txLockRequest));
mapLockRequestRejected.insert(std::make_pair(hashConflicting, txLockRequestConflicting));
// TODO: clean up mapLockRequestRejected later somehow
// (not a big issue since we already PoSe ban malicious masternodes
// and they won't be able to spam)
// TODO: ban all malicious masternodes permanently, do not accept anything from them, ever
// TODO: notify zmq+script about this double-spend attempt
// and let merchant cancel/hold the order if it's not too late...
// can't do anything else, fallback to regular txes
return false;
} else if (mempool.mapNextTx.count(txin.prevout)) {
// check if it's in mempool
hashConflicting = mempool.mapNextTx.find(txin.prevout)->second->GetHash();
if (txHash == hashConflicting) continue; // matches current, not a conflict, skip to next txin
// conflicts with tx in mempool
LogPrintf("CInstantSend::ResolveConflicts -- ERROR: Failed to complete Transaction Lock, conflicts with mempool, txid=%s\n", txHash.ToString());
return false;
}
} // FOREACH
// No conflicts were found so far, check to see if it was already included in block
CTransactionRef txTmp;
uint256 hashBlock;
if (GetTransaction(txHash, txTmp, Params().GetConsensus(), hashBlock, true) && hashBlock != uint256()) {
LogPrint("instantsend", "CInstantSend::ResolveConflicts -- Done, %s is included in block %s\n", txHash.ToString(), hashBlock.ToString());
return true;
}
// Not in block yet, make sure all its inputs are still unspent
for (const auto& txin : txLockCandidate.txLockRequest.tx->vin) {
Coin coin;
if (!GetUTXOCoin(txin.prevout, coin)) {
// Not in UTXO anymore? A conflicting tx was mined while we were waiting for votes.
LogPrintf("CInstantSend::ResolveConflicts -- ERROR: Failed to find UTXO %s, can't complete Transaction Lock\n", txin.prevout.ToStringShort());
return false;
}
}
LogPrint("instantsend", "CInstantSend::ResolveConflicts -- Done, txid=%s\n", txHash.ToString());
return true;
}
int64_t CInstantSend::GetAverageMasternodeOrphanVoteTime()
{
LOCK(cs_instantsend);
// NOTE: should never actually call this function when mapMasternodeOrphanVotes is empty
if (mapMasternodeOrphanVotes.empty()) return 0;
int64_t total = 0;
for (const auto& pair : mapMasternodeOrphanVotes) {
total += pair.second;
}
return total / mapMasternodeOrphanVotes.size();
}
void CInstantSend::CheckAndRemove()
{
if (!masternodeSync.IsMasternodeListSynced()) return;
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.begin();
// remove expired candidates
while (itLockCandidate != mapTxLockCandidates.end()) {
CTxLockCandidate &txLockCandidate = itLockCandidate->second;
uint256 txHash = txLockCandidate.GetHash();
if (txLockCandidate.IsExpired(nCachedBlockHeight)) {
LogPrintf("CInstantSend::CheckAndRemove -- Removing expired Transaction Lock Candidate: txid=%s\n", txHash.ToString());
for (const auto& pair : txLockCandidate.mapOutPointLocks) {
mapLockedOutpoints.erase(pair.first);
mapVotedOutpoints.erase(pair.first);
}
mapLockRequestAccepted.erase(txHash);
mapLockRequestRejected.erase(txHash);
mapTxLockCandidates.erase(itLockCandidate++);
} else {
++itLockCandidate;
}
}
// remove expired votes
std::map<uint256, CTxLockVote>::iterator itVote = mapTxLockVotes.begin();
while (itVote != mapTxLockVotes.end()) {
if (itVote->second.IsExpired(nCachedBlockHeight)) {
LogPrint("instantsend", "CInstantSend::CheckAndRemove -- Removing expired vote: txid=%s masternode=%s\n",
itVote->second.GetTxHash().ToString(), itVote->second.GetMasternodeOutpoint().ToStringShort());
mapTxLockVotes.erase(itVote++);
} else {
++itVote;
}
}
// remove timed out orphan votes
std::map<uint256, CTxLockVote>::iterator itOrphanVote = mapTxLockVotesOrphan.begin();
while (itOrphanVote != mapTxLockVotesOrphan.end()) {
if (itOrphanVote->second.IsTimedOut()) {
LogPrint("instantsend", "CInstantSend::CheckAndRemove -- Removing timed out orphan vote: txid=%s masternode=%s\n",
itOrphanVote->second.GetTxHash().ToString(), itOrphanVote->second.GetMasternodeOutpoint().ToStringShort());
mapTxLockVotes.erase(itOrphanVote->first);
mapTxLockVotesOrphan.erase(itOrphanVote++);
} else {
++itOrphanVote;
}
}
// remove invalid votes and votes for failed lock attempts
itVote = mapTxLockVotes.begin();
while (itVote != mapTxLockVotes.end()) {
if (itVote->second.IsFailed()) {
LogPrint("instantsend", "CInstantSend::CheckAndRemove -- Removing vote for failed lock attempt: txid=%s masternode=%s\n",
itVote->second.GetTxHash().ToString(), itVote->second.GetMasternodeOutpoint().ToStringShort());
mapTxLockVotes.erase(itVote++);
} else {
++itVote;
}
}
// remove timed out masternode orphan votes (DOS protection)
std::map<COutPoint, int64_t>::iterator itMasternodeOrphan = mapMasternodeOrphanVotes.begin();
while (itMasternodeOrphan != mapMasternodeOrphanVotes.end()) {
if (itMasternodeOrphan->second < GetTime()) {
LogPrint("instantsend", "CInstantSend::CheckAndRemove -- Removing timed out orphan masternode vote: masternode=%s\n",
itMasternodeOrphan->first.ToStringShort());
mapMasternodeOrphanVotes.erase(itMasternodeOrphan++);
} else {
++itMasternodeOrphan;
}
}
LogPrintf("CInstantSend::CheckAndRemove -- %s\n", ToString());
}
bool CInstantSend::AlreadyHave(const uint256& hash)
{
LOCK(cs_instantsend);
return mapLockRequestAccepted.count(hash) ||
mapLockRequestRejected.count(hash) ||
mapTxLockVotes.count(hash);
}
void CInstantSend::AcceptLockRequest(const CTxLockRequest& txLockRequest)
{
LOCK(cs_instantsend);
mapLockRequestAccepted.insert(std::make_pair(txLockRequest.GetHash(), txLockRequest));
}
void CInstantSend::RejectLockRequest(const CTxLockRequest& txLockRequest)
{
LOCK(cs_instantsend);
mapLockRequestRejected.insert(std::make_pair(txLockRequest.GetHash(), txLockRequest));
}
bool CInstantSend::HasTxLockRequest(const uint256& txHash)
{
CTxLockRequest txLockRequestTmp;
return GetTxLockRequest(txHash, txLockRequestTmp);
}
bool CInstantSend::GetTxLockRequest(const uint256& txHash, CTxLockRequest& txLockRequestRet)
{
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::iterator it = mapTxLockCandidates.find(txHash);
if (it == mapTxLockCandidates.end() || !it->second.txLockRequest) return false;
txLockRequestRet = it->second.txLockRequest;
return true;
}
bool CInstantSend::GetTxLockVote(const uint256& hash, CTxLockVote& txLockVoteRet)
{
LOCK(cs_instantsend);
std::map<uint256, CTxLockVote>::iterator it = mapTxLockVotes.find(hash);
if (it == mapTxLockVotes.end()) return false;
txLockVoteRet = it->second;
return true;
}
void CInstantSend::Clear()
{
LOCK(cs_instantsend);
mapLockRequestAccepted.clear();
mapLockRequestRejected.clear();
mapTxLockVotes.clear();
mapTxLockVotesOrphan.clear();
mapTxLockCandidates.clear();
mapVotedOutpoints.clear();
mapLockedOutpoints.clear();
mapMasternodeOrphanVotes.clear();
nCachedBlockHeight = 0;
}
bool CInstantSend::IsLockedInstantSendTransaction(const uint256& txHash)
{
if (!fEnableInstantSend || GetfLargeWorkForkFound() || GetfLargeWorkInvalidChainFound() ||
!sporkManager.IsSporkActive(SPORK_3_INSTANTSEND_BLOCK_FILTERING)) return false;
LOCK(cs_instantsend);
// there must be a lock candidate
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate == mapTxLockCandidates.end()) return false;
// which should have outpoints
if (itLockCandidate->second.mapOutPointLocks.empty()) return false;
// and all of these outputs must be included in mapLockedOutpoints with correct hash
for (const auto& pair : itLockCandidate->second.mapOutPointLocks) {
uint256 hashLocked;
if (!GetLockedOutPointTxHash(pair.first, hashLocked) || hashLocked != txHash) return false;
}
return true;
}
int CInstantSend::GetTransactionLockSignatures(const uint256& txHash)
{
if (!fEnableInstantSend) return -1;
if (GetfLargeWorkForkFound() || GetfLargeWorkInvalidChainFound()) return -2;
if (!sporkManager.IsSporkActive(SPORK_2_INSTANTSEND_ENABLED)) return -3;
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate != mapTxLockCandidates.end()) {
return itLockCandidate->second.CountVotes();
}
return -1;
}
bool CInstantSend::IsTxLockCandidateTimedOut(const uint256& txHash)
{
if (!fEnableInstantSend) return false;
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate != mapTxLockCandidates.end()) {
return !itLockCandidate->second.IsAllOutPointsReady() &&
itLockCandidate->second.IsTimedOut();
}
return false;
}
void CInstantSend::Relay(const uint256& txHash, CConnman& connman)
{
LOCK(cs_instantsend);
std::map<uint256, CTxLockCandidate>::const_iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate != mapTxLockCandidates.end()) {
itLockCandidate->second.Relay(connman);
}
}
void CInstantSend::UpdatedBlockTip(const CBlockIndex *pindex)
{
nCachedBlockHeight = pindex->nHeight;
}
void CInstantSend::SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock)
{
// Update lock candidates and votes if corresponding tx confirmed
// or went from confirmed to 0-confirmed or conflicted.
if (tx.IsCoinBase()) return;
LOCK2(cs_main, cs_instantsend);
uint256 txHash = tx.GetHash();
// When tx is 0-confirmed or conflicted, posInBlock is SYNC_TRANSACTION_NOT_IN_BLOCK and nHeightNew should be set to -1
int nHeightNew = posInBlock == CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK ? -1 : pindex->nHeight;
LogPrint("instantsend", "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d\n", txHash.ToString(), nHeightNew);
// Check lock candidates
std::map<uint256, CTxLockCandidate>::iterator itLockCandidate = mapTxLockCandidates.find(txHash);
if (itLockCandidate != mapTxLockCandidates.end()) {
LogPrint("instantsend", "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d lock candidate updated\n",
txHash.ToString(), nHeightNew);
itLockCandidate->second.SetConfirmedHeight(nHeightNew);
// Loop through outpoint locks
for (const auto& pair : itLockCandidate->second.mapOutPointLocks) {
// Check corresponding lock votes
for (const auto& vote : pair.second.GetVotes()) {
uint256 nVoteHash = vote.GetHash();
LogPrint("instantsend", "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d vote %s updated\n",
txHash.ToString(), nHeightNew, nVoteHash.ToString());
const auto& it = mapTxLockVotes.find(nVoteHash);
if (it != mapTxLockVotes.end()) {
it->second.SetConfirmedHeight(nHeightNew);
}
}
}
}
// check orphan votes
for (const auto& pair : mapTxLockVotesOrphan) {
if (pair.second.GetTxHash() == txHash) {
LogPrint("instantsend", "CInstantSend::SyncTransaction -- txid=%s nHeightNew=%d vote %s updated\n",
txHash.ToString(), nHeightNew, pair.first.ToString());
mapTxLockVotes[pair.first].SetConfirmedHeight(nHeightNew);
}
}
}
std::string CInstantSend::ToString() const
{
LOCK(cs_instantsend);
return strprintf("Lock Candidates: %llu, Votes %llu", mapTxLockCandidates.size(), mapTxLockVotes.size());
}
void CInstantSend::DoMaintenance()
{
if (ShutdownRequested()) return;
CheckAndRemove();
}
bool CInstantSend::CanAutoLock()
{
if (!isAutoLockBip9Active) {
return false;
}
if (!sporkManager.IsSporkActive(SPORK_17_INSTANTSEND_AUTOLOCKS)) {
return false;
}
return (mempool.UsedMemoryShare() < AUTO_IX_MEMPOOL_THRESHOLD);
}
//
// CTxLockRequest
//
bool CTxLockRequest::IsValid() const
{
if (tx->vout.size() < 1) return false;
if (tx->vin.size() > WARN_MANY_INPUTS) {
LogPrint("instantsend", "CTxLockRequest::IsValid -- WARNING: Too many inputs: tx=%s", ToString());
}
AssertLockHeld(cs_main);
if (!CheckFinalTx(*tx)) {
LogPrint("instantsend", "CTxLockRequest::IsValid -- Transaction is not final: tx=%s", ToString());
return false;
}
CAmount nValueIn = 0;
int nInstantSendConfirmationsRequired = Params().GetConsensus().nInstantSendConfirmationsRequired;
for (const auto& txin : tx->vin) {
Coin coin;
if (!GetUTXOCoin(txin.prevout, coin)) {
LogPrint("instantsend", "CTxLockRequest::IsValid -- Failed to find UTXO %s\n", txin.prevout.ToStringShort());
return false;
}
int nTxAge = chainActive.Height() - coin.nHeight + 1;
// 1 less than the "send IX" gui requires, in case of a block propagating the network at the time
int nConfirmationsRequired = nInstantSendConfirmationsRequired - 1;
if (nTxAge < nConfirmationsRequired) {
LogPrint("instantsend", "CTxLockRequest::IsValid -- outpoint %s too new: nTxAge=%d, nConfirmationsRequired=%d, txid=%s\n",
txin.prevout.ToStringShort(), nTxAge, nConfirmationsRequired, GetHash().ToString());
return false;
}
nValueIn += coin.out.nValue;
}
if (nValueIn > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN) {
LogPrint("instantsend", "CTxLockRequest::IsValid -- Transaction value too high: nValueIn=%d, tx=%s", nValueIn, ToString());
return false;
}
CAmount nValueOut = tx->GetValueOut();
if (nValueIn - nValueOut < GetMinFee(false)) {
LogPrint("instantsend", "CTxLockRequest::IsValid -- did not include enough fees in transaction: fees=%d, tx=%s", nValueOut - nValueIn, ToString());
return false;
}
return true;
}
CAmount CTxLockRequest::GetMinFee(bool fForceMinFee) const
{
if (!fForceMinFee && CInstantSend::CanAutoLock() && IsSimple()) {
return CAmount();
}
CAmount nMinFee = MIN_FEE;
return std::max(nMinFee, CAmount(tx->vin.size() * nMinFee));
}
int CTxLockRequest::GetMaxSignatures() const
{
return tx->vin.size() * COutPointLock::SIGNATURES_TOTAL;
}
bool CTxLockRequest::IsSimple() const
{
return (tx->vin.size() <= MAX_INPUTS_FOR_AUTO_IX);
}
//
// CTxLockVote
//
bool CTxLockVote::IsValid(CNode* pnode, CConnman& connman) const
{
if (!mnodeman.Has(outpointMasternode)) {
LogPrint("instantsend", "CTxLockVote::IsValid -- Unknown masternode %s\n", outpointMasternode.ToStringShort());
mnodeman.AskForMN(pnode, outpointMasternode, connman);
return false;
}
// Verify that masternodeProTxHash belongs to the same MN referred by the collateral
// Only v13 nodes will send us locks with this field set, and only after spork16 activation
if (!masternodeProTxHash.IsNull()) {
masternode_info_t mnInfo;
if (!mnodeman.GetMasternodeInfo(masternodeProTxHash, mnInfo) || mnInfo.outpoint != outpointMasternode) {
LogPrint("instantsend", "CTxLockVote::IsValid -- invalid masternodeProTxHash %s\n", masternodeProTxHash.ToString());
return false;
}
} else if (deterministicMNManager->IsDeterministicMNsSporkActive()) {
LogPrint("instantsend", "CTxLockVote::IsValid -- missing masternodeProTxHash while DIP3 is active\n");
return false;
}
Coin coin;
if (!GetUTXOCoin(outpoint, coin)) {
LogPrint("instantsend", "CTxLockVote::IsValid -- Failed to find UTXO %s\n", outpoint.ToStringShort());
return false;
}
int nLockInputHeight = coin.nHeight + Params().GetConsensus().nInstantSendConfirmationsRequired - 2;
int nRank;
uint256 expectedQuorumModifierHash;
int nMinRequiredProtocol = std::max(MIN_INSTANTSEND_PROTO_VERSION, mnpayments.GetMinMasternodePaymentsProto());
if (!mnodeman.GetMasternodeRank(outpointMasternode, nRank, expectedQuorumModifierHash, nLockInputHeight, nMinRequiredProtocol)) {
//can be caused by past versions trying to vote with an invalid protocol
LogPrint("instantsend", "CTxLockVote::IsValid -- Can't calculate rank for masternode %s\n", outpointMasternode.ToStringShort());
return false;
}
if (!quorumModifierHash.IsNull()) {
if (quorumModifierHash != expectedQuorumModifierHash) {
LogPrint("instantsend", "CTxLockVote::IsValid -- invalid quorumModifierHash %s, expected %s\n", quorumModifierHash.ToString(), expectedQuorumModifierHash.ToString());
return false;
}
} else if (deterministicMNManager->IsDeterministicMNsSporkActive()) {
LogPrint("instantsend", "CTxLockVote::IsValid -- missing quorumModifierHash while DIP3 is active\n");
return false;
}
LogPrint("instantsend", "CTxLockVote::IsValid -- Masternode %s, rank=%d\n", outpointMasternode.ToStringShort(), nRank);
int nSignaturesTotal = COutPointLock::SIGNATURES_TOTAL;
if (nRank > nSignaturesTotal) {
LogPrint("instantsend", "CTxLockVote::IsValid -- Masternode %s is not in the top %d (%d), vote hash=%s\n",
outpointMasternode.ToStringShort(), nSignaturesTotal, nRank, GetHash().ToString());
return false;
}
if (!CheckSignature()) {
LogPrintf("CTxLockVote::IsValid -- Signature invalid\n");
return false;
}
return true;
}
uint256 CTxLockVote::GetHash() const
{
return SerializeHash(*this);
}
uint256 CTxLockVote::GetSignatureHash() const
{
return GetHash();
}
bool CTxLockVote::CheckSignature() const
{
std::string strError;
masternode_info_t infoMn;
if (!mnodeman.GetMasternodeInfo(outpointMasternode, infoMn)) {
LogPrintf("CTxLockVote::CheckSignature -- Unknown Masternode: masternode=%s\n", outpointMasternode.ToString());
return false;
}
if (deterministicMNManager->IsDeterministicMNsSporkActive()) {
uint256 hash = GetSignatureHash();
CBLSSignature sig;
sig.SetBuf(vchMasternodeSignature);
if (!sig.IsValid() || !sig.VerifyInsecure(infoMn.blsPubKeyOperator, hash)) {
LogPrintf("CTxLockVote::CheckSignature -- VerifyInsecure() failed\n");
return false;
}
} else if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) {
uint256 hash = GetSignatureHash();
if (!CHashSigner::VerifyHash(hash, infoMn.legacyKeyIDOperator, vchMasternodeSignature, strError)) {
// could be a signature in old format
std::string strMessage = txHash.ToString() + outpoint.ToStringShort();
if (!CMessageSigner::VerifyMessage(infoMn.legacyKeyIDOperator, vchMasternodeSignature, strMessage, strError)) {
// nope, not in old format either
LogPrintf("CTxLockVote::CheckSignature -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
}
} else {
std::string strMessage = txHash.ToString() + outpoint.ToStringShort();
if (!CMessageSigner::VerifyMessage(infoMn.legacyKeyIDOperator, vchMasternodeSignature, strMessage, strError)) {
LogPrintf("CTxLockVote::CheckSignature -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
}
return true;
}
bool CTxLockVote::Sign()
{
std::string strError;
if (deterministicMNManager->IsDeterministicMNsSporkActive()) {
uint256 hash = GetSignatureHash();
CBLSSignature sig = activeMasternodeInfo.blsKeyOperator->Sign(hash);
if (!sig.IsValid()) {
return false;
}
sig.GetBuf(vchMasternodeSignature);
} else if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) {
uint256 hash = GetSignatureHash();
if (!CHashSigner::SignHash(hash, activeMasternodeInfo.legacyKeyOperator, vchMasternodeSignature)) {
LogPrintf("CTxLockVote::Sign -- SignHash() failed\n");
return false;
}
if (!CHashSigner::VerifyHash(hash, activeMasternodeInfo.legacyKeyIDOperator, vchMasternodeSignature, strError)) {
LogPrintf("CTxLockVote::Sign -- VerifyHash() failed, error: %s\n", strError);
return false;
}
} else {
std::string strMessage = txHash.ToString() + outpoint.ToStringShort();
if (!CMessageSigner::SignMessage(strMessage, vchMasternodeSignature, activeMasternodeInfo.legacyKeyOperator)) {
LogPrintf("CTxLockVote::Sign -- SignMessage() failed\n");
return false;
}
if (!CMessageSigner::VerifyMessage(activeMasternodeInfo.legacyKeyIDOperator, vchMasternodeSignature, strMessage, strError)) {
LogPrintf("CTxLockVote::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
}
return true;
}
void CTxLockVote::Relay(CConnman& connman) const
{
CInv inv(MSG_TXLOCK_VOTE, GetHash());
CTxLockRequest request;
if (instantsend.GetTxLockRequest(txHash, request) && request) {
connman.RelayInvFiltered(inv, *request.tx);
} else {
connman.RelayInvFiltered(inv, txHash);
}
}
bool CTxLockVote::IsExpired(int nHeight) const
{
// Locks and votes expire nInstantSendKeepLock blocks after the block corresponding tx was included into.
return (nConfirmedHeight != -1) && (nHeight - nConfirmedHeight > Params().GetConsensus().nInstantSendKeepLock);
}
bool CTxLockVote::IsTimedOut() const
{
return GetTime() - nTimeCreated > INSTANTSEND_LOCK_TIMEOUT_SECONDS;
}
bool CTxLockVote::IsFailed() const
{
return (GetTime() - nTimeCreated > INSTANTSEND_FAILED_TIMEOUT_SECONDS) && !instantsend.IsLockedInstantSendTransaction(GetTxHash());
}
//
// COutPointLock
//
bool COutPointLock::AddVote(const CTxLockVote& vote)
{
return mapMasternodeVotes.emplace(vote.GetMasternodeOutpoint(), vote).second;
}
std::vector<CTxLockVote> COutPointLock::GetVotes() const
{
std::vector<CTxLockVote> vRet;
for (const auto& pair : mapMasternodeVotes) {
vRet.push_back(pair.second);
}
return vRet;
}
bool COutPointLock::HasMasternodeVoted(const COutPoint& outpointMasternodeIn) const
{
return mapMasternodeVotes.count(outpointMasternodeIn);
}
void COutPointLock::Relay(CConnman& connman) const
{
for (const auto& pair : mapMasternodeVotes) {
pair.second.Relay(connman);
}
}
//
// CTxLockCandidate
//
void CTxLockCandidate::AddOutPointLock(const COutPoint& outpoint)
{
mapOutPointLocks.insert(std::make_pair(outpoint, COutPointLock(outpoint)));
}
void CTxLockCandidate::MarkOutpointAsAttacked(const COutPoint& outpoint)
{
std::map<COutPoint, COutPointLock>::iterator it = mapOutPointLocks.find(outpoint);
if (it != mapOutPointLocks.end())
it->second.MarkAsAttacked();
}
bool CTxLockCandidate::AddVote(const CTxLockVote& vote)
{
std::map<COutPoint, COutPointLock>::iterator it = mapOutPointLocks.find(vote.GetOutpoint());
if (it == mapOutPointLocks.end()) return false;
return it->second.AddVote(vote);
}
bool CTxLockCandidate::IsAllOutPointsReady() const
{
if (mapOutPointLocks.empty()) return false;
for (const auto& pair : mapOutPointLocks) {
if (!pair.second.IsReady()) return false;
}
return true;
}
bool CTxLockCandidate::HasMasternodeVoted(const COutPoint& outpointIn, const COutPoint& outpointMasternodeIn)
{
std::map<COutPoint, COutPointLock>::iterator it = mapOutPointLocks.find(outpointIn);
return it !=mapOutPointLocks.end() && it->second.HasMasternodeVoted(outpointMasternodeIn);
}
int CTxLockCandidate::CountVotes() const
{
// Note: do NOT use vote count to figure out if tx is locked, use IsAllOutPointsReady() instead
int nCountVotes = 0;
for (const auto& pair : mapOutPointLocks) {
nCountVotes += pair.second.CountVotes();
}
return nCountVotes;
}
bool CTxLockCandidate::IsExpired(int nHeight) const
{
// Locks and votes expire nInstantSendKeepLock blocks after the block corresponding tx was included into.
return (nConfirmedHeight != -1) && (nHeight - nConfirmedHeight > Params().GetConsensus().nInstantSendKeepLock);
}
bool CTxLockCandidate::IsTimedOut() const
{
return GetTime() - nTimeCreated > INSTANTSEND_LOCK_TIMEOUT_SECONDS;
}
void CTxLockCandidate::Relay(CConnman& connman) const
{
connman.RelayTransaction(*txLockRequest.tx);
for (const auto& pair : mapOutPointLocks) {
pair.second.Relay(connman);
}
}
|
/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2023-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#include "readwritesplit.hh"
#include "rwsplitsession.hh"
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <maxscale/router.hh>
#include <maxscale/query_classifier.hh>
#include <maxscale/dcb.hh>
#include <maxscale/modinfo.h>
#include <maxscale/modutil.hh>
#include <maxscale/protocol/mysql.hh>
#include <maxbase/alloc.h>
/**
* Functions within the read-write split router that are specific to
* MySQL. The aim is to either remove these into a separate module or to
* move them into the MySQL protocol modules.
*/
/*
* The following functions are called from elsewhere in the router and
* are defined in rwsplit_internal.hh. They are not intended to be called
* from outside this router.
*/
/* This could be placed in the protocol, with a new API entry point
* It is certainly MySQL specific. Packet types are DB specific, but can be
* assumed to be enums, which can be handled as integers without knowing
* which DB is involved until the packet type needs to be interpreted.
*
*/
/*
* This appears to be MySQL specific
*/
/*
* This one is problematic because it is MySQL specific, but also router
* specific.
*/
/*
* This is mostly router code, but it contains MySQL specific operations that
* maybe could be moved to the protocol module. The modutil functions are mostly
* MySQL specific and could migrate to the MySQL protocol; likewise the
* utility to convert packet type to a string. The aim is for most of this
* code to remain as part of the router.
*/
/**
* @brief Operations to be carried out if request is for all backend servers
*
* If the choice of sending to all backends is in conflict with other bit
* settings in route_target, then error messages are written to the log.
*
* Otherwise, the function route_session_write is called to carry out the
* actual routing.
*
* @param route_target Bit map indicating where packet should be routed
* @param inst Router instance
* @param rses Router session
* @param querybuf Query buffer containing packet
* @param packet_type Integer (enum) indicating type of packet
* @param qtype Query type
* @return bool indicating whether the session can continue
*/
bool RWSplitSession::handle_target_is_all(route_target_t route_target,
GWBUF* querybuf,
int packet_type,
uint32_t qtype)
{
bool result = false;
bool is_large = is_large_query(querybuf);
if (TARGET_IS_MASTER(route_target) || TARGET_IS_SLAVE(route_target))
{
/**
* Conflicting routing targets. Return an error to the client.
*/
char* query_str = modutil_get_query(querybuf);
char* qtype_str = qc_typemask_to_string(qtype);
MXS_ERROR("Can't route %s:%s:\"%s\". SELECT with session data "
"modification is not supported if configuration parameter "
"use_sql_variables_in=all .",
STRPACKETTYPE(packet_type),
qtype_str,
(query_str == NULL ? "(empty)" : query_str));
GWBUF* errbuf = modutil_create_mysql_err_msg(1,
0,
1064,
"42000",
"Routing query to backend failed. "
"See the error log for further details.");
if (errbuf)
{
m_client->func.write(m_client, errbuf);
result = true;
}
MXS_FREE(query_str);
MXS_FREE(qtype_str);
}
else if (m_qc.large_query())
{
// TODO: Append to the already stored session command instead of disabling history
MXS_INFO("Large session write, have to disable session command history");
m_config.disable_sescmd_history = true;
continue_large_session_write(querybuf, qtype);
result = true;
}
else if (route_session_write(gwbuf_clone(querybuf), packet_type, qtype))
{
result = true;
mxb::atomic::add(&m_router->stats().n_all, 1, mxb::atomic::RELAXED);
}
m_qc.set_large_query(is_large);
return result;
}
/**
* @brief Send an error message to the client telling that the server is in read only mode
*
* @param dcb Client DCB
*
* @return True if sending the message was successful, false if an error occurred
*/
bool send_readonly_error(DCB* dcb)
{
bool succp = false;
const char* errmsg = "The MariaDB server is running with the --read-only"
" option so it cannot execute this statement";
GWBUF* err = modutil_create_mysql_err_msg(1,
0,
ER_OPTION_PREVENTS_STATEMENT,
"HY000",
errmsg);
if (err)
{
succp = dcb->func.write(dcb, err);
}
else
{
MXS_ERROR("Memory allocation failed when creating client error message.");
}
return succp;
}
|
#include <service/sendcontext.hpp>
#include <router/abstractrouter.hpp>
#include <routing/path_transfer_message.hpp>
#include <service/endpoint.hpp>
#include <util/logic.hpp>
namespace llarp
{
namespace service
{
SendContext::SendContext(const ServiceInfo& ident,
const Introduction& intro, path::PathSet* send,
Endpoint* ep)
: remoteIdent(ident)
, remoteIntro(intro)
, m_PathSet(send)
, m_DataHandler(ep)
, m_Endpoint(ep)
{
createdAt = ep->Now();
currentConvoTag.Zero();
}
bool
SendContext::Send(const ProtocolFrame& msg, path::Path_ptr path)
{
auto transfer = std::make_shared< const routing::PathTransferMessage >(
msg, remoteIntro.pathID);
{
util::Lock lock(&m_SendQueueMutex);
m_SendQueue.emplace_back(transfer, path);
}
return true;
}
void
SendContext::FlushUpstream()
{
auto r = m_Endpoint->Router();
util::Lock lock(&m_SendQueueMutex);
for(const auto& item : m_SendQueue)
{
if(item.second->SendRoutingMessage(*item.first, r))
{
lastGoodSend = r->Now();
}
else
LogError("Failed to send frame on path");
}
m_SendQueue.clear();
}
/// send on an established convo tag
void
SendContext::EncryptAndSendTo(const llarp_buffer_t& payload, ProtocolType t)
{
SharedSecret shared;
ProtocolFrame f;
f.N.Randomize();
f.T = currentConvoTag;
f.S = ++sequenceNo;
auto now = m_Endpoint->Now();
if(remoteIntro.ExpiresSoon(now))
{
// shift intro
if(MarkCurrentIntroBad(now))
{
LogInfo("intro shifted");
}
}
auto path = m_PathSet->GetNewestPathByRouter(remoteIntro.router);
if(!path)
{
LogError("cannot encrypt and send: no path for intro ", remoteIntro);
return;
}
if(!m_DataHandler->GetCachedSessionKeyFor(f.T, shared))
{
LogError("No cached session key");
return;
}
ProtocolMessage m;
m_DataHandler->PutIntroFor(f.T, remoteIntro);
m_DataHandler->PutReplyIntroFor(f.T, path->intro);
m.proto = t;
m.seqno = m_Endpoint->GetSeqNoForConvo(f.T);
m.introReply = path->intro;
f.F = m.introReply.pathID;
m.sender = m_Endpoint->GetIdentity().pub;
m.tag = f.T;
m.PutBuffer(payload);
if(!f.EncryptAndSign(m, shared, m_Endpoint->GetIdentity()))
{
LogError("failed to sign");
return;
}
Send(f, path);
}
void
SendContext::AsyncEncryptAndSendTo(const llarp_buffer_t& data,
ProtocolType protocol)
{
auto now = m_Endpoint->Now();
if(remoteIntro.ExpiresSoon(now))
{
if(!ShiftIntroduction())
{
LogWarn("no good path yet, your message may drop");
}
}
if(lastGoodSend)
{
EncryptAndSendTo(data, protocol);
}
else
{
AsyncGenIntro(data, protocol);
}
}
} // namespace service
} // namespace llarp
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h> // Must come before other Windows system headers.
#include <oleacc.h>
#include <wrl/client.h>
#include "base/strings/utf_string_conversions.h"
#include "base/win/scoped_variant.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/text_edit_commands.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_test_api.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
class AXSystemCaretWinTest : public test::DesktopWidgetTest {
public:
AXSystemCaretWinTest() : self_(CHILDID_SELF) {}
AXSystemCaretWinTest(const AXSystemCaretWinTest&) = delete;
AXSystemCaretWinTest& operator=(const AXSystemCaretWinTest&) = delete;
~AXSystemCaretWinTest() override = default;
void SetUp() override {
SetUpForInteractiveTests();
test::DesktopWidgetTest::SetUp();
widget_ = CreateTopLevelNativeWidget();
widget_->SetBounds(gfx::Rect(0, 0, 200, 200));
textfield_ = new Textfield();
textfield_->SetBounds(0, 0, 200, 20);
textfield_->SetText(u"Some text.");
widget_->GetRootView()->AddChildView(textfield_);
test::WidgetActivationWaiter waiter(widget_, true);
widget_->Show();
waiter.Wait();
textfield_->RequestFocus();
ASSERT_TRUE(widget_->IsActive());
ASSERT_TRUE(textfield_->HasFocus());
ASSERT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
widget_->GetInputMethod()->GetTextInputType());
}
void TearDown() override {
widget_->CloseNow();
test::DesktopWidgetTest::TearDown();
ui::ResourceBundle::CleanupSharedInstance();
}
protected:
Widget* widget_;
Textfield* textfield_;
base::win::ScopedVariant self_;
};
class WinAccessibilityCaretEventMonitor {
public:
WinAccessibilityCaretEventMonitor(UINT event_min, UINT event_max);
WinAccessibilityCaretEventMonitor(const WinAccessibilityCaretEventMonitor&) =
delete;
WinAccessibilityCaretEventMonitor& operator=(
const WinAccessibilityCaretEventMonitor&) = delete;
~WinAccessibilityCaretEventMonitor();
// Blocks until the next event is received. When it's received, it
// queries accessibility information about the object that fired the
// event and populates the event, hwnd, role, state, and name in the
// passed arguments.
void WaitForNextEvent(DWORD* out_event, UINT* out_role, UINT* out_state);
private:
void OnWinEventHook(HWINEVENTHOOK handle,
DWORD event,
HWND hwnd,
LONG obj_id,
LONG child_id,
DWORD event_thread,
DWORD event_time);
static void CALLBACK WinEventHookThunk(HWINEVENTHOOK handle,
DWORD event,
HWND hwnd,
LONG obj_id,
LONG child_id,
DWORD event_thread,
DWORD event_time);
struct EventInfo {
DWORD event;
HWND hwnd;
LONG obj_id;
LONG child_id;
};
base::circular_deque<EventInfo> event_queue_;
base::RunLoop loop_runner_;
HWINEVENTHOOK win_event_hook_handle_;
static WinAccessibilityCaretEventMonitor* instance_;
};
// static
WinAccessibilityCaretEventMonitor*
WinAccessibilityCaretEventMonitor::instance_ = nullptr;
WinAccessibilityCaretEventMonitor::WinAccessibilityCaretEventMonitor(
UINT event_min,
UINT event_max) {
CHECK(!instance_) << "There can be only one instance of"
<< " WinAccessibilityCaretEventMonitor at a time.";
instance_ = this;
win_event_hook_handle_ =
SetWinEventHook(event_min, event_max, nullptr,
&WinAccessibilityCaretEventMonitor::WinEventHookThunk,
GetCurrentProcessId(),
0, // Hook all threads
WINEVENT_OUTOFCONTEXT);
}
WinAccessibilityCaretEventMonitor::~WinAccessibilityCaretEventMonitor() {
UnhookWinEvent(win_event_hook_handle_);
instance_ = nullptr;
}
void WinAccessibilityCaretEventMonitor::WaitForNextEvent(DWORD* out_event,
UINT* out_role,
UINT* out_state) {
if (event_queue_.empty())
loop_runner_.Run();
EventInfo event_info = event_queue_.front();
event_queue_.pop_front();
*out_event = event_info.event;
Microsoft::WRL::ComPtr<IAccessible> acc_obj;
base::win::ScopedVariant child_variant;
CHECK(S_OK == AccessibleObjectFromEvent(event_info.hwnd, event_info.obj_id,
event_info.child_id, &acc_obj,
child_variant.Receive()));
base::win::ScopedVariant role_variant;
if (S_OK == acc_obj->get_accRole(child_variant, role_variant.Receive()))
*out_role = V_I4(role_variant.ptr());
else
*out_role = 0;
base::win::ScopedVariant state_variant;
if (S_OK == acc_obj->get_accState(child_variant, state_variant.Receive()))
*out_state = V_I4(state_variant.ptr());
else
*out_state = 0;
}
void WinAccessibilityCaretEventMonitor::OnWinEventHook(HWINEVENTHOOK handle,
DWORD event,
HWND hwnd,
LONG obj_id,
LONG child_id,
DWORD event_thread,
DWORD event_time) {
EventInfo event_info;
event_info.event = event;
event_info.hwnd = hwnd;
event_info.obj_id = obj_id;
event_info.child_id = child_id;
event_queue_.push_back(event_info);
loop_runner_.Quit();
}
// static
void CALLBACK
WinAccessibilityCaretEventMonitor::WinEventHookThunk(HWINEVENTHOOK handle,
DWORD event,
HWND hwnd,
LONG obj_id,
LONG child_id,
DWORD event_thread,
DWORD event_time) {
if (instance_ && obj_id == OBJID_CARET) {
instance_->OnWinEventHook(handle, event, hwnd, obj_id, child_id,
event_thread, event_time);
}
}
} // namespace
TEST_F(AXSystemCaretWinTest, TestOnCaretBoundsChangeInTextField) {
TextfieldTestApi textfield_test_api(textfield_);
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
gfx::NativeWindow native_window = widget_->GetNativeWindow();
ASSERT_NE(nullptr, native_window);
HWND hwnd = native_window->GetHost()->GetAcceleratedWidget();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
gfx::Rect window_bounds = native_window->GetBoundsInScreen();
textfield_test_api.ExecuteTextEditCommand(
ui::TextEditCommand::MOVE_TO_BEGINNING_OF_DOCUMENT);
gfx::Point caret_position = textfield_test_api.GetCursorViewRect().origin() +
window_bounds.OffsetFromOrigin();
LONG x, y, width, height;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
EXPECT_EQ(caret_position.x(), x);
EXPECT_EQ(caret_position.y(), y);
EXPECT_EQ(1, width);
textfield_test_api.ExecuteTextEditCommand(
ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT);
gfx::Point caret_position2 = textfield_test_api.GetCursorViewRect().origin() +
window_bounds.OffsetFromOrigin();
EXPECT_NE(caret_position, caret_position2);
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
EXPECT_EQ(caret_position2.x(), x);
EXPECT_EQ(caret_position2.y(), y);
EXPECT_EQ(1, width);
}
TEST_F(AXSystemCaretWinTest, TestOnInputTypeChangeInTextField) {
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
gfx::NativeWindow native_window = widget_->GetNativeWindow();
ASSERT_NE(nullptr, native_window);
HWND hwnd = native_window->GetHost()->GetAcceleratedWidget();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
LONG x, y, width, height;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
// Caret object should still be valid.
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
// Retrieving the caret again should also work.
caret_accessible.Reset();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
LONG x2, y2, width2, height2;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x2, &y2, &width2, &height2, self_));
EXPECT_EQ(x, x2);
EXPECT_EQ(y, y2);
EXPECT_EQ(width, width2);
EXPECT_EQ(height, height2);
}
TEST_F(AXSystemCaretWinTest, TestMovingWindow) {
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
gfx::NativeWindow native_window = widget_->GetNativeWindow();
ASSERT_NE(nullptr, native_window);
HWND hwnd = native_window->GetHost()->GetAcceleratedWidget();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
LONG x, y, width, height;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
widget_->SetBounds(gfx::Rect(100, 100, 500, 500));
LONG x2, y2, width2, height2;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x2, &y2, &width2, &height2, self_));
EXPECT_NE(x, x2);
EXPECT_NE(y, y2);
// The width and height of the caret shouldn't change.
EXPECT_EQ(width, width2);
EXPECT_EQ(height, height2);
// Try maximizing the window.
SendMessage(hwnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
// On Win7, maximizing the window causes our caret object to get destroyed and
// re-created, so re-acquire it.
caret_accessible.Reset();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
LONG x3, y3, width3, height3;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x3, &y3, &width3, &height3, self_));
EXPECT_NE(x2, x3);
EXPECT_NE(y2, y3);
// The width and height of the caret shouldn't change.
EXPECT_EQ(width, width3);
EXPECT_EQ(height, height3);
}
TEST_F(AXSystemCaretWinTest, TestCaretMSAAEvents) {
TextfieldTestApi textfield_test_api(textfield_);
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
gfx::NativeWindow native_window = widget_->GetNativeWindow();
ASSERT_NE(nullptr, native_window);
HWND hwnd = native_window->GetHost()->GetAcceleratedWidget();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
DWORD event;
UINT role;
UINT state;
{
// Set caret to start of textfield.
WinAccessibilityCaretEventMonitor monitor(EVENT_OBJECT_SHOW,
EVENT_OBJECT_LOCATIONCHANGE);
textfield_test_api.ExecuteTextEditCommand(
ui::TextEditCommand::MOVE_TO_BEGINNING_OF_DOCUMENT);
monitor.WaitForNextEvent(&event, &role, &state);
ASSERT_EQ(event, static_cast<DWORD>(EVENT_OBJECT_LOCATIONCHANGE))
<< "Event should be EVENT_OBJECT_LOCATIONCHANGE";
ASSERT_EQ(role, static_cast<UINT>(ROLE_SYSTEM_CARET))
<< "Role should be ROLE_SYSTEM_CARET";
ASSERT_EQ(state, static_cast<UINT>(0)) << "State should be 0";
}
{
// Set caret to end of textfield.
WinAccessibilityCaretEventMonitor monitor(EVENT_OBJECT_SHOW,
EVENT_OBJECT_LOCATIONCHANGE);
textfield_test_api.ExecuteTextEditCommand(
ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT);
monitor.WaitForNextEvent(&event, &role, &state);
ASSERT_EQ(event, static_cast<DWORD>(EVENT_OBJECT_LOCATIONCHANGE))
<< "Event should be EVENT_OBJECT_LOCATIONCHANGE";
ASSERT_EQ(role, static_cast<UINT>(ROLE_SYSTEM_CARET))
<< "Role should be ROLE_SYSTEM_CARET";
ASSERT_EQ(state, static_cast<UINT>(0)) << "State should be 0";
}
{
// Move focus to a button.
LabelButton button{Button::PressedCallback(), std::u16string()};
button.SetBounds(500, 0, 200, 20);
widget_->GetRootView()->AddChildView(&button);
test::WidgetActivationWaiter waiter(widget_, true);
WinAccessibilityCaretEventMonitor monitor(EVENT_OBJECT_SHOW,
EVENT_OBJECT_LOCATIONCHANGE);
widget_->Show();
waiter.Wait();
button.SetFocusBehavior(View::FocusBehavior::ALWAYS);
button.RequestFocus();
monitor.WaitForNextEvent(&event, &role, &state);
ASSERT_EQ(event, static_cast<DWORD>(EVENT_OBJECT_HIDE))
<< "Event should be EVENT_OBJECT_HIDE";
ASSERT_EQ(role, static_cast<UINT>(ROLE_SYSTEM_CARET))
<< "Role should be ROLE_SYSTEM_CARET";
ASSERT_EQ(state, static_cast<UINT>(STATE_SYSTEM_INVISIBLE))
<< "State should be STATE_SYSTEM_INVISIBLE";
}
{
// Move focus back to the text field.
WinAccessibilityCaretEventMonitor monitor(EVENT_OBJECT_SHOW,
EVENT_OBJECT_LOCATIONCHANGE);
textfield_->RequestFocus();
monitor.WaitForNextEvent(&event, &role, &state);
ASSERT_EQ(event, static_cast<DWORD>(EVENT_OBJECT_SHOW))
<< "Event should be EVENT_OBJECT_SHOW";
ASSERT_EQ(role, static_cast<UINT>(ROLE_SYSTEM_CARET))
<< "Role should be ROLE_SYSTEM_CARET";
ASSERT_EQ(state, static_cast<UINT>(0)) << "State should be 0";
}
}
} // namespace views
|
#include <stdio.h>
#include <unistd.h>
#include "Thread.hpp"
#include "Runnable.hpp"
#include "BlockingQueue.hpp"
#include "ExecutorService.hpp"
#include "Integer.hpp"
#include "Executors.hpp"
#include "Future.hpp"
#include "System.hpp"
using namespace obotcha;
DECLARE_CLASS(TestScheduleCancelRun1) IMPLEMENTS(Runnable) {
public:
_TestScheduleCancelRun1() {
interrupt = 0;
value = 0;
}
void run() {
printf("i am running trace1\n");
sleep(2);
value = 1;
printf("i am running trace2\n");
}
void onInterrupt() {
printf("i am interrupt trace1\n");
interrupt = 1;
printf("i am interrupt trace2\n");
}
int getValue() {
return value;
}
int getInterrupt() {
return interrupt;
}
private:
int value;
int interrupt;
};
DECLARE_CLASS(TestScheduleCancelRun2) IMPLEMENTS(Runnable) {
public:
_TestScheduleCancelRun2() {
interrupt = 0;
value = 0;
}
void run() {
sleep(2);
value++;
printf("run thread:%d finished \n",count);
}
void onInterrupt() {
interrupt = 1;
}
int getValue() {
return value;
}
int getInterrupt() {
return interrupt;
}
void setCount(int v) {
count = v;
}
int getCount() {
return count;
}
private:
int value;
int interrupt;
int count;
};
int testThreadScheduleFutureCancel() {
//threadExecutorPool
while(1) {
ExecutorService pool = st(Executors)::newScheduledThreadPool();
TestScheduleCancelRun1 run1 = createTestScheduleCancelRun1();
Future f = pool->submit(run1);
sleep(1);
f->cancel();
sleep(5);
if(run1->getValue() == 1 || run1->getInterrupt() != 1) {
printf("---[TestFuture ScheduledThreadPool Test {cancel()} case1] [FAIL],val is %d,interrupt is %d--- \n",run1->getValue(),run1->getInterrupt());
break;
}
pool->shutdown();
printf("---[TestFuture ScheduledThreadPool Test {cancel()} case2] [Success]--- \n");
break;
}
while(1) {
ExecutorService pool = st(Executors)::newScheduledThreadPool();
ArrayList<Future> futurelist = createArrayList<Future>();
for(int i = 0;i<50;i++) {
Future f = pool->submit(createTestScheduleCancelRun1());
futurelist->add(f);
}
//for(int j = 0;j<50;j++) {
printf("start test cancel \n");
ListIterator<Future> iterator = futurelist->getIterator();
while(iterator->hasValue()) {
Future f = iterator->getValue();
f->cancel();
iterator->next();
}
//}
sleep(1);
pool->shutdown();
printf("pool count is %d \n",pool->getStrongCount());
printf("---[TestFuture ScheduledThreadPool Test {cancel()} case3] [Success]--- \n");
break;
}
while(1) {
ExecutorService pool = st(Executors)::newScheduledThreadPool();
ArrayList<Future> futurelist = createArrayList<Future>();
for(int i = 0;i<50;i++) {
Future f = pool->submit(createTestScheduleCancelRun1());
futurelist->add(f);
}
pool->shutdown();
for(int j = 0;j<50;j++) {
ListIterator<Future> iterator = futurelist->getIterator();
while(iterator->hasValue()) {
Future f = iterator->getValue();
f->cancel();
iterator->next();
}
}
pool->shutdown();
sleep(1);
printf("---[TestFuture ScheduledThreadPool Test {cancel()} case4] [Success]--- \n");
break;
}
while(1) {
ExecutorService pool = st(Executors)::newScheduledThreadPool();
ArrayList<Future> futurelist = createArrayList<Future>();
for(int i = 0;i<55;i++) {
Future f = pool->submit(createTestScheduleCancelRun1());
futurelist->add(f);
}
for(int j = 0;j<50;j++) {
ListIterator<Future> iterator = futurelist->getIterator();
while(iterator->hasValue()) {
Future f = iterator->getValue();
f->cancel();
iterator->next();
}
}
long start = st(System)::currentTimeMillis();
//for(int i = 0;i<50;i++) {
printf("submit testcancel run1 \n");
Future f1 = pool->submit(createTestScheduleCancelRun1());
Future f2 = pool->submit(createTestScheduleCancelRun1());
long end = st(System)::currentTimeMillis();
if((end - start) > 10) {
printf("---[TestFuture ScheduledThreadPool Test {cancel()} case5] [Fail],%d --- \n",end-start);
break;
}
pool->shutdown();
printf("---[TestFuture ScheduledThreadPool Test {cancel()} case6] [Success]--- \n");
break;
}
while(1) {
ExecutorService pool = st(Executors)::newScheduledThreadPool();
ArrayList<Future> futurelist = createArrayList<Future>();
ArrayList<TestScheduleCancelRun2> runlist = createArrayList<TestScheduleCancelRun2>();
for(int i = 0;i<55;i++) {
TestScheduleCancelRun2 run2 = createTestScheduleCancelRun2();
run2->setCount(i);
runlist->add(run2);
Future f = pool->submit(run2);
futurelist->add(f);
}
sleep(1);
printf("start stop future \n");
//for(int j = 0;j<55;j++) {
ListIterator<Future> iterator = futurelist->getIterator();
while(iterator->hasValue()) {
Future f = iterator->getValue();
f->cancel();
iterator->next();
}
//}
sleep(100);
ListIterator<TestScheduleCancelRun2> iterator2 = runlist->getIterator();
while(iterator2->hasValue()) {
TestScheduleCancelRun2 run_2 = iterator2->getValue();
if(run_2->getValue() != 0) {
printf("---[TestFuture ScheduledThreadPool Test {cancel()} case7] [Fail],count is %d,value is %d --- \n",run_2->getCount(),run_2->getValue());
//break;
}
iterator2->next();
}
pool->shutdown();
printf("---[TestFuture ScheduledThreadPool Test {cancel()} case8] [Success] --- \n");
break;
}
}
|
#include <vcl_compiler.h>
// ------------------------------------------------
// this *does* work for SGI CC 7.2.1 -- fsm
template <class T>
struct X
{
int x;
X();
// declaration of static template member.
static X<T> *pl;
};
template <class T>
X<T>::X() : x(1728) { }
// definition (not specialization) of static template member.
template <class T>
X<T> *X<T>::pl = 0;
// explicit instantiation of class also instantiates statics.
template struct X<int>;
// ------------------------------------------------
struct A
{
int x;
mutable int y;
A() : x(0), y(0) { }
void f() { ++ x; }
void g() const { ++ y; }
};
// ------------------------------------------------
#include <vcl_iostream.h>
void vcl_test_implicit_instantiation(int n);
int test_compiler_main(int /*argc*/,char* /*argv*/[])
{
int result = 0;
vcl_cout << "Testing static template member..." << vcl_flush;
if ( X<int>::pl == 0 ) {
vcl_cout << " PASSED" << vcl_endl;
}
else {
vcl_cout << "**FAILED**" << vcl_endl;
result = 1;
}
// If it links, it passed!
vcl_cout << "Testing implicit instantiation..." << vcl_flush;
vcl_test_implicit_instantiation(100);
vcl_cout << " PASSED" << vcl_endl;
return result;
}
#if defined(VCL_USE_IMPLICIT_TEMPLATES) && VCL_USE_IMPLICIT_TEMPLATES
#include <vcl_vector.h>
#include <vcl_map.h>
#include <vcl_algorithm.h>
struct mystery_type
{
mystery_type();
mystery_type(int, float);
mystery_type(mystery_type const &);
mystery_type &operator=(mystery_type const &);
int a;
float b;
};
bool operator==(mystery_type const &, mystery_type const &);
bool operator< (mystery_type const &, mystery_type const &);
void vcl_test_implicit_instantiation(int n)
{
vcl_vector<mystery_type> v;
v.resize(n);
for (int i=0; i<n; ++i) {
v[i].a = i;
v[i].b = i/float(n);
}
v.reserve(2*n);
v.resize(n/2);
vcl_sort(v.begin(), v.end());
v = v;
v.clear();
typedef vcl_map<int, mystery_type, vcl_less<int> > map_t;
map_t m;
for (int i=0; i<n; ++i)
m.insert(map_t::value_type(0, mystery_type(i, i/float(n))));
m.clear();
}
mystery_type::mystery_type()
{ }
mystery_type::mystery_type(int a_, float b_)
: a(a_), b(b_) { }
mystery_type::mystery_type(mystery_type const &that)
: a(that.a), b(that.b) { }
mystery_type &mystery_type::operator=(mystery_type const &that)
{ a = that.a; b = that.b; return *this; }
bool operator==(mystery_type const &x, mystery_type const &y)
{ return (x.a == y.a) && (x.b == y.b); }
bool operator< (mystery_type const &x, mystery_type const &y)
{ return (x.a < y.b) || ((x.a == y.a) && (x.b < y.b)); }
#else
void vcl_test_implicit_instantiation(int) { }
#endif
|
// featbin/apply-ltsv.cc
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "matrix/kaldi-matrix.h"
#include "transform/featxtra-functions.h"
using namespace std;
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
const char *usage =
"Apply LTSV (Long Term Spectral Variability) measure on a "
"matrix of spectral features\n"
"Per-utterance by default, or per-speaker if utt2spk option provided\n"
"Usage: apply-ltsv [options] feats-rspecifier feats-wspecifier\n";
ParseOptions po(usage);
std::string utt2spk_rspecifier;
int32 ar_order = 10; // ARMA filter tab order
int32 ctx_win = 50; // context window parameter
BaseFloat ltsv_slope = 0.2; // sigmoid slope parameter
BaseFloat ltsv_thr = 0.5; // sigmoid threshold parameter
po.Register("ar-order", &ar_order, "Order of the ARMA filtering [default: 10]");
po.Register("ctx-win", &ctx_win, "Context window frame size [default: 50]");
po.Register("ltsv-slope", <sv_slope, "Sigmoid slope parameter [default: 0.2]");
po.Register("ltsv-thr", <sv_thr, "Sigmoid threshold parameter [default: 0.5]");
po.Read(argc, argv);
if (po.NumArgs() != 2) {
po.PrintUsage();
exit(1);
}
kaldi::int32 num_done = 0;
std::string feat_rspecifier = po.GetArg(1);
std::string feat_wspecifier = po.GetArg(2);
SequentialBaseFloatMatrixReader feat_reader(feat_rspecifier);
BaseFloatMatrixWriter feat_writer(feat_wspecifier);
if (utt2spk_rspecifier != "")
KALDI_ERR << "--utt2spk option not compatible with rxfilename as input "
<< "(did you forget ark:?)";
for (;!feat_reader.Done(); feat_reader.Next()) {
std::string utt = feat_reader.Key();
//Matrix<BaseFloat> &feats = feat_reader.Value();
Matrix<BaseFloat> feat(feat_reader.Value());
Matrix<BaseFloat> ltsv;
ApplyArma(ar_order, &feat);
ApplyLtsv(ctx_win, ltsv_slope, ltsv_thr, &feat, <sv);
feat_writer.Write(utt, ltsv);
num_done++;
}
return (num_done != 0 ? 0 : 1);
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/cpu/conv_canonicalization.h"
#include <vector>
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/test_helpers.h"
namespace xla {
namespace cpu {
class ConvCanonicalizationTest : public HloTestBase {
public:
ConvCanonicalizationTest() {
for (int i = 0; i < 2; ++i) {
auto dim = conv_window_.add_dimensions();
dim->set_size(kWindowSize);
dim->set_stride(1);
dim->set_padding_low(0);
dim->set_padding_high(0);
dim->set_window_dilation(1);
dim->set_base_dilation(1);
}
}
protected:
Window conv_window_;
static constexpr int kBatchSize = 50;
static constexpr int kInputSize = 28;
static constexpr int kWindowSize = 5;
static constexpr int kInputFeatureCount = 32;
static constexpr int kOutputFeatureCount = 64;
};
TEST_F(ConvCanonicalizationTest, NonCanonicalToCanonical) {
auto builder = HloComputation::Builder(TestName());
// The input dimensions are in CNHW order.
auto input = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR4FromArray4D(Array4D<float>(
kInputFeatureCount, kBatchSize, kInputSize, kInputSize))));
// The kernel dimensions are in OIHW order.
auto kernel = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR4FromArray4D(Array4D<float>(
kOutputFeatureCount, kInputFeatureCount, kWindowSize, kWindowSize))));
ConvolutionDimensionNumbers dnums;
dnums.set_batch_dimension(1);
dnums.add_spatial_dimensions(2);
dnums.add_spatial_dimensions(3);
dnums.set_feature_dimension(0);
dnums.add_kernel_spatial_dimensions(2);
dnums.add_kernel_spatial_dimensions(3);
dnums.set_kernel_input_feature_dimension(1);
dnums.set_kernel_output_feature_dimension(0);
auto output_size = kInputSize - kWindowSize + 1;
builder.AddInstruction(HloInstruction::CreateConvolve(
ShapeUtil::MakeShape(
F32, {kOutputFeatureCount, kBatchSize, output_size, output_size}),
input, kernel, conv_window_, dnums));
auto module = MakeUnique<HloModule>(TestName());
HloComputation* entry_computation =
module->AddEntryComputation(builder.Build());
ConvCanonicalization conv_canonicalization;
EXPECT_TRUE(conv_canonicalization.Run(module.get()).ValueOrDie());
const HloInstruction* output_reshape = entry_computation->root_instruction();
EXPECT_EQ(HloOpcode::kTranspose, output_reshape->opcode());
const HloInstruction* canonical_conv = output_reshape->operand(0);
EXPECT_EQ(HloOpcode::kConvolution, canonical_conv->opcode());
const HloInstruction* input_reshape = canonical_conv->operand(0);
EXPECT_EQ(HloOpcode::kTranspose, input_reshape->opcode());
const HloInstruction* kernel_reshape = canonical_conv->operand(1);
EXPECT_EQ(HloOpcode::kTranspose, kernel_reshape->opcode());
// The input is in CNHW order. input_reshape should produce
// NHWC for the convolution to hit the Eigen fast path.
EXPECT_TRUE(ContainersEqual(input_reshape->dimensions(), {1, 2, 3, 0}));
// The kernel is in OIHW order. kernel_reshape should produce
// HWIO for the convolution to hit the Eigen fast path.
EXPECT_TRUE(ContainersEqual(kernel_reshape->dimensions(), {2, 3, 1, 0}));
// The output of the canonical convolution is in NHWC order (the same as
// input_reshape's order). output_reshape should restore that order to the
// order of the computation root (CNHW).
EXPECT_TRUE(ContainersEqual(output_reshape->dimensions(), {3, 0, 1, 2}));
}
TEST_F(ConvCanonicalizationTest, CanonicalStaysTheSame) {
auto builder = HloComputation::Builder(TestName());
// The input dimensions are in NHWC order.
auto input = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR4FromArray4D(Array4D<float>(
kBatchSize, kInputSize, kInputSize, kInputFeatureCount))));
// The kernel dimensions are in HWIO order.
auto kernel = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR4FromArray4D(Array4D<float>(
kWindowSize, kWindowSize, kInputFeatureCount, kOutputFeatureCount))));
ConvolutionDimensionNumbers dnums;
dnums.set_batch_dimension(0);
dnums.add_spatial_dimensions(1);
dnums.add_spatial_dimensions(2);
dnums.set_feature_dimension(3);
dnums.add_kernel_spatial_dimensions(0);
dnums.add_kernel_spatial_dimensions(1);
dnums.set_kernel_input_feature_dimension(2);
dnums.set_kernel_output_feature_dimension(3);
auto output_size = kInputSize - kWindowSize + 1;
builder.AddInstruction(HloInstruction::CreateConvolve(
ShapeUtil::MakeShape(
F32, {kBatchSize, output_size, output_size, kOutputFeatureCount}),
input, kernel, conv_window_, dnums));
auto module = MakeUnique<HloModule>(TestName());
module->AddEntryComputation(builder.Build());
ConvCanonicalization conv_canonicalization;
EXPECT_FALSE(conv_canonicalization.Run(module.get()).ValueOrDie());
}
} // namespace cpu
} // namespace xla
|
/*
Copyright (C) 2003-2013 by David White <davewx7@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/bind.hpp>
#include "image_widget.hpp"
#include "input.hpp"
#include "scrollbar_widget.hpp"
#include "widget_factory.hpp"
namespace gui {
namespace {
const std::string UpArrow = "scrollbar-vertical-up-arrow";
const std::string DownArrow = "scrollbar-vertical-down-arrow";
const std::string VerticalHandle = "scrollbar-vertical-handle-middle";
const std::string VerticalHandleBot = "scrollbar-vertical-handle-bottom";
const std::string VerticalHandleTop = "scrollbar-vertical-handle-top";
const std::string VerticalBackground = "scrollbar-vertical-background";
}
scrollbar_widget::scrollbar_widget(boost::function<void(int)> handler)
: handler_(handler),
up_arrow_(new gui_section_widget(UpArrow)),
down_arrow_(new gui_section_widget(DownArrow)),
handle_(new gui_section_widget(VerticalHandle)),
handle_bot_(new gui_section_widget(VerticalHandleBot)),
handle_top_(new gui_section_widget(VerticalHandleTop)),
background_(new gui_section_widget(VerticalBackground)),
window_pos_(0), window_size_(0), range_(0), step_(0), arrow_step_(0),
dragging_handle_(false),
drag_start_(0), drag_anchor_y_(0)
{
set_environment();
}
scrollbar_widget::scrollbar_widget(const variant& v, game_logic::formula_callable* e)
: widget(v,e), window_pos_(0), window_size_(0), range_(0),
step_(0), arrow_step_(0),
dragging_handle_(false), drag_start_(0), drag_anchor_y_(0)
{
handler_ = boost::bind(&scrollbar_widget::handler_delegate, this, _1);
ASSERT_LOG(get_environment() != 0, "You must specify a callable environment");
ffl_handler_ = get_environment()->create_formula(v["on_scroll"]);
up_arrow_ = v.has_key("up_arrow") ? widget_factory::create(v["up_arrow"], e) : new gui_section_widget(UpArrow);
down_arrow_ = v.has_key("down_arrow") ? widget_factory::create(v["down_arrow"], e) : new gui_section_widget(DownArrow);
handle_ = v.has_key("handle") ? widget_factory::create(v["handle"], e) : new gui_section_widget(VerticalHandle);
handle_bot_ = v.has_key("handle_bottom") ? widget_factory::create(v["handle_bottom"], e) : new gui_section_widget(VerticalHandleBot);
handle_top_ = v.has_key("handle_top") ? widget_factory::create(v["handle_top"], e) : new gui_section_widget(VerticalHandleTop);
background_ = v.has_key("background") ? widget_factory::create(v["background"], e) : new gui_section_widget(VerticalBackground);
if(v.has_key("range")) {
std::vector<int> range = v["range"].as_list_int();
ASSERT_EQ(range.size(), 2);
set_range(range[0], range[1]);
}
}
void scrollbar_widget::handler_delegate(int yscroll)
{
using namespace game_logic;
if(get_environment()) {
map_formula_callable_ptr callable(new map_formula_callable(get_environment()));
callable->add("yscroll", variant(yscroll));
variant value = ffl_handler_->execute(*callable);
get_environment()->execute_command(value);
} else {
std::cerr << "scrollbar_widget::handler_delegate() called without environment!" << std::endl;
}
}
void scrollbar_widget::set_range(int total_height, int window_height)
{
window_size_ = window_height;
range_ = total_height;
if(window_pos_ < 0 || window_pos_ > range_ - window_size_) {
window_pos_ = range_ - window_size_;
}
}
void scrollbar_widget::set_loc(int x, int y)
{
widget::set_loc(x, y);
set_dim(width(), height());
}
void scrollbar_widget::set_dim(int w, int h)
{
w = up_arrow_->width();
up_arrow_->set_loc(x(), y());
down_arrow_->set_loc(x(), y() + h - down_arrow_->height());
background_->set_loc(x(), y() + up_arrow_->height());
const int bar_height = h - (down_arrow_->height() + up_arrow_->height());
background_->set_dim(background_->width(), bar_height);
if(range_) {
handle_->set_loc(x(), y() + up_arrow_->height() + (window_pos_*bar_height)/range_);
handle_->set_dim(handle_->width(), std::max<int>(6, (window_size_*bar_height)/range_));
handle_top_->set_loc(x(), y()+ up_arrow_->height() + (window_pos_*bar_height)/range_);
handle_bot_->set_loc(x(), y()+ down_arrow_->height() + (window_pos_*bar_height)/range_ + (window_size_*bar_height)/range_ - handle_bot_->height() +1);
}
//TODO: handle range < heightOfEndcaps
widget::set_dim(w, h);
}
void scrollbar_widget::down_button_pressed()
{
}
void scrollbar_widget::up_button_pressed()
{
}
void scrollbar_widget::handle_draw() const
{
up_arrow_->draw();
down_arrow_->draw();
background_->draw();
handle_->draw();
handle_bot_->draw();
handle_top_->draw();
}
void scrollbar_widget::clip_window_position()
{
if(window_pos_ < 0) {
window_pos_ = 0;
}
if(window_pos_ > range_ - window_size_) {
window_pos_ = range_ - window_size_;
}
}
bool scrollbar_widget::handle_event(const SDL_Event& event, bool claimed)
{
if(claimed) {
return claimed;
}
if(event.type == SDL_MOUSEWHEEL) {
int mx, my;
input::sdl_get_mouse_state(&mx, &my);
if(mx < x() || mx > x() + width()
|| my < y() || my > y() + height()) {
return claimed;
}
const int start_pos = window_pos_;
if(event.wheel.y > 0) {
window_pos_ -= arrow_step_;
} else {
window_pos_ += arrow_step_;
}
clip_window_position();
if(window_pos_ != start_pos) {
set_dim(width(), height());
handler_(window_pos_);
}
return claimed;
} else
if(event.type == SDL_MOUSEBUTTONDOWN) {
const SDL_MouseButtonEvent& e = event.button;
if(e.x < x() || e.x > x() + width() ||
e.y < y() || e.y > y() + height()) {
return claimed;
}
const int start_pos = window_pos_;
claimed = claim_mouse_events();
if(e.y < up_arrow_->y() + up_arrow_->height()) {
//on up arrow
window_pos_ -= arrow_step_;
while(arrow_step_ && window_pos_%arrow_step_) {
//snap to a multiple of the step size.
++window_pos_;
}
} else if(e.y > down_arrow_->y()) {
//on down arrow
window_pos_ += arrow_step_;
while(arrow_step_ && window_pos_%arrow_step_) {
//snap to a multiple of the step size.
--window_pos_;
}
} else if(e.y < handle_->y()) {
//page up
window_pos_ -= window_size_ - arrow_step_;
} else if(e.y > handle_->y() + handle_->height()) {
//page down
window_pos_ += window_size_ - arrow_step_;
} else {
//on handle
dragging_handle_ = true;
drag_start_ = window_pos_;
drag_anchor_y_ = e.y;
}
std::cerr << "HANDLE: " << handle_->y() << ", " << handle_->height() << "\n";
clip_window_position();
if(window_pos_ != start_pos) {
set_dim(width(), height());
handler_(window_pos_);
}
} else if(event.type == SDL_MOUSEBUTTONUP) {
dragging_handle_ = false;
} else if(event.type == SDL_MOUSEMOTION) {
const SDL_MouseMotionEvent& e = event.motion;
int mousex, mousey;
if(!input::sdl_get_mouse_state(&mousex, &mousey)) {
dragging_handle_ = false;
}
if(dragging_handle_) {
const int handle_height = height() - up_arrow_->height() - down_arrow_->height();
const int move = e.y - drag_anchor_y_;
const int window_move = (move*range_)/handle_height;
window_pos_ = drag_start_ + window_move;
if(step_) {
window_pos_ -= window_pos_%step_;
}
clip_window_position();
set_dim(width(), height());
handler_(window_pos_);
}
}
return claimed;
}
void scrollbar_widget::set_value(const std::string& key, const variant& v)
{
if(key == "on_scroll") {
ffl_handler_ = get_environment()->create_formula(v["on_scroll"]);
} else if(key == "up_arrow") {
up_arrow_ = widget_factory::create(v, get_environment());
} else if(key == "down_arrow") {
down_arrow_ = widget_factory::create(v, get_environment());
} else if(key == "handle") {
handle_ = widget_factory::create(v, get_environment());
} else if(key == "handle_bottom") {
handle_bot_ = widget_factory::create(v, get_environment());
} else if(key == "handle_top") {
handle_top_ = widget_factory::create(v, get_environment());
} else if(key == "background") {
background_ = widget_factory::create(v, get_environment());
} else if(key == "range") {
std::vector<int> range = v.as_list_int();
ASSERT_EQ(range.size(), 2);
set_range(range[0], range[1]);
} else if(key == "position") {
window_pos_ = v.as_int();
clip_window_position();
}
widget::set_value(key, v);
}
variant scrollbar_widget::get_value(const std::string& key) const
{
if(key == "range") {
std::vector<variant> vv;
vv.resize(2);
vv.push_back(variant(range_));
vv.push_back(variant(window_size_));
} else if(key == "position") {
return variant(window_pos_);
}
return widget::get_value(key);
}
}
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/* AMCL BLS Curve pairing functions */
//#define HAS_MAIN
#include "pair192_ZZZ.h"
using namespace XXX;
using namespace YYY;
namespace ZZZ {
static void PAIR_line(FP24 *,ECP4 *,ECP4 *,FP *,FP *);
static void glv(BIG u[2],BIG);
static void gs(BIG u[4],BIG);
}
/* Line function */
static void ZZZ::PAIR_line(FP24 *v,ECP4 *A,ECP4 *B,FP *Qx,FP *Qy)
{
FP2 t;
FP4 T,X,Y,lam;
FP8 a,b,c;
ECP4_get(&X,&Y,A);
ECP4_sadd(A,B,&lam);
FP4_mul(&T,&lam,&X); // T=lam*X
FP4_sub(&Y,&Y,&T); // Y=Y-lam*X
FP2_from_FP(&t,Qy);
FP2_neg(&t,&t); // t=-Qy
FP2_norm(&t);
FP4_from_FP2(&T,&t);
#if SEXTIC_TWIST_ZZZ==M_TYPE
FP4_times_i(&T);
#endif
FP8_from_FP4s(&a,&T,&Y); // (-Qy,Y-lam*X)
FP8_norm(&a);
FP2_from_FP(&t,Qx); // t=Qx
FP4_pmul(&T,&lam,&t); // T=lam*Qx
#if SEXTIC_TWIST_ZZZ==D_TYPE
FP8_from_FP4(&b,&T); // (lam*Qx,0)
FP8_zero(&c);
#endif
#if SEXTIC_TWIST_ZZZ==M_TYPE
FP8_from_FP4H(&c,&T); // (lam*Qx,0)
FP8_zero(&b);
#endif
FP24_from_FP8s(v,&a,&b,&c);
}
/* Optimal R-ate pairing r=e(P,Q) */
void ZZZ::PAIR_ate(FP24 *r,ECP4 *P,ECP *Q)
{
BIG x,n,n3;
FP Qx,Qy;
int i,j,nb,bt;
ECP4 A;
FP24 lv;
BIG_rcopy(x,CURVE_Bnx);
BIG_copy(n,x);
BIG_norm(n);
BIG_pmul(n3,n,3);
BIG_norm(n3);
FP_copy(&Qx,&(Q->x));
FP_copy(&Qy,&(Q->y));
ECP4_copy(&A,P);
FP24_one(r);
nb=BIG_nbits(n3); // n3
j=0;
/* Main Miller Loop */
for (i=nb-2; i>=1; i--)
{
j++;
FP24_sqr(r,r);
PAIR_line(&lv,&A,&A,&Qx,&Qy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
//printf("r= "); FP24_output(r); printf("\n");
//if (j>3) exit(0);
bt= BIG_bit(n3,i)-BIG_bit(n,i); // BIG_bit(n,i);
if (bt==1)
{
//printf("bt=1\n");
PAIR_line(&lv,&A,P,&Qx,&Qy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
}
if (bt==-1)
{
//printf("bt=-1\n");
ECP4_neg(P);
PAIR_line(&lv,&A,P,&Qx,&Qy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
ECP4_neg(P);
}
}
#if SIGN_OF_X_ZZZ==NEGATIVEX
FP24_conj(r,r);
#endif
}
/* Optimal R-ate double pairing e(P,Q).e(R,S) */
void ZZZ::PAIR_double_ate(FP24 *r,ECP4 *P,ECP *Q,ECP4 *R,ECP *S)
{
BIG x,n,n3;
FP Qx,Qy,Sx,Sy;
int i,nb,bt;
ECP4 A,B;
FP24 lv;
BIG_rcopy(x,CURVE_Bnx);
BIG_copy(n,x);
BIG_norm(n);
BIG_pmul(n3,n,3);
BIG_norm(n3);
FP_copy(&Qx,&(Q->x));
FP_copy(&Qy,&(Q->y));
FP_copy(&Sx,&(S->x));
FP_copy(&Sy,&(S->y));
ECP4_copy(&A,P);
ECP4_copy(&B,R);
FP24_one(r);
nb=BIG_nbits(n3);
/* Main Miller Loop */
for (i=nb-2; i>=1; i--)
{
FP24_sqr(r,r);
PAIR_line(&lv,&A,&A,&Qx,&Qy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
PAIR_line(&lv,&B,&B,&Sx,&Sy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
bt=BIG_bit(n3,i)-BIG_bit(n,i); // bt=BIG_bit(n,i);
if (bt==1)
{
PAIR_line(&lv,&A,P,&Qx,&Qy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
PAIR_line(&lv,&B,R,&Sx,&Sy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
}
if (bt==-1)
{
ECP4_neg(P);
PAIR_line(&lv,&A,P,&Qx,&Qy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
ECP4_neg(P);
ECP4_neg(R);
PAIR_line(&lv,&B,R,&Sx,&Sy);
FP24_smul(r,&lv,SEXTIC_TWIST_ZZZ);
ECP4_neg(R);
}
}
#if SIGN_OF_X_ZZZ==NEGATIVEX
FP24_conj(r,r);
#endif
}
/* final exponentiation - keep separate for multi-pairings and to avoid thrashing stack */
void ZZZ::PAIR_fexp(FP24 *r)
{
FP2 X;
BIG x;
FP a,b;
FP24 t0,t1,t2,t3,t4,t5,t6,t7; // could lose one of these - r=t3
BIG_rcopy(x,CURVE_Bnx);
FP_rcopy(&a,Fra);
FP_rcopy(&b,Frb);
FP2_from_FPs(&X,&a,&b);
/* Easy part of final exp - r^(p^12-1)(p^4+1)*/
FP24_inv(&t0,r);
FP24_conj(r,r);
FP24_mul(r,&t0);
FP24_copy(&t0,r);
FP24_frob(r,&X,4);
FP24_mul(r,&t0);
// Ghamman & Fouotsa Method - (completely garbled in https://eprint.iacr.org/2016/130)
FP24_usqr(&t7,r); // t7=f^2
FP24_pow(&t1,&t7,x); // t1=t7^u
BIG_fshr(x,1);
FP24_pow(&t2,&t1,x); // t2=t1^(u/2)
BIG_fshl(x,1); // x must be even
#if SIGN_OF_X_ZZZ==NEGATIVEX
FP24_conj(&t1,&t1);
#endif
FP24_conj(&t3,&t1); // t3=1/t1
FP24_mul(&t2,&t3); // t2=t1*t3
FP24_mul(&t2,r); // t2=t2*f
FP24_pow(&t3,&t2,x); // t3=t2^u
FP24_pow(&t4,&t3,x); // t4=t3^u
FP24_pow(&t5,&t4,x); // t5=t4^u
#if SIGN_OF_X_ZZZ==NEGATIVEX
FP24_conj(&t3,&t3);
FP24_conj(&t5,&t5);
#endif
FP24_frob(&t3,&X,6);
FP24_frob(&t4,&X,5);
FP24_mul(&t3,&t4); // t3=t3.t4
FP24_pow(&t6,&t5,x); // t6=t5^u
#if SIGN_OF_X_ZZZ==NEGATIVEX
FP24_conj(&t6,&t6);
#endif
FP24_frob(&t5,&X,4);
FP24_mul(&t3,&t5); // ??
FP24_conj(&t0,&t2); // t0=1/t2
FP24_mul(&t6,&t0); // t6=t6*t0
FP24_copy(&t5,&t6);
FP24_frob(&t5,&X,3);
FP24_mul(&t3,&t5); // t3=t3*t5
FP24_pow(&t5,&t6,x); // t5=t6^x
FP24_pow(&t6,&t5,x); // t6=t5^x
#if SIGN_OF_X_ZZZ==NEGATIVEX
FP24_conj(&t5,&t5);
#endif
FP24_copy(&t0,&t5);
FP24_frob(&t0,&X,2);
FP24_mul(&t3,&t0); // t3=t3*t0
FP24_copy(&t0,&t6); //
FP24_frob(&t0,&X,1);
FP24_mul(&t3,&t0); // t3=t3*t0
FP24_pow(&t5,&t6,x); // t5=t6*x
#if SIGN_OF_X_ZZZ==NEGATIVEX
FP24_conj(&t5,&t5);
#endif
FP24_frob(&t2,&X,7);
FP24_mul(&t5,&t7); // t5=t5*t7
FP24_mul(&t3,&t2); // t3=t3*t2
FP24_mul(&t3,&t5); // t3=t3*t5
FP24_mul(r,&t3);
FP24_reduce(r);
}
#ifdef USE_GLV_ZZZ
/* GLV method */
static void ZZZ::glv(BIG u[2],BIG e)
{
// -(x^4).P = (Beta.x,y)
BIG x,x2,q;
BIG_rcopy(x,CURVE_Bnx);
BIG_smul(x2,x,x);
BIG_smul(x,x2,x2);
BIG_copy(u[0],e);
BIG_mod(u[0],x);
BIG_copy(u[1],e);
BIG_sdiv(u[1],x);
BIG_rcopy(q,CURVE_Order);
BIG_sub(u[1],q,u[1]);
return;
}
#endif // USE_GLV
/* Galbraith & Scott Method */
static void ZZZ::gs(BIG u[8],BIG e)
{
int i;
BIG x,w,q;
BIG_rcopy(q,CURVE_Order);
BIG_rcopy(x,CURVE_Bnx);
BIG_copy(w,e);
for (i=0; i<7; i++)
{
BIG_copy(u[i],w);
BIG_mod(u[i],x);
BIG_sdiv(w,x);
}
BIG_copy(u[7],w);
/* */
#if SIGN_OF_X_ZZZ==NEGATIVEX
BIG_modneg(u[1],u[1],q);
BIG_modneg(u[3],u[3],q);
BIG_modneg(u[5],u[5],q);
BIG_modneg(u[7],u[7],q);
#endif
return;
}
/* Multiply P by e in group G1 */
void ZZZ::PAIR_G1mul(ECP *P,BIG e)
{
#ifdef USE_GLV_ZZZ /* Note this method is patented */
int np,nn;
ECP Q;
FP cru;
BIG t,q;
BIG u[2];
BIG_rcopy(q,CURVE_Order);
glv(u,e);
ECP_affine(P);
ECP_copy(&Q,P);
FP_rcopy(&cru,CURVE_Cru);
FP_mul(&(Q.x),&(Q.x),&cru);
/* note that -a.B = a.(-B). Use a or -a depending on which is smaller */
np=BIG_nbits(u[0]);
BIG_modneg(t,u[0],q);
nn=BIG_nbits(t);
if (nn<np)
{
BIG_copy(u[0],t);
ECP_neg(P);
}
np=BIG_nbits(u[1]);
BIG_modneg(t,u[1],q);
nn=BIG_nbits(t);
if (nn<np)
{
BIG_copy(u[1],t);
ECP_neg(&Q);
}
ECP_mul2(P,&Q,u[0],u[1]);
#else
ECP_mul(P,e);
#endif
}
/* Multiply P by e in group G2 */
void ZZZ::PAIR_G2mul(ECP4 *P,BIG e)
{
#ifdef USE_GS_G2_ZZZ /* Well I didn't patent it :) */
int i,np,nn;
ECP4 Q[8];
FP2 X;
FP fx,fy;
BIG x,y,u[8];
FP_rcopy(&fx,Fra);
FP_rcopy(&fy,Frb);
FP2_from_FPs(&X,&fx,&fy);
//#if SEXTIC_TWIST_ZZZ==M_TYPE
// FP2_inv(&X,&X);
// FP2_norm(&X);
//#endif
BIG_rcopy(y,CURVE_Order);
gs(u,e);
// ECP4_affine(P);
//printf("PPz= "); FP2_output(&(P->z)); printf("\n");
//printf("f= "); FP2_output(&X); printf("\n");
ECP4_copy(&Q[0],P);
for (i=1; i<8; i++)
{
ECP4_copy(&Q[i],&Q[i-1]);
ECP4_frob(&Q[i],&X,1);
}
//printf("Q[0]= "); ECP4_output(&Q[0]); printf("\n");
//printf("Q[1]= "); ECP4_output(&Q[1]); printf("\n");
for (i=0; i<8; i++)
{
np=BIG_nbits(u[i]);
BIG_modneg(x,u[i],y);
nn=BIG_nbits(x);
if (nn<np)
{
BIG_copy(u[i],x);
ECP4_neg(&Q[i]);
}
}
//printf("Q[2]= "); ECP4_output(&Q[2]); printf("\n");
//printf("Q[3]= "); ECP4_output(&Q[3]); printf("\n");
//exit(0);
ECP4_mul8(P,Q,u);
#else
ECP4_mul(P,e);
#endif
}
/* f=f^e */
void ZZZ::PAIR_GTpow(FP24 *f,BIG e)
{
#ifdef USE_GS_GT_ZZZ /* Note that this option requires a lot of RAM! Maybe better to use compressed XTR method, see FP8.c */
int i,np,nn;
FP24 g[8];
FP2 X;
BIG t,q;
FP fx,fy;
BIG u[8];
FP_rcopy(&fx,Fra);
FP_rcopy(&fy,Frb);
FP2_from_FPs(&X,&fx,&fy);
BIG_rcopy(q,CURVE_Order);
gs(u,e);
FP24_copy(&g[0],f);
for (i=1; i<8; i++)
{
FP24_copy(&g[i],&g[i-1]);
FP24_frob(&g[i],&X,1);
}
for (i=0; i<8; i++)
{
np=BIG_nbits(u[i]);
BIG_modneg(t,u[i],q);
nn=BIG_nbits(t);
if (nn<np)
{
BIG_copy(u[i],t);
FP24_conj(&g[i],&g[i]);
}
}
FP24_pow8(f,g,u);
#else
FP24_pow(f,f,e);
#endif
}
/* test group membership test - no longer needed */
/* with GT-Strong curve, now only check that m!=1, conj(m)*m==1, and m.m^{p^4}=m^{p^2} */
/*
int PAIR_GTmember(FP24 *m)
{
BIG a,b;
FP2 X;
FP24 r,w;
if (FP24_isunity(m)) return 0;
FP24_conj(&r,m);
FP24_mul(&r,m);
if (!FP24_isunity(&r)) return 0;
BIG_rcopy(a,CURVE_Fra);
BIG_rcopy(b,CURVE_Frb);
FP2_from_BIGs(&X,a,b);
FP24_copy(&r,m); FP24_frob(&r,&X); FP24_frob(&r,&X);
FP24_copy(&w,&r); FP24_frob(&w,&X); FP24_frob(&w,&X);
FP24_mul(&w,m);
#ifndef GT_STRONG
if (!FP24_equals(&w,&r)) return 0;
BIG_rcopy(a,CURVE_Bnx);
FP24_copy(&r,m); FP24_pow(&w,&r,a); FP24_pow(&w,&w,a);
FP24_sqr(&r,&w); FP24_mul(&r,&w); FP24_sqr(&r,&r);
FP24_copy(&w,m); FP24_frob(&w,&X);
#endif
return FP24_equals(&w,&r);
}
*/
#ifdef HAS_MAIN
using namespace std;
using namespace ZZZ;
// g++ -O2 pair192_BLS24.cpp ecp4_BLS24.cpp fp24_BLS24.cpp fp8_BLS24.cpp fp4_BLS24.cpp fp2_BLS24.cpp ecp_BLS24.cpp fp_BLS24.cpp big_XXX.cpp rom_curve_BLS24.cpp rom_field_BLS24.cpp rand.cpp hash.cpp oct.cpp -o pair192_BLS24.exe
int main()
{
int i;
char byt[32];
csprng rng;
BIG xa,xb,ya,yb,w,a,b,t1,q,u[2],v[4],m,r,xx,x2,x4,p;
ECP4 P,G;
ECP Q,R;
FP24 g,gp;
FP8 t,c,cp,cpm1,cpm2;
FP4 X,Y;
FP2 x,y,f,Aa,Bb;
FP cru;
for (i=0;i<32;i++)
byt[i]=i+9;
RAND_seed(&rng,32,byt);
BIG_rcopy(r,CURVE_Order);
BIG_rcopy(p,Modulus);
BIG_rcopy(xa,CURVE_Gx);
BIG_rcopy(ya,CURVE_Gy);
ECP_set(&Q,xa,ya);
if (Q.inf) printf("Failed to set - point not on curve\n");
else printf("G1 set success\n");
printf("Q= ");
ECP_output(&Q);
printf("\n");
ECP4_generator(&P);
if (P.inf) printf("Failed to set - point not on curve\n");
else printf("G2 set success\n");
BIG_rcopy(a,Fra);
BIG_rcopy(b,Frb);
FP2_from_BIGs(&f,a,b);
//exit(0);
PAIR_ate(&g,&P,&Q);
printf("gb= ");
FP24_output(&g);
printf("\n");
PAIR_fexp(&g);
printf("g= ");
FP24_output(&g);
printf("\n");
//FP24_pow(&g,&g,r);
// printf("g^r= ");
//FP24_output(&g);
//printf("\n");
ECP_copy(&R,&Q);
ECP4_copy(&G,&P);
ECP4_dbl(&G);
ECP_dbl(&R);
ECP_affine(&R);
PAIR_ate(&g,&G,&Q);
PAIR_fexp(&g);
printf("g1= ");
FP24_output(&g);
printf("\n");
PAIR_ate(&g,&P,&R);
PAIR_fexp(&g);
printf("g2= ");
FP24_output(&g);
printf("\n");
PAIR_G1mul(&Q,r);
printf("rQ= ");ECP_output(&Q); printf("\n");
PAIR_G2mul(&P,r);
printf("rP= ");ECP4_output(&P); printf("\n");
//PAIR_GTpow(&g,r);
//printf("g^r= ");FP24_output(&g); printf("\n");
BIG_randomnum(w,r,&rng);
FP24_copy(&gp,&g);
PAIR_GTpow(&g,w);
FP24_trace(&t,&g);
printf("g^r= ");FP8_output(&t); printf("\n");
FP24_compow(&t,&gp,w,r);
printf("t(g)= "); FP8_output(&t); printf("\n");
// PAIR_ate(&g,&P,&R);
// PAIR_fexp(&g);
// printf("g= ");
// FP24_output(&g);
// printf("\n");
// PAIR_GTpow(&g,xa);
}
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2017-2018 The Toschain Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <sync.h>
#include <clientversion.h>
#include <util.h>
#include <warnings.h>
CCriticalSection cs_warnings;
std::string strMiscWarning;
bool fLargeWorkForkFound = false;
bool fLargeWorkInvalidChainFound = false;
void SetMiscWarning(const std::string& strWarning)
{
LOCK(cs_warnings);
strMiscWarning = strWarning;
}
void SetfLargeWorkForkFound(bool flag)
{
LOCK(cs_warnings);
fLargeWorkForkFound = flag;
}
bool GetfLargeWorkForkFound()
{
LOCK(cs_warnings);
return fLargeWorkForkFound;
}
void SetfLargeWorkInvalidChainFound(bool flag)
{
LOCK(cs_warnings);
fLargeWorkInvalidChainFound = flag;
}
std::string GetWarnings(const std::string& strFor)
{
std::string strStatusBar;
std::string strRPC;
std::string strGUI;
const std::string uiAlertSeperator = "<hr />";
LOCK(cs_warnings);
if (!CLIENT_VERSION_IS_RELEASE) {
strStatusBar = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications";
strGUI = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
}
if (gArgs.GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE))
strStatusBar = strRPC = strGUI = "testsafemode enabled";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
strStatusBar = strMiscWarning;
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + strMiscWarning;
}
if (fLargeWorkForkFound)
{
strStatusBar = strRPC = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
}
else if (fLargeWorkInvalidChainFound)
{
strStatusBar = strRPC = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
}
if (strFor == "gui")
return strGUI;
else if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings(): invalid parameter");
return "error";
}
|
#include "BuildOrderManager.h"
#include "Blinkerbot.h"
BuildOrderManager::BuildOrderManager(BlinkerBot & bot) : blinkerBot(bot), enemyHasCloak(false),
currentBases(0), currentGases(0), currentProductionFacilities(0), currentCannons(0), enemyRace(Race::Random)
{
}
ProductionGoal::ProductionGoal(AbilityID type, int quantity)
{
this->type = type;
this->quantity = quantity;
}
void BuildOrderManager::initialise()
{
initialiseKeyTechs();
}
/*
count the numbers of various types of structures under our control
*/
void BuildOrderManager::updateStructureCounts()
{
int bases = 0;
int productionFacilities = 0;
int gases = 0;
int cannons = 0;
int workers = 0;
for (auto structure : blinkerBot.Observation()->GetUnits())
{
if (UnitData::isOurs(structure) && UnitData::isStructure(structure))
{
if (structure->unit_type == UNIT_TYPEID::PROTOSS_NEXUS)
{
bases++;
}
else if (structure->unit_type == UNIT_TYPEID::PROTOSS_GATEWAY ||
structure->unit_type == UNIT_TYPEID::PROTOSS_WARPGATE ||
structure->unit_type == UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY)
{
productionFacilities++;
}
else if (structure->unit_type == UNIT_TYPEID::PROTOSS_ASSIMILATOR)
{
gases++;
}
else if (structure->unit_type == UNIT_TYPEID::PROTOSS_PHOTONCANNON)
{
cannons++;
}
else if (structure->unit_type == UNIT_TYPEID::PROTOSS_PROBE)
{
workers++;
}
}
}
currentBases = bases;
currentGases = gases;
currentProductionFacilities = productionFacilities;
currentCannons = cannons;
currentWorkers = workers;
}
/*
returns a set of AbilityID and int pairs representing things we want to produce and the quantity of each thing we want
*/
std::vector<ProductionGoal> BuildOrderManager::generateGoal()
{
std::vector<ProductionGoal> buildOrderGoal;
//first let's count the number of things we currently have
updateStructureCounts();
float currentSupply = blinkerBot.Observation()->GetFoodUsed();
//next let's calculate how many extra things we want
int extraPylons = std::round((currentSupply * 0.2) / 8);
int extraCannons = currentBases - currentCannons;
int extraProductionFacilities = (currentBases * 3) - currentProductionFacilities + 1;
int extraGases = (currentBases * 2) - currentGases;
int techTotal = completedTechs.size() + getTechsCurrentlyInProduction().size();
if (currentSupply < 200)
{
if (extraPylons > 0)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_PYLON, extraPylons));
}
else
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_PYLON, 1));
}
}
//if there are any necessary techs, let's add the next one to the queue
//we don't want to keep adding techs without expanding though
AbilityID tech = getNextTech();
if (tech != ABILITY_ID::INVALID &&
!(techTotal >= 2 && currentBases < 2) && !(techTotal >= 3 && currentBases < 3))
{
/*
if (extraGases > 0)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_ASSIMILATOR, 1));
extraGases--;
}
*/
buildOrderGoal.push_back(ProductionGoal(tech, 1));
}
//calculate any additional gases we want to take
if (extraGases > 0)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_ASSIMILATOR, extraGases));
//buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_ASSIMILATOR, 1));
}
//if the enemy has cloaked units, we want to make sure we have cannons at each base
if (enemyHasCloak || currentBases > 2 || (currentBases > 1 && enemyRace == Race::Terran))
{
if (extraCannons > 0)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_PHOTONCANNON, extraCannons));
}
}
//add extra gateways at a 2:1 gateway to base ratio as our economy improves
if (extraProductionFacilities > 0)
{
//we don't wanna add too many extra production facilities at one time as this will slow down our production
if (extraProductionFacilities > 2)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_GATEWAY, 2));
}
else
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_GATEWAY, extraProductionFacilities));
}
}
//if we've already got plenty of production facilities then we want to think about expanding
if ((extraProductionFacilities < 2 && extraGases < 1) || miningOut)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_NEXUS, 1));
}
if (buildOrderGoal.empty())
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_PYLON, 1));
}
/*
std::cerr << "current bases: " << currentBases << std::endl;
std::cerr << "current gateways: " << currentProductionFacilities << std::endl;
std::cerr << "goal state: " << currentBases << " bases and " << currentProductionFacilities + extraProductionFacilities << " gateways" << std::endl;
std::cerr << "adding to production queue:" << std::endl;
for (auto item : buildOrderGoal)
{
for (int i = 0; i != item.second; i++)
{
std::cerr << AbilityTypeToName(item.first) << std::endl;
}
}
*/
//prioritise then send to production queue
return prioritiseGoal(buildOrderGoal);
}
/*
called when an upgrade is completed
*/
void BuildOrderManager::onUpgradeComplete(UpgradeID upgrade)
{
removeKeyTech(upgrade);
}
/*
checks the vector of key techs, removes any that have already been researched, and returns the next item
*/
AbilityID BuildOrderManager::getNextTech()
{
//check that there are some remaining techs
if (!keyTechs.empty())
{
//check through to see if any techs are already researched (and remove them if they are)
std::vector<AbilityID>::iterator nextTech = keyTechs.begin();
while (alreadyResearched(*nextTech) && nextTech != keyTechs.end())
{
//std::cerr << "removing already completed tech: " << AbilityTypeToName(*nextTech) << std::endl;
removeKeyTech(*nextTech++);
}
//we might have removed some so make sure we still have some left
if (!keyTechs.empty())
{
//check through to see if any techs are already in progress (and skip them (but don't remove them) if they are)
std::vector<AbilityID>::iterator nextTech = keyTechs.begin();
while (inProgress(*nextTech) && nextTech != keyTechs.end())
{
//std::cerr << "skipping already started tech: " << AbilityTypeToName(*nextTech) << std::endl;
nextTech++;
}
return *nextTech;
}
else
{
return ABILITY_ID::INVALID;
}
}
else
{
return ABILITY_ID::INVALID;
}
}
//checks our structures to see if we already have this ability in progress
bool BuildOrderManager::inProgress(AbilityID ability)
{
for (auto unit : blinkerBot.Observation()->GetUnits())
{
if (UnitData::isOurs(unit) && UnitData::isStructure(unit))
{
for (auto order : unit->orders)
{
if (order.ability_id == ability || UnitData::isComparableUpgrade(order.ability_id, ability))
{
return true;
}
}
}
}
return false;
}
/*
1/2 removes a key tech from the vector
*/
void BuildOrderManager::removeKeyTech(UpgradeID upgrade)
{
for (std::vector<AbilityID>::iterator tech = keyTechs.begin(); tech != keyTechs.end();)
{
if (UnitData::getAbilityID(upgrade) == *tech)
{
//std::cerr << "removing a key tech: " << AbilityTypeToName(*tech) << std::endl;
tech = keyTechs.erase(tech);
addCompletedTech(upgrade);
}
else
{
++tech;
}
}
}
/*
2/2 removes a key tech from the vector
*/
void BuildOrderManager::removeKeyTech(AbilityID ability)
{
for (std::vector<AbilityID>::iterator tech = keyTechs.begin(); tech != keyTechs.end();)
{
if (ability == *tech)
{
//std::cerr << "removing key tech: " << AbilityTypeToName(*tech) << std::endl;
tech = keyTechs.erase(tech);
}
else
{
++tech;
}
}
}
/*
returns true if a tech has already been researched
*/
bool BuildOrderManager::alreadyResearched(AbilityID ability)
{
for (auto completed : completedTechs)
{
if (UnitData::getAbilityID(completed) == ability)
{
return true;
}
}
return false;
}
/*
tells us if the enemy has cloak or not
*/
void BuildOrderManager::receiveCloakSignal(bool signal)
{
enemyHasCloak = signal;
}
/*
returns a set of our bases
*/
std::set<const Unit *> BuildOrderManager::getBases()
{
std::set<const Unit *> bases;
for (auto unit : blinkerBot.Observation()->GetUnits())
{
if (UnitData::isOurs(unit) && UnitData::isTownHall(unit))
{
bases.insert(unit);
}
}
return bases;
}
/*
tells us when one of our bases is mining out
*/
void BuildOrderManager::receiveMiningOutSignal(bool signal)
{
miningOut = signal;
}
/*
creates an ordered list of important upgrades that need to be researched throughout the game
*/
void BuildOrderManager::initialiseKeyTechs()
{
//initial techs are the same regardless of the situation
keyTechs.push_back(ABILITY_ID::RESEARCH_WARPGATE);
keyTechs.push_back(ABILITY_ID::RESEARCH_BLINK);
//the mid-game techs vary depending on the match-up
switch (enemyRace)
{
case Race::Terran:
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL1);
keyTechs.push_back(ABILITY_ID::RESEARCH_PSISTORM);
keyTechs.push_back(ABILITY_ID::RESEARCH_CHARGE);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL2);
keyTechs.push_back(ABILITY_ID::RESEARCH_EXTENDEDTHERMALLANCE);
break;
case Race::Zerg:
keyTechs.push_back(ABILITY_ID::RESEARCH_PSISTORM);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL1);
keyTechs.push_back(ABILITY_ID::RESEARCH_CHARGE);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL2);
keyTechs.push_back(ABILITY_ID::RESEARCH_EXTENDEDTHERMALLANCE);
break;
case Race::Protoss:
keyTechs.push_back(ABILITY_ID::RESEARCH_EXTENDEDTHERMALLANCE);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL1);
keyTechs.push_back(ABILITY_ID::RESEARCH_CHARGE);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL2);
break;
case Race::Random:
default:
keyTechs.push_back(ABILITY_ID::RESEARCH_EXTENDEDTHERMALLANCE);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL1);
keyTechs.push_back(ABILITY_ID::RESEARCH_CHARGE);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL2);
keyTechs.push_back(ABILITY_ID::RESEARCH_PSISTORM);
break;
}
//lategame techs are the same regardless of the situation (just keep the forge goin)
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDWEAPONSLEVEL3);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDARMORLEVEL1);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDARMORLEVEL2);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSGROUNDARMORLEVEL3);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSSHIELDSLEVEL1);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSSHIELDSLEVEL2);
keyTechs.push_back(ABILITY_ID::RESEARCH_PROTOSSSHIELDSLEVEL3);
}
/*
add an upgrade to the set of completed ones
*/
void BuildOrderManager::addCompletedTech(UpgradeID upgrade)
{
completedTechs.insert(upgrade);
}
/*
returns true if the ability is one of our key techs
*/
bool BuildOrderManager::isKeyTech(AbilityID ability)
{
for (auto tech : keyTechs)
{
if (tech == ability)
{
return true;
}
}
return false;
}
/*
alters our build order to deal with rushes
*/
std::vector<ProductionGoal> BuildOrderManager::generateRushDefenceGoal()
{
std::vector<ProductionGoal> buildOrderGoal;
//first count what we have
updateStructureCounts();
int extraProductionFacilities = 3 - currentProductionFacilities;
int extraGases = 1 - currentGases;
//if we don't have any gas yet, then we want to add one
if (extraGases > 0)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_ASSIMILATOR, extraGases));
}
//we wanna get warpgate if we don't have it, but don't tech any further than that yet
AbilityID tech = getNextTech();
if (tech == ABILITY_ID::RESEARCH_WARPGATE)
{
//put in an extra gateway first so we don't get stuck on 1 gate while teching
if (extraProductionFacilities > 0)
{
int earlyGates = 2 - currentProductionFacilities;
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_GATEWAY, earlyGates));
extraProductionFacilities -= earlyGates;
}
buildOrderGoal.push_back(ProductionGoal(tech, 1));
}
//we can go up to 4 gateways to make sure we can defend
if (extraProductionFacilities > 0)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_GATEWAY, extraProductionFacilities));
}
if (enemyRace == Race::Zerg && currentBases < 2)
{
buildOrderGoal.push_back(ProductionGoal(ABILITY_ID::BUILD_NEXUS, 1));
}
return buildOrderGoal;
}
void BuildOrderManager::setEnemyRace(Race race)
{
enemyRace = race;
}
std::set<AbilityID> BuildOrderManager::getTechsCurrentlyInProduction()
{
std::set<AbilityID> inProduction;
for (auto structure : blinkerBot.Observation()->GetUnits())
{
if (UnitData::isOurs(structure) && UnitData::isStructure(structure))
{
for (auto order : structure->orders)
{
if (UnitData::isResearch(order.ability_id))
{
inProduction.insert(order.ability_id);
}
}
}
}
return inProduction;
}
/*
switches the order of ProductionGoals so that more urgent ones are made first
*/
std::vector<ProductionGoal> BuildOrderManager::prioritiseGoal(std::vector<ProductionGoal> goal)
{
std::vector<ProductionGoal> prioritisedGoal;
int minerals = blinkerBot.Observation()->GetMinerals();
int gas = blinkerBot.Observation()->GetVespene();
//if we're floating minerals (or gas income is very low) then let's prioritise gas
if (minerals > gas * 3 || currentGases < 2)
{
for (auto item : goal)
{
if (item.type == ABILITY_ID::BUILD_ASSIMILATOR)
{
prioritisedGoal.push_back(item);
}
}
}
//if we don't have blink yet, we want to get it ASAP
for (auto item : goal)
{
if (item.type == ABILITY_ID::RESEARCH_BLINK)
{
prioritisedGoal.push_back(item);
}
}
//if we already have a bunch of production facilities, prioritise the nexus
if (currentProductionFacilities >= (currentBases * 2) + 1)
{
for (auto item : goal)
{
if (item.type == ABILITY_ID::BUILD_NEXUS)
{
prioritisedGoal.push_back(item);
}
}
}
//if we're floating minerals, priortise some gateways to spend the money
if (minerals > 800)
{
for (auto item : goal)
{
if (item.type == ABILITY_ID::BUILD_GATEWAY)
{
prioritisedGoal.push_back(item);
}
}
}
//otherwise just read the rest into the new goal as-is
for (auto item : goal)
{
bool alreadyAdded = false;
for (auto prioritisedItem : prioritisedGoal)
{
if (item.type == prioritisedItem.type)
{
alreadyAdded = true;
}
}
if (!alreadyAdded)
{
prioritisedGoal.push_back(item);
}
}
return prioritisedGoal;
}
|
#ifndef H2FBB703F_2DC3_46B1_9587_2A90DA15C335
#define H2FBB703F_2DC3_46B1_9587_2A90DA15C335
#include <tlp/test/details/Print.h>
#include <tlp/test/details/Asserter.h>
#include <tlp/test/details/Fixture.h>
#include <tlp/test/details/TestReporter.h>
#endif
|
#include <stdint.h>
#include <vector>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "Klv.h"
class KlvTest : public ::testing::Test {
protected:
KlvTest() {
}
virtual ~KlvTest() {
// Code here will be called immediately after the constructor (right
// before each test).
}
virtual void SetUp() {
// Code here will be called immediately after each test (right
// before the destructor).
// key: 0x06, 0x0E, 0x2B, 0x34, 0x02, 0x0B, 0x01, 0x01, 0x0E, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00
// len: 0x81, 0x90 (144 bytes)
// val: the rest
test_pkt = { 0x06, 0x0E, 0x2B, 0x34, 0x02, 0x0B, 0x01, 0x01, 0x0E, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x81, 0x90, 0x02, 0x08, 0x00, 0x04, 0x6C, 0xAE, 0x70, 0xF9, 0x80, 0xCF, 0x41, 0x01, 0x01, 0x05, 0x02, 0xE1, 0x91, 0x06, 0x02, 0x06, 0x0D, 0x07, 0x02, 0x0A, 0xE1, 0x0B, 0x02, 0x49, 0x52, 0x0C, 0x0E, 0x47, 0x65, 0x6F, 0x64, 0x65, 0x74, 0x69, 0x63, 0x20, 0x57, 0x47, 0x53, 0x38, 0x34, 0x0D, 0x04, 0x4D, 0xCC, 0x41, 0x90, 0x0E, 0x04, 0xB1, 0xD0, 0x3D, 0x96, 0x0F, 0x02, 0x1B, 0x2E, 0x10, 0x02, 0x00, 0x84, 0x11, 0x02, 0x00, 0x4A, 0x12, 0x04, 0xE7, 0x23, 0x0B, 0x61, 0x13, 0x04, 0xFD, 0xE8, 0x63, 0x8E, 0x14, 0x04, 0x03, 0x0B, 0xC7, 0x1C, 0x15, 0x04, 0x00, 0x9F, 0xB9, 0x38, 0x16, 0x04, 0x00, 0x00, 0x01, 0xF8, 0x17, 0x04, 0x4D, 0xEC, 0xDA, 0xF4, 0x18, 0x04, 0xB1, 0xBC, 0x81, 0x74, 0x19, 0x02, 0x0B, 0x8A, 0x28, 0x04, 0x4D, 0xEC, 0xDA, 0xF4, 0x29, 0x04, 0xB1, 0xBC, 0x81, 0x74, 0x2A, 0x02, 0x0B, 0x8A, 0x38, 0x01, 0x31, 0x39, 0x04, 0x00, 0x9F, 0x85, 0x4D, 0x01, 0x02, 0xB7, 0xEB };
}
virtual void TearDown() {
}
// objects delclared here can be used by all tests in the test case for KlvTest
std::vector<uint8_t> test_pkt;
};
TEST_F(KlvTest, TestConstruction) {
// test that fields are set correctly
std::vector<uint8_t> key = { 0x06, 0x0E, 0x2B, 0x34, 0x02, 0x0B, 0x01, 0x01, 0x0E, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00 };
std::vector<uint8_t> len = { 0x81, 0x90 };
std::vector<uint8_t> val = { 0x02, 0x08, 0x00, 0x04, 0x6C, 0xAE, 0x70, 0xF9, 0x80, 0xCF, 0x41, 0x01, 0x01, 0x05, 0x02, 0xE1, 0x91, 0x06, 0x02, 0x06, 0x0D, 0x07, 0x02, 0x0A, 0xE1, 0x0B, 0x02, 0x49, 0x52, 0x0C, 0x0E, 0x47, 0x65, 0x6F, 0x64, 0x65, 0x74, 0x69, 0x63, 0x20, 0x57, 0x47, 0x53, 0x38, 0x34, 0x0D, 0x04, 0x4D, 0xCC, 0x41, 0x90, 0x0E, 0x04, 0xB1, 0xD0, 0x3D, 0x96, 0x0F, 0x02, 0x1B, 0x2E, 0x10, 0x02, 0x00, 0x84, 0x11, 0x02, 0x00, 0x4A, 0x12, 0x04, 0xE7, 0x23, 0x0B, 0x61, 0x13, 0x04, 0xFD, 0xE8, 0x63, 0x8E, 0x14, 0x04, 0x03, 0x0B, 0xC7, 0x1C, 0x15, 0x04, 0x00, 0x9F, 0xB9, 0x38, 0x16, 0x04, 0x00, 0x00, 0x01, 0xF8, 0x17, 0x04, 0x4D, 0xEC, 0xDA, 0xF4, 0x18, 0x04, 0xB1, 0xBC, 0x81, 0x74, 0x19, 0x02, 0x0B, 0x8A, 0x28, 0x04, 0x4D, 0xEC, 0xDA, 0xF4, 0x29, 0x04, 0xB1, 0xBC, 0x81, 0x74, 0x2A, 0x02, 0x0B, 0x8A, 0x38, 0x01, 0x31, 0x39, 0x04, 0x00, 0x9F, 0x85, 0x4D, 0x01, 0x02, 0xB7, 0xEB };
const KLV test_klv(key, len, val);
EXPECT_THAT(test_klv.getKey(), ::testing::ContainerEq(key));
EXPECT_THAT(test_klv.getLenEncoded(), ::testing::ContainerEq(len));
EXPECT_THAT(test_klv.getValue(), ::testing::ContainerEq(val));
}
|
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
int const N = 100001;
int arr[N];
bool cmp(int a, int b) {
return a > b;
}
int main() {
int n, n1, n2;
cin >> n >> n1 >> n2;
if(n1 > n2) swap(n1, n2);
for(int i = 1; i <= n; i++) cin >> arr[i];
sort(arr+1, arr+n+1, cmp);
double t = 0;
long long tmp;
tmp = 0;
for(int i = 1; i <= n1; i++) tmp += arr[i];
t += (1.0 * tmp / n1);
tmp = 0;
for(int i = n1 + 1; i <= n1 + n2; i++) tmp += arr[i];
t += (1.0 * tmp / n2);
cout << fixed << setprecision(8) << t << endl;
}
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Implementation for STM32F103ZET board (STM32): Copyright (c) Oberon microsystems, Inc.
//
// *** Block Storage Configuration ***
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <tinyhal.h>
//--//
#define FLASH_MANUFACTURER_CODE 0x0000 // not used
#define FLASH_DEVICE_CODE 0x0000 // not used
#define FLASH_MEMORY_BASE 0x08000000
#define FLASH_BLOCK_COUNT 256
#define FLASH_BYTES_PER_BLOCK 2048
#define FLASH_BYTES_PER_SECTOR 2
#define FLASH_BLOCK_ERASE_TYPICAL_TIME_USEC 1000000 // not used
#define FLASH_SECTOR_WRITE_TYPICAL_TIME_USEC 10 // not used
#define FLASH_BLOCK_ERASE_MAX_TIME_USEC 4000000 // not used
#define FLASH_SECTOR_WRITE_MAX_TIME_USEC 100 // not used
#define FLASH_BLOCK_ERASE_ACTUAL_TIME_USEC 10000 // not used
//--//
// EBIU Information
#define STM32__CHIP_SELECT 0
#define STM32__WAIT_STATES 5 // not used
#define STM32__RELEASE_COUNTS 0
#define STM32__BIT_WIDTH 16
#define STM32__BASE_ADDRESS FLASH_MEMORY_BASE
#define STM32__SIZE_IN_BYTES FLASH_BLOCK_COUNT * FLASH_BYTES_PER_BLOCK
#define STM32__WP_GPIO_PIN GPIO_PIN_NONE
#define STM32__WP_ACTIVE FALSE
//--//
// BlockDeviceInformation
#define STM32__IS_REMOVABLE FALSE
#define STM32__SUPPORTS_XIP TRUE
#define STM32__WRITE_PROTECTED FALSE
#define STM32__SUPP_COPY_BACK FALSE
#define STM32__NUM_REGIONS 1
//--//
/*
const BlockRange g_STM32_BlockRange[] =
{
{ BlockRange::BLOCKTYPE_CODE , 0, 123 }, // 08000000 CLR 248k
{ BlockRange::BLOCKTYPE_STORAGE_A , 124, 125 }, // 0803E000 storage A 4kR
{ BlockRange::BLOCKTYPE_STORAGE_B , 126, 127 }, // 0803F000 storage B 4k
{ BlockRange::BLOCKTYPE_CONFIG , 128, 131 }, // 08040000 config 8k
{ BlockRange::BLOCKTYPE_DEPLOYMENT, 132, 255 } // 08042000 deployment 248k
};
*/
const BlockRange g_STM32_BlockRange[] =
{
{ BlockRange::BLOCKTYPE_CODE , 0, 240 }, // 08000000 CLR 480k
{ BlockRange::BLOCKTYPE_STORAGE_A , 241, 245 }, // 0803E000 storage A 8k
{ BlockRange::BLOCKTYPE_STORAGE_B , 246, 250 }, // 0803F000 storage B 8k
{ BlockRange::BLOCKTYPE_CONFIG , 251, 255 }, // 08040000 config 8k
// { BlockRange::BLOCKTYPE_CODE, 204, 255 } // 08042000 deployment 104k
};
const BlockRegionInfo g_STM32_BlkRegion[STM32__NUM_REGIONS] =
{
{
STM32__BASE_ADDRESS, // ByteAddress Start; // Starting Sector address
FLASH_BLOCK_COUNT, // UINT32 NumBlocks; // total number of blocks in this region
FLASH_BYTES_PER_BLOCK, // UINT32 BytesPerBlock; // Total number of bytes per block
ARRAYSIZE_CONST_EXPR(g_STM32_BlockRange),
g_STM32_BlockRange,
}
};
//--//
#undef MEMORY_BLOCKTYPE_GCC_SPECIAL_CODE
//--//
const BlockDeviceInfo g_STM32_DeviceInfo=
{
{
STM32__IS_REMOVABLE, // BOOL Removable;
STM32__SUPPORTS_XIP, // BOOL SupportsXIP;
STM32__WRITE_PROTECTED, // BOOL WriteProtected;
STM32__SUPP_COPY_BACK // BOOL SupportsCopyBack
},
FLASH_SECTOR_WRITE_TYPICAL_TIME_USEC, // UINT32 MaxSectorWrite_uSec;
FLASH_BLOCK_ERASE_ACTUAL_TIME_USEC, // UINT32 MaxBlockErase_uSec;
FLASH_BYTES_PER_SECTOR, // UINT32 BytesPerSector;
FLASH_MEMORY_Size, // UINT32 Size;
STM32__NUM_REGIONS, // UINT32 NumRegions;
g_STM32_BlkRegion, // const BlockRegionInfo* pRegions;
};
struct MEMORY_MAPPED_NOR_BLOCK_CONFIG g_STM32_BS_Config =
{
{ // BLOCK_CONFIG
{
STM32__WP_GPIO_PIN, // GPIO_PIN Pin;
STM32__WP_ACTIVE, // BOOL ActiveState;
},
&g_STM32_DeviceInfo, // BlockDeviceinfo
},
{ // CPU_MEMORY_CONFIG
STM32__CHIP_SELECT, // UINT8 CPU_MEMORY_CONFIG::ChipSelect;
TRUE, // UINT8 CPU_MEMORY_CONFIG::ReadOnly;
STM32__WAIT_STATES, // UINT32 CPU_MEMORY_CONFIG::WaitStates;
STM32__RELEASE_COUNTS, // UINT32 CPU_MEMORY_CONFIG::ReleaseCounts;
STM32__BIT_WIDTH, // UINT32 CPU_MEMORY_CONFIG::BitWidth;
STM32__BASE_ADDRESS, // UINT32 CPU_MEMORY_CONFIG::BaseAddress;
STM32__SIZE_IN_BYTES, // UINT32 CPU_MEMORY_CONFIG::SizeInBytes;
0, // UINT8 CPU_MEMORY_CONFIG::XREADYEnable
0, // UINT8 CPU_MEMORY_CONFIG::ByteSignalsForRead
0, // UINT8 CPU_MEMORY_CONFIG::ExternalBufferEnable
},
0, // UINT32 ChipProtection;
FLASH_MANUFACTURER_CODE, // UINT32 ManufacturerCode;
FLASH_DEVICE_CODE, // UINT32 DeviceCode;
};
//--//
#if defined(ADS_LINKER_BUG__NOT_ALL_UNUSED_VARIABLES_ARE_REMOVED)
#pragma arm section rodata = "g_STM32_BS"
#endif
struct BlockStorageDevice g_STM32_BS;
#if defined(ADS_LINKER_BUG__NOT_ALL_UNUSED_VARIABLES_ARE_REMOVED)
#pragma arm section rodata
#endif
//--//
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by george@skymind.io on 2/21/2018.
//
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/helpers/segment.h>
namespace nd4j {
namespace ops {
CUSTOM_OP_IMPL(segment_sum, 2, 1, false, 0, 0) {
auto input = INPUT_VARIABLE(0);
auto idxSegments = INPUT_VARIABLE(1);
auto segmentedOutput = OUTPUT_VARIABLE(0);
REQUIRE_TRUE(idxSegments->isVector(), 0, "segment_sum: segment indexes array should be a vector, but it rank is %i.", idxSegments->rankOf());
REQUIRE_TRUE(idxSegments->lengthOf() == input->sizeAt(0), 0, "segment_sum: segment indexes array length should be equal to the input first dimension, but %i != %i.", idxSegments->lengthOf(), input->sizeAt(0));
auto expected = NDArrayFactory::create(0.f, block.getWorkspace());
auto wrong = NDArrayFactory::create(0.f, block.getWorkspace());
REQUIRE_TRUE(helpers::segmentIndicesValidate(idxSegments, expected, wrong), 0, "segment_sum: segment indices should be arranged, but %2.1f > %2.1f", expected.e<float>(0), wrong.e<float>(0));
helpers::segmentSumFunctor(input, idxSegments, segmentedOutput);
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(segment_sum) {
auto idxVector = INPUT_VARIABLE(1);
auto in = inputShape->at(0);
int outRank = shape::rank(in);
Nd4jLong* outputShape = nullptr;
int val = (*idxVector).e<int>(idxVector->lengthOf() - 1);
int numOfClasses = static_cast<int>(val) + 1;
ALLOCATE(outputShape, block.getWorkspace(), shape::shapeInfoLength(outRank), Nd4jLong);
outputShape[0] = outRank;
outputShape[1] = numOfClasses;
for(int i = 1; i < outRank; ++i)
outputShape[i + 1] = shape::sizeAt(in, i);
ShapeUtils::updateStridesAndType(outputShape, in, shape::order(in));
return SHAPELIST(outputShape);
}
CUSTOM_OP_IMPL(segment_sum_bp, 3, 2, false, 0, 0) {
return helpers::segmentSumFunctorBP(INPUT_VARIABLE(0), INPUT_VARIABLE(1), INPUT_VARIABLE(2), OUTPUT_VARIABLE(0));
}
DECLARE_SHAPE_FN(segment_sum_bp){
Nd4jLong* in = inputShape->at(0);
Nd4jLong* inIdx = inputShape->at(1);
Nd4jLong* outShape;
Nd4jLong* outIndex;
COPY_SHAPE(in, outShape);
COPY_SHAPE(inIdx, outIndex);
return SHAPELIST(outShape, outIndex);
}
DECLARE_TYPES(segment_sum) {
getOpDescriptor()
->setAllowedInputTypes(nd4j::DataType::ANY)
->setSameMode(true);
}
DECLARE_TYPES(segment_sum_bp) {
getOpDescriptor()
->setAllowedInputTypes(nd4j::DataType::ANY)
->setAllowedOutputTypes(0, {ALL_FLOATS})
->setAllowedOutputTypes(1, {ALL_INTS})
->setSameMode(false);
}
}
}
|
/*
WS2812FX.cpp contains all effect methods
Harm Aldick - 2016
www.aldick.org
LICENSE
The MIT License (MIT)
Copyright (c) 2016 Harm Aldick
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.
Modified heavily for WLED
*/
#include "FX.h"
#define IBN 5100
#define PALETTE_SOLID_WRAP (paletteBlend == 1 || paletteBlend == 3)
/*
* No blinking. Just plain old static light.
*/
uint16_t WS2812FX::mode_static(void) {
fill(SEGCOLOR(0));
return (SEGMENT.getOption(7)) ? FRAMETIME : 500; //update faster if in transition
}
/*
* Blink/strobe function
* Alternate between color1 and color2
* if(strobe == true) then create a strobe effect
* NOTE: Maybe re-rework without timer
*/
uint16_t WS2812FX::blink(uint32_t color1, uint32_t color2, bool strobe, bool do_palette) {
uint16_t stateTime = SEGENV.aux1;
uint32_t cycleTime = (255 - SEGMENT.speed)*20;
uint32_t onTime = 0;
uint32_t offTime = cycleTime;
if (!strobe) {
onTime = (cycleTime * SEGMENT.intensity) >> 8;
offTime = cycleTime - onTime;
}
stateTime = ((SEGENV.aux0 & 1) == 0) ? onTime : offTime;
stateTime += 20;
if (now - SEGENV.step > stateTime)
{
SEGENV.aux0++;
SEGENV.aux1 = stateTime;
SEGENV.step = now;
}
uint32_t color = ((SEGENV.aux0 & 1) == 0) ? color1 : color2;
if (color == color1 && do_palette)
{
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0));
}
} else fill(color);
return FRAMETIME;
}
/*
* Normal blinking. 50% on/off time.
*/
uint16_t WS2812FX::mode_blink(void) {
return blink(SEGCOLOR(0), SEGCOLOR(1), false, true);
}
/*
* Classic Blink effect. Cycling through the rainbow.
*/
uint16_t WS2812FX::mode_blink_rainbow(void) {
return blink(color_wheel(SEGENV.call & 0xFF), SEGCOLOR(1), false, false);
}
/*
* Classic Strobe effect.
*/
uint16_t WS2812FX::mode_strobe(void) {
return blink(SEGCOLOR(0), SEGCOLOR(1), true, true);
}
/*
* Classic Strobe effect. Cycling through the rainbow.
*/
uint16_t WS2812FX::mode_strobe_rainbow(void) {
return blink(color_wheel(SEGENV.call & 0xFF), SEGCOLOR(1), true, false);
}
/*
* Color wipe function
* LEDs are turned on (color1) in sequence, then turned off (color2) in sequence.
* if (bool rev == true) then LEDs are turned off in reverse order
*/
uint16_t WS2812FX::color_wipe(bool rev, bool useRandomColors) {
uint32_t cycleTime = 1000 + (255 - SEGMENT.speed)*200;
uint32_t perc = now % cycleTime;
uint16_t prog = (perc * 65535) / cycleTime;
bool back = (prog > 32767);
if (back) {
prog -= 32767;
if (SEGENV.step == 0) SEGENV.step = 1;
} else {
if (SEGENV.step == 2) SEGENV.step = 3; //trigger color change
}
if (useRandomColors) {
if (SEGENV.call == 0) {
SEGENV.aux0 = random8();
SEGENV.step = 3;
}
if (SEGENV.step == 1) { //if flag set, change to new random color
SEGENV.aux1 = get_random_wheel_index(SEGENV.aux0);
SEGENV.step = 2;
}
if (SEGENV.step == 3) {
SEGENV.aux0 = get_random_wheel_index(SEGENV.aux1);
SEGENV.step = 0;
}
}
uint16_t ledIndex = (prog * SEGLEN) >> 15;
uint16_t rem = 0;
rem = (prog * SEGLEN) * 2; //mod 0xFFFF
rem /= (SEGMENT.intensity +1);
if (rem > 255) rem = 255;
uint32_t col1 = useRandomColors? color_wheel(SEGENV.aux1) : SEGCOLOR(1);
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++)
{
uint16_t index = (rev && back)? SEGMENT.stop -1 -i : i;
uint32_t col0 = useRandomColors? color_wheel(SEGENV.aux0) : color_from_palette(index, true, PALETTE_SOLID_WRAP, 0);
if (i - SEGMENT.start < ledIndex)
{
setPixelColor(index, back? col1 : col0);
} else
{
setPixelColor(index, back? col0 : col1);
if (i - SEGMENT.start == ledIndex) setPixelColor(index, color_blend(back? col0 : col1, back? col1 : col0, rem));
}
}
return FRAMETIME;
}
/*
* Lights all LEDs one after another.
*/
uint16_t WS2812FX::mode_color_wipe(void) {
return color_wipe(false, false);
}
/*
* Lights all LEDs one after another. Turns off opposite
*/
uint16_t WS2812FX::mode_color_sweep(void) {
return color_wipe(true, false);
}
/*
* Turns all LEDs after each other to a random color.
* Then starts over with another color.
*/
uint16_t WS2812FX::mode_color_wipe_random(void) {
return color_wipe(false, true);
}
/*
* Random color introduced alternating from start and end of strip.
*/
uint16_t WS2812FX::mode_color_sweep_random(void) {
return color_wipe(true, true);
}
/*
* Lights all LEDs in one random color up. Then switches them
* to the next random color.
*/
uint16_t WS2812FX::mode_random_color(void) {
uint32_t cycleTime = 200 + (255 - SEGMENT.speed)*50;
uint32_t it = now / cycleTime;
uint32_t rem = now % cycleTime;
uint16_t fadedur = (cycleTime * SEGMENT.intensity) >> 8;
uint32_t fade = 255;
if (fadedur) {
fade = (rem * 255) / fadedur;
if (fade > 255) fade = 255;
}
if (SEGENV.call == 0) {
SEGENV.aux0 = random8();
SEGENV.step = 2;
}
if (it != SEGENV.step) //new color
{
SEGENV.aux1 = SEGENV.aux0;
SEGENV.aux0 = get_random_wheel_index(SEGENV.aux0); //aux0 will store our random color wheel index
SEGENV.step = it;
}
fill(color_blend(color_wheel(SEGENV.aux1), color_wheel(SEGENV.aux0), fade));
return FRAMETIME;
}
/*
* Lights every LED in a random color. Changes all LED at the same time
// * to new random colors.
*/
uint16_t WS2812FX::mode_dynamic(void) {
if(SEGENV.call == 0) {
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) _locked[i] = random8();
}
uint32_t cycleTime = 50 + (255 - SEGMENT.speed)*15;
uint32_t it = now / cycleTime;
if (it != SEGENV.step) //new color
{
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
if (random8() <= SEGMENT.intensity) _locked[i] = random8();
}
SEGENV.step = it;
}
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_wheel(_locked[i]));
}
return FRAMETIME;
}
/*
* Does the "standby-breathing" of well known i-Devices.
*/
uint16_t WS2812FX::mode_breath(void) {
uint16_t var = 0;
uint16_t counter = (now * ((SEGMENT.speed >> 3) +10)) & 0xFFFF;
counter = (counter >> 2) + (counter >> 4); //0-16384 + 0-2048
if (counter < 16384) {
if (counter > 8192) counter = 8192 - (counter - 8192);
var = sin16(counter) / 103; //close to parabolic in range 0-8192, max val. 23170
}
uint8_t lum = 30 + var;
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_blend(SEGCOLOR(1), color_from_palette(i, true, PALETTE_SOLID_WRAP, 0), lum));
}
return FRAMETIME;
}
/*
* Sunrise/sunset effect
*/
uint16_t WS2812FX::mode_sunrise(bool sunrise)
{
uint32_t cycleTime = 100 + (255 - SEGMENT.speed)*5;
uint32_t it = now / cycleTime;
uint32_t rem = now % cycleTime;
uint16_t fadedur = (cycleTime * SEGMENT.intensity) >> 2; //fade duration
uint32_t fade = 255;
setPixelColor(SEGMENT.start,0xFF3000); //the effect color, orange is chosen to simulate sunrise/sunset
if (fadedur)
{
fade = (rem * 255) / fadedur;
if (fade > 255) fade = 255; //the brightness is scaled from 0 to 255
}
delay(100000);
return FRAMETIME;
}
/*
* Fades the LEDs between two colors
*/
uint16_t WS2812FX::mode_fade(void) {
uint16_t counter = (now * ((SEGMENT.speed >> 3) +10)) & 0xFFFF;
if (counter > 32767) counter = 32768 - (counter - 32768);
uint8_t lum = counter >> 7;
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_blend(SEGCOLOR(1), color_from_palette(i, true, PALETTE_SOLID_WRAP, 0), lum));
}
return FRAMETIME;
}
/*
* Scan mode parent function
*/
uint16_t WS2812FX::scan(bool dual)
{
if(SEGENV.step > (SEGLEN * 2) - 3) {
SEGENV.step = 0;
}
fill(SEGCOLOR(1));
int led_offset = SEGENV.step - (SEGLEN - 1);
led_offset = abs(led_offset);
uint16_t i = SEGMENT.start + led_offset;
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0));
if (dual) {
uint16_t i2 = SEGMENT.start + SEGLEN - led_offset - 1;
setPixelColor(i2, color_from_palette(i2, true, PALETTE_SOLID_WRAP, 0));
}
SEGENV.step++;
return SPEED_FORMULA_L;
}
//NOTE: add intensity (more than 1 pixel lit)
/*
* Runs a single pixel back and forth.
*/
uint16_t WS2812FX::mode_scan(void) {
return scan(false);
}
/*
* Runs two pixel back and forth in opposite directions.
*/
uint16_t WS2812FX::mode_dual_scan(void) {
return scan(true);
}
/*
* Cycles all LEDs at once through a rainbow.
*/
uint16_t WS2812FX::mode_rainbow(void) {
uint16_t counter = (now * ((SEGMENT.speed >> 3) +2)) & 0xFFFF;
counter = counter >> 8;
fill(color_wheel(counter));
return FRAMETIME;
}
/*
* Cycles a rainbow over the entire string of LEDs.
*/
uint16_t WS2812FX::mode_rainbow_cycle(void) {
uint16_t counter = (now * ((SEGMENT.speed >> 3) +2)) & 0xFFFF;
counter = counter >> 8;
for(uint16_t i=0; i < SEGLEN; i++) {
//intensity/29 = 0 (1/16) 1 (1/8) 2 (1/4) 3 (1/2) 4 (1) 5 (2) 6 (4) 7 (8) 8 (16)
uint8_t index = (i * (16 << (SEGMENT.intensity /29)) / SEGLEN) + counter;
setPixelColor(SEGMENT.start + i, color_wheel(index));
}
return FRAMETIME;
}
/*
* theater chase function
*/
uint16_t WS2812FX::theater_chase(uint32_t color1, uint32_t color2, bool dopalette) {
SEGENV.call = SEGENV.call % 3;
for(uint16_t i=0; i < SEGLEN; i++) {
if((i % 3) == SEGENV.call) {
if (dopalette)
{
setPixelColor(SEGMENT.start + i, color_from_palette(SEGMENT.start + i, true, PALETTE_SOLID_WRAP, 0));
} else {
setPixelColor(SEGMENT.start + i, color1);
}
} else {
setPixelColor(SEGMENT.start + i, color2);
}
}
return 50 + (2 * (uint32_t)(255 - SEGMENT.speed));
}
/*
* Theatre-style crawling lights.
* Inspired by the Adafruit examples.
*/
uint16_t WS2812FX::mode_theater_chase(void) {
return theater_chase(SEGCOLOR(0), SEGCOLOR(1), true);
}
/*
* Theatre-style crawling lights with rainbow effect.
* Inspired by the Adafruit examples.
*/
uint16_t WS2812FX::mode_theater_chase_rainbow(void) {
SEGENV.step = (SEGENV.step + 1) & 0xFF;
return theater_chase(color_wheel(SEGENV.step), SEGCOLOR(1), false);
}
/*
* Running lights effect with smooth sine transition base.
*/
uint16_t WS2812FX::running_base(bool saw) {
uint8_t x_scale = SEGMENT.intensity >> 2;
uint32_t counter = (now * SEGMENT.speed) >> 9;
for(uint16_t i=0; i < SEGLEN; i++) {
uint8_t s = 0;
uint8_t a = i*x_scale - counter;
if (saw) {
if (a < 16)
{
a = 192 + a*8;
} else {
a = map(a,16,255,64,192);
}
}
s = sin8(a);
setPixelColor(SEGMENT.start + i, color_blend(color_from_palette(SEGMENT.start + i, true, PALETTE_SOLID_WRAP, 0), SEGCOLOR(1), s));
}
return FRAMETIME;
}
/*
* Running lights effect with smooth sine transition.
*/
uint16_t WS2812FX::mode_running_lights(void) {
return running_base(false);
}
/*
* Running lights effect with sawtooth transition.
*/
uint16_t WS2812FX::mode_saw(void) {
return running_base(true);
}
/*
* Blink several LEDs in random colors on, reset, repeat.
* Inspired by www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/
*/
uint16_t WS2812FX::mode_twinkle(void) {
if(SEGENV.step == 0) {
fill(SEGCOLOR(1));
SEGENV.step = map(SEGMENT.intensity, 0, 255, 1, SEGLEN); // make sure, at least one LED is on
}
uint16_t i = SEGMENT.start + random16(SEGLEN);
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0));
SEGENV.step--;
return 20 + (5 * (uint16_t)(255 - SEGMENT.speed));
}
/*
* Dissolve function
*/
uint16_t WS2812FX::dissolve(uint32_t color) {
bool wa = (SEGCOLOR(1) != 0 && _brightness < 255); //workaround, can't compare getPixel to color if not full brightness
for (uint16_t j = 0; j <= SEGLEN / 15; j++)
{
if (random8() <= SEGMENT.intensity) {
for (uint8_t times = 0; times < 10; times++) //attempt to spawn a new pixel 5 times
{
uint16_t i = SEGMENT.start + random16(SEGLEN);
if (SEGENV.aux0) { //dissolve to primary/palette
if (getPixelColor(i) == SEGCOLOR(1) || wa) {
if (color == SEGCOLOR(0))
{
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0));
} else { setPixelColor(i, color); }
break; //only spawn 1 new pixel per frame per 50 LEDs
}
} else { //dissolve to secondary
if (getPixelColor(i) != SEGCOLOR(1)) { setPixelColor(i, SEGCOLOR(1)); break; }
}
}
}
}
if (SEGENV.call > (255 - SEGMENT.speed) + 15)
{
SEGENV.aux0 = !SEGENV.aux0;
SEGENV.call = 0;
}
return 20;
}
/*
* Blink several LEDs on and then off
*/
uint16_t WS2812FX::mode_dissolve(void) {
return dissolve(SEGCOLOR(0));
}
/*
* Blink several LEDs on and then off in random colors
*/
uint16_t WS2812FX::mode_dissolve_random(void) {
return dissolve(color_wheel(random8()));
}
/*
* Blinks one LED at a time.
* Inspired by www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/
*/
uint16_t WS2812FX::mode_sparkle(void) {
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 1));
}
SEGENV.aux0 = random16(SEGLEN); // aux0 stores the random led index
setPixelColor(SEGMENT.start + SEGENV.aux0, SEGCOLOR(0));
return 10 + (uint16_t)(255 - SEGMENT.speed);
}
/*
* Lights all LEDs in the color. Flashes single white pixels randomly.
* Inspired by www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/
*/
uint16_t WS2812FX::mode_flash_sparkle(void) {
if(SEGENV.call == 0) {
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0));
}
}
uint16_t i = SEGMENT.start + SEGENV.aux0;
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0));
if(random8(5) == 0) {
SEGENV.aux0 = random16(SEGLEN); // aux0 stores the random led index
setPixelColor(SEGMENT.start + SEGENV.aux0, SEGCOLOR(1));
return 20;
}
return 20 + (uint16_t)(255-SEGMENT.speed);
}
/*
* Like flash sparkle. With more flash.
* Inspired by www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/
*/
uint16_t WS2812FX::mode_hyper_sparkle(void) {
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0));
}
if(random8(5) < 2) {
for(uint16_t i=0; i < max(1, SEGLEN/3); i++) {
setPixelColor(SEGMENT.start + random16(SEGLEN), SEGCOLOR(1));
}
return 20;
}
return 20 + (uint16_t)(255-SEGMENT.speed);
}
/*
* Strobe effect with different strobe count and pause, controlled by speed.
*/
uint16_t WS2812FX::mode_multi_strobe(void) {
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 1));
}
uint16_t delay = 50 + 20*(uint16_t)(255-SEGMENT.speed);
uint16_t count = 2 * ((SEGMENT.speed / 10) + 1);
if(SEGENV.step < count) {
if((SEGENV.step & 1) == 0) {
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, SEGCOLOR(0));
}
delay = 20;
} else {
delay = 50;
}
}
SEGENV.step = (SEGENV.step + 1) % (count + 1);
return delay;
}
/*
* Android loading circle
*/
uint16_t WS2812FX::mode_android(void) {
if (SEGENV.call == 0)
{
SEGENV.aux0 = 0;
SEGENV.step = SEGMENT.start;
}
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 1));
}
if (SEGENV.aux1 > ((float)SEGMENT.intensity/255.0)*(float)SEGLEN)
{
SEGENV.aux0 = 1;
} else
{
if (SEGENV.aux1 < 2) SEGENV.aux0 = 0;
}
uint16_t a = SEGENV.step;
if (SEGENV.aux0 == 0)
{
if (SEGENV.call %3 == 1) {a++;}
else {SEGENV.aux1++;}
} else
{
a++;
if (SEGENV.call %3 != 1) SEGENV.aux1--;
}
if (a >= SEGMENT.stop) a = SEGMENT.start;
if (a + SEGENV.aux1 < SEGMENT.stop)
{
for(int i = a; i < a+SEGENV.aux1; i++) {
setPixelColor(i, SEGCOLOR(0));
}
} else
{
for(int i = a; i < SEGMENT.stop; i++) {
setPixelColor(i, SEGCOLOR(0));
}
for(int i = SEGMENT.start; i < SEGENV.aux1 - (SEGMENT.stop -a); i++) {
setPixelColor(i, SEGCOLOR(0));
}
}
SEGENV.step = a;
return 3 + ((8 * (uint32_t)(255 - SEGMENT.speed)) / SEGLEN);
}
/*
* color chase function.
* color1 = background color
* color2 and color3 = colors of two adjacent leds
*/
uint16_t WS2812FX::chase(uint32_t color1, uint32_t color2, uint32_t color3, bool dopalette) {
uint16_t a = SEGENV.step;
uint16_t b = (a + 1) % SEGLEN;
uint16_t c = (b + 1) % SEGLEN;
if (dopalette) color1 = color_from_palette(SEGMENT.start + a, true, PALETTE_SOLID_WRAP, 1);
setPixelColor(SEGMENT.start + a, color1);
setPixelColor(SEGMENT.start + b, color2);
setPixelColor(SEGMENT.start + c, color3);
SEGENV.step = (SEGENV.step + 1) % SEGLEN;
return SPEED_FORMULA_L;
}
/*
* Bicolor chase, more primary color.
*/
uint16_t WS2812FX::mode_chase_color(void) {
return chase(SEGCOLOR(1), SEGCOLOR(0), SEGCOLOR(0), true);
}
/*
* Primary running followed by random color.
*/
uint16_t WS2812FX::mode_chase_random(void) {
if(SEGENV.step == 0) {
SEGENV.aux0 = get_random_wheel_index(SEGENV.aux0);
}
return chase(color_wheel(SEGENV.aux0), SEGCOLOR(0), SEGCOLOR(0), false);
}
/*
* Primary running on rainbow.
*/
uint16_t WS2812FX::mode_chase_rainbow_white(void) {
uint16_t n = SEGENV.step;
uint16_t m = (SEGENV.step + 1) % SEGLEN;
uint32_t color2 = color_wheel(((n * 256 / SEGLEN) + (SEGENV.call & 0xFF)) & 0xFF);
uint32_t color3 = color_wheel(((m * 256 / SEGLEN) + (SEGENV.call & 0xFF)) & 0xFF);
return chase(SEGCOLOR(0), color2, color3, false);
}
/*
* Red - Amber - Green - Blue lights running
*/
uint16_t WS2812FX::mode_colorful(void) {
uint32_t cols[]{0x00FF0000,0x00EEBB00,0x0000EE00,0x000077CC,0x00FF0000,0x00EEBB00,0x0000EE00};
if (SEGMENT.intensity < 127) //pastel (easter) colors
{
cols[0] = 0x00FF8040;
cols[1] = 0x00E5D241;
cols[2] = 0x0077FF77;
cols[3] = 0x0077F0F0;
for (uint8_t i = 4; i < 7; i++) cols[i] = cols[i-4];
}
int i = SEGMENT.start;
for (i; i < SEGMENT.stop ; i+=4)
{
setPixelColor(i, cols[SEGENV.step]);
setPixelColor(i+1, cols[SEGENV.step+1]);
setPixelColor(i+2, cols[SEGENV.step+2]);
setPixelColor(i+3, cols[SEGENV.step+3]);
}
i+=4;
if(i < SEGMENT.stop)
{
setPixelColor(i, cols[SEGENV.step]);
if(i+1 < SEGMENT.stop)
{
setPixelColor(i+1, cols[SEGENV.step+1]);
if(i+2 < SEGMENT.stop)
{
setPixelColor(i+2, cols[SEGENV.step+2]);
}
}
}
if (SEGMENT.speed > 0) SEGENV.step++; //static if lowest speed
if (SEGENV.step >3) SEGENV.step = 0;
return 50 + (15 * (uint32_t)(255 - SEGMENT.speed));
}
/*
* Emulates a traffic light.
*/
uint16_t WS2812FX::mode_traffic_light(void) {
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++)
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 1));
uint32_t mdelay = 500;
for (int i = SEGMENT.start; i < SEGMENT.stop-2 ; i+=3)
{
switch (SEGENV.step)
{
case 0: setPixelColor(i, 0x00FF0000); mdelay = 150 + (100 * (uint32_t)(255 - SEGMENT.speed));break;
case 1: setPixelColor(i, 0x00FF0000); mdelay = 150 + (20 * (uint32_t)(255 - SEGMENT.speed)); setPixelColor(i+1, 0x00EECC00); break;
case 2: setPixelColor(i+2, 0x0000FF00); mdelay = 150 + (100 * (uint32_t)(255 - SEGMENT.speed));break;
case 3: setPixelColor(i+1, 0x00EECC00); mdelay = 150 + (20 * (uint32_t)(255 - SEGMENT.speed));break;
}
}
SEGENV.step++;
if (SEGENV.step >3) SEGENV.step = 0;
return mdelay;
}
/*
* Primary, secondary running on rainbow.
*/
uint16_t WS2812FX::mode_chase_rainbow(void) {
uint8_t color_sep = 256 / SEGLEN;
uint8_t color_index = SEGENV.call & 0xFF;
uint32_t color = color_wheel(((SEGENV.step * color_sep) + color_index) & 0xFF);
return chase(color, SEGCOLOR(0), SEGCOLOR(1), 0);
}
/*
* Sec flashes running on prim.
*/
#define FLASH_COUNT 4
uint16_t WS2812FX::mode_chase_flash(void) {
uint8_t flash_step = SEGENV.call % ((FLASH_COUNT * 2) + 1);
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0));
}
uint16_t delay = 10 + ((30 * (uint16_t)(255 - SEGMENT.speed)) / SEGLEN);
if(flash_step < (FLASH_COUNT * 2)) {
if(flash_step % 2 == 0) {
uint16_t n = SEGENV.step;
uint16_t m = (SEGENV.step + 1) % SEGLEN;
setPixelColor(SEGMENT.start + n, SEGCOLOR(1));
setPixelColor(SEGMENT.start + m, SEGCOLOR(1));
delay = 20;
} else {
delay = 30;
}
} else {
SEGENV.step = (SEGENV.step + 1) % SEGLEN;
}
return delay;
}
/*
* Prim flashes running, followed by random color.
*/
uint16_t WS2812FX::mode_chase_flash_random(void) {
uint8_t flash_step = SEGENV.call % ((FLASH_COUNT * 2) + 1);
for(uint16_t i=0; i < SEGENV.step; i++) {
setPixelColor(SEGMENT.start + i, color_wheel(SEGENV.aux0));
}
uint16_t delay = 1 + ((10 * (uint16_t)(255 - SEGMENT.speed)) / SEGLEN);
if(flash_step < (FLASH_COUNT * 2)) {
uint16_t n = SEGENV.step;
uint16_t m = (SEGENV.step + 1) % SEGLEN;
if(flash_step % 2 == 0) {
setPixelColor(SEGMENT.start + n, SEGCOLOR(0));
setPixelColor(SEGMENT.start + m, SEGCOLOR(0));
delay = 20;
} else {
setPixelColor(SEGMENT.start + n, color_wheel(SEGENV.aux0));
setPixelColor(SEGMENT.start + m, SEGCOLOR(1));
delay = 30;
}
} else {
SEGENV.step = (SEGENV.step + 1) % SEGLEN;
if(SEGENV.step == 0) {
SEGENV.aux0 = get_random_wheel_index(SEGENV.aux0);
}
}
return delay;
}
/*
* Alternating pixels running function.
*/
uint16_t WS2812FX::running(uint32_t color1, uint32_t color2) {
uint8_t pxw = 1 + (SEGMENT.intensity >> 5);
uint32_t cycleTime = 35 + (255 - SEGMENT.speed);
uint32_t it = now / cycleTime;
if (SEGMENT.speed == 0) it = 0;
for(uint16_t i=0; i < SEGLEN; i++) {
if((i + SEGENV.aux0) % (pxw*2) < pxw) {
if (color1 == SEGCOLOR(0))
{
setPixelColor(SEGMENT.stop -i -1, color_from_palette(SEGMENT.stop -i -1, true, PALETTE_SOLID_WRAP, 0));
} else
{
setPixelColor(SEGMENT.stop -i -1, color1);
}
} else {
setPixelColor(SEGMENT.stop -i -1, color2);
}
}
if (it != SEGENV.step )
{
SEGENV.aux0 = (SEGENV.aux0 +1) % (pxw*2);
SEGENV.step = it;
}
return FRAMETIME;
}
/*
* Alternating color/sec pixels running.
*/
uint16_t WS2812FX::mode_running_color(void) {
return running(SEGCOLOR(0), SEGCOLOR(1));
}
/*
* Alternating red/blue pixels running.
*/
uint16_t WS2812FX::mode_running_red_blue(void) {
return running(RED, BLUE);
}
/*
* Alternating red/green pixels running.
*/
uint16_t WS2812FX::mode_merry_christmas(void) {
return running(RED, GREEN);
}
/*
* Alternating orange/purple pixels running.
*/
uint16_t WS2812FX::mode_halloween(void) {
return running(PURPLE, ORANGE);
}
/*
* Random colored pixels running.
*/
uint16_t WS2812FX::mode_running_random(void) {
for(uint16_t i=SEGLEN-1; i > 0; i--) {
setPixelColor(SEGMENT.start + i, getPixelColor(SEGMENT.start + i - 1));
}
if(SEGENV.step == 0) {
SEGENV.aux0 = get_random_wheel_index(SEGENV.aux0);
setPixelColor(SEGMENT.start, color_wheel(SEGENV.aux0));
}
SEGENV.step++;
if (SEGENV.step > ((255-SEGMENT.intensity) >> 4))
{
SEGENV.step = 0;
}
return SPEED_FORMULA_L;
}
/*
* K.I.T.T.
*/
uint16_t WS2812FX::mode_larson_scanner(void) {
fade_out(SEGMENT.intensity);
uint16_t index = 0;
if(SEGENV.step < SEGLEN) {
index = SEGMENT.start + SEGENV.step;
} else {
index = SEGMENT.start + ((SEGLEN * 2) - SEGENV.step) - 2;
}
setPixelColor(index, color_from_palette(index, true, PALETTE_SOLID_WRAP, 0));
SEGENV.step = (SEGENV.step + 1) % ((SEGLEN * 2) - 2);
return SPEED_FORMULA_L;
}
/*
* Firing comets from one end.
*/
uint16_t WS2812FX::mode_comet(void) {
fade_out(SEGMENT.intensity);
uint16_t index = SEGMENT.start + SEGENV.step;
setPixelColor(index, color_from_palette(index, true, PALETTE_SOLID_WRAP, 0));
SEGENV.step = (SEGENV.step + 1) % SEGLEN;
return SPEED_FORMULA_L;
}
/*
* Fireworks function.
*/
uint16_t WS2812FX::mode_fireworks() {
fade_out(0);
if (SEGENV.call == 0) {
SEGENV.aux0 = UINT16_MAX;
SEGENV.aux1 = UINT16_MAX;
}
bool valid1 = (SEGENV.aux0 < SEGMENT.stop && SEGENV.aux0 >= SEGMENT.start);
bool valid2 = (SEGENV.aux1 < SEGMENT.stop && SEGENV.aux1 >= SEGMENT.start);
uint32_t sv1 = 0, sv2 = 0;
if (valid1) sv1 = getPixelColor(SEGENV.aux0);
if (valid2) sv2 = getPixelColor(SEGENV.aux1);
blur(255-SEGMENT.speed);
if (valid1) setPixelColor(SEGENV.aux0 , sv1);
if (valid2) setPixelColor(SEGENV.aux1, sv2);
for(uint16_t i=0; i<max(1, SEGLEN/20); i++) {
if(random8(129 - (SEGMENT.intensity >> 1)) == 0) {
uint16_t index = SEGMENT.start + random(SEGLEN);
setPixelColor(index, color_from_palette(random8(), false, false, 0));
SEGENV.aux1 = SEGENV.aux0;
SEGENV.aux0 = index;
}
}
return 22;
}
//Twinkling LEDs running. Inspired by https://github.com/kitesurfer1404/WS2812FX/blob/master/src/custom/Rain.h
uint16_t WS2812FX::mode_rain()
{
SEGENV.step += 22;
if (SEGENV.step > SPEED_FORMULA_L) {
SEGENV.step = 0;
//shift all leds right
uint32_t ctemp = getPixelColor(SEGMENT.stop -1);
for(uint16_t i=SEGMENT.stop -1; i>SEGMENT.start; i--) {
setPixelColor(i, getPixelColor(i-1));
}
setPixelColor(SEGMENT.start, ctemp);
SEGENV.aux0++;
SEGENV.aux1++;
if (SEGENV.aux0 == 0) SEGENV.aux0 = UINT16_MAX;
if (SEGENV.aux1 == 0) SEGENV.aux0 = UINT16_MAX;
if (SEGENV.aux0 == SEGMENT.stop) SEGENV.aux0 = SEGMENT.start;
if (SEGENV.aux1 == SEGMENT.stop) SEGENV.aux1 = SEGMENT.start;
}
return mode_fireworks();
}
/*
* Fire flicker function
*/
uint16_t WS2812FX::mode_fire_flicker(void) {
byte w = (SEGCOLOR(0) >> 24) & 0xFF;
byte r = (SEGCOLOR(0) >> 16) & 0xFF;
byte g = (SEGCOLOR(0) >> 8) & 0xFF;
byte b = (SEGCOLOR(0) & 0xFF);
byte lum = (SEGMENT.palette == 0) ? max(w, max(r, max(g, b))) : 255;
lum /= (((256-SEGMENT.intensity)/16)+1);
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
byte flicker = random8(lum);
if (SEGMENT.palette == 0) {
setPixelColor(i, max(r - flicker, 0), max(g - flicker, 0), max(b - flicker, 0), max(w - flicker, 0));
} else {
setPixelColor(i, color_from_palette(i, true, PALETTE_SOLID_WRAP, 0, 255 - flicker));
}
}
return 20 + random((255 - SEGMENT.speed),(2 * (uint16_t)(255 - SEGMENT.speed)));
}
/*
* Gradient run base function
*/
uint16_t WS2812FX::gradient_base(bool loading) {
if (SEGENV.call == 0) SEGENV.step = 0;
float per,val; //0.0 = sec 1.0 = pri
float brd = SEGMENT.intensity;
if (!loading) brd = SEGMENT.intensity/2;
if (brd <1.0) brd = 1.0;
int pp = SEGENV.step;
int p1 = pp-SEGLEN;
int p2 = pp+SEGLEN;
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++)
{
if (loading)
{
val = abs(((i>pp) ? p2:pp) -i);
} else {
val = min(abs(pp-i),min(abs(p1-i),abs(p2-i)));
}
per = val/brd;
if (per >1.0) per = 1.0;
setPixelColor(SEGMENT.start + i, color_blend(SEGCOLOR(0), color_from_palette(SEGMENT.start + i, true, PALETTE_SOLID_WRAP, 1), per*255));
}
SEGENV.step++;
if (SEGENV.step >= SEGMENT.stop) SEGENV.step = SEGMENT.start;
if (SEGMENT.speed == 0) SEGENV.step = SEGMENT.start + (SEGLEN >> 1);
return SPEED_FORMULA_L;
}
/*
* Gradient run
*/
uint16_t WS2812FX::mode_gradient(void) {
return gradient_base(false);
}
/*
* Gradient run with hard transition
*/
uint16_t WS2812FX::mode_loading(void) {
return gradient_base(true);
}
/*
* Lights all LEDs after each other up starting from the outer edges and
* finishing in the middle. Then turns them in reverse order off. Repeat.
*/
uint16_t WS2812FX::mode_dual_color_wipe_in_out(void) {
int end = SEGLEN - SEGENV.step - 1;
bool odd = (SEGLEN % 2) == 1;
int mid = odd ? ((SEGLEN / 2) + 1) : (SEGLEN / 2);
if (SEGENV.step < mid) {
byte pindex = map(SEGENV.step, 0, mid -1, 0, 255);
uint32_t col = color_from_palette(pindex, false, false, 0);
setPixelColor(SEGMENT.start + SEGENV.step, col);
setPixelColor(SEGMENT.start + end, col);
} else {
if (odd) {
// If odd, we need to 'double count' the center LED (once to turn it on,
// once to turn it off). So trail one behind after the middle LED.
setPixelColor(SEGMENT.start + SEGENV.step - 1, SEGCOLOR(1));
setPixelColor(SEGMENT.start + end + 1, SEGCOLOR(1));
} else {
setPixelColor(SEGMENT.start + SEGENV.step, SEGCOLOR(1));
setPixelColor(SEGMENT.start + end, SEGCOLOR(1));
}
}
SEGENV.step++;
if (odd) {
if (SEGENV.step > SEGLEN) {
SEGENV.step = 0;
}
} else {
if (SEGENV.step >= SEGLEN) {
SEGENV.step = 0;
}
}
return SPEED_FORMULA_L;
}
/*
* Lights all LEDs after each other up starting from the outer edges and
* finishing in the middle. Then turns them in that order off. Repeat.
*/
uint16_t WS2812FX::mode_dual_color_wipe_in_in(void) {
bool odd = (SEGLEN % 2) == 1;
int mid = SEGLEN / 2;
byte pindex = 0;
uint32_t col = 0;
if (SEGENV.step <= mid)
{
pindex = map(SEGENV.step, 0, mid, 0, 255);
col = color_from_palette(pindex, false, false, 0);
}
if (odd) {
if (SEGENV.step <= mid) {
setPixelColor(SEGMENT.start + SEGENV.step, col);
setPixelColor(SEGMENT.start + SEGLEN - SEGENV.step - 1, col);
} else {
int i = SEGENV.step - mid;
setPixelColor(SEGMENT.start + i - 1, SEGCOLOR(1));
setPixelColor(SEGMENT.start + SEGLEN - i, SEGCOLOR(1));
}
} else {
if (SEGENV.step < mid) {
setPixelColor(SEGMENT.start + SEGENV.step, col);
setPixelColor(SEGMENT.start + SEGLEN - SEGENV.step - 1, col);
} else {
int i = SEGENV.step - mid;
setPixelColor(SEGMENT.start + i, SEGCOLOR(1));
setPixelColor(SEGMENT.start + SEGLEN - i - 1, SEGCOLOR(1));
}
}
SEGENV.step++;
if (odd) {
if (SEGENV.step > SEGLEN) {
SEGENV.step = 0;
}
} else {
if (SEGENV.step >= SEGLEN) {
SEGENV.step = 0;
}
}
return SPEED_FORMULA_L;
}
/*
* Lights all LEDs after each other up starting from the middle and
* finishing at the edges. Then turns them off in that order. Repeat.
*/
uint16_t WS2812FX::mode_dual_color_wipe_out_out(void) {
int end = SEGLEN - SEGENV.step - 1;
bool odd = (SEGLEN % 2) == 1;
int mid = SEGLEN / 2;
byte pindex = 0;
uint32_t col = 0;
if (SEGENV.step <= mid)
{
pindex = map(SEGENV.step, 0, mid, 255, 0);
col = color_from_palette(pindex, false, false, 0);
}
if (odd) {
if (SEGENV.step <= mid) {
setPixelColor(SEGMENT.start + mid + SEGENV.step, col);
setPixelColor(SEGMENT.start + mid - SEGENV.step, col);
} else {
setPixelColor(SEGMENT.start + SEGENV.step - 1, SEGCOLOR(1));
setPixelColor(SEGMENT.start + end + 1, SEGCOLOR(1));
}
} else {
if (SEGENV.step < mid) {
setPixelColor(SEGMENT.start + mid - SEGENV.step - 1, col);
setPixelColor(SEGMENT.start + mid + SEGENV.step, col);
} else {
setPixelColor(SEGMENT.start + SEGENV.step, SEGCOLOR(1));
setPixelColor(SEGMENT.start + end, SEGCOLOR(1));
}
}
SEGENV.step++;
if (odd) {
if (SEGENV.step > SEGLEN) {
SEGENV.step = 0;
}
} else {
if (SEGENV.step >= SEGLEN) {
SEGENV.step = 0;
}
}
return SPEED_FORMULA_L;
}
/*
* Lights all LEDs after each other up starting from the middle and
* finishing at the edges. Then turns them off in reverse order. Repeat.
*/
uint16_t WS2812FX::mode_dual_color_wipe_out_in(void) {
bool odd = (SEGLEN % 2) == 1;
int mid = SEGLEN / 2;
byte pindex = 0;
uint32_t col = 0;
if (SEGENV.step <= mid)
{
pindex = map(SEGENV.step, 0, mid, 255, 0);
col = color_from_palette(pindex, false, false, 0);
}
if (odd) {
if (SEGENV.step <= mid) {
setPixelColor(SEGMENT.start + mid + SEGENV.step, col);
setPixelColor(SEGMENT.start + mid - SEGENV.step, col);
} else {
int i = SEGENV.step - mid;
setPixelColor(SEGMENT.start + i - 1, SEGCOLOR(1));
setPixelColor(SEGMENT.start + SEGLEN - i, SEGCOLOR(1));
}
} else {
if (SEGENV.step < mid) {
setPixelColor(SEGMENT.start + mid - SEGENV.step - 1, col);
setPixelColor(SEGMENT.start + mid + SEGENV.step, col);
} else {
int i = SEGENV.step - mid;
setPixelColor(SEGMENT.start + i, SEGCOLOR(1));
setPixelColor(SEGMENT.start + SEGLEN - i - 1, SEGCOLOR(1));
}
}
SEGENV.step++;
if (odd) {
if (SEGENV.step > SEGLEN) {
SEGENV.step = 0;
}
} else {
if (SEGENV.step >= SEGLEN) {
SEGENV.step = 0;
}
}
return SPEED_FORMULA_L;
}
/*
* Tricolor chase function
*/
uint16_t WS2812FX::tricolor_chase(uint32_t color1, uint32_t color2) {
uint16_t index = SEGENV.step % 6;
for(uint16_t i=0; i < SEGLEN; i++, index++) {
if(index > 5) index = 0;
uint32_t color = color1;
if(index > 3) color = color_from_palette(i, true, PALETTE_SOLID_WRAP, 1);
else if(index > 1) color = color2;
setPixelColor(SEGMENT.stop - i -1, color);
}
SEGENV.step++;
return 35 + ((350 * (uint32_t)(255 - SEGMENT.speed)) / 255);
}
/*
* Alternating white/red/black pixels running. PLACEHOLDER
*/
uint16_t WS2812FX::mode_circus_combustus(void) {
return tricolor_chase(RED, WHITE);
}
/*
* Tricolor chase mode
*/
uint16_t WS2812FX::mode_tricolor_chase(void) {
return tricolor_chase(SEGCOLOR(2), SEGCOLOR(0));
}
/*
* ICU mode
*/
uint16_t WS2812FX::mode_icu(void) {
uint16_t dest = SEGENV.step & 0xFFFF;
fill(SEGCOLOR(1));
byte pindex = map(dest, 0, SEGLEN/2, 0, 255);
uint32_t col = color_from_palette(pindex, false, false, 0);
setPixelColor(SEGMENT.start + dest, col);
setPixelColor(SEGMENT.start + dest + SEGLEN/2, col);
if(SEGENV.aux0 == dest) { // pause between eye movements
if(random8(6) == 0) { // blink once in a while
setPixelColor(SEGMENT.start + dest, SEGCOLOR(1));
setPixelColor(SEGMENT.start + dest + SEGLEN/2, SEGCOLOR(1));
return 200;
}
SEGENV.aux0 = random16(SEGLEN/2);
return 1000 + random16(2000);
}
if(SEGENV.aux0 > SEGENV.step) {
SEGENV.step++;
dest++;
} else if (SEGENV.aux0 < SEGENV.step) {
SEGENV.step--;
dest--;
}
setPixelColor(SEGMENT.start + dest, col);
setPixelColor(SEGMENT.start + dest + SEGLEN/2, col);
return SPEED_FORMULA_L;
}
/*
* Custom mode by Aircoookie. Color Wipe, but with 3 colors
*/
uint16_t WS2812FX::mode_tricolor_wipe(void)
{
if(SEGENV.step < SEGLEN) {
uint32_t led_offset = SEGENV.step;
setPixelColor(SEGMENT.start + led_offset, SEGCOLOR(0));
} else if (SEGENV.step < SEGLEN*2) {
uint32_t led_offset = SEGENV.step - SEGLEN;
setPixelColor(SEGMENT.start + led_offset, SEGCOLOR(1));
} else
{
uint32_t led_offset = SEGENV.step - SEGLEN*2;
setPixelColor(SEGMENT.start + led_offset, color_from_palette(SEGMENT.start + led_offset, true, PALETTE_SOLID_WRAP, 2));
}
SEGENV.step = (SEGENV.step + 1) % (SEGLEN * 3);
return SPEED_FORMULA_L;
}
/*
* Fades between 3 colors
* Custom mode by Keith Lord: https://github.com/kitesurfer1404/WS2812FX/blob/master/src/custom/TriFade.h
* Modified by Aircoookie
*/
uint16_t WS2812FX::mode_tricolor_fade(void)
{
uint32_t color1 = 0, color2 = 0;
byte stage = 0;
if(SEGENV.step < 256) {
color1 = SEGCOLOR(0);
color2 = SEGCOLOR(1);
stage = 0;
} else if(SEGENV.step < 512) {
color1 = SEGCOLOR(1);
color2 = SEGCOLOR(2);
stage = 1;
} else {
color1 = SEGCOLOR(2);
color2 = SEGCOLOR(0);
stage = 2;
}
byte stp = SEGENV.step % 256;
uint32_t color = 0;
for(uint16_t i=SEGMENT.start; i < SEGMENT.stop; i++) {
if (stage == 2) {
color = color_blend(color_from_palette(i, true, PALETTE_SOLID_WRAP, 2), color2, stp);
} else if (stage == 1) {
color = color_blend(color1, color_from_palette(i, true, PALETTE_SOLID_WRAP, 2), stp);
} else {
color = color_blend(color1, color2, stp);
}
setPixelColor(i, color);
}
SEGENV.step += 4;
if(SEGENV.step >= 768) SEGENV.step = 0;
return 5 + ((uint32_t)(255 - SEGMENT.speed) / 10);
}
/*
* Creates random comets
* Custom mode by Keith Lord: https://github.com/kitesurfer1404/WS2812FX/blob/master/src/custom/MultiComet.h
*/
uint16_t WS2812FX::mode_multi_comet(void)
{
fade_out(SEGMENT.intensity);
static uint16_t comets[] = {UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX};
for(uint8_t i=0; i < 8; i++) {
if(comets[i] < SEGLEN) {
uint16_t index = SEGMENT.start + comets[i];
if (SEGCOLOR(2) != 0)
{
setPixelColor(index, i % 2 ? color_from_palette(index, true, PALETTE_SOLID_WRAP, 0) : SEGCOLOR(2));
} else
{
setPixelColor(index, color_from_palette(index, true, PALETTE_SOLID_WRAP, 0));
}
comets[i]++;
} else {
if(!random(SEGLEN)) {
comets[i] = 0;
}
}
}
return SPEED_FORMULA_L;
}
/*
* Creates two Larson scanners moving in opposite directions
* Custom mode by Keith Lord: https://github.com/kitesurfer1404/WS2812FX/blob/master/src/custom/DualLarson.h
*/
uint16_t WS2812FX::mode_dual_larson_scanner(void){
if (SEGENV.aux0)
{
SEGENV.step--;
} else
{
SEGENV.step++;
}
fade_out(SEGMENT.intensity);
uint16_t index = SEGMENT.start + SEGENV.step;
setPixelColor(index, color_from_palette(index, true, PALETTE_SOLID_WRAP, 0));
index = SEGMENT.stop - SEGENV.step -1;
if (SEGCOLOR(2) != 0)
{
setPixelColor(index, SEGCOLOR(2));
} else
{
setPixelColor(index, color_from_palette(index, true, PALETTE_SOLID_WRAP, 0));
}
if(SEGENV.step >= SEGLEN -1 || SEGENV.step <= 0)
SEGENV.aux0 = !SEGENV.aux0;
return SPEED_FORMULA_L;
}
/*
* Running random pixels
* Custom mode by Keith Lord: https://github.com/kitesurfer1404/WS2812FX/blob/master/src/custom/RandomChase.h
*/
uint16_t WS2812FX::mode_random_chase(void)
{
for(uint16_t i=SEGMENT.stop -1; i>SEGMENT.start; i--) {
setPixelColor(i, getPixelColor(i-1));
}
uint32_t color = getPixelColor(SEGMENT.start);
if (SEGLEN > 1) color = getPixelColor(SEGMENT.start + 1);
uint8_t r = random8(6) != 0 ? (color >> 16 & 0xFF) : random8();
uint8_t g = random8(6) != 0 ? (color >> 8 & 0xFF) : random8();
uint8_t b = random8(6) != 0 ? (color & 0xFF) : random8();
setPixelColor(SEGMENT.start, r, g, b);
return SPEED_FORMULA_L;
}
typedef struct Oscillator {
int16_t pos;
int8_t size;
int8_t dir;
int8_t speed;
} oscillator;
uint16_t WS2812FX::mode_oscillate(void)
{
static oscillator oscillators[2] = {
{SEGLEN/4, SEGLEN/8, 1, 1},
{SEGLEN/4*2, SEGLEN/8, -1, 1}
//{SEGLEN/4*3, SEGLEN/8, 1, 2}
};
for(int8_t i=0; i < sizeof(oscillators)/sizeof(oscillators[0]); i++) {
oscillators[i].pos += oscillators[i].dir * oscillators[i].speed;
if((oscillators[i].dir == -1) && (oscillators[i].pos <= 0)) {
oscillators[i].pos = 0;
oscillators[i].dir = 1;
oscillators[i].speed = random8(1, 3);
}
if((oscillators[i].dir == 1) && (oscillators[i].pos >= (SEGLEN - 1))) {
oscillators[i].pos = SEGLEN - 1;
oscillators[i].dir = -1;
oscillators[i].speed = random8(1, 3);
}
}
for(int16_t i=0; i < SEGLEN; i++) {
uint32_t color = BLACK;
for(int8_t j=0; j < sizeof(oscillators)/sizeof(oscillators[0]); j++) {
if(i >= oscillators[j].pos - oscillators[j].size && i <= oscillators[j].pos + oscillators[j].size) {
color = (color == BLACK) ? SEGMENT.colors[j] : color_blend(color, SEGMENT.colors[j], 128);
}
}
setPixelColor(SEGMENT.start + i, color);
}
return 15 + (uint32_t)(255 - SEGMENT.speed);
}
uint16_t WS2812FX::mode_lightning(void)
{
uint16_t ledstart = SEGMENT.start + random16(SEGLEN); // Determine starting location of flash
uint16_t ledlen = random16(SEGMENT.stop -1 -ledstart); // Determine length of flash (not to go beyond NUM_LEDS-1)
uint8_t bri = 255/random8(1, 3);
if (SEGENV.step == 0)
{
SEGENV.aux0 = random8(3, 3 + SEGMENT.intensity/20); //number of flashes
bri = 52;
SEGENV.aux1 = 1;
}
fill(SEGCOLOR(1));
if (SEGENV.aux1) {
for (int i = ledstart; i < ledstart + ledlen; i++)
{
if (SEGMENT.palette == 0)
{
setPixelColor(i,bri,bri,bri,bri);
} else {
setPixelColor(i,color_from_palette(i, true, PALETTE_SOLID_WRAP, 0, bri));
}
}
SEGENV.aux1 = 0;
SEGENV.step++;
return random8(4, 10); // each flash only lasts 4-10 milliseconds
}
SEGENV.aux1 = 1;
if (SEGENV.step == 1) return (200); // longer delay until next flash after the leader
if (SEGENV.step <= SEGENV.aux0) return (50 + random8(100)); // shorter delay between strokes
SEGENV.step = 0;
return (random8(255 - SEGMENT.speed) * 100); // delay between strikes
}
// Pride2015
// Animated, ever-changing rainbows.
// by Mark Kriegsman: https://gist.github.com/kriegsman/964de772d64c502760e5
uint16_t WS2812FX::mode_pride_2015(void)
{
uint16_t duration = 10 + SEGMENT.speed;
uint16_t sPseudotime = SEGENV.step;
uint16_t sHue16 = SEGENV.aux0;
uint8_t sat8 = beatsin88( 87, 220, 250);
uint8_t brightdepth = beatsin88( 341, 96, 224);
uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
uint8_t msmultiplier = beatsin88(147, 23, 60);
uint16_t hue16 = sHue16;//gHue * 256;
uint16_t hueinc16 = beatsin88(113, 1, 3000);
sPseudotime += duration * msmultiplier;
sHue16 += duration * beatsin88( 400, 5,9);
uint16_t brightnesstheta16 = sPseudotime;
CRGB fastled_col;
for( uint16_t i = SEGMENT.start ; i < SEGMENT.stop; i++) {
hue16 += hueinc16;
uint8_t hue8 = hue16 >> 8;
brightnesstheta16 += brightnessthetainc16;
uint16_t b16 = sin16( brightnesstheta16 ) + 32768;
uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
bri8 += (255 - brightdepth);
CRGB newcolor = CHSV( hue8, sat8, bri8);
fastled_col = col_to_crgb(getPixelColor(i));
nblend( fastled_col, newcolor, 64);
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
SEGENV.step = sPseudotime;
SEGENV.aux0 = sHue16;
return 20;
}
//eight colored dots, weaving in and out of sync with each other
uint16_t WS2812FX::mode_juggle(void){
fade_out(SEGMENT.intensity);
CRGB fastled_col;
byte dothue = 0;
for ( byte i = 0; i < 8; i++) {
uint16_t index = SEGMENT.start + beatsin16(i + 7, 0, SEGLEN -1);
fastled_col = col_to_crgb(getPixelColor(index));
fastled_col |= (SEGMENT.palette==0)?CHSV(dothue, 220, 255):ColorFromPalette(currentPalette, dothue, 255);
setPixelColor(index, fastled_col.red, fastled_col.green, fastled_col.blue);
dothue += 32;
}
return 10 + (uint16_t)(255 - SEGMENT.speed)/4;
}
uint16_t WS2812FX::mode_palette()
{
uint16_t counter = 0;
if (SEGMENT.speed != 0)
{
counter = (now * ((SEGMENT.speed >> 3) +1)) & 0xFFFF;
counter = counter >> 8;
}
bool noWrap = (paletteBlend == 2 || (paletteBlend == 0 && SEGMENT.speed == 0));
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++)
{
uint8_t colorIndex = (i * 255 / SEGLEN) - counter;
if (noWrap) colorIndex = map(colorIndex, 0, 255, 0, 240); //cut off blend at palette "end"
setPixelColor(i, color_from_palette(colorIndex, false, true, 255));
}
return FRAMETIME;
}
// WLED limitation: Analog Clock overlay will NOT work when Fire2012 is active
// Fire2012 by Mark Kriegsman, July 2012
// as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY
////
// This basic one-dimensional 'fire' simulation works roughly as follows:
// There's a underlying array of 'heat' cells, that model the temperature
// at each point along the line. Every cycle through the simulation,
// four steps are performed:
// 1) All cells cool down a little bit, losing heat to the air
// 2) The heat from each cell drifts 'up' and diffuses a little
// 3) Sometimes randomly new 'sparks' of heat are added at the bottom
// 4) The heat from each cell is rendered as a color into the leds array
// The heat-to-color mapping uses a black-body radiation approximation.
//
// Temperature is in arbitrary units from 0 (cold black) to 255 (white hot).
//
// This simulation scales it self a bit depending on NUM_LEDS; it should look
// "OK" on anywhere from 20 to 100 LEDs without too much tweaking.
//
// I recommend running this simulation at anywhere from 30-100 frames per second,
// meaning an interframe delay of about 10-35 milliseconds.
//
// Looks best on a high-density LED setup (60+ pixels/meter).
//
//
// There are two main parameters you can play with to control the look and
// feel of your fire: COOLING (used in step 1 above) (Speed = COOLING), and SPARKING (used
// in step 3 above) (Effect Intensity = Sparking).
uint16_t WS2812FX::mode_fire_2012()
{
uint32_t it = now >> 5; //div 32
if (it != SEGENV.step)
{
// Step 1. Cool down every cell a little
for( int i = SEGMENT.start; i < SEGMENT.stop; i++) {
_locked[i] = qsub8(_locked[i], random8(0, (((20 + SEGMENT.speed /3) * 10) / SEGLEN) + 2));
}
// Step 2. Heat from each cell drifts 'up' and diffuses a little
for( int k= SEGMENT.stop -1; k >= SEGMENT.start + 2; k--) {
_locked[k] = (_locked[k - 1] + _locked[k - 2] + _locked[k - 2] ) / 3;
}
// Step 3. Randomly ignite new 'sparks' of heat near the bottom
if( random8() <= SEGMENT.intensity ) {
int y = SEGMENT.start + random8(7);
if (y < SEGMENT.stop) _locked[y] = qadd8(_locked[y], random8(160,255) );
}
SEGENV.step = it;
}
// Step 4. Map from heat cells to LED colors
for( int j = SEGMENT.start; j < SEGMENT.stop; j++) {
CRGB color = ColorFromPalette( currentPalette, min(_locked[j],240), 255, LINEARBLEND);
setPixelColor(j, color.red, color.green, color.blue);
}
return FRAMETIME;
}
// ColorWavesWithPalettes by Mark Kriegsman: https://gist.github.com/kriegsman/8281905786e8b2632aeb
// This function draws color waves with an ever-changing,
// widely-varying set of parameters, using a color palette.
uint16_t WS2812FX::mode_colorwaves()
{
uint16_t duration = 10 + SEGMENT.speed;
uint16_t sPseudotime = SEGENV.step;
uint16_t sHue16 = SEGENV.aux0;
uint8_t brightdepth = beatsin88( 341, 96, 224);
uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
uint8_t msmultiplier = beatsin88(147, 23, 60);
uint16_t hue16 = sHue16;//gHue * 256;
uint16_t hueinc16 = beatsin88(113, 300, 1500);
sPseudotime += duration * msmultiplier;
sHue16 += duration * beatsin88( 400, 5, 9);
uint16_t brightnesstheta16 = sPseudotime;
CRGB fastled_col;
for ( uint16_t i = SEGMENT.start ; i < SEGMENT.stop; i++) {
hue16 += hueinc16;
uint8_t hue8 = hue16 >> 8;
uint16_t h16_128 = hue16 >> 7;
if ( h16_128 & 0x100) {
hue8 = 255 - (h16_128 >> 1);
} else {
hue8 = h16_128 >> 1;
}
brightnesstheta16 += brightnessthetainc16;
uint16_t b16 = sin16( brightnesstheta16 ) + 32768;
uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
bri8 += (255 - brightdepth);
CRGB newcolor = ColorFromPalette(currentPalette, hue8, bri8);
fastled_col = col_to_crgb(getPixelColor(i));
nblend(fastled_col, newcolor, 128);
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
SEGENV.step = sPseudotime;
SEGENV.aux0 = sHue16;
return 20;
}
// colored stripes pulsing at a defined Beats-Per-Minute (BPM)
uint16_t WS2812FX::mode_bpm()
{
CRGB fastled_col;
uint32_t stp = (now / 20) & 0xFF;
uint8_t beat = beatsin8(SEGMENT.speed, 64, 255);
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
fastled_col = ColorFromPalette(currentPalette, stp + (i * 2), beat - stp + (i * 10));
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
return FRAMETIME;
}
uint16_t WS2812FX::mode_fillnoise8()
{
if (SEGENV.call == 0) SEGENV.step = random16(12345);
CRGB fastled_col;
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
uint8_t index = inoise8(i * SEGLEN, SEGENV.step + i * SEGLEN) % 255;
fastled_col = ColorFromPalette(currentPalette, index, 255, LINEARBLEND);
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
SEGENV.step += beatsin8(SEGMENT.speed, 1, 6); //10,1,4
return 20;
}
uint16_t WS2812FX::mode_noise16_1()
{
uint16_t scale = 320; // the "zoom factor" for the noise
CRGB fastled_col;
SEGENV.step += (1 + SEGMENT.speed/16);
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
uint16_t shift_x = beatsin8(11); // the x position of the noise field swings @ 17 bpm
uint16_t shift_y = SEGENV.step/42; // the y position becomes slowly incremented
uint16_t real_x = (i + shift_x) * scale; // the x position of the noise field swings @ 17 bpm
uint16_t real_y = (i + shift_y) * scale; // the y position becomes slowly incremented
uint32_t real_z = SEGENV.step; // the z position becomes quickly incremented
uint8_t noise = inoise16(real_x, real_y, real_z) >> 8; // get the noise data and scale it down
uint8_t index = sin8(noise * 3); // map LED color based on noise data
fastled_col = ColorFromPalette(currentPalette, index, 255, LINEARBLEND); // With that value, look up the 8 bit colour palette value and assign it to the current LED.
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
return 20;
}
uint16_t WS2812FX::mode_noise16_2()
{
uint16_t scale = 1000; // the "zoom factor" for the noise
CRGB fastled_col;
SEGENV.step += (1 + (SEGMENT.speed >> 1));
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
uint16_t shift_x = SEGENV.step >> 6; // x as a function of time
uint16_t shift_y = SEGENV.step/42;
uint32_t real_x = (i + shift_x) * scale; // calculate the coordinates within the noise field
uint8_t noise = inoise16(real_x, 0, 4223) >> 8; // get the noise data and scale it down
uint8_t index = sin8(noise * 3); // map led color based on noise data
fastled_col = ColorFromPalette(currentPalette, index, noise, LINEARBLEND); // With that value, look up the 8 bit colour palette value and assign it to the current LED.
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
return 20;
}
uint16_t WS2812FX::mode_noise16_3()
{
uint16_t scale = 800; // the "zoom factor" for the noise
CRGB fastled_col;
SEGENV.step += (1 + SEGMENT.speed);
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
uint16_t shift_x = 4223; // no movement along x and y
uint16_t shift_y = 1234;
uint32_t real_x = (i + shift_x) * scale; // calculate the coordinates within the noise field
uint32_t real_y = (i + shift_y) * scale; // based on the precalculated positions
uint32_t real_z = SEGENV.step*8;
uint8_t noise = inoise16(real_x, real_y, real_z) >> 8; // get the noise data and scale it down
uint8_t index = sin8(noise * 3); // map led color based on noise data
fastled_col = ColorFromPalette(currentPalette, index, noise, LINEARBLEND); // With that value, look up the 8 bit colour palette value and assign it to the current LED.
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
return 20;
}
//https://github.com/aykevl/ledstrip-spark/blob/master/ledstrip.ino
uint16_t WS2812FX::mode_noise16_4()
{
CRGB fastled_col;
SEGENV.step += SEGMENT.speed;
uint32_t stp = (now / 160) * SEGMENT.speed;
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
int16_t index = inoise16(uint32_t(i - SEGMENT.start) << 12, stp);
fastled_col = ColorFromPalette(currentPalette, index);
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
return FRAMETIME;
}
//based on https://gist.github.com/kriegsman/5408ecd397744ba0393e
uint16_t WS2812FX::mode_colortwinkle()
{
CRGB fastled_col, prev;
fract8 fadeUpAmount = 8 + (SEGMENT.speed/4), fadeDownAmount = 5 + (SEGMENT.speed/7);
for( uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
fastled_col = col_to_crgb(getPixelColor(i));
prev = fastled_col;
if(_locked[i]) {
CRGB incrementalColor = fastled_col;
incrementalColor.nscale8_video( fadeUpAmount);
fastled_col += incrementalColor;
if( fastled_col.red == 255 || fastled_col.green == 255 || fastled_col.blue == 255) {
_locked[i] = false;
}
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
if (col_to_crgb(getPixelColor(i)) == prev) //fix "stuck" pixels
{
fastled_col += fastled_col;
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
} else {
fastled_col.nscale8( 255 - fadeDownAmount);
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
}
for (uint16_t j = 0; j <= SEGLEN / 50; j++)
{
if ( random8() <= SEGMENT.intensity ) {
for (uint8_t times = 0; times < 5; times++) //attempt to spawn a new pixel 5 times
{
int i = SEGMENT.start + random16(SEGLEN);
if(getPixelColor(i) == 0) {
fastled_col = ColorFromPalette(currentPalette, random8(), 64, NOBLEND);
_locked[i] = true;
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
break; //only spawn 1 new pixel per frame per 50 LEDs
}
}
}
}
return 20;
}
//Calm effect, like a lake at night
uint16_t WS2812FX::mode_lake() {
uint8_t sp = SEGMENT.speed/10;
int wave1 = beatsin8(sp +2, -64,64);
int wave2 = beatsin8(sp +1, -64,64);
uint8_t wave3 = beatsin8(sp +2, 0,80);
CRGB fastled_col;
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++)
{
int index = cos8((i*15)+ wave1)/2 + cubicwave8((i*23)+ wave2)/2;
uint8_t lum = (index > wave3) ? index - wave3 : 0;
fastled_col = ColorFromPalette(currentPalette, map(index,0,255,0,240), lum, LINEARBLEND);
setPixelColor(i, fastled_col.red, fastled_col.green, fastled_col.blue);
}
return FRAMETIME;
}
// meteor effect
// send a meteor from begining to to the end of the strip with a trail that randomly decays.
// adapted from https://www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/#LEDStripEffectMeteorRain
uint16_t WS2812FX::mode_meteor() {
byte meteorSize= 1+ SEGLEN / 10;
uint16_t in = SEGMENT.start + SEGENV.step;
// fade all leds to colors[1] in LEDs one step
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
if (random8() <= 255 - SEGMENT.intensity)
{
byte meteorTrailDecay = 128 + random8(127);
_locked[i] = scale8(_locked[i], meteorTrailDecay);
setPixelColor(i, color_from_palette(_locked[i], false, true, 255));
}
}
// draw meteor
for(int j = 0; j < meteorSize; j++) {
uint16_t index = in + j;
if(in + j >= SEGMENT.stop) {
index = SEGMENT.start + (in + j - SEGMENT.stop);
}
_locked[index] = 240;
setPixelColor(index, color_from_palette(_locked[index], false, true, 255));
}
SEGENV.step = (SEGENV.step + 1) % (SEGLEN);
return SPEED_FORMULA_L;
}
// smooth meteor effect
// send a meteor from begining to to the end of the strip with a trail that randomly decays.
// adapted from https://www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/#LEDStripEffectMeteorRain
uint16_t WS2812FX::mode_meteor_smooth() {
byte meteorSize= 1+ SEGLEN / 10;
uint16_t in = map((SEGENV.step >> 6 & 0xFF), 0, 255, SEGMENT.start, SEGMENT.stop -1);
// fade all leds to colors[1] in LEDs one step
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
if (_locked[i] != 0 && random8() <= 255 - SEGMENT.intensity)
{
int change = 3 - random8(12); //change each time between -8 and +3
_locked[i] += change;
if (_locked[i] > 245) _locked[i] = 0;
if (_locked[i] > 240) _locked[i] = 240;
setPixelColor(i, color_from_palette(_locked[i], false, true, 255));
}
}
// draw meteor
for(int j = 0; j < meteorSize; j++) {
uint16_t index = in + j;
if(in + j >= SEGMENT.stop) {
index = SEGMENT.start + (in + j - SEGMENT.stop);
}
setPixelColor(index, color_blend(getPixelColor(index), color_from_palette(240, false, true, 255), 48));
_locked[index] = 240;
}
SEGENV.step += SEGMENT.speed +1;
return 20;
}
//Railway Crossing / Christmas Fairy lights
uint16_t WS2812FX::mode_railway()
{
uint16_t dur = 40 + (255 - SEGMENT.speed) * 10;
uint16_t rampdur = (dur * SEGMENT.intensity) >> 8;
if (SEGENV.step > dur)
{
//reverse direction
SEGENV.step = 0;
SEGENV.aux0 = !SEGENV.aux0;
}
uint8_t pos = 255;
if (rampdur != 0)
{
uint16_t p0 = (SEGENV.step * 255) / rampdur;
if (p0 < 255) pos = p0;
}
if (SEGENV.aux0) pos = 255 - pos;
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i += 2)
{
setPixelColor(i, color_from_palette(255 - pos, false, false, 255));
if (i < SEGMENT.stop -1)
{
setPixelColor(i + 1, color_from_palette(pos, false, false, 255));
}
}
SEGENV.step += FRAMETIME;
return FRAMETIME;
}
//Water ripple
//propagation velocity from speed
//drop rate from intensity
uint16_t WS2812FX::mode_ripple()
{
uint16_t maxripples = SEGLEN / 4;
if (maxripples == 0) return mode_static();
fill(SEGCOLOR(1));
//draw wave
for (uint16_t rippleI = 0; rippleI < maxripples; rippleI++)
{
uint16_t storeI = SEGMENT.start + 4*rippleI;
uint16_t ripplestate = _locked[storeI];
if (ripplestate)
{
uint8_t rippledecay = (SEGMENT.speed >> 4) +1; //faster decay if faster propagation
uint16_t rippleorigin = (_locked[storeI+1] << 8) + _locked[storeI+2];
uint32_t col = color_from_palette(_locked[storeI+3], false, false, 255);
uint16_t propagation = ((ripplestate/rippledecay -1) * SEGMENT.speed);
int16_t propI = propagation >> 8;
uint8_t propF = propagation & 0xFF;
int16_t left = rippleorigin - propI -1;
uint8_t amp = (ripplestate < 17) ? triwave8((ripplestate-1)*8) : map(ripplestate,17,255,255,2);
for (int16_t v = left; v < left +4; v++)
{
uint8_t mag = scale8(cubicwave8((propF>>2)+(v-left)*64), amp);
if (v >= SEGMENT.start)
{
setPixelColor(v, color_blend(getPixelColor(v), col, mag));
}
int16_t w = left + propI*2 + 3 -(v-left);
if (w < SEGMENT.stop && w >= SEGMENT.start)
{
setPixelColor(w, color_blend(getPixelColor(w), col, mag));
}
}
ripplestate += rippledecay;
_locked[storeI] = (ripplestate > 254) ? 0 : ripplestate;
} else //randomly create new wave
{
if (random16(IBN + 10000) <= SEGMENT.intensity)
{
_locked[storeI] = 1;
uint16_t origin = SEGMENT.start + random16(SEGLEN);
_locked[storeI+1] = origin >> 8;
_locked[storeI+2] = origin & 0xFF;
_locked[storeI+3] = random8(); //color
}
}
}
return 20;
}
// TwinkleFOX by Mark Kriegsman: https://gist.github.com/kriegsman/756ea6dcae8e30845b5a
//
// TwinkleFOX: Twinkling 'holiday' lights that fade in and out.
// Colors are chosen from a palette. Read more about this effect using the link above!
// If COOL_LIKE_INCANDESCENT is set to 1, colors will
// fade out slighted 'reddened', similar to how
// incandescent bulbs change color as they get dim down.
#define COOL_LIKE_INCANDESCENT 1
CRGB WS2812FX::twinklefox_one_twinkle(uint32_t ms, uint8_t salt, bool cat)
{
// Overall twinkle speed (changed)
uint16_t ticks = ms / (32 - (SEGMENT.speed >> 3));
uint8_t fastcycle8 = ticks;
uint16_t slowcycle16 = (ticks >> 8) + salt;
slowcycle16 += sin8(slowcycle16);
slowcycle16 = (slowcycle16 * 2053) + 1384;
uint8_t slowcycle8 = (slowcycle16 & 0xFF) + (slowcycle16 >> 8);
// Overall twinkle density.
// 0 (NONE lit) to 8 (ALL lit at once).
// Default is 5.
uint8_t twinkleDensity = (SEGMENT.intensity >> 5) +1;
uint8_t bright = 0;
if (((slowcycle8 & 0x0E)/2) < twinkleDensity) {
uint8_t ph = fastcycle8;
// This is like 'triwave8', which produces a
// symmetrical up-and-down triangle sawtooth waveform, except that this
// function produces a triangle wave with a faster attack and a slower decay
if (cat) //twinklecat, variant where the leds instantly turn on
{
bright = 255 - ph;
} else { //vanilla twinklefox
if (ph < 86) {
bright = ph * 3;
} else {
ph -= 86;
bright = 255 - (ph + (ph/2));
}
}
}
uint8_t hue = slowcycle8 - salt;
CRGB c;
if (bright > 0) {
c = ColorFromPalette(currentPalette, hue, bright, NOBLEND);
if(COOL_LIKE_INCANDESCENT == 1) {
// This code takes a pixel, and if its in the 'fading down'
// part of the cycle, it adjusts the color a little bit like the
// way that incandescent bulbs fade toward 'red' as they dim.
if (fastcycle8 >= 128)
{
uint8_t cooling = (fastcycle8 - 128) >> 4;
c.g = qsub8(c.g, cooling);
c.b = qsub8(c.b, cooling * 2);
}
}
} else {
c = CRGB::Black;
}
return c;
}
// This function loops over each pixel, calculates the
// adjusted 'clock' that this pixel should use, and calls
// "CalculateOneTwinkle" on each pixel. It then displays
// either the twinkle color of the background color,
// whichever is brighter.
void WS2812FX::twinklefox_base(bool cat)
{
// "PRNG16" is the pseudorandom number generator
// It MUST be reset to the same starting value each time
// this function is called, so that the sequence of 'random'
// numbers that it generates is (paradoxically) stable.
uint16_t PRNG16 = 11337;
// Set up the background color, "bg".
// if AUTO_SELECT_BACKGROUND_COLOR == 1, and the first two colors of
// the current palette are identical, then a deeply faded version of
// that color is used for the background color
CRGB bg;
bg = col_to_crgb(SEGCOLOR(1));
uint8_t bglight = bg.getAverageLight();
if (bglight > 64) {
bg.nscale8_video(16); // very bright, so scale to 1/16th
} else if (bglight > 16) {
bg.nscale8_video(64); // not that bright, so scale to 1/4th
} else {
bg.nscale8_video(86); // dim, scale to 1/3rd.
}
uint8_t backgroundBrightness = bg.getAverageLight();
for (uint16_t i = SEGMENT.start; i < SEGMENT.stop; i++) {
PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
uint16_t myclockoffset16= PRNG16; // use that number as clock offset
PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
// use that number as clock speed adjustment factor (in 8ths, from 8/8ths to 23/8ths)
uint8_t myspeedmultiplierQ5_3 = ((((PRNG16 & 0xFF)>>4) + (PRNG16 & 0x0F)) & 0x0F) + 0x08;
uint32_t myclock30 = (uint32_t)((now * myspeedmultiplierQ5_3) >> 3) + myclockoffset16;
uint8_t myunique8 = PRNG16 >> 8; // get 'salt' value for this pixel
// We now have the adjusted 'clock' for this pixel, now we call
// the function that computes what color the pixel should be based
// on the "brightness = f( time )" idea.
CRGB c = twinklefox_one_twinkle(myclock30, myunique8, cat);
uint8_t cbright = c.getAverageLight();
int16_t deltabright = cbright - backgroundBrightness;
if (deltabright >= 32 || (!bg)) {
// If the new pixel is significantly brighter than the background color,
// use the new color.
setPixelColor(i, c.red, c.green, c.blue);
} else if (deltabright > 0) {
// If the new pixel is just slightly brighter than the background color,
// mix a blend of the new color and the background color
setPixelColor(i, color_blend(crgb_to_col(bg), crgb_to_col(c), deltabright * 8));
} else {
// if the new pixel is not at all brighter than the background color,
// just use the background color.
setPixelColor(i, bg.r, bg.g, bg.b);
}
}
}
uint16_t WS2812FX::mode_twinklefox()
{
twinklefox_base(false);
return FRAMETIME;
}
uint16_t WS2812FX::mode_twinklecat()
{
twinklefox_base(true);
return FRAMETIME;
}
//inspired by https://www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/#LEDStripEffectBlinkingHalloweenEyes
#define HALLOWEEN_EYE_SPACE 3
#define HALLOWEEN_EYE_WIDTH 1
uint16_t WS2812FX::mode_halloween_eyes()
{
uint16_t eyeLength = (2*HALLOWEEN_EYE_WIDTH) + HALLOWEEN_EYE_SPACE;
if (eyeLength > SEGLEN) return mode_static(); //bail if segment too short
fill(SEGCOLOR(1)); //fill background
uint8_t state = SEGENV.aux1 >> 8;
uint16_t stateTime = SEGENV.call;
if (stateTime == 0) stateTime = 2000;
if (state == 0) { //spawn eyes
SEGENV.aux0 = random16(SEGMENT.start, SEGMENT.stop - eyeLength); //start pos
SEGENV.aux1 = random8(); //color
state = 1;
}
if (state < 2) { //fade eyes
uint16_t startPos = SEGENV.aux0;
uint16_t start2ndEye = startPos + HALLOWEEN_EYE_WIDTH + HALLOWEEN_EYE_SPACE;
uint32_t fadestage = (now - SEGENV.step)*255 / stateTime;
if (fadestage > 255) fadestage = 255;
uint32_t c = color_blend(color_from_palette(SEGENV.aux1 & 0xFF, false, false, 0), SEGCOLOR(1), fadestage);
for (uint16_t i = 0; i < HALLOWEEN_EYE_WIDTH; i++)
{
setPixelColor(startPos + i, c);
setPixelColor(start2ndEye + i, c);
}
}
if (now - SEGENV.step > stateTime)
{
state++;
if (state > 2) state = 0;
if (state < 2)
{
stateTime = 100 + (255 - SEGMENT.intensity)*10; //eye fade time
} else {
uint16_t eyeOffTimeBase = (255 - SEGMENT.speed)*10;
stateTime = eyeOffTimeBase + random16(eyeOffTimeBase);
}
SEGENV.step = now;
SEGENV.call = stateTime;
}
SEGENV.aux1 = (SEGENV.aux1 & 0xFF) + (state << 8); //save state
return FRAMETIME;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/cryptohome/cryptohome_library.h"
#include <map>
#include "base/bind.h"
#include "base/chromeos/chromeos_version.h"
#include "base/memory/weak_ptr.h"
#include "base/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "crypto/encryptor.h"
#include "crypto/nss_util.h"
#include "crypto/sha2.h"
#include "crypto/symmetric_key.h"
namespace chromeos {
namespace {
const char kStubSystemSalt[] = "stub_system_salt";
const size_t kNonceSize = 16;
// Does nothing. Used as a Cryptohome::VoidMethodCallback.
void DoNothing(DBusMethodCallStatus call_status) {}
} // namespace
// This class handles the interaction with the ChromeOS cryptohome library APIs.
class CryptohomeLibraryImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryImpl() : weak_ptr_factory_(this) {
}
virtual ~CryptohomeLibraryImpl() {
}
virtual bool TpmIsEnabled() OVERRIDE {
bool result = false;
DBusThreadManager::Get()->GetCryptohomeClient()->CallTpmIsEnabledAndBlock(
&result);
return result;
}
virtual bool TpmIsOwned() OVERRIDE {
bool result = false;
DBusThreadManager::Get()->GetCryptohomeClient()->CallTpmIsOwnedAndBlock(
&result);
return result;
}
virtual bool TpmIsBeingOwned() OVERRIDE {
bool result = false;
DBusThreadManager::Get()->GetCryptohomeClient()->
CallTpmIsBeingOwnedAndBlock(&result);
return result;
}
virtual void TpmCanAttemptOwnership() OVERRIDE {
DBusThreadManager::Get()->GetCryptohomeClient()->TpmCanAttemptOwnership(
base::Bind(&DoNothing));
}
virtual void TpmClearStoredPassword() OVERRIDE {
DBusThreadManager::Get()->GetCryptohomeClient()->
CallTpmClearStoredPasswordAndBlock();
}
virtual bool InstallAttributesGet(
const std::string& name, std::string* value) OVERRIDE {
std::vector<uint8> buf;
bool success = false;
DBusThreadManager::Get()->GetCryptohomeClient()->
InstallAttributesGet(name, &buf, &success);
if (success) {
// Cryptohome returns 'buf' with a terminating '\0' character.
DCHECK(!buf.empty());
DCHECK_EQ(buf.back(), 0);
value->assign(reinterpret_cast<char*>(buf.data()), buf.size() - 1);
}
return success;
}
virtual bool InstallAttributesSet(
const std::string& name, const std::string& value) OVERRIDE {
std::vector<uint8> buf(value.c_str(), value.c_str() + value.size() + 1);
bool success = false;
DBusThreadManager::Get()->GetCryptohomeClient()->
InstallAttributesSet(name, buf, &success);
return success;
}
virtual bool InstallAttributesFinalize() OVERRIDE {
bool success = false;
DBusThreadManager::Get()->GetCryptohomeClient()->
InstallAttributesFinalize(&success);
return success;
}
virtual bool InstallAttributesIsInvalid() OVERRIDE {
bool result = false;
DBusThreadManager::Get()->GetCryptohomeClient()->
InstallAttributesIsInvalid(&result);
return result;
}
virtual bool InstallAttributesIsFirstInstall() OVERRIDE {
bool result = false;
DBusThreadManager::Get()->GetCryptohomeClient()->
InstallAttributesIsFirstInstall(&result);
return result;
}
virtual std::string GetSystemSalt() OVERRIDE {
LoadSystemSalt(); // no-op if it's already loaded.
return StringToLowerASCII(base::HexEncode(
reinterpret_cast<const void*>(system_salt_.data()),
system_salt_.size()));
}
virtual std::string EncryptWithSystemSalt(const std::string& token) OVERRIDE {
// Don't care about token encryption while debugging.
if (!base::chromeos::IsRunningOnChromeOS())
return token;
if (!LoadSystemSaltKey()) {
LOG(WARNING) << "System salt key is not available for encrypt.";
return std::string();
}
return EncryptTokenWithKey(system_salt_key_.get(),
GetSystemSalt(),
token);
}
virtual std::string DecryptWithSystemSalt(
const std::string& encrypted_token_hex) OVERRIDE {
// Don't care about token encryption while debugging.
if (!base::chromeos::IsRunningOnChromeOS())
return encrypted_token_hex;
if (!LoadSystemSaltKey()) {
LOG(WARNING) << "System salt key is not available for decrypt.";
return std::string();
}
return DecryptTokenWithKey(system_salt_key_.get(),
GetSystemSalt(),
encrypted_token_hex);
}
private:
void LoadSystemSalt() {
if (!system_salt_.empty())
return;
DBusThreadManager::Get()->GetCryptohomeClient()->
GetSystemSalt(&system_salt_);
CHECK(!system_salt_.empty());
CHECK_EQ(system_salt_.size() % 2, 0U);
}
// TODO: should this use the system salt for both the password and the salt
// value, or should this use a separate salt value?
bool LoadSystemSaltKey() {
if (!system_salt_key_.get())
system_salt_key_.reset(PassphraseToKey(GetSystemSalt(), GetSystemSalt()));
return system_salt_key_.get();
}
crypto::SymmetricKey* PassphraseToKey(const std::string& passphrase,
const std::string& salt) {
return crypto::SymmetricKey::DeriveKeyFromPassword(
crypto::SymmetricKey::AES, passphrase, salt, 1000, 256);
}
// Encrypts (AES) the token given |key| and |salt|.
std::string EncryptTokenWithKey(crypto::SymmetricKey* key,
const std::string& salt,
const std::string& token) {
crypto::Encryptor encryptor;
if (!encryptor.Init(key, crypto::Encryptor::CTR, std::string())) {
LOG(WARNING) << "Failed to initialize Encryptor.";
return std::string();
}
std::string nonce = salt.substr(0, kNonceSize);
std::string encoded_token;
CHECK(encryptor.SetCounter(nonce));
if (!encryptor.Encrypt(token, &encoded_token)) {
LOG(WARNING) << "Failed to encrypt token.";
return std::string();
}
return StringToLowerASCII(base::HexEncode(
reinterpret_cast<const void*>(encoded_token.data()),
encoded_token.size()));
}
// Decrypts (AES) hex encoded encrypted token given |key| and |salt|.
std::string DecryptTokenWithKey(crypto::SymmetricKey* key,
const std::string& salt,
const std::string& encrypted_token_hex) {
std::vector<uint8> encrypted_token_bytes;
if (!base::HexStringToBytes(encrypted_token_hex, &encrypted_token_bytes)) {
LOG(WARNING) << "Corrupt encrypted token found.";
return std::string();
}
std::string encrypted_token(
reinterpret_cast<char*>(encrypted_token_bytes.data()),
encrypted_token_bytes.size());
crypto::Encryptor encryptor;
if (!encryptor.Init(key, crypto::Encryptor::CTR, std::string())) {
LOG(WARNING) << "Failed to initialize Encryptor.";
return std::string();
}
std::string nonce = salt.substr(0, kNonceSize);
std::string token;
CHECK(encryptor.SetCounter(nonce));
if (!encryptor.Decrypt(encrypted_token, &token)) {
LOG(WARNING) << "Failed to decrypt token.";
return std::string();
}
return token;
}
base::WeakPtrFactory<CryptohomeLibraryImpl> weak_ptr_factory_;
std::vector<uint8> system_salt_;
// A key based on the system salt. Useful for encrypting device-level
// data for which we have no additional credentials.
scoped_ptr<crypto::SymmetricKey> system_salt_key_;
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl);
};
class CryptohomeLibraryStubImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryStubImpl()
: locked_(false) {}
virtual ~CryptohomeLibraryStubImpl() {}
virtual bool TpmIsEnabled() OVERRIDE {
return true;
}
virtual bool TpmIsOwned() OVERRIDE {
return true;
}
virtual bool TpmIsBeingOwned() OVERRIDE {
return true;
}
virtual void TpmCanAttemptOwnership() OVERRIDE {}
virtual void TpmClearStoredPassword() OVERRIDE {}
virtual bool InstallAttributesGet(
const std::string& name, std::string* value) OVERRIDE {
if (install_attrs_.find(name) != install_attrs_.end()) {
*value = install_attrs_[name];
return true;
}
return false;
}
virtual bool InstallAttributesSet(
const std::string& name, const std::string& value) OVERRIDE {
install_attrs_[name] = value;
return true;
}
virtual bool InstallAttributesFinalize() OVERRIDE {
locked_ = true;
return true;
}
virtual bool InstallAttributesIsInvalid() OVERRIDE {
return false;
}
virtual bool InstallAttributesIsFirstInstall() OVERRIDE {
return !locked_;
}
virtual std::string GetSystemSalt() OVERRIDE {
return kStubSystemSalt;
}
virtual std::string EncryptWithSystemSalt(const std::string& token) OVERRIDE {
return token;
}
virtual std::string DecryptWithSystemSalt(
const std::string& encrypted_token_hex) OVERRIDE {
return encrypted_token_hex;
}
private:
std::map<std::string, std::string> install_attrs_;
bool locked_;
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl);
};
CryptohomeLibrary::CryptohomeLibrary() {}
CryptohomeLibrary::~CryptohomeLibrary() {}
static CryptohomeLibrary* g_cryptohome_library = NULL;
static CryptohomeLibrary* g_test_cryptohome_library = NULL;
// static
void CryptohomeLibrary::Initialize() {
CHECK(!g_cryptohome_library);
if (base::chromeos::IsRunningOnChromeOS())
g_cryptohome_library = new CryptohomeLibraryImpl();
else
g_cryptohome_library = new CryptohomeLibraryStubImpl();
}
// static
bool CryptohomeLibrary::IsInitialized() {
return g_cryptohome_library;
}
// static
void CryptohomeLibrary::Shutdown() {
CHECK(g_cryptohome_library);
delete g_cryptohome_library;
g_cryptohome_library = NULL;
}
// static
CryptohomeLibrary* CryptohomeLibrary::Get() {
CHECK(g_cryptohome_library || g_test_cryptohome_library)
<< "CryptohomeLibrary::Get() called before Initialize()";
if (g_test_cryptohome_library)
return g_test_cryptohome_library;
return g_cryptohome_library;
}
// static
void CryptohomeLibrary::SetForTest(CryptohomeLibrary* impl) {
CHECK(!g_test_cryptohome_library || !impl);
g_test_cryptohome_library = impl;
}
// static
CryptohomeLibrary* CryptohomeLibrary::GetTestImpl() {
return new CryptohomeLibraryStubImpl();
}
} // namespace chromeos
|
/*******************************************************************\
Module: Tests for coverage instrumentation
Author: Diffblue Ltd
\*******************************************************************/
#include <goto-instrument/cover_instrument.h>
#include <testing-utils/use_catch.h>
TEST_CASE("cover_intrument_end_of_function", "[core]")
{
// Arrange
goto_programt goto_program{};
goto_program.add(
goto_programt::make_function_call(code_function_callt({}, {})));
goto_program.add(
goto_programt::make_function_call(code_function_callt({}, {})));
goto_program.add(goto_programt::make_end_function());
// Act
cover_instrument_end_of_function(
"foo", goto_program, goto_programt::make_assertion);
// Assert
REQUIRE(goto_program.instructions.size() == 4);
const auto newly_inserted = std::next(goto_program.instructions.begin(), 2);
REQUIRE(newly_inserted->is_assert());
REQUIRE(newly_inserted->get_condition() == false_exprt{});
REQUIRE(newly_inserted->source_location().get_function() == "foo");
}
TEST_CASE("cover_instrument_end_of_function with custom expression", "[core]")
{
// Arrange
goto_programt goto_program{};
goto_program.add(
goto_programt::make_function_call(code_function_callt({}, {})));
goto_program.add(
goto_programt::make_function_call(code_function_callt({}, {})));
goto_program.add(goto_programt::make_end_function());
const cover_instrumenter_baset::assertion_factoryt assertion_factory =
[](const exprt &, const source_locationt &location) {
return goto_programt::make_assertion(true_exprt{}, location);
};
// Act
cover_instrument_end_of_function("foo", goto_program, assertion_factory);
// Assert
REQUIRE(goto_program.instructions.size() == 4);
const auto newly_inserted = std::next(goto_program.instructions.begin(), 2);
REQUIRE(newly_inserted->is_assert());
REQUIRE(newly_inserted->get_condition() == true_exprt{});
REQUIRE(newly_inserted->source_location().get_function() == "foo");
}
|
//---------------------------------*-C++-*-----------------------------------//
/*!
* \file CudaUtils/test/Texture_Vector_Test_Kernel.cc
* \author Seth R Johnson
* \date Sat Sep 21 12:09:12 2013
* \brief Texture_Vector_Test_Kernel definitions.
* \note Copyright (C) 2013 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
// Include fake cuda runtime
#include "../cuda_utils/Pseudo_Cuda.hh"
// Generate the polyglot kernel for host code
#include "Texture_Vector_Test_Kernel.cu"
//---------------------------------------------------------------------------//
// end of cuda_utils/test/Texture_Vector_Test_Kernel.cc
//---------------------------------------------------------------------------//
|
#pragma once
#include <string>
using Code = std::string;
using Input = std::string;
struct Brainfuck final {
std::string interpret(Code const& code, Input const& input) const;
Brainfuck() = default;
Brainfuck(Brainfuck const&) = delete;
Brainfuck& operator=(Brainfuck const&) = delete;
};
|
// Copyright (c) 2012-2019 The PaydayCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h>
#include <key_io.h>
#include <script/script.h>
#include <uint256.h>
#include <util/system.h>
#include <util/strencodings.h>
#include <test/setup_common.h>
#include <string>
#include <vector>
#include <boost/test/unit_test.hpp>
static const std::string strSecret1 = "5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj";
static const std::string strSecret2 = "5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3";
static const std::string strSecret1C = "Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw";
static const std::string strSecret2C = "L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g";
static const std::string addr1 = "SkYqsCFMoSkgZh5gqzses71yRWZsvBTYTA";
static const std::string addr2 = "SbNy74rQ5yGkWw6LiagR8Nnch3TNyMGvd4";
static const std::string addr1C = "Sj6Jtef2gkNXBW5MqxS8qUmsWJeewfKuan";
static const std::string addr2C = "SYij48kVjZiiWawysqsnpF8FL9gaKpPNf9";
static const std::string strAddressBad = "1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF";
BOOST_FIXTURE_TEST_SUITE(key_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(key_test1)
{
CKey key1 = DecodeSecret(strSecret1);
BOOST_CHECK(key1.IsValid() && !key1.IsCompressed());
CKey key2 = DecodeSecret(strSecret2);
BOOST_CHECK(key2.IsValid() && !key2.IsCompressed());
CKey key1C = DecodeSecret(strSecret1C);
BOOST_CHECK(key1C.IsValid() && key1C.IsCompressed());
CKey key2C = DecodeSecret(strSecret2C);
BOOST_CHECK(key2C.IsValid() && key2C.IsCompressed());
CKey bad_key = DecodeSecret(strAddressBad);
BOOST_CHECK(!bad_key.IsValid());
CPubKey pubkey1 = key1. GetPubKey();
CPubKey pubkey2 = key2. GetPubKey();
CPubKey pubkey1C = key1C.GetPubKey();
CPubKey pubkey2C = key2C.GetPubKey();
BOOST_CHECK(key1.VerifyPubKey(pubkey1));
BOOST_CHECK(!key1.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key1.VerifyPubKey(pubkey2));
BOOST_CHECK(!key1.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey1));
BOOST_CHECK(key1C.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey2));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key2.VerifyPubKey(pubkey1));
BOOST_CHECK(!key2.VerifyPubKey(pubkey1C));
BOOST_CHECK(key2.VerifyPubKey(pubkey2));
BOOST_CHECK(!key2.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey1));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey2));
BOOST_CHECK(key2C.VerifyPubKey(pubkey2C));
BOOST_CHECK(DecodeDestination(addr1) == CTxDestination(PKHash(pubkey1)));
BOOST_CHECK(DecodeDestination(addr2) == CTxDestination(PKHash(pubkey2)));
BOOST_CHECK(DecodeDestination(addr1C) == CTxDestination(PKHash(pubkey1C)));
BOOST_CHECK(DecodeDestination(addr2C) == CTxDestination(PKHash(pubkey2C)));
for (int n=0; n<16; n++)
{
std::string strMsg = strprintf("Very secret message %i: 11", n);
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
// normal signatures
std::vector<unsigned char> sign1, sign2, sign1C, sign2C;
BOOST_CHECK(key1.Sign (hashMsg, sign1));
BOOST_CHECK(key2.Sign (hashMsg, sign2));
BOOST_CHECK(key1C.Sign(hashMsg, sign1C));
BOOST_CHECK(key2C.Sign(hashMsg, sign2C));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2C));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2C));
// compact signatures (with key recovery)
std::vector<unsigned char> csign1, csign2, csign1C, csign2C;
BOOST_CHECK(key1.SignCompact (hashMsg, csign1));
BOOST_CHECK(key2.SignCompact (hashMsg, csign2));
BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C));
BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C));
CPubKey rkey1, rkey2, rkey1C, rkey2C;
BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1));
BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2));
BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C));
BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C));
BOOST_CHECK(rkey1 == pubkey1);
BOOST_CHECK(rkey2 == pubkey2);
BOOST_CHECK(rkey1C == pubkey1C);
BOOST_CHECK(rkey2C == pubkey2C);
}
// test deterministic signing
std::vector<unsigned char> detsig, detsigc;
std::string strMsg = "Very deterministic message";
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
BOOST_CHECK(key1.Sign(hashMsg, detsig));
BOOST_CHECK(key1C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc);
BOOST_CHECK(detsig == ParseHex("304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(key2.Sign(hashMsg, detsig));
BOOST_CHECK(key2C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc);
BOOST_CHECK(detsig == ParseHex("3044022052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd5022061d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
BOOST_CHECK(key1.SignCompact(hashMsg, detsig));
BOOST_CHECK(key1C.SignCompact(hashMsg, detsigc));
BOOST_CHECK(detsig == ParseHex("1c5dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(detsigc == ParseHex("205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(key2.SignCompact(hashMsg, detsig));
BOOST_CHECK(key2C.SignCompact(hashMsg, detsigc));
BOOST_CHECK(detsig == ParseHex("1c52d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
BOOST_CHECK(detsigc == ParseHex("2052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
}
BOOST_AUTO_TEST_CASE(key_signature_tests)
{
// When entropy is specified, we should see at least one high R signature within 20 signatures
CKey key = DecodeSecret(strSecret1);
std::string msg = "A message to be signed";
uint256 msg_hash = Hash(msg.begin(), msg.end());
std::vector<unsigned char> sig;
bool found = false;
for (int i = 1; i <=20; ++i) {
sig.clear();
BOOST_CHECK(key.Sign(msg_hash, sig, false, i));
found = sig[3] == 0x21 && sig[4] == 0x00;
if (found) {
break;
}
}
BOOST_CHECK(found);
// When entropy is not specified, we should always see low R signatures that are less than 70 bytes in 256 tries
// We should see at least one signature that is less than 70 bytes.
found = true;
bool found_small = false;
for (int i = 0; i < 256; ++i) {
sig.clear();
std::string msg = "A message to be signed" + std::to_string(i);
msg_hash = Hash(msg.begin(), msg.end());
BOOST_CHECK(key.Sign(msg_hash, sig));
found = sig[3] == 0x20;
BOOST_CHECK(sig.size() <= 70);
found_small |= sig.size() < 70;
}
BOOST_CHECK(found);
BOOST_CHECK(found_small);
}
BOOST_AUTO_TEST_CASE(key_key_negation)
{
// create a dummy hash for signature comparison
unsigned char rnd[8];
std::string str = "Bitcoin key verification\n";
GetRandBytes(rnd, sizeof(rnd));
uint256 hash;
CHash256().Write((unsigned char*)str.data(), str.size()).Write(rnd, sizeof(rnd)).Finalize(hash.begin());
// import the static test key
CKey key = DecodeSecret(strSecret1C);
// create a signature
std::vector<unsigned char> vch_sig;
std::vector<unsigned char> vch_sig_cmp;
key.Sign(hash, vch_sig);
// negate the key twice
BOOST_CHECK(key.GetPubKey().data()[0] == 0x03);
key.Negate();
// after the first negation, the signature must be different
key.Sign(hash, vch_sig_cmp);
BOOST_CHECK(vch_sig_cmp != vch_sig);
BOOST_CHECK(key.GetPubKey().data()[0] == 0x02);
key.Negate();
// after the second negation, we should have the original key and thus the
// same signature
key.Sign(hash, vch_sig_cmp);
BOOST_CHECK(vch_sig_cmp == vch_sig);
BOOST_CHECK(key.GetPubKey().data()[0] == 0x03);
}
BOOST_AUTO_TEST_SUITE_END()
|
/*
* CRL Entry
* (C) 1999-2010 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/crl_ent.h>
#include <botan/x509cert.h>
#include <botan/x509_ext.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/bigint.h>
#include <botan/oids.h>
namespace Botan {
/*
* Create a CRL_Entry
*/
CRL_Entry::CRL_Entry(bool t_on_unknown_crit) :
m_throw_on_unknown_critical(t_on_unknown_crit)
{
m_reason = UNSPECIFIED;
}
/*
* Create a CRL_Entry
*/
CRL_Entry::CRL_Entry(const X509_Certificate& cert, CRL_Code why) :
m_throw_on_unknown_critical(false)
{
m_serial = cert.serial_number();
m_time = X509_Time(std::chrono::system_clock::now());
m_reason = why;
}
/*
* Compare two CRL_Entrys for equality
*/
bool operator==(const CRL_Entry& a1, const CRL_Entry& a2)
{
if(a1.serial_number() != a2.serial_number())
return false;
if(a1.expire_time() != a2.expire_time())
return false;
if(a1.reason_code() != a2.reason_code())
return false;
return true;
}
/*
* Compare two CRL_Entrys for inequality
*/
bool operator!=(const CRL_Entry& a1, const CRL_Entry& a2)
{
return !(a1 == a2);
}
/*
* DER encode a CRL_Entry
*/
void CRL_Entry::encode_into(DER_Encoder& der) const
{
Extensions extensions;
extensions.add(new Cert_Extension::CRL_ReasonCode(m_reason));
der.start_cons(SEQUENCE)
.encode(BigInt::decode(m_serial))
.encode(m_time)
.start_cons(SEQUENCE)
.encode(extensions)
.end_cons()
.end_cons();
}
/*
* Decode a BER encoded CRL_Entry
*/
void CRL_Entry::decode_from(BER_Decoder& source)
{
BigInt serial_number_bn;
m_reason = UNSPECIFIED;
BER_Decoder entry = source.start_cons(SEQUENCE);
entry.decode(serial_number_bn).decode(m_time);
if(entry.more_items())
{
Extensions extensions(m_throw_on_unknown_critical);
entry.decode(extensions);
Data_Store info;
extensions.contents_to(info, info);
m_reason = CRL_Code(info.get1_uint32("X509v3.CRLReasonCode"));
}
entry.end_cons();
m_serial = BigInt::encode(serial_number_bn);
}
}
|
// Full definition ranges for function templates are recorded.
//- @"template <typename T> void f(T t) { }" defines TFnF
//- @f defines/binding TFnF
template <typename T> void f(T t) { }
//- @f defines/binding TFnFTS
//- @"template <> void f(int t) { }" defines TFnFTS
template <> void f(int t) { }
//- @f defines/binding TFnFPS
//- @"template <typename S> void f(S* s) { }" defines TFnFPS
template <typename S> void f(S* s) { }
class C {
//- @f defines/binding TMFn
//- @"template <typename T> void f(T t) { }" defines TMFn
template <typename T> void f(T t) { }
template <typename T> void g();
};
//- @g defines/binding TMFnExt
//- @"template <typename T> void C::g() { }" defines TMFnExt
template <typename T> void C::g() { }
|
/*
* Copyright (C) 2007-2021 Intel Corporation.
* SPDX-License-Identifier: MIT
*/
/* ===================================================================== */
/*! @file
Replace an original function with a custom function defined in the tool. The
new function can have either the same or different signature from that of its
original function.
*/
/* ===================================================================== */
#include "pin.H"
#include <iostream>
#include <stdlib.h>
using std::cout;
using std::dec;
using std::endl;
using std::hex;
/* ===================================================================== */
static int (*pf_bar)(int, int, int, int, int, int, int, int, int, int);
/* ===================================================================== */
int Boo(CONTEXT* ctxt, AFUNPTR pf_Blue, int one, int two, int three, int four, int five, int six, int seven, int eight, int nine,
int zero)
{
int ret = 0;
cout << "Jitting Blue10() with ten arguments and one return value." << endl;
cout << "&ret = " << hex << &ret << dec << endl;
PIN_CallApplicationFunction(ctxt, PIN_ThreadId(), CALLINGSTD_DEFAULT, pf_Blue, NULL, PIN_PARG(int), &ret, PIN_PARG(int), one,
PIN_PARG(int), two, PIN_PARG(int), three, PIN_PARG(int), four, PIN_PARG(int), five, PIN_PARG(int),
six, PIN_PARG(int), seven, PIN_PARG(int), eight, PIN_PARG(int), nine, PIN_PARG(int), zero,
PIN_PARG_END());
cout << "Returned from Blue(); ret = " << ret << endl;
return ret;
}
/* ===================================================================== */
VOID ImageLoad(IMG img, VOID* v)
{
if (IMG_IsMainExecutable(img))
{
PROTO proto = PROTO_Allocate(PIN_PARG(int), CALLINGSTD_DEFAULT, "Bar10", PIN_PARG(int), PIN_PARG(int), PIN_PARG(int),
PIN_PARG(int), PIN_PARG(int), PIN_PARG(int), PIN_PARG(int), PIN_PARG(int), PIN_PARG(int),
PIN_PARG(int), PIN_PARG_END());
VOID* pf_Blue;
RTN rtn1 = RTN_FindByName(img, "Blue10");
if (RTN_Valid(rtn1))
pf_Blue = reinterpret_cast< VOID* >(RTN_Address(rtn1));
else
{
cout << "Blue1 cannot be found." << endl;
exit(1);
}
RTN rtn = RTN_FindByName(img, "Bar10");
if (RTN_Valid(rtn))
{
cout << "Replacing " << RTN_Name(rtn) << " in " << IMG_Name(img) << endl;
pf_bar = (int (*)(int, int, int, int, int, int, int, int, int, int))RTN_ReplaceSignature(
rtn, AFUNPTR(Boo), IARG_PROTOTYPE, proto, IARG_CONTEXT, IARG_PTR, pf_Blue, IARG_UINT32, 1, IARG_UINT32, 2,
IARG_UINT32, 3, IARG_UINT32, 4, IARG_UINT32, 5, IARG_UINT32, 6, IARG_UINT32, 7, IARG_UINT32, 8, IARG_UINT32, 9,
IARG_UINT32, 0, IARG_END);
}
PROTO_Free(proto);
}
}
/* ===================================================================== */
int main(INT32 argc, CHAR* argv[])
{
PIN_InitSymbols();
PIN_Init(argc, argv);
IMG_AddInstrumentFunction(ImageLoad, 0);
PIN_StartProgram();
return 0;
}
/* ===================================================================== */
/* eof */
/* ===================================================================== */
|
// Copyright (C) 2012 GlavSoft LLC.
// All rights reserved.
//
//-------------------------------------------------------------------------
// This file is part of the TightVNC software. Please visit our Web site:
//
// http://www.tightvnc.com/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//-------------------------------------------------------------------------
//
#include "UpdateHandlerImpl.h"
UpdateHandlerImpl::UpdateHandlerImpl(UpdateListener *externalUpdateListener, ScreenDriverFactory *scrDriverFactory,
LogWriter *log)
: m_externalUpdateListener(externalUpdateListener),
m_fullUpdateRequested(false),
m_log(log)
{
m_screenDriver = scrDriverFactory->createScreenDriver(&m_updateKeeper,
this,
&m_backupFrameBuffer,
&m_fbLocMut, log);
// At this point the screen driver must contain valid screen properties.
m_backupFrameBuffer.assignProperties(m_screenDriver->getScreenBuffer());
m_updateKeeper.setBorderRect(&m_screenDriver->getScreenDimension().getRect());
m_updateFilter = new UpdateFilter(m_screenDriver,
&m_backupFrameBuffer,
&m_fbLocMut, log);
// At this point all common resources will be covered the mutex for changes.
m_screenDriver->executeDetection();
// Force first update with full screen grab
m_absoluteRect = m_backupFrameBuffer.getDimension().getRect();
m_updateKeeper.addChangedRect(&m_absoluteRect);
doUpdate();
}
UpdateHandlerImpl::~UpdateHandlerImpl()
{
m_screenDriver->terminateDetection();
delete m_updateFilter;
delete m_screenDriver;
}
void UpdateHandlerImpl::extract(UpdateContainer *updateContainer)
{
Rect copyRect;
Point copySrc;
m_log->debug(_T("UpdateHandlerImpl: getCopiedRegion"));
m_screenDriver->getCopiedRegion(©Rect, ©Src);
{
AutoLock al(&m_updateKeeper); // The following operations should be atomic
m_updateKeeper.addCopyRect(©Rect, ©Src);
m_log->debug(_T("UpdateHandlerImpl: extract Copy Rect"));
m_updateKeeper.extract(updateContainer);
}
// Note: The getVideoRegion() function is not a thread safe function, but it invokes
// only from this one place and so that is why it does not cover by the mutex.
m_log->debug(_T("UpdateHandlerImpl: getVideoRegion"));
updateContainer->videoRegion = m_screenDriver->getVideoRegion();
// Constrain the video region to the current frame buffer border.
m_log->debug(_T("UpdateHandlerImpl: getRect"));
Region fbRect(getFrameBufferDimension().getRect());
m_log->debug(_T("UpdateHandlerImpl: intersect"));
updateContainer->videoRegion.intersect(&fbRect);
m_log->debug(_T("UpdateHandlerImpl::extract : filter updates"));
m_updateFilter->filter(updateContainer);
if (!m_absoluteRect.isEmpty()) {
updateContainer->changedRegion.addRect(&m_screenDriver->getScreenBuffer()->
getDimension().getRect());
m_absoluteRect.clear();
}
// Checking for screen properties changing or frame buffers differ
m_log->debug(_T("UpdateHandlerImpl::extract : Checking for screen properties changing or frame buffers differ"));
if (m_screenDriver->getScreenPropertiesChanged() ||
!m_backupFrameBuffer.isEqualTo(m_screenDriver->getScreenBuffer())) {
Dimension currentDimension = m_backupFrameBuffer.getDimension();
Dimension newDimension = m_screenDriver->getScreenDimension();
if (m_screenDriver->getScreenSizeChanged() || !currentDimension.isEqualTo(&newDimension)) {
updateContainer->screenSizeChanged = true;
}
m_log->debug(_T("UpdateHandlerImpl::extract : applyNewScreenProperties()"));
applyNewScreenProperties();
{
// Only this place the class provides frame buffer changings, and then why it
// must be under the mutex. Getters for the backup frame buffer in here (at this function)
// can work without the mutex, but other getters for the frame buffer in other places
// may be invoked from other threads and then it shall cover by the mutex.
AutoLock al(&m_fbLocMut);
m_backupFrameBuffer.clone(m_screenDriver->getScreenBuffer());
}
updateContainer->changedRegion.clear();
updateContainer->copiedRegion.clear();
m_absoluteRect = m_backupFrameBuffer.getDimension().getRect();
m_updateKeeper.setBorderRect(&m_absoluteRect);
}
// Cursor position must always be present.
updateContainer->cursorPos = m_screenDriver->getCursorPosition();
{
int x = updateContainer->cursorPos.x;
int y = updateContainer->cursorPos.y;
m_log->debug(_T("UpdateHandlerImpl::extract : update cursor position (%d,%d)"), x, y);
}
// Checking for mouse shape changing
if (updateContainer->cursorShapeChanged || m_fullUpdateRequested) {
// Update cursor shape
m_screenDriver->grabCursorShape(&m_backupFrameBuffer.getPixelFormat());
// Store cursor shape
m_cursorShape.clone(m_screenDriver->getCursorShape());
m_fullUpdateRequested = false;
}
m_log->debug(_T("UpdateHandlerImpl::extract finished"));
}
void UpdateHandlerImpl::applyNewScreenProperties()
{
int applyTryCount = 3;
bool applyResult = true;
do {
if (!applyResult) {
WindowsEvent waitEvent; // No way to made it abortable.
waitEvent.waitForEvent(1000);
}
m_log->info(_T("Screen properties changed, applying new screen properties, total tries = %d"), applyTryCount);
applyResult = m_screenDriver->applyNewScreenProperties();
applyTryCount--;
} while (applyTryCount > 0 && !applyResult);
if (!applyResult) {
throw Exception(_T("Unable set new screen properties at all tries"));
}
}
void UpdateHandlerImpl::setFullUpdateRequested(const Region *region)
{
m_updateKeeper.addChangedRegion(region);
m_fullUpdateRequested = true;
}
void UpdateHandlerImpl::executeDetectors()
{
// FIXME: Why following string is here?
m_backupFrameBuffer.assignProperties(m_screenDriver->getScreenBuffer());
m_screenDriver->executeDetection();
}
void UpdateHandlerImpl::terminateDetectors()
{
m_screenDriver->terminateDetection();
}
void UpdateHandlerImpl::onUpdate()
{
UpdateContainer updCont;
m_updateKeeper.getUpdateContainer(&updCont);
if (!updCont.isEmpty()) {
doUpdate();
}
}
bool UpdateHandlerImpl::checkForUpdates(Region *region)
{
return m_updateKeeper.checkForUpdates(region);
}
void UpdateHandlerImpl::setExcludedRegion(const Region *excludedRegion)
{
m_updateKeeper.setExcludedRegion(excludedRegion);
}
|
/*
* @file
* @author TPOC: contact@palisade-crypto.org
*
* @section LICENSE
*
* @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT))
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
* This code shows how the EvalAtIndex and EvalMerge operations work for different cyclotomic rings (both power-of-two and cyclic)
*/
#include <iostream>
#include <fstream>
#include "palisade.h"
#include <random>
using namespace std;
using namespace lbcrypto;
#include <iterator>
void BFVrnsEvalAtIndex2n();
void CKKSEvalAtIndex2n();
void NullEvalAtIndex2n();
void BFVEvalAtIndexCyclic();
void BFVrnsEvalMerge2n();
void NullEvalMerge2n();
int main() {
std::cout << "\nThis code shows how the EvalAtIndex and EvalMerge operations work for different cyclotomic rings (both power-of-two and cyclic).\n" << std::endl;
std::cout << "\n========== BFVrns.EvalAtIndex - Power-of-Two Cyclotomics ===========" << std::endl;
#ifdef NO_QUADMATH
std::cout << "BFVrns is currently not available for this architecture. Skipping"<<std::endl;
#else
BFVrnsEvalAtIndex2n();
#endif
std::cout << "\n========== CKKS.EvalAtIndex - Power-of-Two Cyclotomics ===========" << std::endl;
CKKSEvalAtIndex2n();
std::cout << "\n========== Null.EvalAtIndex - Power-of-Two Cyclotomics ===========" << std::endl;
NullEvalAtIndex2n();
std::cout << "\n========== BFV.EvalAtIndex - Cyclic group ===========" << std::endl;
BFVEvalAtIndexCyclic();
std::cout << "\n========== BFVrns.EvalMerge - Power-of-Two Cyclotomics ===========" << std::endl;
#ifdef NO_QUADMATH
std::cout << "BFVrns is currently not available for this architecture. Skipping"<<std::endl;
#else
BFVrnsEvalMerge2n();
#endif
std::cout << "\n========== Null.EvalMerge - Power-of-Two Cyclotomics ===========" << std::endl;
NullEvalMerge2n();
return 0;
}
void BFVrnsEvalAtIndex2n() {
uint64_t p = 65537;
double sigma = 3.2;
double rootHermiteFactor = 1.006;
CryptoContext<DCRTPoly> cc = CryptoContextFactory<DCRTPoly>::genCryptoContextBFVrns(
p, rootHermiteFactor, sigma, 0, 1, 0, OPTIMIZED,3);
int32_t n = cc->GetCryptoParameters()->GetElementParams()->GetCyclotomicOrder()/2;
// enable features that you wish to use
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<DCRTPoly> kp = cc->KeyGen();
vector<int32_t> indexList = {2,3,4,5,6,7,8,9,10,-n+2,-n+3, n-1, n-2, -1, -2, -3, -4, -5};
cc->EvalAtIndexKeyGen(kp.secretKey, indexList);
std::vector<int64_t> vectorOfInts = { 1,2,3,4,5,6,7,8, 9, 10 };
vectorOfInts.resize(n);
vectorOfInts[n-1]=n;
vectorOfInts[n-2]=n-1;
vectorOfInts[n-3]=n-2;
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
auto ciphertext = cc->Encrypt(kp.publicKey, intArray);
for (size_t i = 0; i < 18; i++) {
auto permutedCiphertext = cc->EvalAtIndex(ciphertext, indexList[i]);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, permutedCiphertext, &intArrayNew);
intArrayNew->SetLength(10);
std::cout << "Automorphed array - at index " << indexList[i] << ": " << *intArrayNew << std::endl;
}
}
void CKKSEvalAtIndex2n() {
usint m = 8192;
usint init_size = 3;
usint dcrtBits = 40;
CryptoContext<DCRTPoly> cc =
CryptoContextFactory<DCRTPoly>::genCryptoContextCKKSWithParamsGen(
m,
init_size, /*numPrimes*/
dcrtBits,
10, /*relinWindow*/
16, /*batch size*/
OPTIMIZED,
3 /*depth*/);
int32_t n = m/4;
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
cc->Enable(LEVELEDSHE);
// Initialize the public key containers.
LPKeyPair<DCRTPoly> kp = cc->KeyGen();
vector<int32_t> indexList = {2,3,4,5,6,7,8,9,10,-n+2,-n+3, n-1, n-2, -1, -2, -3, -4, -5};
cc->EvalAtIndexKeyGen(kp.secretKey, indexList);
std::vector<std::complex<double>> vectorOfInts = { 1,2,3,4,5,6,7,8, 9, 10 };
vectorOfInts.resize(n);
vectorOfInts[n-1]=n;
vectorOfInts[n-2]=n-1;
vectorOfInts[n-3]=n-2;
Plaintext intArray = cc->MakeCKKSPackedPlaintext(vectorOfInts);
auto ciphertext = cc->Encrypt(kp.publicKey, intArray);
for (size_t i = 0; i < 18; i++) {
auto permutedCiphertext = cc->EvalAtIndex(ciphertext, indexList[i]);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, permutedCiphertext, &intArrayNew);
intArrayNew->SetLength(10);
std::cout << "Automorphed array - at index " << indexList[i] << ": " << *intArrayNew << std::endl;
}
}
void NullEvalAtIndex2n() {
uint64_t p = 65537;
usint m = 8192;
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextNull(m,p);
int32_t n = cc->GetCryptoParameters()->GetElementParams()->GetCyclotomicOrder()/2;
// enable features that you wish to use
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
vector<int32_t> indexList = {2,3,4,5,6,7,8,9,10,-n+2,-n+3, n-1, n-2, -1, -2, -3, -4, -5};
cc->EvalAtIndexKeyGen(kp.secretKey, indexList);
std::vector<int64_t> vectorOfInts = { 1,2,3,4,5,6,7,8, 9, 10 };
vectorOfInts.resize(n);
vectorOfInts[n-1]=n;
vectorOfInts[n-2]=n-1;
vectorOfInts[n-3]=n-2;
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
auto ciphertext = cc->Encrypt(kp.publicKey, intArray);
for (size_t i = 0; i < 18; i++) {
auto permutedCiphertext = cc->EvalAtIndex(ciphertext, indexList[i]);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, permutedCiphertext, &intArrayNew);
intArrayNew->SetLength(10);
std::cout << "Automorphed array - at index " << indexList[i] << ": " << *intArrayNew << std::endl;
}
}
void BFVEvalAtIndexCyclic() {
usint m = 22;
usint p = 2333;
BigInteger modulusP(p);
BigInteger modulusQ("955263939794561");
BigInteger squareRootOfRoot("941018665059848");
//usint n = GetTotient(m);
BigInteger bigmodulus("80899135611688102162227204937217");
BigInteger bigroot("77936753846653065954043047918387");
auto cycloPoly = GetCyclotomicPolynomial<BigVector>(m, modulusQ);
ChineseRemainderTransformArb<BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ);
float stdDev = 4;
shared_ptr<ILParams> params(new ILParams(m, modulusQ, squareRootOfRoot, bigmodulus, bigroot));
BigInteger delta(modulusQ.DividedBy(modulusP));
EncodingParams encodingParams(new EncodingParamsImpl(p));
PackedEncoding::SetParams(m, encodingParams);
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextBFV(
params, encodingParams,
8, stdDev, delta.ToString());
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
int32_t n = 10;
vector<int32_t> indexList = {2,3,4,-n+2, n, n-1, n-2, -1, -2};
cc->EvalAtIndexKeyGen(kp.secretKey, indexList);
std::vector<int64_t> vectorOfInts = { 1,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
auto ciphertext = cc->Encrypt(kp.publicKey, intArray);
for (size_t i = 0; i < 9; i++) {
auto permutedCiphertext = cc->EvalAtIndex(ciphertext, indexList[i]);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, permutedCiphertext, &intArrayNew);
intArrayNew->SetLength(10);
std::cout << "Automorphed array - at index " << indexList[i] << ": " << *intArrayNew << std::endl;
}
}
void BFVrnsEvalMerge2n() {
uint64_t p = 65537;
double sigma = 3.2;
double rootHermiteFactor = 1.006;
CryptoContext<DCRTPoly> cc = CryptoContextFactory<DCRTPoly>::genCryptoContextBFVrns(
p, rootHermiteFactor, sigma, 0, 2, 0, OPTIMIZED,3);
// enable features that you wish to use
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<DCRTPoly> kp = cc->KeyGen();
vector<int32_t> indexList = {-1,-2,-3,-4,-5};
cc->EvalAtIndexKeyGen(kp.secretKey, indexList);
std::vector<Ciphertext<DCRTPoly>> ciphertexts;
std::vector<int64_t> vectorOfInts1 = { 32,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray1 = cc->MakePackedPlaintext(vectorOfInts1);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray1));
std::vector<int64_t> vectorOfInts2 = { 2,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray2 = cc->MakePackedPlaintext(vectorOfInts2);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray2));
std::vector<int64_t> vectorOfInts3 = { 4,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray3 = cc->MakePackedPlaintext(vectorOfInts3);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray3));
std::vector<int64_t> vectorOfInts4 = { 8,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray4 = cc->MakePackedPlaintext(vectorOfInts4);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray4));
std::vector<int64_t> vectorOfInts5 = { 16,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray5 = cc->MakePackedPlaintext(vectorOfInts5);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray5));
std::cout << "Input ciphertext " << *intArray1 << std::endl;
std::cout << "Input ciphertext " << *intArray2 << std::endl;
std::cout << "Input ciphertext " << *intArray3 << std::endl;
std::cout << "Input ciphertext " << *intArray4 << std::endl;
std::cout << "Input ciphertext " << *intArray5 << std::endl;
auto mergedCiphertext = cc->EvalMerge(ciphertexts);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, mergedCiphertext, &intArrayNew);
intArrayNew->SetLength(10);
std::cout << "\nMerged ciphertext " << *intArrayNew << std::endl;
}
void NullEvalMerge2n() {
uint64_t p = 65537;
usint m = 32;
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextNull(m,p);
// enable features that you wish to use
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
vector<int32_t> indexList = {-1,-2,-3,-4,-5};
cc->EvalAtIndexKeyGen(kp.secretKey, indexList);
std::vector<Ciphertext<Poly>> ciphertexts;
std::vector<int64_t> vectorOfInts1 = { 32,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray1 = cc->MakePackedPlaintext(vectorOfInts1);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray1));
std::vector<int64_t> vectorOfInts2 = { 2,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray2 = cc->MakePackedPlaintext(vectorOfInts2);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray2));
std::vector<int64_t> vectorOfInts3 = { 4,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray3 = cc->MakePackedPlaintext(vectorOfInts3);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray3));
std::vector<int64_t> vectorOfInts4 = { 8,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray4 = cc->MakePackedPlaintext(vectorOfInts4);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray4));
std::vector<int64_t> vectorOfInts5 = { 16,2,3,4,5,6,7,8, 9, 10 };
Plaintext intArray5 = cc->MakePackedPlaintext(vectorOfInts5);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray5));
std::cout << "Input ciphertext " << *intArray1 << std::endl;
std::cout << "Input ciphertext " << *intArray2 << std::endl;
std::cout << "Input ciphertext " << *intArray3 << std::endl;
std::cout << "Input ciphertext " << *intArray4 << std::endl;
std::cout << "Input ciphertext " << *intArray5 << std::endl;
auto mergedCiphertext = cc->EvalMerge(ciphertexts);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, mergedCiphertext, &intArrayNew);
intArrayNew->SetLength(10);
std::cout << "\nMerged ciphertext " << *intArrayNew << std::endl;
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/service/cloud_print/job_status_updater.h"
#include "base/json/json_reader.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/net/http_return.h"
#include "chrome/service/cloud_print/cloud_print_consts.h"
#include "chrome/service/cloud_print/cloud_print_helpers.h"
#include "googleurl/src/gurl.h"
JobStatusUpdater::JobStatusUpdater(const std::string& printer_name,
const std::string& job_id,
cloud_print::PlatformJobId& local_job_id,
const std::string& auth_token,
const GURL& cloud_print_server_url,
cloud_print::PrintSystem* print_system,
Delegate* delegate)
: printer_name_(printer_name), job_id_(job_id),
local_job_id_(local_job_id), auth_token_(auth_token),
cloud_print_server_url_(cloud_print_server_url),
print_system_(print_system), delegate_(delegate), stopped_(false) {
DCHECK(delegate_);
}
JobStatusUpdater::~JobStatusUpdater() {}
// Start checking the status of the local print job.
void JobStatusUpdater::UpdateStatus() {
// It does not matter if we had already sent out an update and are waiting for
// a response. This is a new update and we will simply cancel the old request
// and send a new one.
if (!stopped_) {
bool need_update = false;
// If the job has already been completed, we just need to update the server
// with that status. The *only* reason we would come back here in that case
// is if our last server update attempt failed.
if (last_job_details_.status == cloud_print::PRINT_JOB_STATUS_COMPLETED) {
need_update = true;
} else {
cloud_print::PrintJobDetails details;
if (print_system_->GetJobDetails(printer_name_, local_job_id_,
&details)) {
if (details != last_job_details_) {
last_job_details_ = details;
need_update = true;
}
} else {
// If GetJobDetails failed, the most likely case is that the job no
// longer exists in the OS queue. We are going to assume it is done in
// this case.
last_job_details_.Clear();
last_job_details_.status = cloud_print::PRINT_JOB_STATUS_COMPLETED;
need_update = true;
}
}
if (need_update) {
request_ = new CloudPrintURLFetcher;
request_->StartGetRequest(
CloudPrintHelpers::GetUrlForJobStatusUpdate(
cloud_print_server_url_, job_id_, last_job_details_),
this, auth_token_, kCloudPrintAPIMaxRetryCount);
}
}
}
void JobStatusUpdater::Stop() {
request_ = NULL;
DCHECK(delegate_);
stopped_ = true;
delegate_->OnJobCompleted(this);
}
// CloudPrintURLFetcher::Delegate implementation.
CloudPrintURLFetcher::ResponseAction JobStatusUpdater::HandleJSONData(
const URLFetcher* source,
const GURL& url,
DictionaryValue* json_data,
bool succeeded) {
if (last_job_details_.status == cloud_print::PRINT_JOB_STATUS_COMPLETED) {
MessageLoop::current()->PostTask(
FROM_HERE, NewRunnableMethod(this, &JobStatusUpdater::Stop));
}
return CloudPrintURLFetcher::STOP_PROCESSING;
}
void JobStatusUpdater::OnRequestAuthError() {
if (delegate_)
delegate_->OnAuthError();
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include <map>
#include <boost/version.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <leveldb/env.h>
#include <leveldb/cache.h>
#include <leveldb/filter_policy.h>
#include <memenv/memenv.h>
#include "kernel.h"
#include "checkpoints.h"
#include "txdb.h"
#include "util.h"
#include "main.h"
using namespace std;
using namespace boost;
leveldb::DB *txdb; // global pointer for LevelDB object instance
static leveldb::Options GetOptions() {
leveldb::Options options;
int nCacheSizeMB = GetArgInt("-dbcache", 25);
options.block_cache = leveldb::NewLRUCache(nCacheSizeMB * 1048576);
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
return options;
}
void init_blockindex(leveldb::Options& options, bool fRemoveOld = false) {
// First time init.
filesystem::path directory = GetDataDir() / "txleveldb";
if (fRemoveOld) {
filesystem::remove_all(directory); // remove directory
unsigned int nFile = 1;
while (true)
{
filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile);
// Break if no such file
if( !filesystem::exists( strBlockFile ) )
break;
filesystem::remove(strBlockFile);
nFile++;
}
}
filesystem::create_directory(directory);
printf("Opening LevelDB in %s\n", directory.string().c_str());
leveldb::Status status = leveldb::DB::Open(options, directory.string(), &txdb);
if (!status.ok()) {
throw runtime_error(strprintf("init_blockindex(): error opening database environment %s", status.ToString().c_str()));
}
}
// CDB subclasses are created and destroyed VERY OFTEN. That's why
// we shouldn't treat this as a free operations.
CTxDB::CTxDB(const char* pszMode)
{
assert(pszMode);
activeBatch = NULL;
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
if (txdb) {
pdb = txdb;
return;
}
bool fCreate = strchr(pszMode, 'c');
options = GetOptions();
options.create_if_missing = fCreate;
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
init_blockindex(options); // Init directory
pdb = txdb;
if (Exists(string("version")))
{
ReadVersion(nVersion);
printf("Transaction index version is %d\n", nVersion);
if (nVersion < DATABASE_VERSION)
{
printf("Required index version is %d, removing old database\n", DATABASE_VERSION);
// Leveldb instance destruction
delete txdb;
txdb = pdb = NULL;
delete activeBatch;
activeBatch = NULL;
init_blockindex(options, true); // Remove directory and create new database
pdb = txdb;
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(DATABASE_VERSION); // Save transaction index version
fReadOnly = fTmp;
}
}
else if (fCreate)
{
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(DATABASE_VERSION);
fReadOnly = fTmp;
}
printf("Opened LevelDB successfully\n");
}
void CTxDB::Close()
{
delete txdb;
txdb = pdb = NULL;
delete options.filter_policy;
options.filter_policy = NULL;
delete options.block_cache;
options.block_cache = NULL;
delete activeBatch;
activeBatch = NULL;
}
bool CTxDB::TxnBegin()
{
assert(!activeBatch);
activeBatch = new leveldb::WriteBatch();
return true;
}
bool CTxDB::TxnCommit()
{
assert(activeBatch);
leveldb::Status status = pdb->Write(leveldb::WriteOptions(), activeBatch);
delete activeBatch;
activeBatch = NULL;
if (!status.ok()) {
printf("LevelDB batch commit failure: %s\n", status.ToString().c_str());
return false;
}
return true;
}
class CBatchScanner : public leveldb::WriteBatch::Handler {
public:
std::string needle;
bool *deleted;
std::string *foundValue;
bool foundEntry;
CBatchScanner() : foundEntry(false) {}
virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) {
if (key.ToString() == needle) {
foundEntry = true;
*deleted = false;
*foundValue = value.ToString();
}
}
virtual void Delete(const leveldb::Slice& key) {
if (key.ToString() == needle) {
foundEntry = true;
*deleted = true;
}
}
};
// When performing a read, if we have an active batch we need to check it first
// before reading from the database, as the rest of the code assumes that once
// a database transaction begins reads are consistent with it. It would be good
// to change that assumption in future and avoid the performance hit, though in
// practice it does not appear to be large.
bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) const {
assert(activeBatch);
*deleted = false;
CBatchScanner scanner;
scanner.needle = key.str();
scanner.deleted = deleted;
scanner.foundValue = value;
leveldb::Status status = activeBatch->Iterate(&scanner);
if (!status.ok()) {
throw runtime_error(status.ToString());
}
return scanner.foundEntry;
}
bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
{
assert(!fClient);
txindex.SetNull();
return Read(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
{
assert(!fClient);
return Write(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
{
assert(!fClient);
// Add to tx index
uint256 hash = tx.GetHash();
CTxIndex txindex(pos, tx.vout.size());
return Write(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::EraseTxIndex(const CTransaction& tx)
{
assert(!fClient);
uint256 hash = tx.GetHash();
return Erase(make_pair(string("tx"), hash));
}
bool CTxDB::ContainsTx(uint256 hash)
{
assert(!fClient);
return Exists(make_pair(string("tx"), hash));
}
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
{
assert(!fClient);
tx.SetNull();
if (!ReadTxIndex(hash, txindex))
return false;
return (tx.ReadFromDisk(txindex.pos));
}
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
{
CTxIndex txindex;
return ReadDiskTx(hash, tx, txindex);
}
bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
{
return ReadDiskTx(outpoint.hash, tx, txindex);
}
bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
{
CTxIndex txindex;
return ReadDiskTx(outpoint.hash, tx, txindex);
}
bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
}
bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
{
return Read(string("hashBestChain"), hashBestChain);
}
bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
{
return Write(string("hashBestChain"), hashBestChain);
}
bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
{
return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
}
bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
{
return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
}
bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
{
return Read(string("hashSyncCheckpoint"), hashCheckpoint);
}
bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
{
return Write(string("hashSyncCheckpoint"), hashCheckpoint);
}
bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
{
return Read(string("strCheckpointPubKey"), strPubKey);
}
bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
{
return Write(string("strCheckpointPubKey"), strPubKey);
}
bool CTxDB::ReadModifierUpgradeTime(unsigned int& nUpgradeTime)
{
return Read(string("nUpgradeTime"), nUpgradeTime);
}
bool CTxDB::WriteModifierUpgradeTime(const unsigned int& nUpgradeTime)
{
return Write(string("nUpgradeTime"), nUpgradeTime);
}
static CBlockIndex *InsertBlockIndex(uint256 hash)
{
if (hash == 0)
return NULL;
// Return existing
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool CTxDB::LoadBlockIndex()
{
if (mapBlockIndex.size() > 0) {
// Already loaded once in this session. It can happen during migration
// from BDB.
return true;
}
// The block index is an in-memory structure that maps hashes to on-disk
// locations where the contents of the block can be found. Here, we scan it
// out of the DB and into mapBlockIndex.
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
// Seek to start key.
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
ssStartKey << make_pair(string("blockindex"), uint256(0));
iterator->Seek(ssStartKey.str());
// Now read each entry.
while (iterator->Valid())
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(iterator->key().data(), iterator->key().size());
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(iterator->value().data(), iterator->value().size());
string strType;
ssKey >> strType;
// Did we reach the end of the data to read?
if (fRequestShutdown || strType != "blockindex")
break;
CDiskBlockIndex diskindex;
ssValue >> diskindex;
uint256 blockHash = diskindex.GetBlockHash();
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(blockHash);
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
pindexNew->nFile = diskindex.nFile;
pindexNew->nBlockPos = diskindex.nBlockPos;
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nMint = diskindex.nMint;
pindexNew->nMoneySupply = diskindex.nMoneySupply;
pindexNew->nFlags = diskindex.nFlags;
pindexNew->nStakeModifier = diskindex.nStakeModifier;
pindexNew->prevoutStake = diskindex.prevoutStake;
pindexNew->nStakeTime = diskindex.nStakeTime;
pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
// Watch for genesis block
if (pindexGenesisBlock == NULL && blockHash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
pindexGenesisBlock = pindexNew;
if (!pindexNew->CheckIndex()) {
delete iterator;
return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
}
// WXCOIN: build setStakeSeen
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
iterator->Next();
}
delete iterator;
if (fRequestShutdown)
return true;
// Calculate nChainTrust
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
{
CBlockIndex* pindex = item.second;
pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
// WXCOIN: calculate stake modifier checksum
pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindex->nHeight, pindex->nStakeModifier);
}
// Load hashBestChain pointer to end of best chain
if (!ReadHashBestChain(hashBestChain))
{
if (pindexGenesisBlock == NULL)
return true;
return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
}
if (!mapBlockIndex.count(hashBestChain))
return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
pindexBest = mapBlockIndex[hashBestChain];
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexBest->nChainTrust;
printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// WXCOIN: load hashSyncCheckpoint
if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
// Load bnBestInvalidTrust, OK if it doesn't exist
CBigNum bnBestInvalidTrust;
ReadBestInvalidTrust(bnBestInvalidTrust);
nBestInvalidTrust = bnBestInvalidTrust.getuint256();
// Verify blocks in the best chain
int nCheckLevel = GetArgInt("-checklevel", 1);
int nCheckDepth = GetArgInt( "-checkblocks", 2500);
if (nCheckDepth == 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > nBestHeight)
nCheckDepth = nBestHeight;
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CBlockIndex* pindexFork = NULL;
map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
break;
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
// check level 1: verify block validity
// check level 7: verify block signature too
if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
{
printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 2: verify transaction index validity
if (nCheckLevel>1)
{
pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
mapBlockPos[pos] = pindex;
BOOST_FOREACH(const CTransaction &tx, block.vtx)
{
uint256 hashTx = tx.GetHash();
CTxIndex txindex;
if (ReadTxIndex(hashTx, txindex))
{
// check level 3: checker transaction hashes
if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
{
// either an error or a duplicate transaction
CTransaction txFound;
if (!txFound.ReadFromDisk(txindex.pos))
{
printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
else
if (txFound.GetHash() != hashTx) // not a duplicate tx
{
printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
}
// check level 4: check whether spent txouts were spent within the main chain
unsigned int nOutput = 0;
if (nCheckLevel>3)
{
BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
{
if (!txpos.IsNull())
{
pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
if (!mapBlockPos.count(posFind))
{
printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 6: check whether spent txouts were spent by a valid transaction that consume them
if (nCheckLevel>5)
{
CTransaction txSpend;
if (!txSpend.ReadFromDisk(txpos))
{
printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
else if (!txSpend.CheckTransaction())
{
printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
else
{
bool fFound = false;
BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
fFound = true;
if (!fFound)
{
printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
}
}
}
nOutput++;
}
}
}
// check level 5: check whether all prevouts are marked spent
if (nCheckLevel>4)
{
BOOST_FOREACH(const CTxIn &txin, tx.vin)
{
CTxIndex txindex;
if (ReadTxIndex(txin.prevout.hash, txindex))
if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
{
printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
}
}
}
}
}
if (pindexFork && !fRequestShutdown)
{
// Reorg back to the fork
printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
CBlock block;
if (!block.ReadFromDisk(pindexFork))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
CTxDB txdb;
block.SetBestChain(txdb, pindexFork);
}
return true;
}
|
/*!
@file
Forward declares `boost::hana::contains` and `boost::hana::in`.
@copyright Louis Dionne 2013-2016
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_FWD_CONTAINS_HPP
#define BOOST_HANA_FWD_CONTAINS_HPP
#include <boost/hana/config.hpp>
#include <boost/hana/core/when.hpp>
#include <boost/hana/functional/flip.hpp>
#include <boost/hana/functional/infix.hpp>
BOOST_HANA_NAMESPACE_BEGIN
//! Returns whether the key occurs in the structure.
//! @ingroup group-Searchable
//!
//! Given a `Searchable` structure `xs` and a `key`, `contains` returns
//! whether any of the keys of the structure is equal to the given `key`.
//! If the structure is not finite, an equal key has to appear at a finite
//! position in the structure for this method to finish. For convenience,
//! `contains` can also be applied in infix notation.
//!
//!
//! @param xs
//! The structure to search.
//!
//! @param key
//! A key to be searched for in the structure. The key has to be
//! `Comparable` with the other keys of the structure.
//!
//!
//! Example
//! -------
//! @include example/contains.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
constexpr auto contains = [](auto&& xs, auto&& key) {
return tag-dispatched;
};
#else
template <typename S, typename = void>
struct contains_impl : contains_impl<S, when<true>> { };
struct contains_t {
template <typename Xs, typename Key>
constexpr auto operator()(Xs&& xs, Key&& key) const;
};
constexpr auto contains = hana::infix(contains_t{});
#endif
//! Return whether the key occurs in the structure.
//! @ingroup group-Searchable
//!
//! Specifically, this is equivalent to `contains`, except `in` takes its
//! arguments in reverse order. Like `contains`, `in` can also be applied
//! in infix notation for increased expressiveness. This function is not a
//! method that can be overriden; it is just a convenience function
//! provided with the concept.
//!
//!
//! Example
//! -------
//! @include example/in.cpp
constexpr auto in = hana::infix(hana::flip(hana::contains));
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_FWD_CONTAINS_HPP
|
#include <iostream>
#include <climits>
using namespace std;
#define MAX 1000
void print(int arr[], int n)
{
for(int i=0; i<n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int max(int arr[], int n)
{
int max = INT_MIN;
for(int i=0; i<n; i++)
{
if(arr[i] > max)
max = arr[i];
}
return max;
}
void count_sort(int arr[], int B[], int n)
{
int i, k = max(arr, n);
int C[k+1] = {0};
for(i=0; i<n; i++)
{
C[arr[i]]+=1;
}
for(i=1; i<=k; i++)
{
C[i]+=C[i-1];
}
for(i=n-1; i>=0; i--)
{
B[C[arr[i]]-1] = arr[i];
C[arr[i]]-=1;
}
}
int main()
{
int n, *arr, *B, i, j;
cout << "///Count Sort///\n\nEnter the number of array elements: ";
cin >> n;
arr = new int[n];
B = new int[n];
cout << "Enter the array elements: ";
for(i=0; i<n; i++)
{
cin >> arr[i];
}
count_sort(arr, B, n);
cout << "The sorted array is:" << endl;
print(B, n);
delete []arr;
delete []B;
fflush(stdin);
getchar();
return 0;
}
|
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "BioStruct3D.h"
#include <U2Core/Log.h>
#include <U2Core/U2Region.h>
#include <U2Core/U2SafePoints.h>
namespace U2 {
/* class BioStruct3D */
QString BioStruct3D::MoleculeAnnotationTag("chain_info");
QString BioStruct3D::AlphaHelixAnnotationTag("alpha_helix");
QString BioStruct3D::BetaStrandAnnotationTag("beta_strand");
QString BioStruct3D::TurnAnnotationTag("turn");
QString BioStruct3D::ChainIdQualifierName("chain_id");
QString BioStruct3D::SecStructAnnotationTag("sec_struct");
QString BioStruct3D::SecStructTypeQualifierName("sec_struct_type");
BioStruct3D::BioStruct3D()
: moleculeMap(), modelMap(),
secondaryStructures(),
interMolecularBonds(),
descr(), pdbId(),
radius(0), rotationCenter(),
transform() {
transform.loadIdentity();
}
BioStruct3D::BioStruct3D(const BioStruct3D &other)
: moleculeMap(other.moleculeMap), modelMap(other.modelMap),
secondaryStructures(other.secondaryStructures),
interMolecularBonds(other.interMolecularBonds),
descr(other.descr), pdbId(other.pdbId),
radius(other.radius), rotationCenter(other.rotationCenter),
transform(other.transform) {
}
void BioStruct3D::calcCenterAndMaxDistance() {
Vector3D siteSum;
Vector3D center;
double dist;
radius = 0.0;
int numberOfAtoms = 0;
// loop trough all atoms twice - once to get average center, then once to
// find max distance from this center
for (int i = 0; i < 2; ++i) {
foreach (SharedMolecule molecule, moleculeMap) {
foreach (Molecule3DModel model3d, molecule->models.values()) {
foreach (const AtomData *atom, model3d.atoms) {
Vector3D site = atom->coord3d;
if (i == 0) {
siteSum += atom->coord3d;
++numberOfAtoms;
} else {
dist = (site - center).length();
if (dist > radius) {
radius = dist;
}
}
}
}
}
if (i == 0) {
if (numberOfAtoms == 0) {
algoLog.trace("Number of atoms is 0!");
} else {
center = siteSum / numberOfAtoms;
}
}
}
algoLog.trace(QString("center: (%1,%2,%3)\n maxDistFromCenter: %4").arg(center.x).arg(center.y).arg(center.z).arg(radius));
rotationCenter = center;
}
int BioStruct3D::getNumberOfAtoms() const {
// get first coordinates set
const AtomCoordSet &coordSet = modelMap.begin().value();
return coordSet.count();
}
QList<SharedAtom> BioStruct3D::getAllAtoms() const {
const AtomCoordSet &coordSet = modelMap.begin().value();
return coordSet.values();
}
QMap<int, QList<SharedAnnotationData>> BioStruct3D::generateAnnotations() const {
QMap<int, QList<SharedAnnotationData>> result = generateChainAnnotations();
generateSecStructureAnnotations(result);
return result;
}
QMap<int, QList<SharedAnnotationData>> BioStruct3D::generateChainAnnotations() const {
QMap<int, QList<SharedAnnotationData>> result;
const char *molNameQualifier = "molecule_name";
//const char* pdbChainIdQualifier = "pdb_id";
QMap<int, SharedMolecule>::ConstIterator iter = moleculeMap.constBegin();
while (iter != moleculeMap.end()) {
int length = iter.value()->residueMap.size();
SharedAnnotationData sd(new AnnotationData);
sd->location->regions << U2Region(0, length);
sd->name = BioStruct3D::MoleculeAnnotationTag;
if ((*iter)->chainId > 0) {
sd->qualifiers.append(U2Qualifier(ChainIdQualifierName, QString("%1").arg((*iter)->chainId)));
}
if (!(*iter)->name.isEmpty()) {
sd->qualifiers.append(U2Qualifier(molNameQualifier, (*iter)->name));
}
result[iter.key()].append(sd);
++iter;
}
return result;
}
int BioStruct3D::getNumberOfResidues() const {
int numResidues = 0;
foreach (SharedMolecule mol, moleculeMap) {
numResidues += mol->residueMap.size();
}
return numResidues;
}
const SharedAtom BioStruct3D::getAtomById(int atomIndex, int modelIndex) const {
if (modelMap.contains(modelIndex)) {
const AtomCoordSet &coordSet = modelMap.value(modelIndex);
if (coordSet.contains(atomIndex)) {
return coordSet.value(atomIndex);
}
}
return SharedAtom(NULL);
}
const SharedResidue BioStruct3D::getResidueById(int chainIndex, ResidueIndex residueIndex) const {
const SharedMolecule mol = moleculeMap.value(chainIndex);
foreach (const ResidueIndex &id, mol->residueMap.keys()) {
if (id.toInt() == residueIndex.toInt()) {
return mol->residueMap.value(id);
}
}
return SharedResidue(NULL);
}
const QString BioStruct3D::getSecStructTypeName(SecondaryStructure::Type type) {
switch (type) {
case SecondaryStructure::Type_AlphaHelix:
return BioStruct3D::AlphaHelixAnnotationTag;
case SecondaryStructure::Type_PiHelix:
return "pi_helix";
case SecondaryStructure::Type_310Helix:
return "310_helix";
case SecondaryStructure::Type_BetaStrand:
return BioStruct3D::BetaStrandAnnotationTag;
case SecondaryStructure::Type_BetaBridge:
return "beta_bridge";
case SecondaryStructure::Type_Turn:
return BioStruct3D::TurnAnnotationTag;
case SecondaryStructure::Type_BendRegion:
return "bend_region";
default:
return QString("unknown");
}
}
void BioStruct3D::generateSecStructureAnnotations(QMap<int, QList<SharedAnnotationData>> &result) const {
// TODO: issue 0000637
if (moleculeMap.isEmpty())
return;
foreach (const SharedSecondaryStructure &struc, secondaryStructures) {
SharedAnnotationData sd(NULL);
int chainId = struc->chainIndex;
assert(chainId != 0);
int initResidueId = moleculeMap.value(chainId)->residueMap.constBegin().key().toInt();
sd = new AnnotationData;
sd->name = BioStruct3D::SecStructAnnotationTag;
U2Qualifier qual(SecStructTypeQualifierName, getSecStructTypeName(struc->type));
sd->qualifiers.append(qual);
int numResidues = struc->endSequenceNumber - struc->startSequenceNumber + 1;
// TODO: determine why can it happen and fix if it's a bug
if (numResidues < 0) {
continue;
}
int startIndex = struc->startSequenceNumber - initResidueId;
U2Region chainRegion(startIndex, numResidues);
sd->location->regions << chainRegion;
Q_ASSERT(moleculeMap.contains(chainId));
result[chainId].append(sd);
}
}
QByteArray BioStruct3D::getRawSequenceByChainIndex(int id) const {
QByteArray sequence("");
SAFE_POINT(moleculeMap.contains(id), QString("Can't find chain identifier for index: %1").arg(id), sequence);
const SharedMolecule molecule = moleculeMap.value(id);
foreach (const SharedResidue residue, molecule->residueMap) {
QChar c = residue->acronym;
sequence.append(c);
}
return sequence;
}
char BioStruct3D::getChainIdByIndex(int index) const {
SAFE_POINT(moleculeMap.contains(index), QString("Can't find chain identifier for index: %1").arg(index), 0);
return moleculeMap.value(index)->chainId;
}
int BioStruct3D::getIndexByChainId(char chainId) const {
foreach (int curIndex, moleculeMap.keys()) {
const SharedMolecule molecule = moleculeMap.value(curIndex);
if (molecule->chainId == chainId) {
return curIndex;
}
}
return -1;
}
const QList<int> BioStruct3D::getModelsNames() const {
return modelMap.keys();
}
const Molecule3DModel BioStruct3D::getModelByName(int moleculeId, int name) const {
int index = modelMap.keys().indexOf(name);
assert(index != -1 && "invalid model id");
return getModelByIndex(moleculeId, index);
}
const Molecule3DModel BioStruct3D::getModelByIndex(int moleculeId, int index) const {
return moleculeMap[moleculeId]->models[index];
}
void BioStruct3D::setRadius(double value) {
radius = value;
}
void BioStruct3D::setCenter(const Vector3D &value) {
rotationCenter = value;
}
/* class U2CORE_EXPORT BioStruct3DChainSelection */
BioStruct3DChainSelection::BioStruct3DChainSelection(const BioStruct3D &biostruct_)
: biostruct(biostruct_), data(new BioStruct3DChainSelectionData()) {
}
BioStruct3DChainSelection::BioStruct3DChainSelection(const BioStruct3DChainSelection &other)
: biostruct(other.biostruct), data(other.data) {
}
bool BioStruct3DChainSelection::inSelection(int chainId, int residueId) const {
return data->selection.contains(chainId, residueId);
}
void BioStruct3DChainSelection::add(int chain, const U2Region ®ion) {
int start = biostruct.moleculeMap[chain]->residueMap.begin().key().toInt();
for (int i = region.startPos; i < region.endPos(); ++i) {
if (!data->selection.contains(chain, start + i)) {
data->selection.insert(chain, start + i);
}
}
}
void BioStruct3DChainSelection::add(int chain, const QVector<U2Region> ®ions) {
foreach (const U2Region ®ion, regions) {
add(chain, region);
}
}
void BioStruct3DChainSelection::remove(int chain, const U2Region ®ion) {
int start = biostruct.moleculeMap[chain]->residueMap.begin().key().toInt();
for (int i = region.startPos; i < region.endPos(); ++i) {
data->selection.remove(chain, start + i);
}
}
void BioStruct3DChainSelection::remove(int chain, const QVector<U2Region> ®ions) {
foreach (const U2Region ®ion, regions) {
remove(chain, region);
}
}
void BioStruct3DChainSelection::update(int chain, const U2Region &add, const U2Region &remove) {
this->remove(chain, remove);
this->add(chain, add);
}
void BioStruct3DChainSelection::update(int chain, const QVector<U2Region> &adds, const QVector<U2Region> &removes) {
remove(chain, removes);
add(chain, adds);
}
bool ResidueIndex::operator<(const ResidueIndex &other) const {
if (order == other.order) {
if (resId == other.resId) {
return insCode < other.insCode;
} else {
return resId < other.resId;
}
} else {
return order < other.order;
}
}
bool ResidueIndex::operator==(const ResidueIndex &other) const {
return (other.insCode == insCode) && (other.resId == resId);
}
bool ResidueIndex::operator!=(const ResidueIndex &other) const {
return !(*this == other);
}
int ResidueIndex::getOrder() const {
return order;
}
char ResidueIndex::getInsCode() const {
return insCode;
}
} // namespace U2
|
#include "LogFile.h"
#include "FileUtil.h"
#include <assert.h>
#include <stdio.h>
#include <time.h>
namespace GaoServer {
LogFile::LogFile(const std::string& basename, int flushEveryN)
: basename_(basename),
flushEveryN_(flushEveryN),
count_(0),
mutex_(new MutexLock) {
file_.reset(new AppendFile(basename));
}
LogFile::~LogFile()
{ }
void LogFile::append(const char* logline, int len)
{
MutexLockGuard lock(*mutex_);
append_unlocked(logline, len);
}
void LogFile::flush()
{
MutexLockGuard lock(*mutex_);
file_->flush();
}
void LogFile::append_unlocked(const char* logline, int len)
{
file_->append(logline, len);
++count_;
if (count_ >= flushEveryN_)
{
count_ = 0;
file_->flush();
}
}
}
|
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2018 The BlastX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "multisigdialog.h"
#include "forms/ui_multisigdialog.h"
#include "askpassphrasedialog.h"
#include "primitives/transaction.h"
#include "addressbookpage.h"
#include "utilstrencodings.h"
#include "core_io.h"
#include "script/script.h"
#include "base58.h"
#include "coins.h"
#include "keystore.h"
#include "init.h"
#include "wallet.h"
#include "script/sign.h"
#include "script/interpreter.h"
#include "utilmoneystr.h"
#include "guiutil.h"
#include "qvalidatedlineedit.h"
#include "bitcoinamountfield.h"
#include <QtCore/QVariant>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpinBox>
#include <QClipboard>
MultisigDialog::MultisigDialog(QWidget* parent) : QDialog(parent),
ui(new Ui::MultisigDialog),
model(0)
{
ui->setupUi(this);
multisigTx = CMutableTransaction();
//flag to show keyScrollArea on first priv key added
isFirstPrivKey = true;
isFirstRawTx = true;
ui->keyScrollArea->hide();
ui->txInputsScrollArea->hide();
connect(ui->commitButton, SIGNAL(clicked()), this, SLOT(commitMultisigTx()));
//populate lists with initial objects
on_addAddressButton_clicked();
on_addAddressButton_clicked();
on_addDestinationButton_clicked();
this->setStyleSheet(GUIUtil::loadStyleSheet());
}
MultisigDialog::~MultisigDialog()
{
delete ui;
}
void MultisigDialog::setModel(WalletModel *model)
{
this->model = model;
}
void MultisigDialog::showTab(int index)
{
ui->multisigTabWidget->setCurrentIndex(index);
this->show();
}
void MultisigDialog::updateCoinControl(CAmount nAmount, unsigned int nQuantity)
{
ui->labelAmount_int->setText(QString::fromStdString(FormatMoney(nAmount)));
ui->labelQuantity_int->setText(QString::number(nQuantity));
}
/**
* Private Slots
*/
//slot for pasting addresses
void MultisigDialog::pasteText()
{
QWidget* pasteButton = qobject_cast<QWidget*>(sender());
if(!pasteButton)return;
QFrame* addressFrame = qobject_cast<QFrame*>(pasteButton->parentWidget());
if(!addressFrame)return;
QValidatedLineEdit* vle = addressFrame->findChild<QValidatedLineEdit*>("address");
if(!vle)return;
vle->setText(QApplication::clipboard()->text());
}
//slot for deleting QFrames with the delete buttons
void MultisigDialog::deleteFrame()
{
QWidget *buttonWidget = qobject_cast<QWidget*>(sender());
if(!buttonWidget)return;
//if deleting last raw input/priv key, hide scroll area
if(buttonWidget->objectName() == "inputDeleteButton" && ui->inputsList->count() == 1){
isFirstRawTx = true;
ui->txInputsScrollArea->hide();
}else if(buttonWidget->objectName() == "keyDeleteButton" && ui->keyList->count() == 1){
isFirstPrivKey = true;
ui->keyScrollArea->hide();
}
QFrame* frame = qobject_cast<QFrame*>(buttonWidget->parentWidget());
if(!frame)return;
delete frame;
}
//slot to open address book dialog
void MultisigDialog::addressBookButtonReceiving()
{
QWidget* addressButton = qobject_cast<QWidget*>(sender());
if(!addressButton)return;
QFrame* addressFrame = qobject_cast<QFrame*>(addressButton->parentWidget());
if(!addressFrame)return;
QValidatedLineEdit* vle = addressFrame->findChild<QValidatedLineEdit*>("address");
if(!vle)return;
if (model && model->getAddressTableModel()) {
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec()) {
vle->setText(dlg.getReturnValue());
}
}
}
//create address
void MultisigDialog::on_addMultisigButton_clicked()
{
if(!model)
return;
int m = ui->enterMSpinbox->value();
vector<string> keys;
for (int i = 0; i < ui->addressList->count(); i++) {
QWidget* address = qobject_cast<QWidget*>(ui->addressList->itemAt(i)->widget());
QValidatedLineEdit* vle = address->findChild<QValidatedLineEdit*>("address");
if(!vle->text().isEmpty()){
keys.push_back(vle->text().toStdString());
}
}
addMultisig(m, keys);
}
void MultisigDialog::on_importAddressButton_clicked(){
if(!model)
return;
string sRedeem = ui->importRedeem->text().toStdString();
if(sRedeem.empty()){
ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }");
ui->addMultisigStatus->setText("Import box empty!");
return;
}
vector<string> vRedeem;
size_t pos = 0;
//search redeem input delimited by space
while ((pos = sRedeem.find(" ")) != std::string::npos) {
vRedeem.push_back(sRedeem.substr(0, pos));
sRedeem.erase(0, pos + 1);
}
vector<string> keys(vRedeem.begin()+1, vRedeem.end()-1);
addMultisig(stoi(vRedeem[0]), keys);
// rescan to find txs associated with imported address
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
pwalletMain->ReacceptWalletTransactions();
}
bool MultisigDialog::addMultisig(int m, vector<string> keys){
try{
string error;
CScript redeem;
if(!createRedeemScript(m, keys, redeem, error)){
throw runtime_error(error.data());
}
if (::IsMine(*pwalletMain, redeem) == ISMINE_SPENDABLE){
throw runtime_error("The wallet already contains this script");
}
if(!pwalletMain->AddCScript(redeem)){
throw runtime_error("Failure: address invalid or already exists");
}
CScriptID innerID(redeem);
string label = ui->multisigAddressLabel->text().toStdString();
pwalletMain->SetAddressBook(innerID, label, "receive");
if (!pwalletMain->AddMultiSig(redeem)){
throw runtime_error("Failure: unable to add address as watch only");
}
ui->addMultisigStatus->setStyleSheet("QLabel { color: black; }");
ui->addMultisigStatus->setText("Multisignature address " +
QString::fromStdString(CBitcoinAddress(innerID).ToString()) +
" has been added to the wallet.\nSend the redeem below for other owners to import:\n" +
QString::fromStdString(redeem.ToString()));
}catch(const runtime_error& e) {
ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }");
ui->addMultisigStatus->setText(tr(e.what()));
return false;
}
return true;
}
//spend
void MultisigDialog::on_createButton_clicked()
{
if(!model)
return;
vector<CTxIn> vUserIn;
vector<CTxOut> vUserOut;
try{
//Add inputs from Coin Control if any are selected
if (CoinControlDialog::coinControl->HasSelected()) {
vector<COutPoint> vSelected;
CoinControlDialog::coinControl->ListSelected(vSelected);
for (auto outpoint : vSelected)
vUserIn.emplace_back(CTxIn(outpoint));
}else{//check for raw inputs
for(int i = 0; i < ui->inputsList->count(); i++){
QWidget* input = qobject_cast<QWidget*>(ui->inputsList->itemAt(i)->widget());
QLineEdit* txIdLine = input->findChild<QLineEdit*>("txInputId");
if(txIdLine->text().isEmpty()){
ui->createButtonStatus->setStyleSheet("QLabel { color: red; }");
ui->createButtonStatus->setText(tr("Invalid Tx Hash."));
return;
}
QSpinBox* txVoutLine = input->findChild<QSpinBox*>("txInputVout");
int nOutput = txVoutLine->value();
if(nOutput < 0){
ui->createButtonStatus->setStyleSheet("QLabel { color: red; }");
ui->createButtonStatus->setText(tr("Vout position must be positive."));
return;
}
uint256 txid = uint256S(txIdLine->text().toStdString());
CTxIn in(COutPoint(txid, nOutput));
vUserIn.emplace_back(in);
}
}
//validate destinations
bool validInput = true;
for(int i = 0; i < ui->destinationsList->count(); i++){
QWidget* dest = qobject_cast<QWidget*>(ui->destinationsList->itemAt(i)->widget());
QValidatedLineEdit* addr = dest->findChild<QValidatedLineEdit*>("destinationAddress");
BitcoinAmountField* amt = dest->findChild<BitcoinAmountField*>("destinationAmount");
CBitcoinAddress address;
bool validDest = true;
if(!model->validateAddress(addr->text())){
addr->setValid(false);
validDest = false;
}else{
address = CBitcoinAddress(addr->text().toStdString());
}
if(!amt->validate()){
amt->setValid(false);
validDest = false;
}
if(!validDest){
validInput = false;
continue;
}
CScript scriptPubKey = GetScriptForDestination(address.Get());
CTxOut out(amt->value(), scriptPubKey);
vUserOut.push_back(out);
}
//if all user data valid create a multisig tx
if(validInput){
//clear member variable
multisigTx = CMutableTransaction();
string error;
string fee;
if(!createMultisigTransaction(vUserIn, vUserOut, fee, error)){
throw runtime_error(error);
}
//display status string
ui->createButtonStatus->setStyleSheet("QTextEdit{ color: black }");
QString status(strprintf("Transaction has successfully created with a fee of %s.\n"
"The transaction has been automatically imported to the sign tab.\n"
"Please continue on to sign the tx from this wallet, to access the hex to send to other owners.", fee).c_str());
ui->createButtonStatus->setText(status);
ui->transactionHex->setText(QString::fromStdString(EncodeHexTx(multisigTx)));
}
}catch(const runtime_error& e){
ui->createButtonStatus->setStyleSheet("QTextEdit{ color: red }");
ui->createButtonStatus->setText(tr(e.what()));
}
}
bool MultisigDialog::createMultisigTransaction(vector<CTxIn> vUserIn, vector<CTxOut> vUserOut, string& feeStringRet, string& errorRet)
{
try{
//attempt to access the given inputs
CCoinsViewCache view = getInputsCoinsViewCache(vUserIn);
//retrieve total input val and change dest
CAmount totalIn = 0;
vector<CAmount> vInputVals;
CScript changePubKey;
bool fFirst = true;
for(CTxIn in : vUserIn){
const CCoins* coins = view.AccessCoins(in.prevout.hash);
if(!coins->IsAvailable(in.prevout.n) || coins == NULL){
continue;
}
CTxOut prevout = coins->vout[in.prevout.n];
CScript privKey = prevout.scriptPubKey;
vInputVals.push_back(prevout.nValue);
totalIn += prevout.nValue;
if(!fFirst){
if(privKey != changePubKey){
throw runtime_error("Address mismatch! Inputs must originate from the same multisignature address.");
}
}else{
fFirst = false;
changePubKey = privKey;
}
}
CAmount totalOut = 0;
//retrieve total output val
for(CTxOut out : vUserOut){
totalOut += out.nValue;
}
if(totalIn < totalOut){
throw runtime_error("Not enough BLAST provided as input to complete transaction (including fee).");
}
//calculate change amount
CAmount changeAmount = totalIn - totalOut;
CTxOut change(changeAmount, changePubKey);
//generate random position for change
unsigned int changeIndex = rand() % (vUserOut.size() + 1);
//insert change into random position
if(changeIndex < vUserOut.size()){
vUserOut.insert(vUserOut.begin() + changeIndex, change);
}else{
vUserOut.emplace_back(change);
}
//populate tx
CMutableTransaction tx;
tx.vin = vUserIn;
tx.vout = vUserOut;
const CCoins* coins = view.AccessCoins(tx.vin[0].prevout.hash);
if(coins == NULL || !coins->IsAvailable(tx.vin[0].prevout.n)){
throw runtime_error("Coins unavailable (unconfirmed/spent)");
}
CScript prevPubKey = coins->vout[tx.vin[0].prevout.n].scriptPubKey;
//get payment destination
CTxDestination address;
if(!ExtractDestination(prevPubKey, address)){
throw runtime_error("Could not find address for destination.");
}
CScriptID hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (!pwalletMain->GetCScript(hash, redeemScript)){
throw runtime_error("could not redeem");
}
txnouttype type;
vector<CTxDestination> addresses;
int nReq;
if(!ExtractDestinations(redeemScript, type, addresses, nReq)){
throw runtime_error("Could not extract destinations from redeem script.");
}
for(CTxIn& in : tx.vin){
in.scriptSig.clear();
//scale estimate to account for multisig scriptSig
for(unsigned int i = 0; i < 50*(nReq+addresses.size()); i++){
in.scriptSig << INT64_MAX;
}
}
//calculate fee
unsigned int nBytes = tx.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
CAmount fee = ::minRelayTxFee.GetFee(nBytes);
if(tx.vout.at(changeIndex).nValue > fee){
tx.vout.at(changeIndex).nValue -= fee;
feeStringRet = strprintf("%d",((double)fee)/COIN).c_str();
}else{
throw runtime_error("Not enough BLAST provided to cover fee");
}
//clear junk from script sigs
for(CTxIn& in : tx.vin){
in.scriptSig.clear();
}
multisigTx = tx;
}catch(const runtime_error& e){
errorRet = e.what();
return false;
}
return true;
}
//sign
void MultisigDialog::on_signButton_clicked()
{
if(!model)
return;
try{
//parse tx hex
CTransaction txRead;
if(!DecodeHexTx(txRead, ui->transactionHex->text().toStdString())){
throw runtime_error("Failed to decode transaction hex!");
}
CMutableTransaction tx(txRead);
//check if transaction is already fully verified
if(isFullyVerified(tx)){
this->multisigTx = tx;
ui->commitButton->setEnabled(true);
ui->signButtonStatus->setText("This transaction is ready to commit. \nThe commit button in now enabled.");
return;
}
string errorOut = string();
bool fComplete = signMultisigTx(tx, errorOut, ui->keyList);
if(!errorOut.empty()){
throw runtime_error(errorOut.data());
}else{
this->multisigTx = tx;
}
ui->signButtonStatus->setStyleSheet("QTextEdit{ color: black }");
ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx));
}catch(const runtime_error& e){
ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }");
ui->signButtonStatus->setText(tr(e.what()));
}
}
/***
*private helper functions
*/
QString MultisigDialog::buildMultisigTxStatusString(bool fComplete, const CMutableTransaction& tx)
{
string sTxHex = EncodeHexTx(tx);
if(fComplete){
ui->commitButton->setEnabled(true);
string sTxId = tx.GetHash().GetHex();
string sTxComplete = "Complete: true!\n"
"The commit button has now been enabled for you to finalize the transaction.\n"
"Once the commit button is clicked, the transaction will be published and coins transferred "
"to their destinations.\nWARNING: THE ACTIONS OF THE COMMIT BUTTON ARE FINAL AND CANNOT BE REVERSED.";
return QString(strprintf("%s\nTx Id:\n%s\nTx Hex:\n%s",sTxComplete, sTxId, sTxHex).c_str());
} else {
string sTxIncomplete = "Complete: false.\n"
"You may now send the hex below to another owner to sign.\n"
"Keep in mind the transaction must be passed from one owner to the next for signing.\n"
"Ensure all owners have imported the redeem before trying to sign. (besides creator)";
return QString(strprintf("%s\nTx Hex: %s", sTxIncomplete, sTxHex).c_str());
}
}
CCoinsViewCache MultisigDialog::getInputsCoinsViewCache(const vector<CTxIn>& vin)
{
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache& viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
for(const CTxIn& txin : vin) {
const uint256& prevHash = txin.prevout.hash;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
return view;
}
bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, QVBoxLayout* keyList)
{
//will be set false if all inputs are not fully signed(valid)
bool fComplete = true;
//if keyslist is not default value AND has items in list then true
bool fGivenKeys = (keyList != nullptr) && (keyList->count() > 0);
try{
//copy of vin for reference before vin is mutated
vector<CTxIn> oldVin(tx.vin);
CBasicKeyStore privKeystore;
//if keys were given, attempt to collect redeem and scriptpubkey
if(fGivenKeys){
for(int i = 0; i < keyList->count(); i++){
QWidget* keyFrame = qobject_cast<QWidget*>(keyList->itemAt(i)->widget());
QLineEdit* key = keyFrame->findChild<QLineEdit*>("key");
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(key->text().toStdString()))
throw runtime_error("Invalid private key");
CKey cKey = vchSecret.GetKey();
if (!cKey.IsValid())
throw runtime_error("Private key outside allowed range");
privKeystore.AddKey(cKey);
}
for(CTxIn& txin : tx.vin){
//get inputs
CTransaction txVin;
uint256 hashBlock;
if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true))
throw runtime_error("txin could not be found");
if (hashBlock == 0)
throw runtime_error("txin is unconfirmed");
//get pubkey from input
CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey;
//get payment destination
CTxDestination address;
if(!ExtractDestination(prevPubKey, address)){
throw runtime_error("Could not find address for destination.");
}
//get redeem script related to destination
CScriptID hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (!pwalletMain->GetCScript(hash, redeemScript)){
errorOut = "could not redeem";
}
privKeystore.AddCScript(redeemScript);
}
}else{
if (model->getEncryptionStatus() == model->Locked) {
if (!model->requestUnlock(true).isValid()) {
// Unlock wallet was cancelled
throw runtime_error("Error: Your wallet is locked. Please enter the wallet passphrase first.");
}
}
}
//choose between local wallet and provided
const CKeyStore& keystore = fGivenKeys ? privKeystore : *pwalletMain;
//attempt to sign each input from local wallet
int nIn = 0;
for(CTxIn& txin : tx.vin){
//get inputs
CTransaction txVin;
uint256 hashBlock;
if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true))
throw runtime_error("txin could not be found");
if (hashBlock == 0)
throw runtime_error("txin is unconfirmed");
txin.scriptSig.clear();
CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey;
//sign what we can
SignSignature(keystore, prevPubKey, tx, nIn);
//merge in any previous signatures
txin.scriptSig = CombineSignatures(prevPubKey, tx, nIn, txin.scriptSig, oldVin[nIn].scriptSig);
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&tx, nIn))){
fComplete = false;
}
nIn++;
}
ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx));
}catch(const runtime_error& e){
errorOut = string(e.what());
fComplete = false;
}
return fComplete;
}
// quick check for an already fully signed tx
bool MultisigDialog::isFullyVerified(CMutableTransaction& tx){
try{
int nIn = 0;
for(CTxIn& txin : tx.vin){
CTransaction txVin;
uint256 hashBlock;
if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)){
throw runtime_error("txin could not be found");
}
if (hashBlock == 0){
throw runtime_error("txin is unconfirmed");
}
//get pubkey from this input as output in last tx
CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey;
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&tx, nIn))){
return false;
}
nIn++;
}
}catch(const runtime_error& e){
return false;
}
return true;
}
void MultisigDialog::commitMultisigTx()
{
CMutableTransaction tx(multisigTx);
try{
#ifdef ENABLE_WALLET
CWalletTx wtx(pwalletMain, tx);
CReserveKey keyChange(pwalletMain);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw runtime_error(string("Transaction rejected - Failed to commit"));
#else
uint256 hashTx = tx.GetHash();
CCoinsViewCache& view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fOverrideFees = false;
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) {
if (state.IsInvalid())
throw runtime_error(strprintf("Transaction rejected - %i: %s", state.GetRejectCode(), state.GetRejectReason()));
else
throw runtime_error(string("Transaction rejected - ") + state.GetRejectReason());
}
} else if (fHaveChain) {
throw runtime_error("transaction already in block chain");
}
RelayTransaction(tx);
#endif
//disable commit if successfully committed
ui->commitButton->setEnabled(false);
ui->signButtonStatus->setText(strprintf("Transaction has been successfully published with transaction ID:\n %s", tx.GetHash().GetHex()).c_str());
}catch(const runtime_error& e){
ui->signButtonStatus->setText(e.what());
}
}
bool MultisigDialog::createRedeemScript(int m, vector<string> vKeys, CScript& redeemRet, string& errorRet)
{
try{
int n = vKeys.size();
//gather pub keys
if (n < 1)
throw runtime_error("a Multisignature address must require at least one key to redeem");
if (n < m)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %d keys, but need at least %d to redeem)",
m, n));
if (n > 15)
throw runtime_error("Number of addresses involved in the Multisignature address creation > 15\nReduce the number");
vector<CPubKey> pubkeys;
pubkeys.resize(n);
int i = 0;
for(vector<string>::iterator it = vKeys.begin(); it != vKeys.end(); ++it) {
string keyString = *it;
#ifdef ENABLE_WALLET
// Case 1: BlastX address and we have full public key:
CBitcoinAddress address(keyString);
if (pwalletMain && address.IsValid()) {
CKeyID keyID;
if (!address.GetKeyID(keyID)) {
throw runtime_error(
strprintf("%s does not refer to a key", keyString));
}
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s", keyString));
if (!vchPubKey.IsFullyValid()){
string sKey = keyString.empty()?"(empty)":keyString;
throw runtime_error(" Invalid public key: " + sKey );
}
pubkeys[i++] = vchPubKey;
}
//case 2: hex pub key
else
#endif
if (IsHex(keyString)) {
CPubKey vchPubKey(ParseHex(keyString));
if (!vchPubKey.IsFullyValid()){
throw runtime_error(" Invalid public key: " + keyString);
}
pubkeys[i++] = vchPubKey;
} else {
throw runtime_error(" Invalid public key: " + keyString);
}
}
//populate redeem script
//OP_N for required signatures
redeemRet << redeemRet.EncodeOP_N(m);
//public keys
for(CPubKey& key : pubkeys){
vector<unsigned char> vKey= ToByteVector(key);
redeemRet << vKey;
}
//OP_N for total pubkeys
redeemRet << redeemRet.EncodeOP_N(pubkeys.size());
redeemRet << OP_CHECKMULTISIG;
return true;
}catch(const runtime_error& e){
errorRet = string(e.what());
return false;
}
}
/***
* Begin QFrame object creation methods
*/
//creates an address object on the create tab
void MultisigDialog::on_addAddressButton_clicked()
{
//max addresses 15
if(ui->addressList->count() > 14){
ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }");
ui->addMultisigStatus->setText(tr("Maximum possible addresses reached. (16)"));
return;
}
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
QFrame* addressFrame = new QFrame();
sizePolicy.setHeightForWidth(addressFrame->sizePolicy().hasHeightForWidth());
addressFrame->setSizePolicy(sizePolicy);
addressFrame->setFrameShape(QFrame::StyledPanel);
addressFrame->setFrameShadow(QFrame::Raised);
addressFrame->setObjectName(QStringLiteral("addressFrame"));
QVBoxLayout* frameLayout = new QVBoxLayout(addressFrame);
frameLayout->setSpacing(1);
frameLayout->setObjectName(QStringLiteral("frameLayout"));
frameLayout->setContentsMargins(6, 6, 6, 6);
QHBoxLayout* addressLayout = new QHBoxLayout();
addressLayout->setSpacing(0);
addressLayout->setObjectName(QStringLiteral("addressLayout"));
QLabel* addressLabel = new QLabel(addressFrame);
addressLabel->setObjectName(QStringLiteral("addressLabel"));
addressLabel->setText(QApplication::translate("MultisigDialog", strprintf("Address / Key %i:", ui->addressList->count()+1).c_str() , 0));
addressLayout->addWidget(addressLabel);
QValidatedLineEdit* address = new QValidatedLineEdit(addressFrame);
address->setObjectName(QStringLiteral("address"));
addressLayout->addWidget(address);
QPushButton* addressBookButton = new QPushButton(addressFrame);
addressBookButton->setObjectName(QStringLiteral("addressBookButton"));
QIcon icon3;
icon3.addFile(QStringLiteral(":/icons/address-book"), QSize(), QIcon::Normal, QIcon::Off);
addressBookButton->setIcon(icon3);
addressBookButton->setAutoDefault(false);
connect(addressBookButton, SIGNAL(clicked()), this, SLOT(addressBookButtonReceiving()));
addressLayout->addWidget(addressBookButton);
QPushButton* addressPasteButton = new QPushButton(addressFrame);
addressPasteButton->setObjectName(QStringLiteral("addressPasteButton"));
QIcon icon4;
icon4.addFile(QStringLiteral(":/icons/editpaste"), QSize(), QIcon::Normal, QIcon::Off);
addressPasteButton->setIcon(icon4);
addressPasteButton->setAutoDefault(false);
connect(addressPasteButton, SIGNAL(clicked()), this, SLOT(pasteText()));
addressLayout->addWidget(addressPasteButton);
QPushButton* addressDeleteButton = new QPushButton(addressFrame);
addressDeleteButton->setObjectName(QStringLiteral("addressDeleteButton"));
QIcon icon5;
icon5.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
addressDeleteButton->setIcon(icon5);
addressDeleteButton->setAutoDefault(false);
connect(addressDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame()));
addressLayout->addWidget(addressDeleteButton);
frameLayout->addLayout(addressLayout);
ui->addressList->addWidget(addressFrame);
}
void MultisigDialog::on_pushButtonCoinControl_clicked()
{
CoinControlDialog coinControlDialog(this, true);
coinControlDialog.setModel(model);
coinControlDialog.exec();
}
void MultisigDialog::on_addInputButton_clicked()
{
if(isFirstRawTx){
isFirstRawTx = false;
ui->txInputsScrollArea->show();
}
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
QFrame* txInputFrame = new QFrame(ui->txInputsWidget);
sizePolicy.setHeightForWidth(txInputFrame->sizePolicy().hasHeightForWidth());
txInputFrame->setFrameShape(QFrame::StyledPanel);
txInputFrame->setFrameShadow(QFrame::Raised);
txInputFrame->setObjectName(QStringLiteral("txInputFrame"));
QVBoxLayout* frameLayout = new QVBoxLayout(txInputFrame);
frameLayout->setSpacing(1);
frameLayout->setObjectName(QStringLiteral("txInputFrameLayout"));
frameLayout->setContentsMargins(6, 6, 6, 6);
QHBoxLayout* txInputLayout = new QHBoxLayout();
txInputLayout->setObjectName(QStringLiteral("txInputLayout"));
QLabel* txInputIdLabel = new QLabel(txInputFrame);
txInputIdLabel->setObjectName(QStringLiteral("txInputIdLabel"));
txInputIdLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Tx Hash: ", ui->inputsList->count()+1).c_str(), 0));
txInputLayout->addWidget(txInputIdLabel);
QLineEdit* txInputId = new QLineEdit(txInputFrame);
txInputId->setObjectName(QStringLiteral("txInputId"));
txInputLayout->addWidget(txInputId);
QSpacerItem* horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);
txInputLayout->addItem(horizontalSpacer);
QLabel* txInputVoutLabel = new QLabel(txInputFrame);
txInputVoutLabel->setObjectName(QStringLiteral("txInputVoutLabel"));
txInputVoutLabel->setText(QApplication::translate("MultisigDialog", "Vout Position: ", 0));
txInputLayout->addWidget(txInputVoutLabel);
QSpinBox* txInputVout = new QSpinBox(txInputFrame);
txInputVout->setObjectName("txInputVout");
sizePolicy.setHeightForWidth(txInputVout->sizePolicy().hasHeightForWidth());
txInputVout->setSizePolicy(sizePolicy);
txInputLayout->addWidget(txInputVout);
QPushButton* inputDeleteButton = new QPushButton(txInputFrame);
inputDeleteButton->setObjectName(QStringLiteral("inputDeleteButton"));
QIcon icon;
icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
inputDeleteButton->setIcon(icon);
inputDeleteButton->setAutoDefault(false);
connect(inputDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame()));
txInputLayout->addWidget(inputDeleteButton);
frameLayout->addLayout(txInputLayout);
ui->inputsList->addWidget(txInputFrame);
}
void MultisigDialog::on_addDestinationButton_clicked()
{
QFrame* destinationFrame = new QFrame(ui->destinationsScrollAreaContents);
destinationFrame->setObjectName(QStringLiteral("destinationFrame"));
destinationFrame->setFrameShape(QFrame::StyledPanel);
destinationFrame->setFrameShadow(QFrame::Raised);
QVBoxLayout* frameLayout = new QVBoxLayout(destinationFrame);
frameLayout->setObjectName(QStringLiteral("destinationFrameLayout"));
QHBoxLayout* destinationLayout = new QHBoxLayout();
destinationLayout->setSpacing(0);
destinationLayout->setObjectName(QStringLiteral("destinationLayout"));
QLabel* destinationAddressLabel = new QLabel(destinationFrame);
destinationAddressLabel->setObjectName(QStringLiteral("destinationAddressLabel"));
destinationLayout->addWidget(destinationAddressLabel);
QValidatedLineEdit* destinationAddress = new QValidatedLineEdit(destinationFrame);
destinationAddress->setObjectName(QStringLiteral("destinationAddress"));
destinationLayout->addWidget(destinationAddress);
QSpacerItem* horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);
destinationLayout->addItem(horizontalSpacer);
QLabel* destinationAmountLabel = new QLabel(destinationFrame);
destinationAmountLabel->setObjectName(QStringLiteral("destinationAmountLabel"));
destinationLayout->addWidget(destinationAmountLabel);
BitcoinAmountField* destinationAmount = new BitcoinAmountField(destinationFrame);
destinationAmount->setObjectName(QStringLiteral("destinationAmount"));
destinationAddressLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Address: ", ui->destinationsList->count()+1).c_str(), 0));
destinationAmountLabel->setText(QApplication::translate("MultisigDialog", "Amount: ", 0));
destinationLayout->addWidget(destinationAmount);
QPushButton* destinationDeleteButton = new QPushButton(destinationFrame);
destinationDeleteButton->setObjectName(QStringLiteral("destinationDeleteButton"));
QIcon icon;
icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
destinationDeleteButton->setIcon(icon);
destinationDeleteButton->setAutoDefault(false);
connect(destinationDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame()));
destinationLayout->addWidget(destinationDeleteButton);
frameLayout->addLayout(destinationLayout);
ui->destinationsList->addWidget(destinationFrame);
}
void MultisigDialog::on_addPrivKeyButton_clicked()
{
if(isFirstPrivKey){//on first click the scroll area must show
isFirstPrivKey = false;
ui->keyScrollArea->show();
}
if(ui->keyList->count() > 14){
ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }");
ui->signButtonStatus->setText(tr("Maximum (15)"));
return;
}
QFrame* keyFrame = new QFrame(ui->keyScrollAreaContents);
keyFrame->setObjectName(QStringLiteral("keyFrame"));
keyFrame->setFrameShape(QFrame::StyledPanel);
keyFrame->setFrameShadow(QFrame::Raised);
QHBoxLayout* keyLayout = new QHBoxLayout(keyFrame);
keyLayout->setObjectName(QStringLiteral("keyLayout"));
QLabel* keyLabel = new QLabel(keyFrame);
keyLabel->setObjectName(QStringLiteral("keyLabel"));
keyLabel->setText(QApplication::translate("MultisigDialog", strprintf("Key %i: ", (ui->keyList->count()+1)).c_str(), 0));
keyLayout->addWidget(keyLabel);
QLineEdit* key = new QLineEdit(keyFrame);
key->setObjectName(QStringLiteral("key"));
key->setEchoMode(QLineEdit::Password);
keyLayout->addWidget(key);
QPushButton* keyDeleteButton = new QPushButton(keyFrame);
keyDeleteButton->setObjectName(QStringLiteral("keyDeleteButton"));
QIcon icon;
icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
keyDeleteButton->setIcon(icon);
keyDeleteButton->setAutoDefault(false);
connect(keyDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame()));
keyLayout->addWidget(keyDeleteButton);
ui->keyList->addWidget(keyFrame);
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Canonicalizer functions for working with and resolving relative URLs.
#include <lib/syslog/cpp/macros.h>
#include <iostream>
#include "src/lib/url/url_canon.h"
#include "src/lib/url/url_canon_internal.h"
#include "src/lib/url/url_constants.h"
#include "src/lib/url/url_file.h"
#include "src/lib/url/url_parse_internal.h"
#include "src/lib/url/url_util_internal.h"
namespace url {
namespace {
// Firefox does a case-sensitive compare (which is probably wrong--Mozilla bug
// 379034), whereas IE is case-insensitive.
//
// We choose to be more permissive like IE. We don't need to worry about
// unescaping or anything here: neither IE or Firefox allow this. We also
// don't have to worry about invalid scheme characters since we are comparing
// against the canonical scheme of the base.
//
// The base URL should always be canonical, therefore it should be ASCII.
bool AreSchemesEqual(const char* base, const Component& base_scheme, const char* cmp,
const Component& cmp_scheme) {
if (base_scheme.len() != cmp_scheme.len())
return false;
for (size_t i = 0; i < base_scheme.len(); i++) {
// We assume the base is already canonical, so we don't have to
// canonicalize it.
if (CanonicalSchemeChar(cmp[cmp_scheme.begin + i]) != base[base_scheme.begin + i])
return false;
}
return true;
}
// Copies all characters in the range [begin, end) of |spec| to the output,
// up until and including the last slash. There should be a slash in the
// range, if not, nothing will be copied.
//
// For stardard URLs the input should be canonical, but when resolving relative
// URLs on a non-standard base (like "data:") the input can be anything.
void CopyToLastSlash(const char* spec, int begin, int end, CanonOutput* output) {
// Find the last slash.
int last_slash = -1;
for (int i = end - 1; i >= begin; i--) {
if (spec[i] == '/' || spec[i] == '\\') {
last_slash = i;
break;
}
}
if (last_slash < 0)
return; // No slash.
// Copy.
for (int i = begin; i <= last_slash; i++)
output->push_back(spec[i]);
}
// Copies a single component from the source to the output. This is used
// when resolving relative URLs and a given component is unchanged. Since the
// source should already be canonical, we don't have to do anything special,
// and the input is ASCII.
void CopyOneComponent(const char* source, const Component& source_component, CanonOutput* output,
Component* output_component) {
if (!source_component.is_valid()) {
// This component is not present.
*output_component = Component();
return;
}
output_component->begin = output->length();
int source_end = source_component.end();
for (int i = source_component.begin; i < source_end; i++)
output->push_back(source[i]);
output_component->set_len(output->length() - output_component->begin);
}
// A subroutine of DoResolveRelativeURL, this resolves the URL knowning that
// the input is a relative path or less (qyuery or ref).
bool DoResolveRelativePath(const char* base_url, const Parsed& base_parsed, bool base_is_file,
const char* relative_url, const Component& relative_component,
CharsetConverter* query_converter, CanonOutput* output,
Parsed* out_parsed) {
bool success = true;
// We know the authority section didn't change, copy it to the output. We
// also know we have a path so can copy up to there.
Component path, query, ref;
ParsePathInternal(relative_url, relative_component, &path, &query, &ref);
// Canonical URLs always have a path, so we can use that offset.
output->Append(base_url, base_parsed.path.begin);
if (path.is_nonempty()) {
// The path is replaced or modified.
int true_path_begin = output->length();
int base_path_begin = base_parsed.path.begin;
if (IsURLSlash(relative_url[path.begin])) {
// Easy case: the path is an absolute path on the server, so we can
// just replace everything from the path on with the new versions.
// Since the input should be canonical hierarchical URL, we should
// always have a path.
success &= CanonicalizePath(relative_url, path, output, &out_parsed->path);
} else {
// Relative path, replace the query, and reference. We take the
// original path with the file part stripped, and append the new path.
// The canonicalizer will take care of resolving ".." and "."
int path_begin = output->length();
CopyToLastSlash(base_url, base_path_begin, base_parsed.path.end(), output);
success &= CanonicalizePartialPath(relative_url, path, path_begin, output);
out_parsed->path = MakeRange(path_begin, output->length());
// Copy the rest of the stuff after the path from the relative path.
}
// Finish with the query and reference part (these can't fail).
CanonicalizeQuery(relative_url, query, query_converter, output, &out_parsed->query);
CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
// Fix the path beginning to add back the "C:" we may have written above.
out_parsed->path = MakeRange(true_path_begin, out_parsed->path.end());
return success;
}
// If we get here, the path is unchanged: copy to output.
CopyOneComponent(base_url, base_parsed.path, output, &out_parsed->path);
if (query.is_valid()) {
// Just the query specified, replace the query and reference (ignore
// failures for refs)
CanonicalizeQuery(relative_url, query, query_converter, output, &out_parsed->query);
CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
return success;
}
// If we get here, the query is unchanged: copy to output. Note that the
// range of the query parameter doesn't include the question mark, so we
// have to add it manually if there is a component.
if (base_parsed.query.is_valid())
output->push_back('?');
CopyOneComponent(base_url, base_parsed.query, output, &out_parsed->query);
if (ref.is_valid()) {
// Just the reference specified: replace it (ignoring failures).
CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
return success;
}
// We should always have something to do in this function, the caller checks
// that some component is being replaced.
FX_DCHECK(false) << "Not reached";
return success;
}
// Resolves a relative URL that happens to be an absolute file path. Examples
// include: "//hostname/path", "/c:/foo", and "//hostname/c:/foo".
bool DoResolveAbsoluteFile(const char* relative_url, const Component& relative_component,
CharsetConverter* query_converter, CanonOutput* output,
Parsed* out_parsed) {
// Parse the file URL. The file URl parsing function uses the same logic
// as we do for determining if the file is absolute, in which case it will
// not bother to look for a scheme.
Parsed relative_parsed;
ParseFileURL(&relative_url[relative_component.begin], relative_component.len(), &relative_parsed);
return CanonicalizeFileURL(&relative_url[relative_component.begin], relative_component.len(),
relative_parsed, query_converter, output, out_parsed);
}
} // namespace
// See IsRelativeURL in the header file for usage.
bool IsRelativeURL(const char* base, const Parsed& base_parsed, const char* url, size_t url_len,
bool is_base_hierarchical, bool* is_relative, Component* relative_component) {
*is_relative = false; // So we can default later to not relative.
// Trim whitespace and construct a new range for the substring.
size_t begin = 0;
TrimURL(url, &begin, &url_len);
if (begin >= url_len) {
// Empty URLs are relative, but do nothing.
*relative_component = Component(begin, 0);
*is_relative = true;
return true;
}
// See if we've got a scheme, if not, we know this is a relative URL.
// BUT, just because we have a scheme, doesn't make it absolute.
// "http:foo.html" is a relative URL with path "foo.html". If the scheme is
// empty, we treat it as relative (":foo"), like IE does.
Component scheme;
const bool scheme_is_empty = !ExtractScheme(url, url_len, &scheme) || scheme.len() == 0;
if (scheme_is_empty) {
if (url[begin] == '#') {
// |url| is a bare fragment (e.g. "#foo"). This can be resolved against
// any base. Fall-through.
} else if (!is_base_hierarchical) {
// Don't allow relative URLs if the base scheme doesn't support it.
return false;
}
*relative_component = MakeRange(begin, url_len);
*is_relative = true;
return true;
}
// If the scheme isn't valid, then it's relative.
int scheme_end = scheme.end();
for (int i = scheme.begin; i < scheme_end; i++) {
if (!CanonicalSchemeChar(url[i])) {
if (!is_base_hierarchical) {
// Don't allow relative URLs if the base scheme doesn't support it.
return false;
}
*relative_component = MakeRange(begin, url_len);
*is_relative = true;
return true;
}
}
// If the scheme is not the same, then we can't count it as relative.
if (!AreSchemesEqual(base, base_parsed.scheme, url, scheme))
return true;
// When the scheme that they both share is not hierarchical, treat the
// incoming scheme as absolute (this way with the base of "data:foo",
// "data:bar" will be reported as absolute.
if (!is_base_hierarchical)
return true;
size_t colon_offset = scheme.end();
// ExtractScheme guarantees that the colon immediately follows what it
// considers to be the scheme. CountConsecutiveSlashes will handle the
// case where the begin offset is the end of the input.
size_t num_slashes = CountConsecutiveSlashes(url, colon_offset + 1, url_len);
if (num_slashes == 0 || num_slashes == 1) {
// No slashes means it's a relative path like "http:foo.html". One slash
// is an absolute path. "http:/home/foo.html"
*is_relative = true;
*relative_component = MakeRange(colon_offset + 1, url_len);
return true;
}
// Two or more slashes after the scheme we treat as absolute.
return true;
}
// TODO(brettw) treat two slashes as root like Mozilla for FTP?
bool ResolveRelativeURL(const char* base_url, const Parsed& base_parsed, bool base_is_file,
const char* relative_url, const Component& relative_component,
CharsetConverter* query_converter, CanonOutput* output,
Parsed* out_parsed) {
// Starting point for our output parsed. We'll fix what we change.
*out_parsed = base_parsed;
// Sanity check: the input should have a host or we'll break badly below.
// We can only resolve relative URLs with base URLs that have hosts and
// paths (even the default path of "/" is OK).
//
// We allow hosts with no length so we can handle file URLs, for example.
if (base_parsed.path.is_invalid_or_empty()) {
// On error, return the input (resolving a relative URL on a non-relative
// base = the base).
size_t base_len = base_parsed.Length();
for (size_t i = 0; i < base_len; i++)
output->push_back(base_url[i]);
return false;
}
if (relative_component.is_invalid_or_empty()) {
// Empty relative URL, leave unchanged, only removing the ref component.
size_t base_len = base_parsed.Length();
if (base_parsed.ref.is_valid()) {
base_len -= base_parsed.ref.len() + 1;
}
out_parsed->ref.reset();
output->Append(base_url, base_len);
return true;
}
size_t num_slashes =
CountConsecutiveSlashes(relative_url, relative_component.begin, relative_component.end());
// Other platforms need explicit handling for file: URLs with multiple
// slashes because the generic scheme parsing always extracts a host, but a
// file: URL only has a host if it has exactly 2 slashes. Even if it does
// have a host, we want to use the special host detection logic for file
// URLs provided by DoResolveAbsoluteFile(), as opposed to the generic host
// detection logic, for consistency with parsing file URLs from scratch.
// This also handles the special case where the URL is only slashes,
// since that doesn't have a host part either.
if (base_is_file && (num_slashes >= 2 || num_slashes == relative_component.len())) {
return DoResolveAbsoluteFile(relative_url, relative_component, query_converter, output,
out_parsed);
}
// Any other double-slashes mean that this is relative to the scheme.
if (num_slashes >= 2) {
// Make & parse an url with base_url's scheme and everything else from
// relative_url.
std::string new_url;
new_url.reserve(base_parsed.scheme.len() + 1 + relative_component.len());
new_url.append(&base_url[base_parsed.scheme.begin], base_parsed.scheme.len());
new_url.push_back(':');
new_url.append(&relative_url[relative_component.begin], relative_component.len());
Parsed new_parsed;
ParseStandardURL(new_url.c_str(), new_url.size(), &new_parsed);
// Canonicalize the combined url.
return CanonicalizeStandardURL(new_url.c_str(), new_url.size(), new_parsed, query_converter,
output, out_parsed);
}
// When we get here, we know that the relative URL is on the same host.
return DoResolveRelativePath(base_url, base_parsed, base_is_file, relative_url,
relative_component, query_converter, output, out_parsed);
}
} // namespace url
|
#include <QtCharts/QChartView>
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QWidget>
#include <QObject>
#include "graphic.h"
QT_CHARTS_USE_NAMESPACE
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow window;
Graphic *graphic = new Graphic;
QChartView chartView(graphic);
chartView.setRenderHint(QPainter::Antialiasing);
window.setCentralWidget(&chartView);
window.resize(600, 300);
window.show();
return a.exec();
}
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/dms-enterprise/model/GetMetaTableDetailInfoResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dms_enterprise;
using namespace AlibabaCloud::Dms_enterprise::Model;
GetMetaTableDetailInfoResult::GetMetaTableDetailInfoResult() :
ServiceResult()
{}
GetMetaTableDetailInfoResult::GetMetaTableDetailInfoResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetMetaTableDetailInfoResult::~GetMetaTableDetailInfoResult()
{}
void GetMetaTableDetailInfoResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto detailInfoNode = value["DetailInfo"];
auto allColumnListNode = detailInfoNode["ColumnList"]["Column"];
for (auto detailInfoNodeColumnListColumn : allColumnListNode)
{
DetailInfo::Column columnObject;
if(!detailInfoNodeColumnListColumn["Description"].isNull())
columnObject.description = detailInfoNodeColumnListColumn["Description"].asString();
if(!detailInfoNodeColumnListColumn["ColumnType"].isNull())
columnObject.columnType = detailInfoNodeColumnListColumn["ColumnType"].asString();
if(!detailInfoNodeColumnListColumn["Position"].isNull())
columnObject.position = detailInfoNodeColumnListColumn["Position"].asString();
if(!detailInfoNodeColumnListColumn["DataLength"].isNull())
columnObject.dataLength = std::stoi(detailInfoNodeColumnListColumn["DataLength"].asString());
if(!detailInfoNodeColumnListColumn["Nullable"].isNull())
columnObject.nullable = detailInfoNodeColumnListColumn["Nullable"].asString() == "true";
if(!detailInfoNodeColumnListColumn["ColumnName"].isNull())
columnObject.columnName = detailInfoNodeColumnListColumn["ColumnName"].asString();
if(!detailInfoNodeColumnListColumn["AutoIncrement"].isNull())
columnObject.autoIncrement = detailInfoNodeColumnListColumn["AutoIncrement"].asString() == "true";
if(!detailInfoNodeColumnListColumn["DataPrecision"].isNull())
columnObject.dataPrecision = std::stoi(detailInfoNodeColumnListColumn["DataPrecision"].asString());
if(!detailInfoNodeColumnListColumn["DataScale"].isNull())
columnObject.dataScale = std::stoi(detailInfoNodeColumnListColumn["DataScale"].asString());
if(!detailInfoNodeColumnListColumn["ColumnId"].isNull())
columnObject.columnId = detailInfoNodeColumnListColumn["ColumnId"].asString();
detailInfo_.columnList.push_back(columnObject);
}
auto allIndexListNode = detailInfoNode["IndexList"]["Index"];
for (auto detailInfoNodeIndexListIndex : allIndexListNode)
{
DetailInfo::Index indexObject;
if(!detailInfoNodeIndexListIndex["IndexName"].isNull())
indexObject.indexName = detailInfoNodeIndexListIndex["IndexName"].asString();
if(!detailInfoNodeIndexListIndex["IndexType"].isNull())
indexObject.indexType = detailInfoNodeIndexListIndex["IndexType"].asString();
if(!detailInfoNodeIndexListIndex["Unique"].isNull())
indexObject.unique = detailInfoNodeIndexListIndex["Unique"].asString() == "true";
if(!detailInfoNodeIndexListIndex["IndexId"].isNull())
indexObject.indexId = detailInfoNodeIndexListIndex["IndexId"].asString();
auto allIndexColumns = value["IndexColumns"]["ColumnNames"];
for (auto value : allIndexColumns)
indexObject.indexColumns.push_back(value.asString());
detailInfo_.indexList.push_back(indexObject);
}
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["ErrorMessage"].isNull())
errorMessage_ = value["ErrorMessage"].asString();
if(!value["ErrorCode"].isNull())
errorCode_ = value["ErrorCode"].asString();
}
GetMetaTableDetailInfoResult::DetailInfo GetMetaTableDetailInfoResult::getDetailInfo()const
{
return detailInfo_;
}
std::string GetMetaTableDetailInfoResult::getErrorCode()const
{
return errorCode_;
}
std::string GetMetaTableDetailInfoResult::getErrorMessage()const
{
return errorMessage_;
}
bool GetMetaTableDetailInfoResult::getSuccess()const
{
return success_;
}
|
#include "duckdb/function/aggregate/distributive_functions.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/common/types/null_value.hpp"
#include "duckdb/common/vector_operations/vector_operations.hpp"
using namespace std;
namespace duckdb {
struct CountOperator {
template <class STATE_TYPE> static inline void Operation(STATE_TYPE state) {
(*state)++;
}
};
static void countstar_update(Vector inputs[], idx_t input_count, Vector &addresses) {
// add one to each address
auto states = (int64_t **)addresses.GetData();
VectorOperations::Exec(addresses, [&](idx_t i, idx_t k) { states[i][0]++; });
}
static void countstar_simple_update(Vector inputs[], idx_t input_count, data_ptr_t state_) {
// count star: just add the count
auto state = (int64_t *)state_;
*state += inputs[0].size();
}
static void count_update(Vector inputs[], idx_t input_count, Vector &addresses) {
auto &input = inputs[0];
if (input.vector_type == VectorType::CONSTANT_VECTOR) {
// constant input
if (!input.nullmask[0]) {
// constant NULL
countstar_update(inputs, input_count, addresses);
}
return;
}
// regular input: first normalize
input.Normalify();
// now check nullmask
if (!input.nullmask.any()) {
// no null values, perform regular count(*) update
countstar_update(inputs, input_count, addresses);
return;
}
auto states = (int64_t **)addresses.GetData();
VectorOperations::Exec(input, [&](idx_t i, idx_t k) {
if (!input.nullmask[i]) {
states[i][0]++;
}
});
}
static void count_combine(Vector &state, Vector &combined) {
VectorOperations::Scatter::Add(state, combined);
}
static void count_simple_update(Vector inputs[], idx_t input_count, data_ptr_t state_) {
auto state = (int64_t *)state_;
auto &input = inputs[0];
if (input.vector_type == VectorType::CONSTANT_VECTOR) {
// constant vector, check if it is a constant NULL
// if not, add the results
if (!input.nullmask[0]) {
*state += input.size();
}
} else {
// other vector type: normalify first
input.Normalify();
if (input.nullmask.any()) {
// NULL values, count the amount of NULL entries
VectorOperations::Exec(input, [&](idx_t i, idx_t k) {
if (!input.nullmask[i]) {
(*state)++;
}
});
} else {
// no NULL values, return all
*state += input.size();
}
}
}
AggregateFunction CountFun::GetFunction() {
return AggregateFunction({SQLType(SQLTypeId::ANY)}, SQLType::BIGINT, get_bigint_type_size,
bigint_payload_initialize, count_update, count_combine, gather_finalize,
count_simple_update);
}
AggregateFunction CountStarFun::GetFunction() {
return AggregateFunction("count_star", {SQLType(SQLTypeId::ANY)}, SQLType::BIGINT, get_bigint_type_size,
bigint_payload_initialize, countstar_update, count_combine, gather_finalize,
countstar_simple_update);
}
void CountFun::RegisterFunction(BuiltinFunctions &set) {
AggregateFunction count_function = CountFun::GetFunction();
AggregateFunctionSet count("count");
count.AddFunction(count_function);
// the count function can also be called without arguments
count_function.arguments.clear();
count.AddFunction(count_function);
set.AddFunction(count);
}
void CountStarFun::RegisterFunction(BuiltinFunctions &set) {
set.AddFunction(CountStarFun::GetFunction());
}
} // namespace duckdb
|
/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(ossrs)
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.
*/
#include <srs_app_server.hpp>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <algorithm>
using namespace std;
#include <srs_kernel_log.hpp>
#include <srs_kernel_error.hpp>
#include <srs_app_rtmp_conn.hpp>
#include <srs_app_config.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_app_http_api.hpp>
#include <srs_app_http_conn.hpp>
#include <srs_app_ingest.hpp>
#include <srs_app_source.hpp>
#include <srs_app_utility.hpp>
#include <srs_app_heartbeat.hpp>
#include <srs_app_bitch.hpp>
#include <srs_app_mpegts_udp.hpp>
#include <srs_app_rtsp.hpp>
#include <srs_app_statistic.hpp>
#include <srs_app_caster_flv.hpp>
#include <srs_core_mem_watch.hpp>
// signal defines.
#define SIGNAL_RELOAD SIGHUP
// system interval in ms,
// all resolution times should be times togother,
// for example, system-interval is x=1s(1000ms),
// then rusage can be 3*x, for instance, 3*1=3s,
// the meminfo canbe 6*x, for instance, 6*1=6s,
// for performance refine, @see: https://github.com/ossrs/srs/issues/194
// @remark, recomment to 1000ms.
#define SRS_SYS_CYCLE_INTERVAL 1000
// update time interval:
// SRS_SYS_CYCLE_INTERVAL * SRS_SYS_TIME_RESOLUTION_MS_TIMES
// @see SYS_TIME_RESOLUTION_US
#define SRS_SYS_TIME_RESOLUTION_MS_TIMES 1
// update rusage interval:
// SRS_SYS_CYCLE_INTERVAL * SRS_SYS_RUSAGE_RESOLUTION_TIMES
#define SRS_SYS_RUSAGE_RESOLUTION_TIMES 3
// update network devices info interval:
// SRS_SYS_CYCLE_INTERVAL * SRS_SYS_NETWORK_RTMP_SERVER_RESOLUTION_TIMES
#define SRS_SYS_NETWORK_RTMP_SERVER_RESOLUTION_TIMES 3
// update rusage interval:
// SRS_SYS_CYCLE_INTERVAL * SRS_SYS_CPU_STAT_RESOLUTION_TIMES
#define SRS_SYS_CPU_STAT_RESOLUTION_TIMES 3
// update the disk iops interval:
// SRS_SYS_CYCLE_INTERVAL * SRS_SYS_DISK_STAT_RESOLUTION_TIMES
#define SRS_SYS_DISK_STAT_RESOLUTION_TIMES 6
// update rusage interval:
// SRS_SYS_CYCLE_INTERVAL * SRS_SYS_MEMINFO_RESOLUTION_TIMES
#define SRS_SYS_MEMINFO_RESOLUTION_TIMES 6
// update platform info interval:
// SRS_SYS_CYCLE_INTERVAL * SRS_SYS_PLATFORM_INFO_RESOLUTION_TIMES
#define SRS_SYS_PLATFORM_INFO_RESOLUTION_TIMES 9
// update network devices info interval:
// SRS_SYS_CYCLE_INTERVAL * SRS_SYS_NETWORK_DEVICE_RESOLUTION_TIMES
#define SRS_SYS_NETWORK_DEVICE_RESOLUTION_TIMES 9
std::string srs_listener_type2string(SrsListenerType type)
{
switch (type) {
case SrsListenerRtmpStream:
return "RTMP";
case SrsListenerHttpApi:
return "HTTP-API";
case SrsListenerHttpStream:
return "HTTP-Server";
case SrsListenerMpegTsOverUdp:
return "MPEG-TS over UDP";
case SrsListenerRtsp:
return "RTSP";
case SrsListenerFlv:
return "HTTP-FLV";
default:
return "UNKONWN";
}
}
SrsListener::SrsListener(SrsServer* svr, SrsListenerType t)
{
port = 0;
server = svr;
type = t;
}
SrsListener::~SrsListener()
{
}
SrsListenerType SrsListener::listen_type()
{
return type;
}
SrsStreamListener::SrsStreamListener(SrsServer* svr, SrsListenerType t) : SrsListener(svr, t)
{
listener = NULL;
}
SrsStreamListener::~SrsStreamListener()
{
srs_freep(listener);
}
int SrsStreamListener::listen(string i, int p)
{
int ret = ERROR_SUCCESS;
ip = i;
port = p;
srs_freep(listener);
listener = new SrsTcpListener(this, ip, port);
if ((ret = listener->listen()) != ERROR_SUCCESS) {
srs_error("tcp listen failed. ret=%d", ret);
return ret;
}
srs_info("listen thread current_cid=%d, "
"listen at port=%d, type=%d, fd=%d started success, ep=%s:%d",
_srs_context->get_id(), p, type, listener->fd(), i.c_str(), p);
srs_trace("%s listen at tcp://%s:%d, fd=%d", srs_listener_type2string(type).c_str(), ip.c_str(), port, listener->fd());
return ret;
}
int SrsStreamListener::on_tcp_client(st_netfd_t stfd)
{
int ret = ERROR_SUCCESS;
if ((ret = server->accept_client(type, stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
return ret;
}
return ret;
}
#ifdef SRS_AUTO_STREAM_CASTER
SrsRtspListener::SrsRtspListener(SrsServer* svr, SrsListenerType t, SrsConfDirective* c) : SrsListener(svr, t)
{
listener = NULL;
// the caller already ensure the type is ok,
// we just assert here for unknown stream caster.
srs_assert(type == SrsListenerRtsp);
if (type == SrsListenerRtsp) {
caster = new SrsRtspCaster(c);
}
}
SrsRtspListener::~SrsRtspListener()
{
srs_freep(caster);
srs_freep(listener);
}
int SrsRtspListener::listen(string i, int p)
{
int ret = ERROR_SUCCESS;
// the caller already ensure the type is ok,
// we just assert here for unknown stream caster.
srs_assert(type == SrsListenerRtsp);
ip = i;
port = p;
srs_freep(listener);
listener = new SrsTcpListener(this, ip, port);
if ((ret = listener->listen()) != ERROR_SUCCESS) {
srs_error("rtsp caster listen failed. ret=%d", ret);
return ret;
}
srs_info("listen thread, current_cid=%d, "
"listen at port=%d, type=%d, fd=%d started success, ep=%s:%d",
_srs_context->get_id(), port, type, fd, ip.c_str(), port);
srs_trace("%s listen at tcp://%s:%d, fd=%d", srs_listener_type2string(type).c_str(), ip.c_str(), port, listener->fd());
return ret;
}
int SrsRtspListener::on_tcp_client(st_netfd_t stfd)
{
int ret = ERROR_SUCCESS;
if ((ret = caster->on_tcp_client(stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
return ret;
}
return ret;
}
SrsHttpFlvListener::SrsHttpFlvListener(SrsServer* svr, SrsListenerType t, SrsConfDirective* c) : SrsListener(svr, t)
{
listener = NULL;
// the caller already ensure the type is ok,
// we just assert here for unknown stream caster.
srs_assert(type == SrsListenerFlv);
if (type == SrsListenerFlv) {
caster = new SrsAppCasterFlv(c);
}
}
SrsHttpFlvListener::~SrsHttpFlvListener()
{
srs_freep(caster);
srs_freep(listener);
}
int SrsHttpFlvListener::listen(string i, int p)
{
int ret = ERROR_SUCCESS;
// the caller already ensure the type is ok,
// we just assert here for unknown stream caster.
srs_assert(type == SrsListenerFlv);
ip = i;
port = p;
if ((ret = caster->initialize()) != ERROR_SUCCESS) {
return ret;
}
srs_freep(listener);
listener = new SrsTcpListener(this, ip, port);
if ((ret = listener->listen()) != ERROR_SUCCESS) {
srs_error("flv caster listen failed. ret=%d", ret);
return ret;
}
srs_info("listen thread, current_cid=%d, "
"listen at port=%d, type=%d, fd=%d started success, ep=%s:%d",
_srs_context->get_id(), port, type, fd, ip.c_str(), port);
srs_trace("%s listen at tcp://%s:%d, fd=%d", srs_listener_type2string(type).c_str(), ip.c_str(), port, listener->fd());
return ret;
}
int SrsHttpFlvListener::on_tcp_client(st_netfd_t stfd)
{
int ret = ERROR_SUCCESS;
if ((ret = caster->on_tcp_client(stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
return ret;
}
return ret;
}
#endif
SrsUdpStreamListener::SrsUdpStreamListener(SrsServer* svr, SrsListenerType t, ISrsUdpHandler* c) : SrsListener(svr, t)
{
listener = NULL;
caster = c;
}
SrsUdpStreamListener::~SrsUdpStreamListener()
{
srs_freep(listener);
}
int SrsUdpStreamListener::listen(string i, int p)
{
int ret = ERROR_SUCCESS;
// the caller already ensure the type is ok,
// we just assert here for unknown stream caster.
srs_assert(type == SrsListenerMpegTsOverUdp);
ip = i;
port = p;
srs_freep(listener);
listener = new SrsUdpListener(caster, ip, port);
if ((ret = listener->listen()) != ERROR_SUCCESS) {
srs_error("udp caster listen failed. ret=%d", ret);
return ret;
}
srs_info("listen thread current_cid=%d, "
"listen at port=%d, type=%d, fd=%d started success, ep=%s:%d",
_srs_context->get_id(), p, type, listener->fd(), i.c_str(), p);
// notify the handler the fd changed.
if ((ret = caster->on_stfd_change(listener->stfd())) != ERROR_SUCCESS) {
srs_error("notify handler fd changed. ret=%d", ret);
return ret;
}
srs_trace("%s listen at udp://%s:%d, fd=%d", srs_listener_type2string(type).c_str(), ip.c_str(), port, listener->fd());
return ret;
}
#ifdef SRS_AUTO_STREAM_CASTER
SrsUdpCasterListener::SrsUdpCasterListener(SrsServer* svr, SrsListenerType t, SrsConfDirective* c) : SrsUdpStreamListener(svr, t, NULL)
{
// the caller already ensure the type is ok,
// we just assert here for unknown stream caster.
srs_assert(type == SrsListenerMpegTsOverUdp);
if (type == SrsListenerMpegTsOverUdp) {
caster = new SrsMpegtsOverUdp(c);
}
}
SrsUdpCasterListener::~SrsUdpCasterListener()
{
srs_freep(caster);
}
#endif
SrsSignalManager* SrsSignalManager::instance = NULL;
SrsSignalManager::SrsSignalManager(SrsServer* server)
{
SrsSignalManager::instance = this;
_server = server;
sig_pipe[0] = sig_pipe[1] = -1;
pthread = new SrsEndlessThread("signal", this);
signal_read_stfd = NULL;
}
SrsSignalManager::~SrsSignalManager()
{
srs_close_stfd(signal_read_stfd);
if (sig_pipe[0] > 0) {
::close(sig_pipe[0]);
}
if (sig_pipe[1] > 0) {
::close(sig_pipe[1]);
}
srs_freep(pthread);
}
int SrsSignalManager::initialize()
{
int ret = ERROR_SUCCESS;
/* Create signal pipe */
if (pipe(sig_pipe) < 0) {
ret = ERROR_SYSTEM_CREATE_PIPE;
srs_error("create signal manager pipe failed. ret=%d", ret);
return ret;
}
if ((signal_read_stfd = st_netfd_open(sig_pipe[0])) == NULL) {
ret = ERROR_SYSTEM_CREATE_PIPE;
srs_error("create signal manage st pipe failed. ret=%d", ret);
return ret;
}
return ret;
}
int SrsSignalManager::start()
{
/**
* Note that if multiple processes are used (see below),
* the signal pipe should be initialized after the fork(2) call
* so that each process has its own private pipe.
*/
struct sigaction sa;
/* Install sig_catcher() as a signal handler */
sa.sa_handler = SrsSignalManager::sig_catcher;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGNAL_RELOAD, &sa, NULL);
sa.sa_handler = SrsSignalManager::sig_catcher;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sa.sa_handler = SrsSignalManager::sig_catcher;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
sa.sa_handler = SrsSignalManager::sig_catcher;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGUSR2, &sa, NULL);
sa.sa_handler = SrsSignalManager::sig_catcher;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGCHLD, &sa, NULL);
srs_trace("signal installed");
return pthread->start();
}
int SrsSignalManager::cycle()
{
int ret = ERROR_SUCCESS;
int signo;
/* Read the next signal from the pipe */
st_read(signal_read_stfd, &signo, sizeof(int), ST_UTIME_NO_TIMEOUT);
/* Process signal synchronously */
_server->on_signal(signo);
return ret;
}
void SrsSignalManager::sig_catcher(int signo)
{
int err;
/* Save errno to restore it after the write() */
err = errno;
/* write() is reentrant/async-safe */
int fd = SrsSignalManager::instance->sig_pipe[1];
write(fd, &signo, sizeof(int));
errno = err;
}
ISrsServerCycle::ISrsServerCycle()
{
}
ISrsServerCycle::~ISrsServerCycle()
{
}
SrsServer::SrsServer()
{
signal_reload = false;
signal_gmc_stop = false;
signal_gracefully_quit = false;
pid_fd = -1;
signal_manager = NULL;
handler = NULL;
ppid = ::getppid();
// donot new object in constructor,
// for some global instance is not ready now,
// new these objects in initialize instead.
#ifdef SRS_AUTO_HTTP_API
http_api_mux = new SrsHttpServeMux();
#endif
#ifdef SRS_AUTO_HTTP_SERVER
http_server = new SrsHttpServer(this);
#endif
#ifdef SRS_AUTO_HTTP_CORE
http_heartbeat = NULL;
#endif
#ifdef SRS_AUTO_INGEST
ingester = NULL;
#endif
#ifdef SRS_SUPPORT_CDN_CLUSTER
cdn_bitch = NULL;
#endif
}
SrsServer::~SrsServer()
{
destroy();
}
void SrsServer::destroy()
{
srs_warn("start destroy server");
dispose();
#ifdef SRS_AUTO_HTTP_API
srs_freep(http_api_mux);
#endif
#ifdef SRS_AUTO_HTTP_SERVER
srs_freep(http_server);
#endif
#ifdef SRS_AUTO_HTTP_CORE
srs_freep(http_heartbeat);
#endif
#ifdef SRS_AUTO_INGEST
srs_freep(ingester);
#endif
#ifdef SRS_SUPPORT_CDN_CLUSTER
srs_freep(cdn_bitch);
#endif
if (pid_fd > 0) {
::close(pid_fd);
pid_fd = -1;
}
srs_freep(signal_manager);
}
void SrsServer::dispose()
{
_srs_config->unsubscribe(this);
// prevent fresh clients.
close_listeners(SrsListenerRtmpStream);
close_listeners(SrsListenerHttpApi);
close_listeners(SrsListenerHttpStream);
close_listeners(SrsListenerMpegTsOverUdp);
close_listeners(SrsListenerRtsp);
close_listeners(SrsListenerFlv);
// @remark don't dispose ingesters, for too slow.
// dispose the source for hls and dvr.
SrsSource::dispose_all();
// @remark don't dispose all connections, for too slow.
#ifdef SRS_AUTO_MEM_WATCH
srs_memory_report();
#endif
}
int SrsServer::initialize(ISrsServerCycle* cycle_handler)
{
int ret = ERROR_SUCCESS;
// ensure the time is ok.
srs_update_system_time_ms();
// for the main objects(server, config, log, context),
// never subscribe handler in constructor,
// instead, subscribe handler in initialize method.
srs_assert(_srs_config);
_srs_config->subscribe(this);
srs_assert(!signal_manager);
signal_manager = new SrsSignalManager(this);
handler = cycle_handler;
if(handler && (ret = handler->initialize()) != ERROR_SUCCESS){
return ret;
}
#ifdef SRS_AUTO_HTTP_API
if ((ret = http_api_mux->initialize()) != ERROR_SUCCESS) {
return ret;
}
#endif
#ifdef SRS_AUTO_HTTP_SERVER
srs_assert(http_server);
if ((ret = http_server->initialize()) != ERROR_SUCCESS) {
return ret;
}
#endif
#ifdef SRS_AUTO_HTTP_CORE
srs_assert(!http_heartbeat);
http_heartbeat = new SrsHttpHeartbeat();
#endif
#ifdef SRS_AUTO_INGEST
srs_assert(!ingester);
ingester = new SrsIngester();
#endif
#ifdef SRS_SUPPORT_CDN_CLUSTER
srs_assert(!cdn_bitch);
cdn_bitch = new SrsCdnBitch();
#endif
return ret;
}
int SrsServer::initialize_bitch() {
int pid = fork();
if (pid < 0) {
srs_error("create process error. ret=-1");
return -1;
}
//child process && exec
if (pid == 0) {
SrsConfDirective* bitch_cmd_conf = _srs_config->get_bitch_command();
if ((int)bitch_cmd_conf->args.size() == 5) {
if (execl(bitch_cmd_conf->args[0].c_str(), "bitch", bitch_cmd_conf->args[1].c_str(), bitch_cmd_conf->args[2].c_str(), bitch_cmd_conf->args[3].c_str(), bitch_cmd_conf->args[4].c_str(), NULL) < 0) {
srs_error("exec bitch process failed, err: %d", errno);
return -1;
}
} else {
srs_error("bitch cmd params size error, size: %d", (int)bitch_cmd_conf->args.size());
return -1;
}
} else {
srs_trace("bitch process pid: %d\n", pid);
}
return ERROR_SUCCESS;
}
int SrsServer::initialize_st()
{
int ret = ERROR_SUCCESS;
// init st
if ((ret = srs_st_init()) != ERROR_SUCCESS) {
srs_error("init st failed. ret=%d", ret);
return ret;
}
// @remark, st alloc segment use mmap, which only support 32757 threads,
// if need to support more, for instance, 100k threads, define the macro MALLOC_STACK.
// TODO: FIXME: maybe can use "sysctl vm.max_map_count" to refine.
if (_srs_config->get_max_connections() > 32756) {
ret = ERROR_ST_EXCEED_THREADS;
srs_error("st mmap for stack allocation must <= %d threads, "
"@see Makefile of st for MALLOC_STACK, please build st manually by "
"\"make EXTRA_CFLAGS=-DMALLOC_STACK linux-debug\", ret=%d", ret);
return ret;
}
// set current log id.
_srs_context->generate_id();
// check asprocess.
bool asprocess = _srs_config->get_asprocess();
if (asprocess && ppid == 1) {
ret = ERROR_SYSTEM_ASSERT_FAILED;
srs_error("for asprocess, ppid should never be init(1), ret=%d", ret);
return ret;
}
srs_trace("server main cid=%d, pid=%d, ppid=%d, asprocess=%d",
_srs_context->get_id(), ::getpid(), ppid, asprocess);
return ret;
}
int SrsServer::initialize_signal()
{
return signal_manager->initialize();
}
int SrsServer::acquire_pid_file()
{
int ret = ERROR_SUCCESS;
// when srs in dolphin mode, no need the pid file.
if (_srs_config->is_dolphin()) {
return ret;
}
std::string pid_file = _srs_config->get_pid_file();
// -rw-r--r--
// 644
int mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
int fd;
// open pid file
if ((fd = ::open(pid_file.c_str(), O_WRONLY | O_CREAT, mode)) < 0) {
ret = ERROR_SYSTEM_PID_ACQUIRE;
srs_error("open pid file %s error, ret=%#x", pid_file.c_str(), ret);
return ret;
}
// require write lock
struct flock lock;
lock.l_type = F_WRLCK; // F_RDLCK, F_WRLCK, F_UNLCK
lock.l_start = 0; // type offset, relative to l_whence
lock.l_whence = SEEK_SET; // SEEK_SET, SEEK_CUR, SEEK_END
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) < 0) {
if(errno == EACCES || errno == EAGAIN) {
ret = ERROR_SYSTEM_PID_ALREADY_RUNNING;
srs_error("srs is already running! ret=%#x", ret);
::close(fd);
return ret;
}
ret = ERROR_SYSTEM_PID_LOCK;
srs_error("require lock for file %s error! ret=%#x", pid_file.c_str(), ret);
return ret;
}
// truncate file
if (ftruncate(fd, 0) < 0) {
ret = ERROR_SYSTEM_PID_TRUNCATE_FILE;
srs_error("truncate pid file %s error! ret=%#x", pid_file.c_str(), ret);
return ret;
}
int pid = (int)getpid();
// write the pid
char buf[512];
snprintf(buf, sizeof(buf), "%d", pid);
if (write(fd, buf, strlen(buf)) != (int)strlen(buf)) {
ret = ERROR_SYSTEM_PID_WRITE_FILE;
srs_error("write our pid error! pid=%d file=%s ret=%#x", pid, pid_file.c_str(), ret);
return ret;
}
// auto close when fork child process.
int val;
if ((val = fcntl(fd, F_GETFD, 0)) < 0) {
ret = ERROR_SYSTEM_PID_GET_FILE_INFO;
srs_error("fnctl F_GETFD error! file=%s ret=%#x", pid_file.c_str(), ret);
return ret;
}
val |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, val) < 0) {
ret = ERROR_SYSTEM_PID_SET_FILE_INFO;
srs_error("fcntl F_SETFD error! file=%s ret=%#x", pid_file.c_str(), ret);
return ret;
}
srs_trace("write pid=%d to %s success!", pid, pid_file.c_str());
pid_fd = fd;
return ret;
}
int SrsServer::listen()
{
int ret = ERROR_SUCCESS;
if ((ret = listen_rtmp()) != ERROR_SUCCESS) {
return ret;
}
if ((ret = listen_http_api()) != ERROR_SUCCESS) {
return ret;
}
if ((ret = listen_http_stream()) != ERROR_SUCCESS) {
return ret;
}
if ((ret = listen_stream_caster()) != ERROR_SUCCESS) {
return ret;
}
return ret;
}
int SrsServer::register_signal()
{
// start signal process thread.
return signal_manager->start();
}
int SrsServer::http_handle()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_API
srs_assert(http_api_mux);
if ((ret = http_api_mux->handle("/", new SrsHttpNotFoundHandler())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/", new SrsGoApiApi())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/", new SrsGoApiV1())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/versions", new SrsGoApiVersion())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/summaries", new SrsGoApiSummaries())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/rusages", new SrsGoApiRusages())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/self_proc_stats", new SrsGoApiSelfProcStats())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/system_proc_stats", new SrsGoApiSystemProcStats())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/meminfos", new SrsGoApiMemInfos())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/authors", new SrsGoApiAuthors())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/features", new SrsGoApiFeatures())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/vhosts/", new SrsGoApiVhosts())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/streams/", new SrsGoApiStreams())) != ERROR_SUCCESS) {
return ret;
}
if ((ret = http_api_mux->handle("/api/v1/clients/", new SrsGoApiClients())) != ERROR_SUCCESS) {
return ret;
}
// test the request info.
if ((ret = http_api_mux->handle("/api/v1/tests/requests", new SrsGoApiRequests())) != ERROR_SUCCESS) {
return ret;
}
// test the error code response.
if ((ret = http_api_mux->handle("/api/v1/tests/errors", new SrsGoApiError())) != ERROR_SUCCESS) {
return ret;
}
// test the redirect mechenism.
if ((ret = http_api_mux->handle("/api/v1/tests/redirects", new SrsHttpRedirectHandler("/api/v1/tests/errors", SRS_CONSTS_HTTP_MovedPermanently))) != ERROR_SUCCESS) {
return ret;
}
// test the http vhost.
if ((ret = http_api_mux->handle("error.srs.com/api/v1/tests/errors", new SrsGoApiError())) != ERROR_SUCCESS) {
return ret;
}
// TODO: FIXME: for console.
// TODO: FIXME: support reload.
std::string dir = _srs_config->get_http_stream_dir() + "/console";
if ((ret = http_api_mux->handle("/console/", new SrsHttpFileServer(dir))) != ERROR_SUCCESS) {
srs_error("http: mount console dir=%s failed. ret=%d", dir.c_str(), ret);
return ret;
}
srs_trace("http: api mount /console to %s", dir.c_str());
#endif
return ret;
}
int SrsServer::ingest()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_INGEST
if ((ret = ingester->start()) != ERROR_SUCCESS) {
srs_error("start ingest streams failed. ret=%d", ret);
return ret;
}
#endif
return ret;
}
int SrsServer::cycle()
{
int ret = ERROR_SUCCESS;
ret = do_cycle();
#ifdef SRS_AUTO_GPERF_MC
destroy();
// remark, for gmc, never invoke the exit().
srs_warn("sleep a long time for system st-threads to cleanup.");
st_usleep(3 * 1000 * 1000);
srs_warn("system quit");
#else
// normally quit with neccessary cleanup by dispose().
srs_warn("main cycle terminated, system quit normally.");
dispose();
srs_trace("srs terminated");
// for valgrind to detect.
srs_freep(_srs_config);
srs_freep(_srs_log);
exit(0);
#endif
return ret;
}
void SrsServer::remove(SrsConnection* conn)
{
std::vector<SrsConnection*>::iterator it = std::find(conns.begin(), conns.end(), conn);
// removed by destroy, ignore.
if (it == conns.end()) {
srs_warn("server moved connection, ignore.");
return;
}
conns.erase(it);
srs_info("conn removed. conns=%d", (int)conns.size());
SrsStatistic* stat = SrsStatistic::instance();
stat->kbps_add_delta(conn);
stat->on_disconnect(conn->srs_id());
// all connections are created by server,
// so we free it here.
srs_freep(conn);
}
void SrsServer::on_signal(int signo)
{
if (signo == SIGNAL_RELOAD) {
signal_reload = true;
return;
}
if (signo == SIGINT || signo == SIGUSR2) {
#ifdef SRS_AUTO_GPERF_MC
srs_trace("gmc is on, main cycle will terminate normally.");
signal_gmc_stop = true;
#else
srs_trace("user terminate program");
#ifdef SRS_AUTO_MEM_WATCH
srs_memory_report();
#endif
exit(0);
#endif
return;
}
if (signo == SIGTERM && !signal_gracefully_quit) {
srs_trace("user terminate program, gracefully quit.");
signal_gracefully_quit = true;
return;
}
if (signo == SIGCHLD) {
if (int pid = wait(NULL) > 0) {
srs_trace("child: %d exit and srs terminate", pid);
} else {
srs_error("parent recover child failed");
}
exit(0);
}
}
int SrsServer::do_cycle()
{
int ret = ERROR_SUCCESS;
// find the max loop
int max = srs_max(0, SRS_SYS_TIME_RESOLUTION_MS_TIMES);
#ifdef SRS_AUTO_STAT
max = srs_max(max, SRS_SYS_RUSAGE_RESOLUTION_TIMES);
max = srs_max(max, SRS_SYS_CPU_STAT_RESOLUTION_TIMES);
max = srs_max(max, SRS_SYS_DISK_STAT_RESOLUTION_TIMES);
max = srs_max(max, SRS_SYS_MEMINFO_RESOLUTION_TIMES);
max = srs_max(max, SRS_SYS_PLATFORM_INFO_RESOLUTION_TIMES);
max = srs_max(max, SRS_SYS_NETWORK_DEVICE_RESOLUTION_TIMES);
max = srs_max(max, SRS_SYS_NETWORK_RTMP_SERVER_RESOLUTION_TIMES);
#endif
// for asprocess.
bool asprocess = _srs_config->get_asprocess();
// the deamon thread, update the time cache
while (true) {
if(handler && (ret = handler->on_cycle((int)conns.size())) != ERROR_SUCCESS){
srs_error("cycle handle failed. ret=%d", ret);
return ret;
}
// the interval in config.
int heartbeat_max_resolution = (int)(_srs_config->get_heartbeat_interval() / SRS_SYS_CYCLE_INTERVAL);
int bitch_max_resolution = (int)(_srs_config->get_bitch_expire_ms()/ SRS_SYS_CYCLE_INTERVAL);
// dynamic fetch the max.
int temp_max = max;
temp_max = srs_max(temp_max, heartbeat_max_resolution);
temp_max = srs_max(temp_max, bitch_max_resolution);
for (int i = 0; i < temp_max; i++) {
st_usleep(SRS_SYS_CYCLE_INTERVAL * 1000);
// asprocess check.
if (asprocess && ::getppid() != ppid) {
srs_warn("asprocess ppid changed from %d to %d", ppid, ::getppid());
return ret;
}
// gracefully quit for SIGINT or SIGTERM.
if (signal_gracefully_quit) {
srs_trace("cleanup for gracefully terminate.");
return ret;
}
// for gperf heap checker,
// @see: research/gperftools/heap-checker/heap_checker.cc
// if user interrupt the program, exit to check mem leak.
// but, if gperf, use reload to ensure main return normally,
// because directly exit will cause core-dump.
#ifdef SRS_AUTO_GPERF_MC
if (signal_gmc_stop) {
srs_warn("gmc got singal to stop server.");
return ret;
}
#endif
// do reload the config.
if (signal_reload) {
signal_reload = false;
srs_info("get signal reload, to reload the config.");
if ((ret = _srs_config->reload()) != ERROR_SUCCESS) {
srs_error("reload config failed. ret=%d", ret);
return ret;
}
srs_trace("reload config success.");
}
// notice the stream sources to cycle.
if ((ret = SrsSource::cycle_all()) != ERROR_SUCCESS) {
return ret;
}
// update the cache time
if ((i % SRS_SYS_TIME_RESOLUTION_MS_TIMES) == 0) {
srs_info("update current time cache.");
srs_update_system_time_ms();
}
#ifdef SRS_AUTO_STAT
if ((i % SRS_SYS_RUSAGE_RESOLUTION_TIMES) == 0) {
srs_info("update resource info, rss.");
srs_update_system_rusage();
}
if ((i % SRS_SYS_CPU_STAT_RESOLUTION_TIMES) == 0) {
srs_info("update cpu info, cpu usage.");
srs_update_proc_stat();
}
if ((i % SRS_SYS_DISK_STAT_RESOLUTION_TIMES) == 0) {
srs_info("update disk info, disk iops.");
srs_update_disk_stat();
}
if ((i % SRS_SYS_MEMINFO_RESOLUTION_TIMES) == 0) {
srs_info("update memory info, usage/free.");
srs_update_meminfo();
}
if ((i % SRS_SYS_PLATFORM_INFO_RESOLUTION_TIMES) == 0) {
srs_info("update platform info, uptime/load.");
srs_update_platform_info();
}
if ((i % SRS_SYS_NETWORK_DEVICE_RESOLUTION_TIMES) == 0) {
srs_info("update network devices info.");
srs_update_network_devices();
}
if ((i % SRS_SYS_NETWORK_RTMP_SERVER_RESOLUTION_TIMES) == 0) {
srs_info("update network server kbps info.");
resample_kbps();
}
#ifdef SRS_AUTO_HTTP_CORE
if (_srs_config->get_heartbeat_enabled()) {
if ((i % heartbeat_max_resolution) == 0) {
srs_info("do http heartbeat, for internal server to report.");
http_heartbeat->heartbeat();
}
}
#endif
#endif
#ifdef SRS_SUPPORT_CDN_CLUSTER
if (_srs_config->get_cluster_enabled() && _srs_config->get_bitch_enabled()) {
if ((i % bitch_max_resolution) == 0) {
srs_info("dynamic vhost config to load, for expire time to reload.");
cdn_bitch->api();
}
}
#endif
srs_info("server main thread loop");
}
}
return ret;
}
int SrsServer::listen_rtmp()
{
int ret = ERROR_SUCCESS;
// stream service port.
std::vector<std::string> ip_ports = _srs_config->get_listens();
srs_assert((int)ip_ports.size() > 0);
close_listeners(SrsListenerRtmpStream);
for (int i = 0; i < (int)ip_ports.size(); i++) {
SrsListener* listener = new SrsStreamListener(this, SrsListenerRtmpStream);
listeners.push_back(listener);
std::string ip;
int port;
srs_parse_endpoint(ip_ports[i], ip, port);
if ((ret = listener->listen(ip, port)) != ERROR_SUCCESS) {
srs_error("RTMP stream listen at %s:%d failed. ret=%d", ip.c_str(), port, ret);
return ret;
}
}
return ret;
}
int SrsServer::listen_http_api()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_API
close_listeners(SrsListenerHttpApi);
if (_srs_config->get_http_api_enabled()) {
SrsListener* listener = new SrsStreamListener(this, SrsListenerHttpApi);
listeners.push_back(listener);
std::string ep = _srs_config->get_http_api_listen();
std::string ip;
int port;
srs_parse_endpoint(ep, ip, port);
if ((ret = listener->listen(ip, port)) != ERROR_SUCCESS) {
srs_error("HTTP api listen at %s:%d failed. ret=%d", ip.c_str(), port, ret);
return ret;
}
}
#endif
return ret;
}
int SrsServer::listen_http_stream()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_SERVER
close_listeners(SrsListenerHttpStream);
if (_srs_config->get_http_stream_enabled()) {
SrsListener* listener = new SrsStreamListener(this, SrsListenerHttpStream);
listeners.push_back(listener);
std::string ep = _srs_config->get_http_stream_listen();
std::string ip;
int port;
srs_parse_endpoint(ep, ip, port);
if ((ret = listener->listen(ip, port)) != ERROR_SUCCESS) {
srs_error("HTTP stream listen at %s:%d failed. ret=%d", ip.c_str(), port, ret);
return ret;
}
}
#endif
return ret;
}
int SrsServer::listen_stream_caster()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_STREAM_CASTER
close_listeners(SrsListenerMpegTsOverUdp);
std::vector<SrsConfDirective*>::iterator it;
std::vector<SrsConfDirective*> stream_casters = _srs_config->get_stream_casters();
for (it = stream_casters.begin(); it != stream_casters.end(); ++it) {
SrsConfDirective* stream_caster = *it;
if (!_srs_config->get_stream_caster_enabled(stream_caster)) {
continue;
}
SrsListener* listener = NULL;
std::string caster = _srs_config->get_stream_caster_engine(stream_caster);
if (srs_stream_caster_is_udp(caster)) {
listener = new SrsUdpCasterListener(this, SrsListenerMpegTsOverUdp, stream_caster);
} else if (srs_stream_caster_is_rtsp(caster)) {
listener = new SrsRtspListener(this, SrsListenerRtsp, stream_caster);
} else if (srs_stream_caster_is_flv(caster)) {
listener = new SrsHttpFlvListener(this, SrsListenerFlv, stream_caster);
} else {
ret = ERROR_STREAM_CASTER_ENGINE;
srs_error("unsupported stream caster %s. ret=%d", caster.c_str(), ret);
return ret;
}
srs_assert(listener != NULL);
listeners.push_back(listener);
int port = _srs_config->get_stream_caster_listen(stream_caster);
if (port <= 0) {
ret = ERROR_STREAM_CASTER_PORT;
srs_error("invalid stream caster port %d. ret=%d", port, ret);
return ret;
}
// TODO: support listen at <[ip:]port>
if ((ret = listener->listen("0.0.0.0", port)) != ERROR_SUCCESS) {
srs_error("StreamCaster listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
#endif
return ret;
}
void SrsServer::close_listeners(SrsListenerType type)
{
std::vector<SrsListener*>::iterator it;
for (it = listeners.begin(); it != listeners.end();) {
SrsListener* listener = *it;
if (listener->listen_type() != type) {
++it;
continue;
}
srs_freep(listener);
it = listeners.erase(it);
}
}
void SrsServer::resample_kbps()
{
SrsStatistic* stat = SrsStatistic::instance();
// collect delta from all clients.
for (std::vector<SrsConnection*>::iterator it = conns.begin(); it != conns.end(); ++it) {
SrsConnection* conn = *it;
// add delta of connection to server kbps.,
// for next sample() of server kbps can get the stat.
stat->kbps_add_delta(conn);
}
// TODO: FXME: support all other connections.
// sample the kbps, get the stat.
SrsKbps* kbps = stat->kbps_sample();
srs_update_rtmp_server((int)conns.size(), kbps);
}
int SrsServer::accept_client(SrsListenerType type, st_netfd_t client_stfd)
{
int ret = ERROR_SUCCESS;
int fd = st_netfd_fileno(client_stfd);
int max_connections = _srs_config->get_max_connections();
if ((int)conns.size() >= max_connections) {
srs_error("exceed the max connections, drop client: "
"clients=%d, max=%d, fd=%d", (int)conns.size(), max_connections, fd);
srs_close_stfd(client_stfd);
return ret;
}
// avoid fd leak when fork.
// @see https://github.com/ossrs/srs/issues/518
if (true) {
int val;
if ((val = fcntl(fd, F_GETFD, 0)) < 0) {
ret = ERROR_SYSTEM_PID_GET_FILE_INFO;
srs_error("fnctl F_GETFD error! fd=%d. ret=%#x", fd, ret);
srs_close_stfd(client_stfd);
return ret;
}
val |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, val) < 0) {
ret = ERROR_SYSTEM_PID_SET_FILE_INFO;
srs_error("fcntl F_SETFD error! fd=%d ret=%#x", fd, ret);
srs_close_stfd(client_stfd);
return ret;
}
}
SrsConnection* conn = NULL;
if (type == SrsListenerRtmpStream) {
conn = new SrsRtmpConn(this, client_stfd);
} else if (type == SrsListenerHttpApi) {
#ifdef SRS_AUTO_HTTP_API
conn = new SrsHttpApi(this, client_stfd, http_api_mux);
#else
srs_warn("close http client for server not support http-api");
srs_close_stfd(client_stfd);
return ret;
#endif
} else if (type == SrsListenerHttpStream) {
#ifdef SRS_AUTO_HTTP_SERVER
conn = new SrsResponseOnlyHttpConn(this, client_stfd, http_server);
#else
srs_warn("close http client for server not support http-server");
srs_close_stfd(client_stfd);
return ret;
#endif
} else {
// TODO: FIXME: handler others
}
srs_assert(conn);
// directly enqueue, the cycle thread will remove the client.
conns.push_back(conn);
srs_verbose("add conn to vector.");
// cycle will start process thread and when finished remove the client.
// @remark never use the conn, for it maybe destroyed.
if ((ret = conn->start()) != ERROR_SUCCESS) {
return ret;
}
srs_verbose("conn started success.");
srs_verbose("accept client finished. conns=%d, ret=%d", (int)conns.size(), ret);
return ret;
}
int SrsServer::on_reload_listen()
{
return listen();
}
int SrsServer::on_reload_pid()
{
if (pid_fd > 0) {
::close(pid_fd);
pid_fd = -1;
}
return acquire_pid_file();
}
int SrsServer::on_reload_vhost_added(std::string vhost)
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_SERVER
if (!_srs_config->get_vhost_http_enabled(vhost)) {
return ret;
}
// TODO: FIXME: should handle the event in SrsHttpStaticServer
if ((ret = on_reload_vhost_http_updated()) != ERROR_SUCCESS) {
return ret;
}
#endif
return ret;
}
int SrsServer::on_reload_vhost_removed(std::string /*vhost*/)
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_SERVER
// TODO: FIXME: should handle the event in SrsHttpStaticServer
if ((ret = on_reload_vhost_http_updated()) != ERROR_SUCCESS) {
return ret;
}
#endif
return ret;
}
int SrsServer::on_reload_http_api_enabled()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_API
ret = listen_http_api();
#endif
return ret;
}
int SrsServer::on_reload_http_api_disabled()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_API
close_listeners(SrsListenerHttpApi);
#endif
return ret;
}
int SrsServer::on_reload_http_stream_enabled()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_SERVER
ret = listen_http_stream();
#endif
return ret;
}
int SrsServer::on_reload_http_stream_disabled()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_SERVER
close_listeners(SrsListenerHttpStream);
#endif
return ret;
}
// TODO: FIXME: rename to http_remux
int SrsServer::on_reload_http_stream_updated()
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_SERVER
if ((ret = on_reload_http_stream_enabled()) != ERROR_SUCCESS) {
return ret;
}
// TODO: FIXME: should handle the event in SrsHttpStaticServer
if ((ret = on_reload_vhost_http_updated()) != ERROR_SUCCESS) {
return ret;
}
#endif
return ret;
}
int SrsServer::on_publish(SrsSource* s, SrsRequest* r)
{
int ret = ERROR_SUCCESS;
#ifdef SRS_AUTO_HTTP_SERVER
if ((ret = http_server->http_mount(s, r)) != ERROR_SUCCESS) {
return ret;
}
#endif
return ret;
}
void SrsServer::on_unpublish(SrsSource* s, SrsRequest* r)
{
#ifdef SRS_AUTO_HTTP_SERVER
http_server->http_unmount(s, r);
#endif
}
|
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <file_selector_windows/file_selector_plugin.h>
#include <menubar/menubar_plugin.h>
#include <url_launcher_windows/url_launcher_windows.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
FileSelectorPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FileSelectorPlugin"));
MenubarPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("MenubarPlugin"));
UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
}
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2020 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "pch.hpp"
#include "Auddio.h"
#include "Common.h"
#include <musikcore/support/NarrowCast.h>
#include <musikcore/sdk/HttpClient.h>
#include <musikcore/support/Preferences.h>
#include <musikcore/support/PreferenceKeys.h>
#include <sstream>
#pragma warning(push, 0)
#include <nlohmann/json.hpp>
#include <curl/curl.h>
#pragma warning(pop)
/* https://api.audd.io/findLyrics/?q=the%20beatles%20sgt%20pepper%20reprise */
using namespace musik::core;
using namespace musik::core::prefs;
using AuddioClient = musik::core::sdk::HttpClient<std::stringstream>;
static std::shared_ptr<AuddioClient> createClient() {
return AuddioClient::Create(std::stringstream());
}
static std::string encode(std::string value) {
static CURL* curl = curl_easy_init();
if (curl && value.c_str()) {
char* encoded = curl_easy_escape(
curl,
value.c_str(),
narrow_cast<int>(value.size()));
if (encoded) {
value = encoded;
curl_free(encoded);
}
}
return value;
}
static std::string getApiToken() {
auto prefs = Preferences::ForComponent(components::Settings);
return prefs->GetString(keys::AuddioApiToken);
}
namespace musik { namespace core { namespace auddio {
bool Available() {
return getApiToken().size() > 0;
}
void FindLyrics(TrackPtr track, LyricsCallback callback) {
std::string apiToken = getApiToken();
if (!apiToken.size()) {
callback(track, "");
return;
}
std::string artist = encode(track->GetString("artist"));
std::string title = encode(track->GetString("title"));
std::string url =
"https://api.audd.io/findLyrics/?q=" +
artist + "%20" + title +
"&api_token=" + apiToken;
auto client = createClient();
client->Url(url)
.Mode(AuddioClient::Thread::Background)
.Run([track, callback](AuddioClient* client, int statusCode, CURLcode curlCode) {
std::string lyrics;
if (statusCode == 200) {
try {
std::string response = client->Stream().str();
auto json = nlohmann::json::parse(response);
if (json.value("status", "") == "success") {
lyrics = json["result"][0]["lyrics"].get<std::string>();
}
}
catch (...) {
/* not much we can do... */
}
}
callback(track, lyrics);
});
}
} } }
|
#ifndef INCLUDE_VNI_GENERATED_vnl_op_code_t_HXX_
#define INCLUDE_VNI_GENERATED_vnl_op_code_t_HXX_
// AUTO GENERATED by virtual-network-interface codegen
#include <vnl/Type.hxx>
namespace vnl {
class op_code_t : public vnl::Enum {
public:
static const uint32_t VNI_HASH = 0x1aa757db;
static const uint32_t NOOP = 0xddc2502d;
static const uint32_t MOV = 0x838be867;
static const uint32_t REF = 0xe67c57c5;
static const uint32_t CMP = 0x2ec5e872;
static const uint32_t ADD = 0xe9e85174;
static const uint32_t SUB = 0xa7b233f3;
static const uint32_t MUL = 0x4f98c20;
static const uint32_t DIV = 0x5350cdda;
static const uint32_t MOD = 0x7af82e75;
static const uint32_t PUSH = 0x89652f06;
static const uint32_t POP = 0x6c605d8f;
static const uint32_t LOAD = 0x455eb8a3;
static const uint32_t STORE = 0xe2fbdba5;
static const uint32_t PUSH_BACK = 0x728e271a;
static const uint32_t PUSH_FRONT = 0x3dc1e640;
static const uint32_t POP_BACK = 0xb147a790;
static const uint32_t POP_FRONT = 0x6ddb3cbf;
static const uint32_t SET = 0x8e65fc1c;
static const uint32_t GET = 0x8376aa8a;
static const uint32_t ERASE = 0xe8106fb8;
static const uint32_t JMP = 0x9bf2f564;
static const uint32_t CALL = 0x91caf30d;
static const uint32_t RET = 0x1f0f91d7;
static const uint32_t READ = 0x139dda85;
static const uint32_t WRITE = 0x4c9fd481;
operator uint32_t() const {
return value;
}
op_code_t& operator=(const uint32_t& val) {
value = val;
return *this;
}
op_code_t();
virtual uint32_t get_vni_hash() const { return VNI_HASH; }
virtual const char* get_type_name() const { return "vnl.op_code_t"; }
virtual void to_string_ex(vnl::String& str) const;
};
} // namespace
#endif // INCLUDE_VNI_GENERATED_vnl_op_code_t_HXX_
|
/*******************************************************************************
* Copyright (c) 2012-2014, The Microsystems Design Labratory (MDL)
* Department of Computer Science and Engineering, The Pennsylvania State University
* All rights reserved.
*
* This source code is part of NVMain - A cycle accurate timing, bit accurate
* energy simulator for both volatile (e.g., DRAM) and non-volatile memory
* (e.g., PCRAM). The source code is free and you can redistribute and/or
* modify it by providing that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Author list:
* Matt Poremba ( Email: mrp5060 at psu dot edu
* Website: http://www.cse.psu.edu/~poremba/ )
* Tao Zhang ( Email: tzz106 at cse dot psu dot edu
* Website: http://www.cse.psu.edu/~tzz106 )
*******************************************************************************/
#include "Banks/CachedDDR3Bank/CachedDDR3Bank.h"
#include "include/NVMHelpers.h"
#include "src/EventQueue.h"
#include <cassert>
using namespace NVM;
CachedDDR3Bank::CachedDDR3Bank( )
{
cachedRowBuffer = NULL;
readOnlyBuffers = true;
rowBufferSize = 32;
rowBufferCount = 4;
inRDBCount = 0;
RDBAllocations = 0;
writebackCount = 0;
RDBReads = 0;
RDBWrites = 0;
allocationReadsHisto = "";
allocationWritesHisto = "";
}
CachedDDR3Bank::~CachedDDR3Bank( )
{
if( cachedRowBuffer )
{
for( ncounter_t bufferIdx = 0; bufferIdx < rowBufferCount; bufferIdx++ )
{
delete cachedRowBuffer[bufferIdx]->dirty;
delete cachedRowBuffer[bufferIdx];
}
delete [] cachedRowBuffer;
}
}
void CachedDDR3Bank::SetConfig( Config *config, bool createChildren )
{
// Assume entire row is cached if CachedRowSize is unset
config->GetValueUL( "COLS", rowBufferSize );
config->GetBool( "CachedRowsReadOnly", readOnlyBuffers );
config->GetValueUL( "CachedRowSize", rowBufferSize );
config->GetValueUL( "CachedRowCount", rowBufferCount );
/* Initialize row buffers. */
cachedRowBuffer = new CachedRowBuffer*[rowBufferCount];
for( ncounter_t bufferIdx = 0; bufferIdx < rowBufferCount; bufferIdx++ )
{
cachedRowBuffer[bufferIdx] = new CachedRowBuffer;
cachedRowBuffer[bufferIdx]->used = false;
cachedRowBuffer[bufferIdx]->dirty = new bool[rowBufferSize];
for( ncounter_t dirtyIdx = 0; dirtyIdx < rowBufferSize; dirtyIdx++ )
{
cachedRowBuffer[bufferIdx]->dirty[dirtyIdx] = false;
}
}
DDR3Bank::SetConfig( config, createChildren );
}
bool CachedDDR3Bank::Activate( NVMainRequest *request )
{
bool foundRDB = false;
assert( nextActivate <= GetEventQueue()->GetCurrentCycle() );
/* See if there is an available row buffer. */
for( ncounter_t bufferIdx = 0; bufferIdx < rowBufferCount; bufferIdx++ )
{
/* Check if this row is already active. For read-only, we must activate to allow for write-through to bank. */
if( cachedRowBuffer[bufferIdx]->used &&
request->address.GetRow( ) == cachedRowBuffer[bufferIdx]->address.GetRow( ) )
{
foundRDB = true;
break;
}
/* Look for unused buffers. Don't break so the assertion is checked. */
if( !cachedRowBuffer[bufferIdx]->used && !foundRDB )
{
foundRDB = true;
cachedRowBuffer[bufferIdx]->used = true;
cachedRowBuffer[bufferIdx]->address = request->address;
cachedRowBuffer[bufferIdx]->colStart = request->address.GetCol()
- (request->address.GetCol() % rowBufferSize);
cachedRowBuffer[bufferIdx]->colEnd = cachedRowBuffer[bufferIdx]->colStart + rowBufferSize;
cachedRowBuffer[bufferIdx]->reads = 0;
cachedRowBuffer[bufferIdx]->writes = 0;
RDBAllocations++;
//std::cout << statName << ": Buffer " << bufferIdx << " bound to address 0x" << std::hex
// << request->address.GetPhysicalAddress( ) << std::dec << " from col "
// << cachedRowBuffer[bufferIdx]->colStart << " to col "
// << cachedRowBuffer[bufferIdx]->colEnd << std::endl;
break;
}
}
/* If we haven't found an RDB, evict the LRU row. */
ncounter_t dirtyCount = 0;
if( !foundRDB )
{
ncounter_t bufferIdx = rowBufferCount - 1;
if( allocationReadsMap.count( cachedRowBuffer[bufferIdx]->reads ) )
allocationReadsMap[ cachedRowBuffer[bufferIdx]->reads ]++;
else
allocationReadsMap[ cachedRowBuffer[bufferIdx]->reads ] = 1;
if( allocationWritesMap.count( cachedRowBuffer[bufferIdx]->writes ) )
allocationWritesMap[ cachedRowBuffer[bufferIdx]->writes ]++;
else
allocationWritesMap[ cachedRowBuffer[bufferIdx]->writes ] = 1;
cachedRowBuffer[bufferIdx]->used = true;
cachedRowBuffer[bufferIdx]->address = request->address;
cachedRowBuffer[bufferIdx]->colStart = request->address.GetCol()
- (request->address.GetCol() % rowBufferSize);
cachedRowBuffer[bufferIdx]->colEnd = cachedRowBuffer[bufferIdx]->colStart + rowBufferSize;
cachedRowBuffer[bufferIdx]->reads = 0;
cachedRowBuffer[bufferIdx]->writes = 0;
RDBAllocations++;
//std::cout << statName << ": Buffer " << bufferIdx << " bound to address 0x" << std::hex
// << request->address.GetPhysicalAddress( ) << std::dec << " from col "
// << cachedRowBuffer[bufferIdx]->colStart << " to col "
// << cachedRowBuffer[bufferIdx]->colEnd << std::endl;
for( ncounter_t dirtyIdx = 0; dirtyIdx < rowBufferSize; dirtyIdx++ )
{
if( cachedRowBuffer[bufferIdx]->dirty[dirtyIdx] )
dirtyCount++;
cachedRowBuffer[bufferIdx]->dirty[dirtyIdx] = false;
}
writebackCount += dirtyCount;
}
assert( !(readOnlyBuffers && dirtyCount > 0) );
ncycle_t activateTimer = 0;
/* If dirty, simulate writebacks. */
// TODO: Check if row is already activated? It's probably not since LRU is evicted..
if( dirtyCount > 0 )
{
activateTimer += p->tRCD; /* Time for extra activate */
activateTimer -= p->tAL; /* Act -> Write time. */
activateTimer += MAX( p->tBURST, p->tCCD ) /* Write time. */
* (dirtyCount - 1);
activateTimer += p->tAL + p->tCWD /* Write + Write -> Precharge time. */
+ p->tBURST + p->tWR;
activateTimer += (p->UsePrecharge /* Precharge time. */
? p->tRP : 0);
}
activateTimer += p->tRCD; /* The activate issued to this method. */
activateTimer += rowBufferSize * p->tCCD; /* The time to read the selected row region. */
/*
* Update timing constraints.
*
* Assume we can write immediately after activate, and can read after one burst (Assumes
* trigger request is prioritized...)
*/
nextRead = MAX( nextRead, GetEventQueue()->GetCurrentCycle() + activateTimer - p->tAL - rowBufferSize * p->tCCD + p->tCCD );
nextWrite = MAX( nextWrite, GetEventQueue()->GetCurrentCycle() + activateTimer - p->tAL - rowBufferSize * p->tCCD );
/* Don't allow closing the row until the RDB is full. */
nextPrecharge = MAX( nextPrecharge, GetEventQueue()->GetCurrentCycle() + MAX(activateTimer, p->tRAS) );
nextPowerDown = MAX( nextPowerDown, GetEventQueue()->GetCurrentCycle() + MAX(activateTimer, p->tRAS) );
/* Set the bank state. */
ncounter_t activateRow, activateSubArray;
request->address.GetTranslatedAddress( &activateRow, NULL, NULL, NULL, NULL, &activateSubArray );
/* issue ACTIVATE to the target subarray */
// TODO: Should we delay this in the case of writebacks for visualization purposes?
bool success = GetChild( request )->IssueCommand( request );
if( success )
{
/* bank-level update */
openRow = activateRow;
state = DDR3BANK_OPEN;
activeSubArrayQueue.push_front( activateSubArray );
activates++;
}
else
{
std::cerr << "NVMain Error: Bank " << bankId << " failed to "
<< "activate the subarray " << activateSubArray << std::endl;
}
return success;
}
bool CachedDDR3Bank::Read( NVMainRequest *request )
{
bool rv = false;
/* Check if this is in the RDB. */
for( ncounter_t bufferIdx = 0; bufferIdx < rowBufferCount; bufferIdx++ )
{
if( cachedRowBuffer[bufferIdx]->address.GetRow( ) == request->address.GetRow( )
&& request->address.GetCol( ) >= cachedRowBuffer[bufferIdx]->colStart
&& request->address.GetCol( ) < cachedRowBuffer[bufferIdx]->colEnd )
{
rv = true;
/* Only update read and write based on RDB timings; other commands will bypass RDB. */
nextRead = MAX( nextRead, GetEventQueue()->GetCurrentCycle() + MAX( p->tBURST, p->tRDB ) );
nextWrite = MAX( nextWrite, GetEventQueue()->GetCurrentCycle() + MAX( p->tBURST, p->tRDB ) + p->tRTRS );
/* Assume the data is placed on the bus immediately after the command. */
NVMainRequest *busReq = new NVMainRequest( );
*busReq = *request;
busReq->type = BUS_READ;
busReq->owner = this;
GetEventQueue( )->InsertEvent( EventResponse, this, busReq,
GetEventQueue()->GetCurrentCycle() + 1 );
/* Notify owner of read completion as well */
GetEventQueue( )->InsertEvent( EventResponse, this, request,
GetEventQueue()->GetCurrentCycle() + MAX( p->tBURST, p->tRDB ) );
/* Swap the cached status back to normal. */
request->type = (request->type == CACHED_READ ? READ : request->type);
//std::cout << GetEventQueue()->GetCurrentCycle() << " " << statName
// << ": Served read request 0x" << std::hex
// << request->address.GetPhysicalAddress() << std::dec << std::endl;
RDBReads++;
cachedRowBuffer[bufferIdx]->reads++;
/* Move this buffer to LRU. */
CachedRowBuffer *tempBuffer = cachedRowBuffer[bufferIdx];
for( uint64_t j = bufferIdx; j > 0; j-- )
{
cachedRowBuffer[j] = cachedRowBuffer[j-1];
}
cachedRowBuffer[0] = tempBuffer;
break;
}
}
if( !rv )
{
rv = DDR3Bank::Read( request );
}
return rv;
}
bool CachedDDR3Bank::Write( NVMainRequest *request )
{
bool rv = false;
/* Check if this is in the RDB. */
if( !readOnlyBuffers )
{
for( ncounter_t bufferIdx = 0; bufferIdx < rowBufferCount; bufferIdx++ )
{
if( cachedRowBuffer[bufferIdx]->address.GetRow( ) == request->address.GetRow( )
&& request->address.GetCol( ) >= cachedRowBuffer[bufferIdx]->colStart
&& request->address.GetCol( ) < cachedRowBuffer[bufferIdx]->colEnd )
{
rv = true;
/* Only update read and write based on RDB timings; other commands will bypass RDB. */
nextRead = MAX( nextRead, GetEventQueue()->GetCurrentCycle() + MAX( p->tBURST, p->tRDB ) + p->tRTRS );
nextWrite = MAX( nextWrite, GetEventQueue()->GetCurrentCycle() + MAX( p->tBURST, p->tRDB ) );
/* Set this word to be dirty. */
cachedRowBuffer[bufferIdx]->dirty[request->address.GetCol( )] = true;
/* Assume the data is placed on the bus immediately after the command. */
NVMainRequest *busReq = new NVMainRequest( );
*busReq = *request;
busReq->type = BUS_WRITE;
busReq->owner = this;
GetEventQueue( )->InsertEvent( EventResponse, this, busReq,
GetEventQueue()->GetCurrentCycle() + 1 );
/* Notify owner of read completion as well */
GetEventQueue( )->InsertEvent( EventResponse, this, request,
GetEventQueue()->GetCurrentCycle() + MAX( p->tBURST, p->tRDB ) );
/* Swap the cached status back to normal. */
request->type = (request->type == CACHED_WRITE ? WRITE : request->type);
//std::cout << GetEventQueue()->GetCurrentCycle() << " " << statName
// << ": Served write request 0x" << std::hex
// << request->address.GetPhysicalAddress() << std::dec << std::endl;
RDBWrites++;
cachedRowBuffer[bufferIdx]->writes++;
/* Move this buffer to LRU. */
CachedRowBuffer *tempBuffer = cachedRowBuffer[bufferIdx];
for( uint64_t j = bufferIdx; j > 0; j-- )
{
cachedRowBuffer[j] = cachedRowBuffer[j-1];
}
cachedRowBuffer[0] = tempBuffer;
break;
}
}
}
if( !rv )
{
rv = DDR3Bank::Write( request );
}
return rv;
}
bool CachedDDR3Bank::IsIssuable( NVMainRequest *request, FailReason *reason )
{
bool rv = false;
bool inRDB = false;
bool cacheableRequest = false;
for( ncounter_t bufferIdx = 0; bufferIdx < rowBufferCount; bufferIdx++ )
{
if( cachedRowBuffer[bufferIdx]->address.GetRow( ) == request->address.GetRow( )
&& request->address.GetCol( ) >= cachedRowBuffer[bufferIdx]->colStart
&& request->address.GetCol( ) < cachedRowBuffer[bufferIdx]->colEnd )
{
inRDB = true;
}
}
if( request->type == READ || request->type == READ_PRECHARGE || request->type == CACHED_READ ||
( !readOnlyBuffers && (request->type == WRITE || request->type == WRITE_PRECHARGE
|| request->type == CACHED_WRITE )
)
)
{
cacheableRequest = true;
}
if( inRDB && cacheableRequest )
{
assert( request->type == READ || request->type == READ_PRECHARGE ||
request->type == WRITE || request->type == WRITE_PRECHARGE ||
request->type == CACHED_READ || request->type == CACHED_WRITE );
inRDBCount++;
rv = true;
//std::cout << GetEventQueue()->GetCurrentCycle() << " " << statName << ": Found 0x"
// << std::hex << request->address.GetPhysicalAddress( ) << std::dec
// << " in RDB. Row = " << request->address.GetRow( ) << " Col = "
// << request->address.GetCol( ) << std::endl;
}
else if( request->type != CACHED_READ && request->type != CACHED_WRITE )
{
rv = DDR3Bank::IsIssuable( request, reason );
}
return rv;
}
void CachedDDR3Bank::RegisterStats( )
{
AddStat(inRDBCount);
AddStat(RDBAllocations);
AddStat(writebackCount);
AddStat(RDBReads);
AddStat(RDBWrites);
AddStat(allocationReadsHisto);
AddStat(allocationWritesHisto);
}
void CachedDDR3Bank::CalculateStats( )
{
allocationReadsHisto = PyDictHistogram<uint64_t, uint64_t>( allocationReadsMap );
allocationWritesHisto = PyDictHistogram<uint64_t, uint64_t>( allocationWritesMap );
}
|
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2014-2017. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/move for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_MOVE_DETAIL_POINTER_ELEMENT_HPP
#define BOOST_MOVE_DETAIL_POINTER_ELEMENT_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
#ifndef BOOST_MOVE_DETAIL_WORKAROUND_HPP
#include <boost/move/detail/workaround.hpp>
#endif //BOOST_MOVE_DETAIL_WORKAROUND_HPP
namespace lslboost {
namespace movelib {
namespace detail{
//////////////////////
//struct first_param
//////////////////////
template <typename T> struct first_param
{ typedef void type; };
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <template <typename, typename...> class TemplateClass, typename T, typename... Args>
struct first_param< TemplateClass<T, Args...> >
{
typedef T type;
};
#else //C++03 compilers
template < template //0arg
<class
> class TemplateClass, class T
>
struct first_param
< TemplateClass<T> >
{ typedef T type; };
template < template //1arg
<class,class
> class TemplateClass, class T
, class P0>
struct first_param
< TemplateClass<T, P0> >
{ typedef T type; };
template < template //2arg
<class,class,class
> class TemplateClass, class T
, class P0, class P1>
struct first_param
< TemplateClass<T, P0, P1> >
{ typedef T type; };
template < template //3arg
<class,class,class,class
> class TemplateClass, class T
, class P0, class P1, class P2>
struct first_param
< TemplateClass<T, P0, P1, P2> >
{ typedef T type; };
template < template //4arg
<class,class,class,class,class
> class TemplateClass, class T
, class P0, class P1, class P2, class P3>
struct first_param
< TemplateClass<T, P0, P1, P2, P3> >
{ typedef T type; };
template < template //5arg
<class,class,class,class,class,class
> class TemplateClass, class T
, class P0, class P1, class P2, class P3, class P4>
struct first_param
< TemplateClass<T, P0, P1, P2, P3, P4> >
{ typedef T type; };
template < template //6arg
<class,class,class,class,class,class,class
> class TemplateClass, class T
, class P0, class P1, class P2, class P3, class P4, class P5>
struct first_param
< TemplateClass<T, P0, P1, P2, P3, P4, P5> >
{ typedef T type; };
template < template //7arg
<class,class,class,class,class,class,class,class
> class TemplateClass, class T
, class P0, class P1, class P2, class P3, class P4, class P5, class P6>
struct first_param
< TemplateClass<T, P0, P1, P2, P3, P4, P5, P6> >
{ typedef T type; };
template < template //8arg
<class,class,class,class,class,class,class,class,class
> class TemplateClass, class T
, class P0, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
struct first_param
< TemplateClass<T, P0, P1, P2, P3, P4, P5, P6, P7> >
{ typedef T type; };
template < template //9arg
<class,class,class,class,class,class,class,class,class,class
> class TemplateClass, class T
, class P0, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
struct first_param
< TemplateClass<T, P0, P1, P2, P3, P4, P5, P6, P7, P8> >
{ typedef T type; };
#endif //!defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <typename T>
struct has_internal_pointer_element
{
template <typename X>
static char test(int, typename X::element_type*);
template <typename X>
static int test(...);
static const bool value = (1 == sizeof(test<T>(0, 0)));
};
template<class Ptr, bool = has_internal_pointer_element<Ptr>::value>
struct pointer_element_impl
{
typedef typename Ptr::element_type type;
};
template<class Ptr>
struct pointer_element_impl<Ptr, false>
{
typedef typename lslboost::movelib::detail::first_param<Ptr>::type type;
};
} //namespace detail{
template <typename Ptr>
struct pointer_element
{
typedef typename ::lslboost::movelib::detail::pointer_element_impl<Ptr>::type type;
};
template <typename T>
struct pointer_element<T*>
{ typedef T type; };
} //namespace movelib {
} //namespace lslboost {
#endif // defined(BOOST_MOVE_DETAIL_POINTER_ELEMENT_HPP)
|
/*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
* Copyright (c) 2019 The RmlUi Team, and contributors
*
* 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.
*
*/
#include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
#include "../../Include/RmlUi/Core/PropertyIdSet.h"
#include "../../Include/RmlUi/Core/PropertyDefinition.h"
#include "PropertyParserNumber.h"
#include "PropertyParserAnimation.h"
#include "PropertyParserColour.h"
#include "PropertyParserKeyword.h"
#include "PropertyParserString.h"
#include "PropertyParserTransform.h"
#include "PropertyShorthandDefinition.h"
#include "IdNameMap.h"
namespace Rml {
static StyleSheetSpecification* style_sheet_specification_instance = nullptr;
struct DefaultStyleSheetParsers {
PropertyParserNumber number = PropertyParserNumber(Property::NUMBER);
PropertyParserNumber length = PropertyParserNumber(Property::LENGTH, Property::PX);
PropertyParserNumber length_percent = PropertyParserNumber(Property::LENGTH_PERCENT, Property::PX);
PropertyParserNumber number_length_percent = PropertyParserNumber(Property::NUMBER_LENGTH_PERCENT, Property::PX);
PropertyParserNumber angle = PropertyParserNumber(Property::ANGLE, Property::RAD);
PropertyParserKeyword keyword = PropertyParserKeyword();
PropertyParserString string = PropertyParserString();
PropertyParserAnimation animation = PropertyParserAnimation(PropertyParserAnimation::ANIMATION_PARSER);
PropertyParserAnimation transition = PropertyParserAnimation(PropertyParserAnimation::TRANSITION_PARSER);
PropertyParserColour color = PropertyParserColour();
PropertyParserTransform transform = PropertyParserTransform();
};
StyleSheetSpecification::StyleSheetSpecification() :
// Reserve space for all defined ids and some more for custom properties
properties((size_t)PropertyId::MaxNumIds, 2 * (size_t)ShorthandId::NumDefinedIds)
{
RMLUI_ASSERT(style_sheet_specification_instance == nullptr);
style_sheet_specification_instance = this;
default_parsers.reset(new DefaultStyleSheetParsers);
}
StyleSheetSpecification::~StyleSheetSpecification()
{
RMLUI_ASSERT(style_sheet_specification_instance == this);
style_sheet_specification_instance = nullptr;
}
PropertyDefinition& StyleSheetSpecification::RegisterProperty(PropertyId id, const String& property_name, const String& default_value, bool inherited, bool forces_layout)
{
return properties.RegisterProperty(property_name, default_value, inherited, forces_layout, id);
}
ShorthandId StyleSheetSpecification::RegisterShorthand(ShorthandId id, const String& shorthand_name, const String& property_names, ShorthandType type)
{
return properties.RegisterShorthand(shorthand_name, property_names, type, id);
}
bool StyleSheetSpecification::Initialise()
{
if (style_sheet_specification_instance == nullptr)
{
new StyleSheetSpecification();
style_sheet_specification_instance->RegisterDefaultParsers();
style_sheet_specification_instance->RegisterDefaultProperties();
}
return true;
}
void StyleSheetSpecification::Shutdown()
{
if (style_sheet_specification_instance != nullptr)
{
delete style_sheet_specification_instance;
}
}
// Registers a parser for use in property definitions.
bool StyleSheetSpecification::RegisterParser(const String& parser_name, PropertyParser* parser)
{
ParserMap::iterator iterator = style_sheet_specification_instance->parsers.find(parser_name);
if (iterator != style_sheet_specification_instance->parsers.end())
{
Log::Message(Log::LT_WARNING, "Parser with name %s already exists!", parser_name.c_str());
return false;
}
style_sheet_specification_instance->parsers[parser_name] = parser;
return true;
}
// Returns the parser registered with a specific name.
PropertyParser* StyleSheetSpecification::GetParser(const String& parser_name)
{
ParserMap::iterator iterator = style_sheet_specification_instance->parsers.find(parser_name);
if (iterator == style_sheet_specification_instance->parsers.end())
return nullptr;
return (*iterator).second;
}
// Registers a property with a new definition.
PropertyDefinition& StyleSheetSpecification::RegisterProperty(const String& property_name, const String& default_value, bool inherited, bool forces_layout)
{
RMLUI_ASSERTMSG((size_t)style_sheet_specification_instance->properties.property_map->GetId(property_name) < (size_t)PropertyId::FirstCustomId, "Custom property name matches an internal property, please make a unique name for the given property.");
return style_sheet_specification_instance->RegisterProperty(PropertyId::Invalid, property_name, default_value, inherited, forces_layout);
}
// Returns a property definition.
const PropertyDefinition* StyleSheetSpecification::GetProperty(const String& property_name)
{
return style_sheet_specification_instance->properties.GetProperty(property_name);
}
const PropertyDefinition* StyleSheetSpecification::GetProperty(PropertyId id)
{
return style_sheet_specification_instance->properties.GetProperty(id);
}
const PropertyIdSet& StyleSheetSpecification::GetRegisteredProperties()
{
return style_sheet_specification_instance->properties.GetRegisteredProperties();
}
const PropertyIdSet & StyleSheetSpecification::GetRegisteredInheritedProperties()
{
return style_sheet_specification_instance->properties.GetRegisteredInheritedProperties();
}
const PropertyIdSet& StyleSheetSpecification::GetRegisteredPropertiesForcingLayout()
{
return style_sheet_specification_instance->properties.GetRegisteredPropertiesForcingLayout();
}
// Registers a shorthand property definition.
ShorthandId StyleSheetSpecification::RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type)
{
RMLUI_ASSERTMSG(style_sheet_specification_instance->properties.property_map->GetId(shorthand_name) == PropertyId::Invalid, "Custom shorthand name matches a property name, please make a unique name.");
RMLUI_ASSERTMSG((size_t)style_sheet_specification_instance->properties.shorthand_map->GetId(shorthand_name) < (size_t)ShorthandId::FirstCustomId, "Custom shorthand name matches an internal shorthand, please make a unique name for the given shorthand property.");
return style_sheet_specification_instance->properties.RegisterShorthand(shorthand_name, property_names, type);
}
// Returns a shorthand definition.
const ShorthandDefinition* StyleSheetSpecification::GetShorthand(const String& shorthand_name)
{
return style_sheet_specification_instance->properties.GetShorthand(shorthand_name);
}
const ShorthandDefinition* StyleSheetSpecification::GetShorthand(ShorthandId id)
{
return style_sheet_specification_instance->properties.GetShorthand(id);
}
// Parses a property declaration, setting any parsed and validated properties on the given dictionary.
bool StyleSheetSpecification::ParsePropertyDeclaration(PropertyDictionary& dictionary, const String& property_name, const String& property_value)
{
return style_sheet_specification_instance->properties.ParsePropertyDeclaration(dictionary, property_name, property_value);
}
PropertyId StyleSheetSpecification::GetPropertyId(const String& property_name)
{
return style_sheet_specification_instance->properties.property_map->GetId(property_name);
}
ShorthandId StyleSheetSpecification::GetShorthandId(const String& shorthand_name)
{
return style_sheet_specification_instance->properties.shorthand_map->GetId(shorthand_name);
}
const String& StyleSheetSpecification::GetPropertyName(PropertyId id)
{
return style_sheet_specification_instance->properties.property_map->GetName(id);
}
const String& StyleSheetSpecification::GetShorthandName(ShorthandId id)
{
return style_sheet_specification_instance->properties.shorthand_map->GetName(id);
}
PropertyIdSet StyleSheetSpecification::GetShorthandUnderlyingProperties(ShorthandId id)
{
PropertyIdSet result;
const ShorthandDefinition* shorthand = style_sheet_specification_instance->properties.GetShorthand(id);
if (!shorthand)
return result;
for (auto& item : shorthand->items)
{
if (item.type == ShorthandItemType::Property)
{
result.Insert(item.property_id);
}
else if (item.type == ShorthandItemType::Shorthand)
{
// When we have a shorthand pointing to another shorthands, call us recursively. Add the union of the previous result and new properties.
result |= GetShorthandUnderlyingProperties(item.shorthand_id);
}
}
return result;
}
const PropertySpecification& StyleSheetSpecification::GetPropertySpecification()
{
return style_sheet_specification_instance->properties;
}
// Registers RmlUi's default parsers.
void StyleSheetSpecification::RegisterDefaultParsers()
{
RegisterParser("number", &default_parsers->number);
RegisterParser("length", &default_parsers->length);
RegisterParser("length_percent", &default_parsers->length_percent);
RegisterParser("number_length_percent", &default_parsers->number_length_percent);
RegisterParser("angle", &default_parsers->angle);
RegisterParser("keyword", &default_parsers->keyword);
RegisterParser("string", &default_parsers->string);
RegisterParser("animation", &default_parsers->animation);
RegisterParser("transition", &default_parsers->transition);
RegisterParser("color", &default_parsers->color);
RegisterParser("transform", &default_parsers->transform);
}
// Registers RmlUi's default style properties.
void StyleSheetSpecification::RegisterDefaultProperties()
{
/*
Style property specifications (ala RCSS).
Note: Whenever keywords or default values are changed, make sure its computed value is
changed correspondingly, see `ComputedValues.h`.
When adding new properties, it may be desirable to add it to the computed values as well.
Then, make sure to resolve it as appropriate in `ElementStyle.cpp`.
*/
RegisterProperty(PropertyId::MarginTop, "margin-top", "0px", false, true)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::MarginRight, "margin-right", "0px", false, true)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::MarginBottom, "margin-bottom", "0px", false, true)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::MarginLeft, "margin-left", "0px", false, true)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterShorthand(ShorthandId::Margin, "margin", "margin-top, margin-right, margin-bottom, margin-left", ShorthandType::Box);
RegisterProperty(PropertyId::PaddingTop, "padding-top", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::PaddingRight, "padding-right", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::PaddingBottom, "padding-bottom", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::PaddingLeft, "padding-left", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterShorthand(ShorthandId::Padding, "padding", "padding-top, padding-right, padding-bottom, padding-left", ShorthandType::Box);
RegisterProperty(PropertyId::BorderTopWidth, "border-top-width", "0px", false, true).AddParser("length");
RegisterProperty(PropertyId::BorderRightWidth, "border-right-width", "0px", false, true).AddParser("length");
RegisterProperty(PropertyId::BorderBottomWidth, "border-bottom-width", "0px", false, true).AddParser("length");
RegisterProperty(PropertyId::BorderLeftWidth, "border-left-width", "0px", false, true).AddParser("length");
RegisterShorthand(ShorthandId::BorderWidth, "border-width", "border-top-width, border-right-width, border-bottom-width, border-left-width", ShorthandType::Box);
RegisterProperty(PropertyId::BorderTopColor, "border-top-color", "black", false, false).AddParser("color");
RegisterProperty(PropertyId::BorderRightColor, "border-right-color", "black", false, false).AddParser("color");
RegisterProperty(PropertyId::BorderBottomColor, "border-bottom-color", "black", false, false).AddParser("color");
RegisterProperty(PropertyId::BorderLeftColor, "border-left-color", "black", false, false).AddParser("color");
RegisterShorthand(ShorthandId::BorderColor, "border-color", "border-top-color, border-right-color, border-bottom-color, border-left-color", ShorthandType::Box);
RegisterShorthand(ShorthandId::BorderTop, "border-top", "border-top-width, border-top-color", ShorthandType::FallThrough);
RegisterShorthand(ShorthandId::BorderRight, "border-right", "border-right-width, border-right-color", ShorthandType::FallThrough);
RegisterShorthand(ShorthandId::BorderBottom, "border-bottom", "border-bottom-width, border-bottom-color", ShorthandType::FallThrough);
RegisterShorthand(ShorthandId::BorderLeft, "border-left", "border-left-width, border-left-color", ShorthandType::FallThrough);
RegisterShorthand(ShorthandId::Border, "border", "border-top, border-right, border-bottom, border-left", ShorthandType::RecursiveRepeat);
RegisterProperty(PropertyId::BorderTopLeftRadius, "border-top-left-radius", "0px", false, false).AddParser("length");
RegisterProperty(PropertyId::BorderTopRightRadius, "border-top-right-radius", "0px", false, false).AddParser("length");
RegisterProperty(PropertyId::BorderBottomRightRadius, "border-bottom-right-radius", "0px", false, false).AddParser("length");
RegisterProperty(PropertyId::BorderBottomLeftRadius, "border-bottom-left-radius", "0px", false, false).AddParser("length");
RegisterShorthand(ShorthandId::BorderRadius, "border-radius", "border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius", ShorthandType::Box);
RegisterProperty(PropertyId::Display, "display", "inline", false, true).AddParser("keyword", "none, block, inline, inline-block, table, table-row, table-row-group, table-column, table-column-group, table-cell");
RegisterProperty(PropertyId::Position, "position", "static", false, true).AddParser("keyword", "static, relative, absolute, fixed");
RegisterProperty(PropertyId::Top, "top", "auto", false, false)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight);
RegisterProperty(PropertyId::Right, "right", "auto", false, false)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::Bottom, "bottom", "auto", false, false)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight);
RegisterProperty(PropertyId::Left, "left", "auto", false, false)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::Float, "float", "none", false, true).AddParser("keyword", "none, left, right");
RegisterProperty(PropertyId::Clear, "clear", "none", false, true).AddParser("keyword", "none, left, right, both");
RegisterProperty(PropertyId::BoxSizing, "box-sizing", "content-box", false, true).AddParser("keyword", "content-box, border-box");
RegisterProperty(PropertyId::ZIndex, "z-index", "auto", false, false)
.AddParser("keyword", "auto")
.AddParser("number");
RegisterProperty(PropertyId::Width, "width", "auto", false, true)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::MinWidth, "min-width", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::MaxWidth, "max-width", "-1px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockWidth);
RegisterProperty(PropertyId::Height, "height", "auto", false, true)
.AddParser("keyword", "auto")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight);
RegisterProperty(PropertyId::MinHeight, "min-height", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight);
RegisterProperty(PropertyId::MaxHeight, "max-height", "-1px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight);
RegisterProperty(PropertyId::LineHeight, "line-height", "1.2", true, true).AddParser("number_length_percent").SetRelativeTarget(RelativeTarget::FontSize);
RegisterProperty(PropertyId::VerticalAlign, "vertical-align", "baseline", false, true)
.AddParser("keyword", "baseline, middle, sub, super, text-top, text-bottom, top, bottom")
.AddParser("length_percent").SetRelativeTarget(RelativeTarget::LineHeight);
RegisterProperty(PropertyId::OverflowX, "overflow-x", "visible", false, true).AddParser("keyword", "visible, hidden, auto, scroll");
RegisterProperty(PropertyId::OverflowY, "overflow-y", "visible", false, true).AddParser("keyword", "visible, hidden, auto, scroll");
RegisterShorthand(ShorthandId::Overflow, "overflow", "overflow-x, overflow-y", ShorthandType::Replicate);
RegisterProperty(PropertyId::Clip, "clip", "auto", true, false).AddParser("keyword", "auto, none").AddParser("number");
RegisterProperty(PropertyId::Visibility, "visibility", "visible", false, false).AddParser("keyword", "visible, hidden");
// Need some work on this if we are to include images.
RegisterProperty(PropertyId::BackgroundColor, "background-color", "transparent", false, false).AddParser("color");
RegisterShorthand(ShorthandId::Background, "background", "background-color", ShorthandType::FallThrough);
RegisterProperty(PropertyId::Color, "color", "white", true, false).AddParser("color");
RegisterProperty(PropertyId::ImageColor, "image-color", "white", false, false).AddParser("color");
RegisterProperty(PropertyId::Opacity, "opacity", "1", true, false).AddParser("number");
RegisterProperty(PropertyId::FontFamily, "font-family", "", true, true).AddParser("string");
RegisterProperty(PropertyId::FontStyle, "font-style", "normal", true, true).AddParser("keyword", "normal, italic");
RegisterProperty(PropertyId::FontWeight, "font-weight", "normal", true, true).AddParser("keyword", "normal, bold");
RegisterProperty(PropertyId::FontSize, "font-size", "12px", true, true).AddParser("length").AddParser("length_percent").SetRelativeTarget(RelativeTarget::ParentFontSize);
RegisterShorthand(ShorthandId::Font, "font", "font-style, font-weight, font-size, font-family", ShorthandType::FallThrough);
RegisterProperty(PropertyId::TextAlign, "text-align", "left", true, true).AddParser("keyword", "left, right, center, justify");
RegisterProperty(PropertyId::TextDecoration, "text-decoration", "none", true, false).AddParser("keyword", "none, underline, overline, line-through");
RegisterProperty(PropertyId::TextTransform, "text-transform", "none", true, true).AddParser("keyword", "none, capitalize, uppercase, lowercase");
RegisterProperty(PropertyId::WhiteSpace, "white-space", "normal", true, true).AddParser("keyword", "normal, pre, nowrap, pre-wrap, pre-line");
RegisterProperty(PropertyId::WordBreak, "word-break", "normal", true, true).AddParser("keyword", "normal, break-all, break-word");
RegisterProperty(PropertyId::RowGap, "row-gap", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight);
RegisterProperty(PropertyId::ColumnGap, "column-gap", "0px", false, true).AddParser("length_percent").SetRelativeTarget(RelativeTarget::ContainingBlockHeight);
RegisterShorthand(ShorthandId::Gap, "gap", "row-gap, column-gap", ShorthandType::Replicate);
RegisterProperty(PropertyId::Cursor, "cursor", "", true, false).AddParser("string");
// Functional property specifications.
RegisterProperty(PropertyId::Drag, "drag", "none", false, false).AddParser("keyword", "none, drag, drag-drop, block, clone");
RegisterProperty(PropertyId::TabIndex, "tab-index", "none", false, false).AddParser("keyword", "none, auto");
RegisterProperty(PropertyId::Focus, "focus", "auto", true, false).AddParser("keyword", "none, auto");
RegisterProperty(PropertyId::ScrollbarMargin, "scrollbar-margin", "0", false, false).AddParser("length");
RegisterProperty(PropertyId::PointerEvents, "pointer-events", "auto", true, false).AddParser("keyword", "none, auto");
// Perspective and Transform specifications
RegisterProperty(PropertyId::Perspective, "perspective", "none", false, false).AddParser("keyword", "none").AddParser("length");
RegisterProperty(PropertyId::PerspectiveOriginX, "perspective-origin-x", "50%", false, false).AddParser("keyword", "left, center, right").AddParser("length_percent");
RegisterProperty(PropertyId::PerspectiveOriginY, "perspective-origin-y", "50%", false, false).AddParser("keyword", "top, center, bottom").AddParser("length_percent");
RegisterShorthand(ShorthandId::PerspectiveOrigin, "perspective-origin", "perspective-origin-x, perspective-origin-y", ShorthandType::FallThrough);
RegisterProperty(PropertyId::Transform, "transform", "none", false, false).AddParser("transform");
RegisterProperty(PropertyId::TransformOriginX, "transform-origin-x", "50%", false, false).AddParser("keyword", "left, center, right").AddParser("length_percent");
RegisterProperty(PropertyId::TransformOriginY, "transform-origin-y", "50%", false, false).AddParser("keyword", "top, center, bottom").AddParser("length_percent");
RegisterProperty(PropertyId::TransformOriginZ, "transform-origin-z", "0", false, false).AddParser("length");
RegisterShorthand(ShorthandId::TransformOrigin, "transform-origin", "transform-origin-x, transform-origin-y, transform-origin-z", ShorthandType::FallThrough);
RegisterProperty(PropertyId::Transition, "transition", "none", false, false).AddParser("transition");
RegisterProperty(PropertyId::Animation, "animation", "none", false, false).AddParser("animation");
RegisterProperty(PropertyId::Decorator, "decorator", "", false, false).AddParser("string");
RegisterProperty(PropertyId::FontEffect, "font-effect", "", true, false).AddParser("string");
// Rare properties (not added to computed values)
RegisterProperty(PropertyId::FillImage, "fill-image", "", false, false).AddParser("string");
RMLUI_ASSERTMSG(style_sheet_specification_instance->properties.property_map->AssertAllInserted(PropertyId::NumDefinedIds), "Missing specification for one or more Property IDs.");
RMLUI_ASSERTMSG(style_sheet_specification_instance->properties.shorthand_map->AssertAllInserted(ShorthandId::NumDefinedIds), "Missing specification for one or more Shorthand IDs.");
}
} // namespace Rml
|
class Solution {
public:
string getSmallestString(int n, int k) {
string s="";
for(int i=0;i<n;i++)
s+='a';
k=k-n;
for(int i=n-1;i>=0;i--)
{
if(k==0)
break;
else if(k<25)
{
s[i] = (char)('a'+k);
k=0;
}
else{
s[i] = (char)('a'+25);
k = k - 25;
}
}
return s;
}
};
|
/*!
* \file x11/RandR/iRandR_reload.cpp
* \brief \b Classes: \a iRandR
*/
/*
* Copyright (C) 2015 EEnginE project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "uLog.hpp"
#include "iRandR.hpp"
#include <string.h> // memcpy
using namespace e_engine;
using namespace unix_x11;
#define CODE(err) static_cast<int>(lError->err)
#define CHECK_ERROR(func, ret) \
if (lError) { \
eLOG("RandR: ", #func, " returned ", CODE(error_code), " -- ", CODE(major_code), ", ", CODE(minor_code)); \
lNumErrors++; \
free(lError); \
lError = nullptr; \
goto error; \
} \
if (!ret) { \
eLOG(#func, " returned a NULL pointer"); \
lNumErrors++; \
goto error; \
}
#define CLEANUP(P) \
if (P) \
free(P); \
P = nullptr;
bool iRandR::reload(bool _overwriteLatest, bool _overwriteDefaults) {
if (!vIsRandRSupported_B)
return false;
unsigned int lNumErrors = 0;
xcb_generic_error_t * lError = nullptr;
xcb_randr_screen_size_t * lSizes = nullptr;
xcb_randr_get_output_primary_reply_t *lPrimary = nullptr;
xcb_randr_get_crtc_info_reply_t * lCrtcInfo = nullptr;
xcb_randr_get_output_info_reply_t * lOutputInfo = nullptr;
std::vector<internal::_config *> lCFGs;
if (_overwriteLatest)
lCFGs.emplace_back(&vLatestConfig_RandR);
if (_overwriteDefaults)
lCFGs.emplace_back(&vDefaultConfig_RandR);
CLEANUP(vScreenInfo_XCB);
CLEANUP(vScreenResources_XCB);
auto lSICookie = xcb_randr_get_screen_info(vConnection_XCB, vRootWindow_XCB);
auto lSRCoockie = xcb_randr_get_screen_resources(vConnection_XCB, vRootWindow_XCB);
vScreenInfo_XCB = xcb_randr_get_screen_info_reply(vConnection_XCB, lSICookie, &lError);
CHECK_ERROR(xcb_randr_get_screen_info, vScreenInfo_XCB);
vScreenResources_XCB = xcb_randr_get_screen_resources_reply(vConnection_XCB, lSRCoockie, &lError);
CHECK_ERROR(xcb_randr_get_screen_resources, vScreenResources_XCB);
vCRTCs_XCB = xcb_randr_get_screen_resources_crtcs(vScreenResources_XCB);
vOutputs_XCB = xcb_randr_get_screen_resources_outputs(vScreenResources_XCB);
vModes_XCB = xcb_randr_get_screen_resources_modes(vScreenResources_XCB);
lSizes = xcb_randr_get_screen_info_sizes(vScreenInfo_XCB);
if (vScreenInfo_XCB->sizeID < vScreenInfo_XCB->nSizes) {
vScreenWidth_uI = static_cast<uint32_t>(lSizes[vScreenInfo_XCB->sizeID].width);
vScreenHeight_uI = static_cast<uint32_t>(lSizes[vScreenInfo_XCB->sizeID].height);
} else {
wLOG("RandR: Unable to determine screen size: sizeID bigger than number of returned sizes");
vScreenWidth_uI = 0;
vScreenHeight_uI = 0;
}
for (auto *cfg : lCFGs) {
auto lPrimCookie = xcb_randr_get_output_primary(vConnection_XCB, vRootWindow_XCB);
lPrimary = xcb_randr_get_output_primary_reply(vConnection_XCB, lPrimCookie, &lError);
CHECK_ERROR(xcb_randr_get_output_primary, lPrimary);
cfg->primary = lPrimary->output;
CLEANUP(lPrimary);
cfg->gamma.clear();
for (int i = 0; i < vScreenResources_XCB->num_crtcs; ++i) {
auto lGammaCookie = xcb_randr_get_crtc_gamma(vConnection_XCB, vCRTCs_XCB[i]);
auto *lGamma = xcb_randr_get_crtc_gamma_reply(vConnection_XCB, lGammaCookie, &lError);
CHECK_ERROR(xcb_randr_get_crtc_gamma, lGamma);
cfg->gamma.emplace_back(std::make_shared<internal::_gamma>(lGamma->size, vCRTCs_XCB[i]));
memcpy(cfg->gamma.back()->red, xcb_randr_get_crtc_gamma_red(lGamma), lGamma->size);
memcpy(cfg->gamma.back()->green, xcb_randr_get_crtc_gamma_green(lGamma), lGamma->size);
memcpy(cfg->gamma.back()->blue, xcb_randr_get_crtc_gamma_blue(lGamma), lGamma->size);
CLEANUP(lGamma);
}
}
// Clear old data
vCRTC_V_RandR.clear();
vOutput_V_RandR.clear();
vMode_V_RandR.clear();
vLatestConfig_RandR.CRTCInfo.clear();
// CRTC
for (int i = 0; i < vScreenResources_XCB->num_crtcs; ++i) {
internal::_crtc lTempCRTC_RandR;
auto lCrtcCookie = xcb_randr_get_crtc_info(vConnection_XCB, vCRTCs_XCB[i], vScreenInfo_XCB->config_timestamp);
lCrtcInfo = xcb_randr_get_crtc_info_reply(vConnection_XCB, lCrtcCookie, &lError);
CHECK_ERROR(xcb_randr_get_crtc_info, lCrtcInfo);
lTempCRTC_RandR.id = vCRTCs_XCB[i];
lTempCRTC_RandR.timestamp = lCrtcInfo->timestamp;
lTempCRTC_RandR.posX = lCrtcInfo->x;
lTempCRTC_RandR.posY = lCrtcInfo->y;
lTempCRTC_RandR.width = lCrtcInfo->width;
lTempCRTC_RandR.height = lCrtcInfo->height;
lTempCRTC_RandR.mode = lCrtcInfo->mode;
lTempCRTC_RandR.rotation = lCrtcInfo->rotation;
lTempCRTC_RandR.rotations = lCrtcInfo->rotations;
xcb_randr_output_t *lOutputs = xcb_randr_get_crtc_info_outputs(lCrtcInfo);
xcb_randr_output_t *lPossible = xcb_randr_get_crtc_info_possible(lCrtcInfo);
for (uint16_t j = 0; j < lCrtcInfo->num_outputs; ++j) {
lTempCRTC_RandR.outputs.push_back(lOutputs[j]);
}
for (uint16_t j = 0; j < lCrtcInfo->num_possible_outputs; ++j) {
lTempCRTC_RandR.possibleOutputs.push_back(lPossible[j]);
}
vCRTC_V_RandR.push_back(lTempCRTC_RandR);
CLEANUP(lCrtcInfo);
}
// Output
for (int i = 0; i < vScreenResources_XCB->num_outputs; ++i) {
internal::_output lTempOutput_RandR;
auto lOutCookie = xcb_randr_get_output_info(vConnection_XCB, vOutputs_XCB[i], vScreenInfo_XCB->config_timestamp);
lOutputInfo = xcb_randr_get_output_info_reply(vConnection_XCB, lOutCookie, &lError);
CHECK_ERROR(xcb_randr_get_output_info, lOutputInfo);
char *lName = reinterpret_cast<char *>(xcb_randr_get_output_info_name(lOutputInfo));
lTempOutput_RandR.id = vOutputs_XCB[i];
lTempOutput_RandR.timestamp = lOutputInfo->timestamp;
lTempOutput_RandR.crtc = lOutputInfo->crtc;
lTempOutput_RandR.name = std::string(lName, lOutputInfo->name_len);
lTempOutput_RandR.mm_width = lOutputInfo->mm_width;
lTempOutput_RandR.mm_height = lOutputInfo->mm_height;
lTempOutput_RandR.connection = static_cast<xcb_randr_connection_t>(lOutputInfo->connection);
lTempOutput_RandR.subpixel_order = lOutputInfo->subpixel_order;
lTempOutput_RandR.npreferred = lOutputInfo->num_preferred;
xcb_randr_crtc_t * lOutCrtcs = xcb_randr_get_output_info_crtcs(lOutputInfo);
xcb_randr_output_t *lOutColnes = xcb_randr_get_output_info_clones(lOutputInfo);
xcb_randr_mode_t * lOutModes = xcb_randr_get_output_info_modes(lOutputInfo);
for (uint16_t j = 0; j < lOutputInfo->num_crtcs; ++j)
lTempOutput_RandR.crtcs.emplace_back(lOutCrtcs[j]);
for (uint16_t j = 0; j < lOutputInfo->num_clones; ++j)
lTempOutput_RandR.clones.emplace_back(lOutColnes[j]);
for (uint16_t j = 0; j < lOutputInfo->num_modes; ++j)
lTempOutput_RandR.modes.emplace_back(lOutModes[j]);
vOutput_V_RandR.emplace_back(lTempOutput_RandR);
CLEANUP(lOutputInfo);
}
// Modes
for (int i = 0; i < vScreenResources_XCB->num_modes; ++i) {
internal::_mode lTempMode_RandR;
xcb_randr_mode_info_t lTempModeInfo = vModes_XCB[i];
lTempMode_RandR.id = lTempModeInfo.id;
lTempMode_RandR.width = lTempModeInfo.width;
lTempMode_RandR.height = lTempModeInfo.height;
lTempMode_RandR.dotClock = lTempModeInfo.dot_clock;
lTempMode_RandR.hSyncStart = lTempModeInfo.hsync_start;
lTempMode_RandR.hSyncEnd = lTempModeInfo.hsync_end;
lTempMode_RandR.hTotal = lTempModeInfo.htotal;
lTempMode_RandR.hSkew = lTempModeInfo.hskew;
lTempMode_RandR.vSyncStart = lTempModeInfo.vsync_start;
lTempMode_RandR.vSyncEnd = lTempModeInfo.vsync_end;
lTempMode_RandR.vTotal = lTempModeInfo.vtotal;
lTempMode_RandR.modeFlags = lTempModeInfo.mode_flags;
/* v refresh frequency in Hz */
unsigned int lVTotalTemp = lTempMode_RandR.vTotal;
if (lTempMode_RandR.modeFlags & XCB_RANDR_MODE_FLAG_DOUBLE_SCAN)
lVTotalTemp *= 2;
if (lTempMode_RandR.modeFlags & XCB_RANDR_MODE_FLAG_INTERLACE)
lVTotalTemp /= 2;
if (lTempMode_RandR.hTotal && lVTotalTemp)
lTempMode_RandR.refresh = (static_cast<double>(lTempMode_RandR.dotClock) /
(static_cast<double>(lTempMode_RandR.hTotal) * static_cast<double>(lVTotalTemp)));
else
lTempMode_RandR.refresh = 0;
/* h sync frequency in Hz */
if (lTempMode_RandR.hTotal)
lTempMode_RandR.syncFreq = lTempMode_RandR.dotClock / lTempMode_RandR.hTotal;
else
lTempMode_RandR.syncFreq = 0;
vMode_V_RandR.push_back(lTempMode_RandR);
}
vLatestConfig_RandR.CRTCInfo = vCRTC_V_RandR;
if (_overwriteLatest)
vDefaultConfig_RandR.CRTCInfo = vCRTC_V_RandR;
vMode_V_RandR.sort();
return true;
error:
CLEANUP(vScreenInfo_XCB);
CLEANUP(vScreenResources_XCB);
CLEANUP(lPrimary);
CLEANUP(lCrtcInfo);
CLEANUP(lOutputInfo);
return false;
}
// kate: indent-mode cstyle; indent-width 2; replace-tabs on; line-numbers on;
|
#include <Eigen/Dense>
#include <Utils.hpp>
#include "CommonGates.hpp"
#include "FermionOperator.hpp"
#include "ObservableTransform.hpp"
#include "PauliOperator.hpp"
#include "cppmicroservices/BundleActivator.h"
#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/ServiceProperties.h"
#include "qrt.hpp"
#include "xacc.hpp"
#include "xacc_internal_compiler.hpp"
#include "xacc_observable.hpp"
#include "xacc_service.hpp"
#include "qcor_observable.hpp"
using namespace cppmicroservices;
using namespace xacc;
namespace {
class NisqQubitAllocator : public qcor::AncQubitAllocator {
public:
static NisqQubitAllocator *getInstance() {
if (!g_instance) {
g_instance = new NisqQubitAllocator();
}
return g_instance;
}
static NisqQubitAllocator *g_instance;
};
NisqQubitAllocator *NisqQubitAllocator::g_instance = nullptr;
} // namespace
namespace qcor {
template <typename T>
bool ptr_is_a(std::shared_ptr<Observable> ptr) {
return std::dynamic_pointer_cast<T>(ptr) != nullptr;
}
class NISQ : public ::quantum::QuantumRuntime,
// Cloneable for use in qir-qrt ctrl, pow, adj regions.
public xacc::Cloneable<::quantum::QuantumRuntime> {
protected:
bool mark_as_compute = false;
std::shared_ptr<CompositeInstruction> program;
std::shared_ptr<xacc::IRProvider> provider;
void one_qubit_inst(const std::string &name, const qubit &qidx,
std::vector<double> parameters = {}) {
auto inst = provider->createInstruction(
name, std::vector<std::size_t>{qidx.second});
inst->setBufferNames({qidx.first});
for (int i = 0; i < parameters.size(); i++) {
inst->setParameter(i, parameters[i]);
}
if (mark_as_compute) {
inst->attachMetadata({{"__qcor__compute__segment__", true}});
}
program->addInstruction(inst);
}
void two_qubit_inst(const std::string &name, const qubit &qidx1,
const qubit &qidx2, std::vector<double> parameters = {}) {
auto inst = provider->createInstruction(
name, std::vector<std::size_t>{qidx1.second, qidx2.second});
inst->setBufferNames({qidx1.first, qidx2.first});
for (int i = 0; i < parameters.size(); i++) {
inst->setParameter(i, parameters[i]);
}
if (mark_as_compute) {
inst->attachMetadata({{"__qcor__compute__segment__", true}});
}
program->addInstruction(inst);
}
public:
std::shared_ptr<::quantum::QuantumRuntime> clone() override {
return std::make_shared<NISQ>();
}
void initialize(const std::string kernel_name) override {
provider = xacc::getIRProvider("quantum");
program = std::make_shared<CompositeInstruction>(kernel_name);
setGlobalQubitManager(NisqQubitAllocator::getInstance());
}
QubitAllocator *get_anc_qubit_allocator() {
return NisqQubitAllocator::getInstance();
}
void __begin_mark_segment_as_compute() override { mark_as_compute = true; }
void __end_mark_segment_as_compute() override { mark_as_compute = false; }
bool isComputeSection() override { return mark_as_compute; }
void h(const qubit &qidx) override { one_qubit_inst("H", qidx); }
void x(const qubit &qidx) override { one_qubit_inst("X", qidx); }
void y(const qubit &qidx) override { one_qubit_inst("Y", qidx); }
void z(const qubit &qidx) override { one_qubit_inst("Z", qidx); }
void s(const qubit &qidx) override { one_qubit_inst("S", qidx); }
void sdg(const qubit &qidx) override { one_qubit_inst("Sdg", qidx); }
void t(const qubit &qidx) override { one_qubit_inst("T", qidx); }
void tdg(const qubit &qidx) override { one_qubit_inst("Tdg", qidx); }
void rx(const qubit &qidx, const double theta) override {
one_qubit_inst("Rx", qidx, {theta});
}
void ry(const qubit &qidx, const double theta) override {
one_qubit_inst("Ry", qidx, {theta});
}
void rz(const qubit &qidx, const double theta) override {
one_qubit_inst("Rz", qidx, {theta});
}
void u1(const qubit &qidx, const double theta) override {
one_qubit_inst("U1", qidx, {theta});
}
void u3(const qubit &qidx, const double theta, const double phi,
const double lambda) override {
one_qubit_inst("U", qidx, {theta, phi, lambda});
}
void reset(const qubit &qidx) override { one_qubit_inst("Reset", qidx); }
bool mz(const qubit &qidx) override {
one_qubit_inst("Measure", qidx);
return false;
}
void cnot(const qubit &src_idx, const qubit &tgt_idx) override {
two_qubit_inst("CNOT", src_idx, tgt_idx);
}
void cy(const qubit &src_idx, const qubit &tgt_idx) override {
two_qubit_inst("CY", src_idx, tgt_idx);
}
void cz(const qubit &src_idx, const qubit &tgt_idx) override {
two_qubit_inst("CZ", src_idx, tgt_idx);
}
void ch(const qubit &src_idx, const qubit &tgt_idx) override {
two_qubit_inst("CH", src_idx, tgt_idx);
}
void swap(const qubit &src_idx, const qubit &tgt_idx) override {
two_qubit_inst("Swap", src_idx, tgt_idx);
}
void cphase(const qubit &src_idx, const qubit &tgt_idx,
const double theta) override {
two_qubit_inst("CPhase", src_idx, tgt_idx, {theta});
}
void crz(const qubit &src_idx, const qubit &tgt_idx,
const double theta) override {
two_qubit_inst("CRZ", src_idx, tgt_idx, {theta});
}
void general_instruction(std::shared_ptr<xacc::Instruction> inst) override {
std::vector<double> params;
for (auto p : inst->getParameters()) {
params.push_back(p.as<double>());
}
if (inst->bits().size() == 1) {
one_qubit_inst(
inst->name(),
qubit{
inst->getBufferNames().empty() ? "q" : inst->getBufferNames()[0],
inst->bits()[0]},
params);
} else if (inst->bits().size() == 2) {
two_qubit_inst(
inst->name(),
qubit{
inst->getBufferNames().empty() ? "q" : inst->getBufferNames()[0],
inst->bits()[0]},
qubit{
inst->getBufferNames().empty() ? "q" : inst->getBufferNames()[1],
inst->bits()[1]},
params);
} else {
xacc::error(
"Nisq quantum runtime general_instruction can only take 1 and 2 "
"qubit operations.");
}
return;
}
// void exp(qreg q, const double theta, xacc::Observable &H) override {
// exp(q, theta, xacc::as_shared_ptr(&H));
// }
// void exp(qreg q, const double theta, Operator *H) override {
// exp(q, theta, xacc::as_shared_ptr(H));
// }
void exp(qreg q, const double theta, Operator &op) override {
auto Hptr_input =
std::dynamic_pointer_cast<xacc::Observable>(op.get_as_opaque());
auto obs_str = Hptr_input->toString();
auto fermi_to_pauli = xacc::getService<xacc::ObservableTransform>("jw");
std::shared_ptr<xacc::Observable> Hptr;
if (ptr_is_a<xacc::quantum::FermionOperator>(Hptr_input)) {
Hptr = fermi_to_pauli->transform(Hptr_input);
} else if (obs_str.find("^") != std::string::npos) {
auto fermionObservable = xacc::quantum::getObservable("fermion", obs_str);
Hptr = fermi_to_pauli->transform(fermionObservable);
} else if (ptr_is_a<xacc::quantum::PauliOperator>(Hptr_input)) {
Hptr = Hptr_input;
} else if (obs_str.find("X") != std::string::npos ||
obs_str.find("Y") != std::string::npos ||
obs_str.find("Z") != std::string::npos) {
Hptr = xacc::quantum::getObservable("pauli", obs_str);
} else {
xacc::error(
"[qcor::exp()] Error, cannot cast incoming Observable ptr to "
"something we can process.");
}
std::map<std::string, xacc::quantum::Term> terms;
xacc::ScopeTimer timer("timer", false);
// Convert the IR into a Hamiltonian
xacc::quantum::PauliOperator &H =
dynamic_cast<xacc::quantum::PauliOperator &>(*Hptr.get());
terms = H.getTerms();
double pi = xacc::constants::pi;
auto gateRegistry = xacc::getIRProvider("quantum");
std::vector<xacc::InstPtr> exp_insts;
auto q_name = q.name();
for (auto inst : terms) {
auto spinInst = inst.second;
if (spinInst.isIdentity()) {
continue;
}
// Get the individual pauli terms
auto termsMap = std::get<2>(spinInst);
std::vector<std::pair<int, std::string>> terms;
for (auto &kv : termsMap) {
if (kv.second != "I" && !kv.second.empty()) {
terms.push_back({kv.first, kv.second});
}
}
// The largest qubit index is on the last term
int largestQbitIdx = terms[terms.size() - 1].first;
std::vector<std::size_t> qidxs;
std::vector<xacc::InstPtr> basis_front, basis_back;
for (auto &term : terms) {
auto qid = term.first;
auto pop = term.second;
qidxs.push_back(qid);
if (pop == "X") {
basis_front.emplace_back(
std::make_shared<xacc::quantum::Hadamard>(q[qid].second));
basis_back.emplace_back(
std::make_shared<xacc::quantum::Hadamard>(q[qid].second));
basis_front.back()->setBufferNames(
std::vector<std::string>(1, q[qid].first));
basis_back.back()->setBufferNames(
std::vector<std::string>(1, q[qid].first));
} else if (pop == "Y") {
basis_front.emplace_back(
std::make_shared<xacc::quantum::Rx>(q[qid].second, 1.57079362679));
basis_back.emplace_back(
std::make_shared<xacc::quantum::Rx>(q[qid].second,
-1.57079362679));
basis_front.back()->setBufferNames(
std::vector<std::string>(1, q[qid].first));
basis_back.back()->setBufferNames(
std::vector<std::string>(1, q[qid].first));
}
}
// std::cout << "QIDS: " << qidxs << "\n";
Eigen::MatrixXi cnot_pairs(2, qidxs.size() - 1);
for (int i = 0; i < qidxs.size() - 1; i++) {
cnot_pairs(0, i) = qidxs[i];
}
for (int i = 0; i < qidxs.size() - 1; i++) {
cnot_pairs(1, i) = qidxs[i + 1];
}
// std::cout << "HOWDY: \n" << cnot_pairs << "\n";
std::vector<xacc::InstPtr> cnot_front, cnot_back;
for (int i = 0; i < qidxs.size() - 1; i++) {
Eigen::VectorXi pairs = cnot_pairs.col(i);
auto c = pairs(0);
auto t = pairs(1);
cnot_front.emplace_back(std::make_shared<xacc::quantum::CNOT>(q[c].second,
q[t].second));
cnot_front.back()->setBufferNames(std::vector<std::string>{q[c].first,
q[t].first});
}
for (int i = qidxs.size() - 2; i >= 0; i--) {
Eigen::VectorXi pairs = cnot_pairs.col(i);
auto c = pairs(0);
auto t = pairs(1);
cnot_back.emplace_back(std::make_shared<xacc::quantum::CNOT>(q[c].second,
q[t].second));
cnot_back.back()->setBufferNames(std::vector<std::string>{q[c].first,
q[t].first});
}
exp_insts.insert(exp_insts.end(),
std::make_move_iterator(basis_front.begin()),
std::make_move_iterator(basis_front.end()));
exp_insts.insert(exp_insts.end(),
std::make_move_iterator(cnot_front.begin()),
std::make_move_iterator(cnot_front.end()));
// FIXME, we assume real coefficients, if its zero,
// check that the imag part is not zero and use it
if (std::fabs(std::real(spinInst.coeff())) > 1e-12) {
exp_insts.emplace_back(std::make_shared<xacc::quantum::Rz>(
q[qidxs[qidxs.size() - 1]].second, std::real(spinInst.coeff()) *
theta));
exp_insts.back()->setBufferNames(std::vector<std::string>(1,
q[qidxs[qidxs.size() - 1]].first));
} else if (std::fabs(std::imag(spinInst.coeff())) > 1e-12) {
exp_insts.emplace_back(std::make_shared<xacc::quantum::Rz>(
q[qidxs[qidxs.size() - 1]].second, std::imag(spinInst.coeff()) *
theta));
exp_insts.back()->setBufferNames(std::vector<std::string>(1,
q[qidxs[qidxs.size() - 1]].first));
}
exp_insts.insert(exp_insts.end(),
std::make_move_iterator(cnot_back.begin()),
std::make_move_iterator(cnot_back.end()));
exp_insts.insert(exp_insts.end(),
std::make_move_iterator(basis_back.begin()),
std::make_move_iterator(basis_back.end()));
}
program->addInstructions(std::move(exp_insts), false);
}
void submit(xacc::AcceleratorBuffer *buffer) override {
// xacc::internal_compiler::execute_pass_manager();
auto anc_allocator = NisqQubitAllocator::getInstance();
if (anc_allocator->get_buffer() &&
anc_allocator->get_buffer()->size() > 0) {
std::vector<xacc::AcceleratorBuffer *> buffer_list{
buffer, anc_allocator->get_buffer().get()};
submit(buffer_list.data(), buffer_list.size());
} else {
if (__print_final_submission) {
std::cout << "SUBMIT:\n" << program->toString() << "\n";
}
xacc::internal_compiler::execute(
buffer, program->as_xacc());
}
clearProgram();
}
void submit(xacc::AcceleratorBuffer **buffers, const int nBuffers) override {
// What if we get an array of buffers but they
// are all the same pointer
std::set<xacc::AcceleratorBuffer *> ptrs;
for (int i = 0; i < nBuffers; i++) {
ptrs.insert(buffers[i]);
}
// Add the kernel-allocated temporary buffer if necessary:
auto anc_allocator = NisqQubitAllocator::getInstance();
if (anc_allocator->get_buffer() &&
anc_allocator->get_buffer()->size() > 0) {
ptrs.insert(anc_allocator->get_buffer().get());
}
// If size is 1 here, then we only have
// one pointer, like in the case of qubit.results()
if (ptrs.size() == 1) {
submit(buffers[0]);
return;
}
if (__print_final_submission) {
std::cout << "SUBMIT:\n" << program->toString() << "\n";
}
xacc::internal_compiler::execute(
buffers, nBuffers, program->as_xacc());
}
void set_current_program(std::shared_ptr<CompositeInstruction> p) override {
program = p;
}
std::shared_ptr<CompositeInstruction> get_current_program() override {
return program;
}
void clearProgram() {
if (program && provider)
program = std::make_shared<CompositeInstruction>(program->name());
}
void set_current_buffer(xacc::AcceleratorBuffer *buffer) override {
// Nothing to do: the NISQ runtime doesn't keep track of runtime buffer
// info.
}
const std::string name() const override { return "nisq"; }
const std::string description() const override { return ""; }
};
} // namespace qcor
namespace {
/**
*/
class US_ABI_LOCAL NisqQRTActivator : public BundleActivator {
public:
NisqQRTActivator() {}
/**
*/
void Start(BundleContext context) {
auto xt = std::make_shared<qcor::NISQ>();
context.RegisterService<::quantum::QuantumRuntime>(xt);
}
/**
*/
void Stop(BundleContext /*context*/) {}
};
} // namespace
CPPMICROSERVICES_EXPORT_BUNDLE_ACTIVATOR(NisqQRTActivator)
|
/**
\file Neuron.cpp
\brief Implements the neuron class.
**/
#include "StdAfx.h"
#include "Synapse.h"
#include "Neuron.h"
#include "FiringRateModule.h"
namespace FiringRateSim
{
namespace Neurons
{
/**
\brief Default constructor.
\author dcofer
\date 3/29/2011
**/
Neuron::Neuron()
{
m_lpFRModule = NULL;
m_bEnabled = true;
m_aryVn[0]=0.0;
m_aryVn[1]=0.0;
m_aryVth[0] = 0;
m_aryVth[1] = 0;
m_fltCn = (float) 75e-6; //Membrane capacitance
m_fltInvCn = 1/m_fltCn;
m_fltGn = (float) 0.1e-6; //Membrane conductance
m_fltVth = (float) 0; //Firing frequency voltage threshold
m_fltVthi = m_fltVth;
m_fltFmin = (float) 0.25; //Minimum Firing frequency
m_fltGain = (float) 0.1e-3; //Firing frequency gain
m_fltExternalI = 0; //Externally injected current
m_fltIntrinsicI = 0;
m_fltSynapticI = 0;
m_fltAdapterI = 0;
m_fltAdapterMemoryI = 0;
m_fltTotalMemoryI = 0;
m_fltVn = 0;
m_fltFiringFreq = 0;
m_fltVndisp = 0;
m_fltVthdisp = 0;
m_fltVrest = 0;
m_fltVNoiseMax = (float) 0.1e-4; //Max noise is 0.4 mV
m_bUseNoise = true;
m_fltVNoise = 0;
m_fltDCTH = 0;
m_fltAccomTimeMod = 0;
m_fltAccomTimeConst = (float) 100e-3;
m_fltRelativeAccom = 0;
m_bUseAccom = false;
m_fltVthadd = 0;
m_bGainType = true;
m_fltIinit = 0;
m_fltInitTime = 0;
}
/**
\brief Destructor.
\author dcofer
\date 3/29/2011
**/
Neuron::~Neuron()
{
try
{
m_arySynapses.RemoveAll();
}
catch(...)
{Std_TraceMsg(0, "Caught Error in desctructor of Neuron\r\n", "", -1, false, true);}
}
/**
\brief Gets the membrane capacitance.
\author dcofer
\date 3/29/2011
\return membrane capacitance.
**/
float Neuron::Cn()
{return m_fltCn;}
/**
\brief Sets the membrane capacitance.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::Cn(float fltVal)
{
Std_IsAboveMin((float) 0, fltVal, true, "Cn");
m_fltCn=fltVal;
m_fltInvCn = 1/m_fltCn;
}
/**
\brief Gets the membrane conductance.
\author dcofer
\date 3/29/2011
\return membrane conductance.
**/
float Neuron::Gn()
{return m_fltGn;}
/**
\brief Sets the membrane conductance.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::Gn(float fltVal)
{
Std_IsAboveMin((float) 0, fltVal, true, "Cn");
m_fltGn=fltVal;
}
/**
\brief Gets the voltage threshold for firing.
\author dcofer
\date 3/29/2011
\return voltage threshold.
**/
float Neuron::Vth()
{return m_fltVth;}
/**
\brief Sets the voltage threshold for firing.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::Vth(float fltVal)
{
float fltDiff = fltVal - m_fltVrest;
m_fltVthi = fltDiff;
m_fltVth = fltDiff;
m_fltVthdisp = m_fltVrest + m_fltVth;
m_aryVth[0] = fltDiff;
m_aryVth[1] = fltDiff;
m_fltVthadd = fltDiff;
}
/**
\brief Gets the minimum firing frequency.
\author dcofer
\date 3/29/2011
\return minimum firing frequency.
**/
float Neuron::Fmin()
{return m_fltFmin;}
/**
\brief Sets the minimum firing frequency.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::Fmin(float fltVal)
{
Std_IsAboveMin((float) 0, fltVal, true, "Fmin", true);
m_fltFmin=fltVal;
}
/**
\brief Gets the firing frequency gain.
\author dcofer
\date 3/29/2011
\return firing frequency gain.
**/
float Neuron::Gain()
{return m_fltGain;}
/**
\brief Sets the firing frequency gain.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::Gain(float fltVal)
{
Std_IsAboveMin((float) 0, fltVal, true, "Gain");
m_fltGain=fltVal;
}
/**
\brief Gets the external current.
\author dcofer
\date 3/29/2011
\return external current.
**/
float Neuron::ExternalI()
{return m_fltExternalI;}
/**
\brief Sets the external current.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::ExternalI(float fltVal)
{
m_fltExternalI=fltVal;
}
/**
\brief Adds to the external current.
\author dcofer
\date 3/29/2011
\param fltVal The new value to add.
**/
void Neuron::AddExternalI(float fltVal)
{
m_fltExternalI+=fltVal;
}
/**
\brief Gets the rest potential.
\author dcofer
\date 3/29/2011
\return rest potential.
**/
float Neuron::Vrest()
{return m_fltVrest;}
/**
\brief Sets the rest potential.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::Vrest(float fltVal)
{
m_fltVrest = fltVal;
Vth(m_fltVthi);
if(!m_lpSim->SimRunning())
m_fltVndisp = m_fltVrest;
}
/**
\brief Gets the maximum noise voltage.
\author dcofer
\date 3/29/2011
\return maximum noise voltage.
**/
float Neuron::VNoiseMax()
{return m_fltVNoiseMax;}
/**
\brief Gets whether to use noise.
\author dcofer
\date 3/29/2011
\return true if it uses noise, false else.
**/
bool Neuron::UseNoise() {return m_bUseNoise;}
/**
\brief Sets whether to use noise.
\author dcofer
\date 3/29/2011
\param bVal true to use noise.
**/
void Neuron::UseNoise(bool bVal)
{
m_bUseNoise = bVal;
}
/**
\brief Gets whether to use accommodation.
\author dcofer
\date 3/29/2011
\return true to use accommodation, false else.
**/
bool Neuron::UseAccom() {return m_bUseAccom;}
/**
\brief Sets whether to use accommodation.
\author dcofer
\date 3/29/2011
\param bVal true to use accommodation, false else.
**/
void Neuron::UseAccom(bool bVal)
{
m_bUseAccom = bVal;
if(m_bUseAccom && m_lpFRModule)
m_fltDCTH = exp(-m_lpFRModule->TimeStep()/m_fltAccomTimeConst);
else
m_fltDCTH = 0;
}
/**
\brief Sets the maximum noise voltage.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::VNoiseMax(float fltVal)
{
m_fltVNoiseMax = fltVal;
if(m_fltVNoiseMax != 0)
m_bUseNoise = true;
else
m_bUseNoise = false;
}
/**
\brief Gets the relative accomodation.
\author dcofer
\date 3/29/2011
\return relative accomodation.
**/
float Neuron::RelativeAccommodation()
{return m_fltRelativeAccom;}
/**
\brief Sets the relative accomodation.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::RelativeAccommodation(float fltVal)
{
Std_InValidRange((float) 0, (float) 1, fltVal, true, "RelativeAccomodation");
m_fltRelativeAccom = fltVal;
if(m_fltRelativeAccom != 0)
m_bUseAccom = true;
else
m_bUseAccom = false;
if(m_bUseAccom && m_lpFRModule)
m_fltDCTH = exp(-m_lpFRModule->TimeStep()/m_fltAccomTimeConst);
else
m_fltDCTH = 0;
}
/**
\brief Gets the accomodation time constant.
\author dcofer
\date 3/29/2011
\return accomodation time constant.
**/
float Neuron::AccommodationTimeConstant()
{return m_fltAccomTimeConst;}
/**
\brief Sets the accomodation time constant.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::AccommodationTimeConstant(float fltVal)
{
m_fltAccomTimeConst = fltVal;
if(m_bUseAccom && m_lpFRModule)
m_fltDCTH = exp(-m_lpFRModule->TimeStep()/m_fltAccomTimeConst);
else
m_fltDCTH = 0;
}
float Neuron::Iinit() {return m_fltIinit;}
void Neuron::Iinit(float fltVal) {m_fltIinit = fltVal;}
float Neuron::InitTime() {return m_fltInitTime;}
void Neuron::InitTime(float fltVal)
{
Std_InValidRange((float) 0, (float) 10, fltVal, true, "InitTime");
m_fltInitTime = fltVal;
}
/**
\brief Gets the gain type. (Old way or new way)
\author dcofer
\date 3/29/2011
\return true to use new way, false to use old way.
**/
bool Neuron::GainType()
{return m_bGainType;}
/**
\brief Sets the gain type. (Old way or new way)
\author dcofer
\date 3/29/2011
\param bVal true to use new way, false to use old way.
**/
void Neuron::GainType(bool bVal)
{
m_bGainType = bVal;
}
/**
\brief Gets the membrane voltage.
\author dcofer
\date 3/29/2011
\return membrane voltage.
**/
float Neuron::Vn()
{return m_fltVn;}
/**
\brief Calculates the current firing frequency.
\author dcofer
\date 3/29/2011
\param [in,out] m_lpFRModule Pointer to a fast module.
\return firing frequency.
**/
float Neuron::FiringFreq(FiringRateModule *m_lpFRModule)
{
return CalculateFiringFrequency(m_aryVn[m_lpFRModule->ActiveArray()], m_aryVth[m_lpFRModule->ActiveArray()]);
}
/**
\brief Gets the intrinsic current.
\author dcofer
\date 3/29/2011
\return intrinsic current.
**/
float Neuron::IntrinsicCurrent()
{return m_fltIntrinsicI;}
/**
\brief Sets the intrinsic current.
\author dcofer
\date 3/29/2011
\param fltVal The new value.
**/
void Neuron::IntrinsicCurrent(float fltVal)
{m_fltIntrinsicI = fltVal;}
/**
\brief Gets the neuron type.
\author dcofer
\date 3/29/2011
\return neuron type.
**/
unsigned char Neuron::NeuronType()
{return RUGULAR_NEURON;}
void Neuron::Copy(CStdSerialize *lpSource)
{
Node::Copy(lpSource);
Neuron *lpOrig = dynamic_cast<Neuron *>(lpSource);
m_lpFRModule = lpOrig->m_lpFRModule;
m_fltCn = lpOrig->m_fltCn;
m_fltInvCn = lpOrig->m_fltInvCn;
m_fltGn = lpOrig->m_fltGn;
m_fltFmin = lpOrig->m_fltFmin;
m_fltGain = lpOrig->m_fltGain;
m_fltExternalI = lpOrig->m_fltExternalI;
m_fltIntrinsicI = lpOrig->m_fltIntrinsicI;
m_fltSynapticI = lpOrig->m_fltSynapticI;
m_fltAdapterI = lpOrig->m_fltAdapterI;
m_fltAdapterMemoryI = lpOrig->m_fltAdapterMemoryI;
m_fltTotalMemoryI = lpOrig->m_fltTotalMemoryI;
m_fltVNoiseMax = lpOrig->m_fltVNoiseMax;
m_bUseNoise = lpOrig->m_bUseNoise;
m_bGainType = lpOrig->m_bGainType;
m_fltDCTH = lpOrig->m_fltDCTH;
m_fltAccomTimeMod = lpOrig->m_fltAccomTimeMod;
m_fltAccomTimeConst = lpOrig->m_fltAccomTimeConst;
m_fltRelativeAccom = lpOrig->m_fltRelativeAccom;
m_bUseAccom = lpOrig->m_bUseAccom;
m_fltVn = lpOrig->m_fltVn;
m_fltFiringFreq = lpOrig->m_fltFiringFreq;
m_aryVn[0] = lpOrig->m_aryVn[0];
m_aryVn[1] = lpOrig->m_aryVn[1];
m_fltVNoise = lpOrig->m_fltVNoise;
m_fltVth = lpOrig->m_fltVth;
m_fltVthi = lpOrig->m_fltVthi;
m_fltVthadd = lpOrig->m_fltVthadd;
m_aryVth[0] = lpOrig->m_aryVth[0];
m_aryVth[1] = lpOrig->m_aryVth[1];
m_fltVrest = lpOrig->m_fltVrest;
m_fltVndisp = lpOrig->m_fltVndisp;
m_fltIinit = lpOrig->m_fltIinit;
m_fltInitTime = lpOrig->m_fltInitTime;
}
/**
\brief Gets a pointer to the synapses array.
\author dcofer
\date 3/29/2011
\return Pointer to the synapses.
**/
CStdPtrArray<Synapse> *Neuron::GetSynapses()
{return &m_arySynapses;}
void Neuron::AddSynapse(Synapse *lpSynapse)
{
if(!lpSynapse)
THROW_ERROR(Nl_Err_lSynapseToAddNull, Nl_Err_strSynapseToAddNull);
m_arySynapses.Add(lpSynapse);
}
/**
\brief Adds a synapse using an xml packet.
\author dcofer
\date 3/29/2011
\param strXml The xml of the synapse to add.
**/
void Neuron::AddSynapse(std::string strXml, bool bDoNotInit)
{
CStdXml oXml;
oXml.Deserialize(strXml);
oXml.FindElement("Root");
oXml.FindChildElement("Synapse");
Synapse *lpSynapse = LoadSynapse(oXml);
if(!bDoNotInit)
lpSynapse->Initialize();
}
/**
\brief Removes the synapse described by iIndex.
\author dcofer
\date 3/29/2011
\param iIndex Zero-based index of the synapse in the array.
**/
void Neuron::RemoveSynapse(int iIndex)
{
if( iIndex<0 || iIndex>=m_arySynapses.GetSize() )
THROW_ERROR(Std_Err_lInvalidIndex, Std_Err_strInvalidIndex);
m_arySynapses.RemoveAt(iIndex);
}
/**
\brief Removes the synapse by the GUID ID.
\author dcofer
\date 3/29/2011
\param strID GUID ID for the synapse to remove.
\param bThrowError true to throw error if synaspe not found.
**/
void Neuron::RemoveSynapse(std::string strID, bool bThrowError)
{
int iPos = FindSynapseListPos(strID, bThrowError);
m_arySynapses.RemoveAt(iPos);
}
/**
\brief Gets a synapse by its index in the array.
\author dcofer
\date 3/29/2011
\param iIndex Zero-based index of the synaspe to return.
\return null if it fails, else the synapse.
**/
Synapse *Neuron::GetSynapse(int iIndex)
{
if( iIndex<0 || iIndex>=m_arySynapses.GetSize() )
THROW_ERROR(Std_Err_lInvalidIndex, Std_Err_strInvalidIndex);
return m_arySynapses[iIndex];
}
/**
\brief Searches for a synapse with the specified ID and returns its position in the list.
\author dcofer
\date 3/29/2011
\param strID GUID ID of the synapse to find.
\param bThrowError true to throw error if no synapse is found.
\return The found synapse list position.
**/
int Neuron::FindSynapseListPos(std::string strID, bool bThrowError)
{
std::string sID = Std_ToUpper(Std_Trim(strID));
int iCount = m_arySynapses.GetSize();
for(int iIndex=0; iIndex<iCount; iIndex++)
if(m_arySynapses[iIndex]->ID() == sID)
return iIndex;
if(bThrowError)
THROW_TEXT_ERROR(Nl_Err_lSynapseNotFound, Nl_Err_strSynapseNotFound, "ID");
return -1;
}
/**
\brief Gets the total number of synapses.
\author dcofer
\date 3/29/2011
\return The total number of synapses.
**/
int Neuron::TotalSynapses()
{return m_arySynapses.GetSize();}
/**
\brief Clears the synapses list.
\author dcofer
\date 3/29/2011
**/
void Neuron::ClearSynapses()
{m_arySynapses.RemoveAll();}
void Neuron::TimeStepModified()
{
if(m_bUseAccom && m_lpFRModule)
m_fltDCTH = exp(-m_lpFRModule->TimeStep()/m_fltAccomTimeConst);
else
m_fltDCTH = 0;
}
void Neuron::StepSimulation()
{
if(m_bEnabled)
{
////Test code
//int i=5;
//if(m_strID == "742CB5DC-6BFB-4BAB-8CC2-36A4725A33D5")
// i=6;
//Lets get the Summation of synaptic inputs
m_fltSynapticI = CalculateSynapticCurrent(m_lpFRModule);
m_fltIntrinsicI = CalculateIntrinsicCurrent(m_lpFRModule, m_fltExternalI+m_fltSynapticI);
//If we need to apply an init current then do so.
if(m_fltInitTime > 0 && m_lpSim->Time() < m_fltInitTime)
m_fltIntrinsicI += m_fltIinit;
//if(m_fltInitTime > 0 && m_lpSim->Time() >= m_fltInitTime)
// m_fltIntrinsicI = m_fltIntrinsicI; //For testing only comment out!!
if(m_bUseNoise)
m_fltVNoise = Std_FRand(-m_fltVNoiseMax, m_fltVNoiseMax);
//Get the total current being applied to the neuron.
m_fltTotalMemoryI = m_fltSynapticI + m_fltIntrinsicI + m_fltExternalI + m_fltAdapterI;
m_aryVn[m_lpFRModule->InactiveArray()] = m_aryVn[m_lpFRModule->ActiveArray()] + m_fltVNoise +
(m_lpFRModule->TimeStep() * m_fltInvCn *
(m_fltSynapticI + m_fltIntrinsicI + m_fltExternalI + m_fltAdapterI -
(m_aryVn[m_lpFRModule->ActiveArray()]*m_fltGn)));
m_fltVn = m_aryVn[m_lpFRModule->InactiveArray()];
m_fltVndisp = m_fltVrest + m_fltVn;
if(m_bUseAccom)
{
if(m_fltAccomTimeMod != 0 && m_lpFRModule)
m_fltDCTH = exp(-m_lpFRModule->TimeStep()/m_fltAccomTimeMod);
m_fltVthadd = (m_aryVth[m_lpFRModule->ActiveArray()]-m_fltVthi)*m_fltDCTH + m_fltRelativeAccom*m_fltVn*(1-m_fltDCTH);
m_aryVth[m_lpFRModule->InactiveArray()] = m_fltVthi + m_fltVthadd;
}
else
m_aryVth[m_lpFRModule->InactiveArray()] = m_fltVthi;
m_fltVth = m_aryVth[m_lpFRModule->InactiveArray()];
m_fltVthdisp = m_fltVrest + m_fltVth;
m_fltFiringFreq = CalculateFiringFrequency(m_fltVn, m_fltVth);
m_fltAdapterI = 0; //Reset the adapter current for the next cycle.
}
}
/**
\brief Calculates the firing frequency of the neuron.
\author dcofer
\date 3/29/2011
\param fltVn The membrane potential.
\param fltVth The threshold potential.
\return The calculated firing frequency.
**/
float Neuron::CalculateFiringFrequency(float fltVn, float fltVth)
{
float fltFreq;
if(m_bGainType)
{
if(fltVn<fltVth)
fltFreq=0;
else
fltFreq = (m_fltGain*(fltVn-fltVth)) + m_fltFmin;
//Final insurance
if(fltFreq<1e-6) fltFreq = 0;
if(fltFreq>1) fltFreq = 1;
}
else
{
if(fltVn<fltVth)
fltFreq = 0;
else
{
fltFreq = m_fltFmin - m_fltGain * fltVth;
if (fltVn < (1 - fltFreq)/m_fltGain)
fltFreq = (m_fltGain * fltVn) + fltFreq;
else
fltFreq = 1;
}
//Final insurance
if(fltFreq<1e-6) fltFreq = 0;
if(fltFreq>1) fltFreq = 1;
}
return fltFreq;
}
/**
\brief Calculates the intrinsic current.
\author dcofer
\date 3/29/2011
\param [in,out] m_lpFRModule Pointer to the parent FiringRateModule.
\param fltInputCurrent The input current.
\return The calculated intrinsic current.
**/
float Neuron::CalculateIntrinsicCurrent(FiringRateModule *m_lpFRModule, float fltInputCurrent)
{return 0;}
/**
\brief Calculates the total incoming synaptic current.
\author dcofer
\date 3/29/2011
\param [in,out] m_lpFRModule Pointer to the parent FiringRateModule.
\return The calculated synaptic current.
**/
float Neuron::CalculateSynapticCurrent(FiringRateModule *m_lpFRModule)
{
unsigned char iSynapse, iCount;
float fltSynapticI=0;
Synapse *lpSynapse=NULL;
iCount = m_arySynapses.GetSize();
for(iSynapse=0; iSynapse<iCount; iSynapse++)
{
lpSynapse = m_arySynapses[iSynapse];
if(lpSynapse->Enabled() && lpSynapse->FromNeuron())
lpSynapse->Process(fltSynapticI);
}
return fltSynapticI;
}
/**
\brief Injects current into this neuron.
\author dcofer
\date 3/29/2011
\param fltVal The new current to add.
**/
void Neuron::InjectCurrent(float fltVal)
{m_fltExternalI+=fltVal;}
void Neuron::Initialize()
{
Node::Initialize();
if(m_bUseAccom)
m_fltDCTH = exp(-m_lpFRModule->TimeStep()/m_fltAccomTimeConst);
int iCount = m_arySynapses.GetSize();
for(int iIndex=0; iIndex<iCount; iIndex++)
m_arySynapses[iIndex]->Initialize();
}
void Neuron::SetSystemPointers(Simulator *lpSim, Structure *lpStructure, NeuralModule *lpModule, Node *lpNode, bool bVerify)
{
Node::SetSystemPointers(lpSim, lpStructure, lpModule, lpNode, false);
m_lpFRModule = dynamic_cast<FiringRateModule *>(lpModule);
if(bVerify) VerifySystemPointers();
}
void Neuron::VerifySystemPointers()
{
Node::VerifySystemPointers();
if(!m_lpFRModule)
THROW_PARAM_ERROR(Al_Err_lUnableToCastNeuralModuleToDesiredType, Al_Err_strUnableToCastNeuralModuleToDesiredType, "ID: ", m_lpFRModule->ID());
if(!m_lpOrganism)
THROW_PARAM_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Link: ", m_strID);
}
void Neuron::ResetSimulation()
{
AnimatSim::Node::ResetSimulation();
m_fltExternalI = 0;
m_fltIntrinsicI = 0;
m_fltSynapticI = 0;
m_fltAdapterI = 0;
m_fltAdapterMemoryI = 0;
m_fltTotalMemoryI = 0;
m_fltFiringFreq = 0;
m_fltVNoise = 0;
m_aryVn[0]=0;
m_aryVn[1]=0;
m_fltVn = 0;
m_fltVth = m_fltVthi;
m_fltVndisp = m_fltVrest;
m_fltVthdisp = m_fltVrest + m_fltVth;
m_aryVth[0] = m_aryVth[1] = m_fltVth;
m_fltAccomTimeMod = 0;
m_fltVthadd = 0;
int iCount = m_arySynapses.GetSize();
for(int iSynapse=0; iSynapse<iCount; iSynapse++)
m_arySynapses[iSynapse]->ResetSimulation();
}
void Neuron::AddExternalNodeInput(int iTargetDataType, float fltInput)
{
m_fltAdapterI += fltInput;
m_fltAdapterMemoryI = m_fltAdapterI;
}
#pragma region DataAccesMethods
float *Neuron::GetDataPointer(const std::string &strDataType)
{
std::string strType = Std_CheckString(strDataType);
if(strType == "INTRINSICCURRENT")
return &m_fltIntrinsicI;
if(strType == "EXTERNALCURRENT")
return &m_fltExternalI;
if(strType == "SYNAPTICCURRENT")
return &m_fltSynapticI;
if(strType == "ADAPTERCURRENT")
return &m_fltAdapterMemoryI;
if(strType == "TOTALCURRENT")
return &m_fltTotalMemoryI;
if(strType == "MEMBRANEVOLTAGE")
return &m_fltVndisp;
if(strType == "FIRINGFREQUENCY")
return &m_fltFiringFreq;
if(strType == "NOISEVOLTAGE")
return &m_fltVNoise;
if(strType == "THRESHOLD")
return &m_fltVthdisp;
if(strType == "Gm")
return &m_fltGn;
if(strType == "VREST")
return &m_fltVrest;
if(strType == "ACCOMTIMEMOD")
return &m_fltAccomTimeMod;
//If it was not one of those above then we have a problem.
THROW_PARAM_ERROR(Nl_Err_lInvalidNeuronDataType, Nl_Err_strInvalidNeuronDataType, "Neuron Data Type", strDataType);
return NULL;
}
bool Neuron::SetData(const std::string &strDataType, const std::string &strValue, bool bThrowError)
{
std::string strType = Std_CheckString(strDataType);
if(Node::SetData(strDataType, strValue, false))
return true;
if(strType == "CM")
{
Cn(atof(strValue.c_str()));
return true;
}
if(strType == "GM")
{
Gn(atof(strValue.c_str()));
return true;
}
if(strType == "VTH")
{
Vth(atof(strValue.c_str()));
return true;
}
if(strType == "VREST")
{
Vrest(atof(strValue.c_str()));
return true;
}
if(strType == "RELATIVEACCOMMODATION")
{
RelativeAccommodation(atof(strValue.c_str()));
return true;
}
if(strType == "ACCOMMODATIONTIMECONSTANT")
{
AccommodationTimeConstant(atof(strValue.c_str()));
return true;
}
if(strType == "VNOISEMAX")
{
VNoiseMax(atof(strValue.c_str()));
return true;
}
if(strType == "FMIN")
{
Fmin(atof(strValue.c_str()));
return true;
}
if(strType == "GAIN")
{
Gain(atof(strValue.c_str()));
return true;
}
if(strType == "GAINTYPE")
{
GainType(Std_ToBool(strValue));
return true;
}
if(strType == "ADDEXTERNALCURRENT")
{
AddExternalI(atof(strValue.c_str()));
return true;
}
if(strType == "IINIT")
{
Iinit(atof(strValue.c_str()));
return true;
}
if(strType == "INITTIME")
{
InitTime(atof(strValue.c_str()));
return true;
}
//If it was not one of those above then we have a problem.
if(bThrowError)
THROW_PARAM_ERROR(Al_Err_lInvalidDataType, Al_Err_strInvalidDataType, "Data Type", strDataType);
return false;
}
void Neuron::QueryProperties(CStdPtrArray<TypeProperty> &aryProperties)
{
Node::QueryProperties(aryProperties);
aryProperties.Add(new TypeProperty("IntrinsicCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("ExternalCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("SynapticCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("AdapterCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("TotalCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("MembraneVoltage", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("FiringFrequency", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("NoiseVoltage", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("Threshold", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("AccomTimeMod", AnimatPropertyType::Float, AnimatPropertyDirection::Get));
aryProperties.Add(new TypeProperty("Cm", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("Gm", AnimatPropertyType::Float, AnimatPropertyDirection::Both));
aryProperties.Add(new TypeProperty("Vth", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("Vrest", AnimatPropertyType::Float, AnimatPropertyDirection::Both));
aryProperties.Add(new TypeProperty("RelativeAccommodation", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("AccommodationTimeConstant", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("VNoiseMax", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("Fmin", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("Gain", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("GainType", AnimatPropertyType::Boolean, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("AddExternalCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("Iinit", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
aryProperties.Add(new TypeProperty("InitTime", AnimatPropertyType::Float, AnimatPropertyDirection::Set));
}
bool Neuron::AddItem(const std::string &strItemType, const std::string &strXml, bool bThrowError, bool bDoNotInit)
{
std::string strType = Std_CheckString(strItemType);
if(strType == "SYNAPSE")
{
AddSynapse(strXml, bDoNotInit);
return true;
}
//If it was not one of those above then we have a problem.
if(bThrowError)
THROW_PARAM_ERROR(Al_Err_lInvalidItemType, Al_Err_strInvalidItemType, "Item Type", strItemType);
return false;
}
bool Neuron::RemoveItem(const std::string &strItemType, const std::string &strID, bool bThrowError)
{
std::string strType = Std_CheckString(strItemType);
if(strType == "SYNAPSE")
{
RemoveSynapse(strID, bThrowError);
return true;
}
//If it was not one of those above then we have a problem.
if(bThrowError)
THROW_PARAM_ERROR(Al_Err_lInvalidItemType, Al_Err_strInvalidItemType, "Item Type", strItemType);
return false;
}
#pragma endregion
long Neuron::CalculateSnapshotByteSize()
{
//We need bytes for the internal state variables for this neuron.
return (sizeof(m_aryVn) + sizeof(m_fltExternalI) + sizeof(m_fltIntrinsicI) + sizeof(m_fltSynapticI) + sizeof(m_fltVn) + sizeof(m_fltFiringFreq));
}
void Neuron::SaveKeyFrameSnapshot(byte *aryBytes, long &lIndex)
{
memcpy((void *) (aryBytes+lIndex), (void *)m_aryVn, sizeof(m_aryVn));
lIndex += sizeof(m_aryVn);
memcpy((void *) (aryBytes+lIndex), (void *)&m_fltExternalI, sizeof(m_fltExternalI));
lIndex += sizeof(m_fltExternalI);
memcpy((void *) (aryBytes+lIndex), (void *)&m_fltIntrinsicI, sizeof(m_fltIntrinsicI));
lIndex += sizeof(m_fltIntrinsicI);
memcpy((void *) (aryBytes+lIndex), (void *)&m_fltSynapticI, sizeof(m_fltSynapticI));
lIndex += sizeof(m_fltSynapticI);
memcpy((void *) (aryBytes+lIndex), (void *)&m_fltVn, sizeof(m_fltVn));
lIndex += sizeof(m_fltVn);
memcpy((void *) (aryBytes+lIndex), (void *)&m_fltFiringFreq, sizeof(m_fltFiringFreq));
lIndex += sizeof(m_fltFiringFreq);
}
void Neuron::LoadKeyFrameSnapshot(byte *aryBytes, long &lIndex)
{
memcpy((void *)m_aryVn, (void *) (aryBytes+lIndex) , sizeof(m_aryVn));
lIndex += sizeof(m_aryVn);
memcpy((void *)&m_fltExternalI, (void *) (aryBytes+lIndex), sizeof(m_fltExternalI));
lIndex += sizeof(m_fltExternalI);
memcpy((void *)&m_fltIntrinsicI, (void *) (aryBytes+lIndex), sizeof(m_fltIntrinsicI));
lIndex += sizeof(m_fltIntrinsicI);
memcpy((void *)&m_fltSynapticI, (void *) (aryBytes+lIndex), sizeof(m_fltSynapticI));
lIndex += sizeof(m_fltSynapticI);
memcpy((void *)&m_fltVn, (void *) (aryBytes+lIndex), sizeof(m_fltVn));
lIndex += sizeof(m_fltVn);
memcpy((void *)&m_fltFiringFreq, (void *) (aryBytes+lIndex), sizeof(m_fltFiringFreq));
lIndex += sizeof(m_fltFiringFreq);
}
void Neuron::Load(CStdXml &oXml)
{
int iCount, iIndex;
Node::Load(oXml);
oXml.IntoElem(); //Into Neuron Element
m_arySynapses.RemoveAll();
Enabled(oXml.GetChildBool("Enabled", true));
Cn(oXml.GetChildFloat("Cn"));
Gn(oXml.GetChildFloat("Gn"));
Vrest(oXml.GetChildFloat("Vrest", 0));
Vth(oXml.GetChildFloat("Vth"));
Fmin(oXml.GetChildFloat("Fmin"));
Gain(oXml.GetChildFloat("Gain"));
ExternalI(oXml.GetChildFloat("ExternalI"));
VNoiseMax(fabs(oXml.GetChildFloat("VNoiseMax", m_fltVNoiseMax)));
Iinit(oXml.GetChildFloat("Iinit", m_fltIinit));
InitTime(oXml.GetChildFloat("InitTime", m_fltInitTime));
m_fltVndisp = m_fltVrest;
m_fltVthdisp = m_fltVrest + m_fltVth;
GainType(oXml.GetChildBool("GainType", true));
m_aryVth[0] = m_aryVth[1] = m_fltVth;
if(m_fltVNoiseMax != 0)
UseNoise(true);
else
UseNoise(false);
RelativeAccommodation(fabs(oXml.GetChildFloat("RelativeAccom", m_fltRelativeAccom)));
AccommodationTimeConstant(fabs(oXml.GetChildFloat("AccomTimeConst", m_fltAccomTimeConst)));
if(m_fltRelativeAccom != 0)
UseAccom(true);
else
UseAccom(false);
//*** Begin Loading Synapses. *****
if(oXml.FindChildElement("Synapses", false))
{
oXml.IntoElem(); //Into Synapses Element
iCount = oXml.NumberOfChildren();
for(iIndex=0; iIndex<iCount; iIndex++)
{
oXml.FindChildByIndex(iIndex);
LoadSynapse(oXml);
}
oXml.OutOfElem();
}
//*** End Loading Synapses. *****
oXml.OutOfElem(); //OutOf Neuron Element
}
/**
\brief Loads a synapse.
\author dcofer
\date 3/29/2011
\param [in,out] oXml The xml to load.
\return Pointer to the created synapse.
**/
Synapse *Neuron::LoadSynapse(CStdXml &oXml)
{
std::string strType;
Synapse *lpSynapse=NULL;
try
{
oXml.IntoElem(); //Into Synapse Element
strType = oXml.GetChildString("Type");
oXml.OutOfElem(); //OutOf Synapse Element
lpSynapse = dynamic_cast<Synapse *>(m_lpSim->CreateObject(Nl_NeuralModuleName(), "Synapse", strType));
if(!lpSynapse)
THROW_TEXT_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Synapse");
lpSynapse->SetSystemPointers(m_lpSim, m_lpStructure, m_lpFRModule, this, true);
lpSynapse->Load(oXml);
AddSynapse(lpSynapse);
return lpSynapse;
}
catch(CStdErrorInfo oError)
{
if(lpSynapse) delete lpSynapse;
RELAY_ERROR(oError);
return NULL;
}
catch(...)
{
if(lpSynapse) delete lpSynapse;
THROW_ERROR(Std_Err_lUnspecifiedError, Std_Err_strUnspecifiedError);
return NULL;
}
}
} //Neurons
} //FiringRateSim
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include <proton/connection.hpp>
#include <proton/connection_options.hpp>
#include <proton/container.hpp>
#include <proton/default_container.hpp>
#include <proton/messaging_handler.hpp>
#include <proton/thread_safe.hpp>
#include <proton/transport.hpp>
#include <iostream>
using proton::connection_options;
#include "fake_cpp11.hpp"
class handler_2 : public proton::messaging_handler {
void on_connection_open(proton::connection &c) OVERRIDE {
std::cout << "connection events going to handler_2" << std::endl;
std::cout << "connection max_frame_size: " << c.max_frame_size() <<
", idle timeout: " << c.idle_timeout() << std::endl;
c.close();
}
};
class main_handler : public proton::messaging_handler {
private:
std::string url;
handler_2 conn_handler;
public:
main_handler(const std::string& u) : url(u) {}
void on_container_start(proton::container &c) OVERRIDE {
// Connection options for this connection. Merged with and overriding the container's
// client_connection_options() settings.
c.connect(url, connection_options().handler(conn_handler).max_frame_size(2468));
}
void on_connection_open(proton::connection &c) OVERRIDE {
std::cout << "unexpected connection event on main handler" << std::endl;
c.close();
}
};
int main(int argc, char **argv) {
try {
std::string url = argc > 1 ? argv[1] : "127.0.0.1:5672/examples";
main_handler handler(url);
proton::default_container container(handler);
// Global connection options for future connections on container.
container.client_connection_options(connection_options().max_frame_size(12345).idle_timeout(proton::duration(15000)));
container.run();
return 0;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 1;
}
|
/*******************************************************************************
* Copyright 2020 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "test_generator2.h"
class TestPtnGenerator : public TestGenerator {
public:
void setInitialRegValue() {
/* Here modify arrays of inputGenReg, inputPredReg, inputZReg */
// setInputZregAllRandomHex();
}
void setCheckRegFlagAll() {
/* Here modify arrays of checkGenRegMode, checkPredRegMode, checkZRegMode */
}
void genJitTestCode() {
/* Here write JIT code with x86_64 mnemonic function to be tested. */
/* rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, r8, r9, r10, r11, r12,
r13, r14, r15 */
Label L0, L1;
L(L1);
add(rax, 1);
cmp(rax, 10);
jge(L0);
jmp(L1);
L(L0);
}
};
int main(int argc, char *argv[]) {
/* Initializing arrays of inputData, inputGenReg, inputPredReg, inputZReg,
* checkGenRegMode, checkPredRegMode,checkZRegMode */
TestPtnGenerator gen;
/* Set bool output_jit_on_, bool exec_jit_on_ = 0; */
gen.parseArgs(argc, argv);
/* Generate JIT code and get function pointer */
void (*f)();
if (gen.isOutputJitOn()) {
f = (void (*)())gen.gen();
}
/* Dump generated JIT code to a binary file */
gen.dumpJitCode();
/* 1:Execute JIT code, 2:dump all register values, 3:dump register values to
* be checked */
if (gen.isExecJitOn()) {
/* Before executing JIT code, dump inputData, inputGenReg, inputPredReg,
* inputZReg. */
gen.dumpInputReg();
f(); /* Execute JIT code */
gen.dumpOutputReg(); /* Dump all register values */
gen.dumpCheckReg(); /* Dump register values to be checked */
}
return 0;
}
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <ScriptCanvas/Core/Datum.h>
#include <ScriptCanvas/Core/EBusHandler.h>
#include <ScriptCanvas/Core/Graph.h>
#include <ScriptCanvas/Core/Nodeable.h>
#include <ScriptCanvas/Core/NodeableNode.h>
#include <ScriptCanvas/Core/NodeableNodeOverloaded.h>
#include <ScriptCanvas/Core/SubgraphInterfaceUtility.h>
#include <ScriptCanvas/Debugger/ValidationEvents/DataValidation/ScopedDataConnectionEvent.h>
#include <ScriptCanvas/Debugger/ValidationEvents/ParsingValidation/ParsingValidations.h>
#include <ScriptCanvas/Grammar/ParsingMetaData.h>
#include <ScriptCanvas/Libraries/Core/AzEventHandler.h>
#include <ScriptCanvas/Libraries/Core/EBusEventHandler.h>
#include <ScriptCanvas/Libraries/Core/FunctionDefinitionNode.h>
#include <ScriptCanvas/Libraries/Core/ExtractProperty.h>
#include <ScriptCanvas/Libraries/Core/ForEach.h>
#include <ScriptCanvas/Libraries/Core/FunctionCallNode.h>
#include <ScriptCanvas/Libraries/Core/Method.h>
#include <ScriptCanvas/Libraries/Core/Start.h>
#include <ScriptCanvas/Translation/TranslationUtilities.h>
#include <ScriptCanvas/Variable/VariableData.h>
#include "ExecutionTraversalListeners.h"
#include "ParsingUtilities.h"
#include "Primitives.h"
namespace ScriptCanvas
{
namespace Grammar
{
void NodelingInParserIterationListener::CountOnlyGrammarCalls()
{
m_countOnlyGrammarCalls = true;
}
void NodelingInParserIterationListener::EvaluateLeaf(ExecutionTreeConstPtr node, const Slot*, int)
{
bool without = true;
bool addedToOutCall = false;
if (node->GetSymbol() == Symbol::UserOut)
{
m_outCalls.push_back(node);
without = false;
addedToOutCall = true;
}
if (auto nodeling = azrtti_cast<const ScriptCanvas::Nodes::Core::FunctionDefinitionNode*>(node->GetId().m_node))
{
if (!m_countOnlyGrammarCalls && !addedToOutCall)
{
m_outCalls.push_back(node);
}
m_uniqueNodelings.insert(nodeling);
without = false;
}
if (without)
{
m_leavesWithoutNodelings.push_back(node);
}
}
const AZStd::vector<ExecutionTreeConstPtr>& NodelingInParserIterationListener::GetLeavesWithoutNodelings() const
{
return m_leavesWithoutNodelings;
}
const AZStd::unordered_set<const ScriptCanvas::Nodes::Core::FunctionDefinitionNode*>& NodelingInParserIterationListener::GetNodelingsOut() const
{
return m_uniqueNodelings;
}
const AZStd::vector<ExecutionTreeConstPtr>& NodelingInParserIterationListener::GetOutCalls() const
{
return m_outCalls;
}
void NodelingInParserIterationListener::Reset()
{
m_uniqueNodelings.clear();
m_outCalls.clear();
m_leavesWithoutNodelings.clear();
}
void PureFunctionListener::Evaluate(ExecutionTreeConstPtr node, [[maybe_unused]] const Slot* slot, [[maybe_unused]] int level)
{
ParseVariableUse(node, m_usedVariables);
m_isPure = m_isPure
&& Grammar::IsPure(node->GetSymbol())
&& Grammar::IsPure(node->GetId().m_node, node->GetId().m_slot);
}
const VariableUseage& PureFunctionListener::GetUsedVariables() const
{
return m_usedVariables;
}
bool PureFunctionListener::IsPure() const
{
return m_isPure && m_usedVariables.memberVariables.empty();
}
VariableUseage&& PureFunctionListener::MoveUsedVariables()
{
return AZStd::move(m_usedVariables);
}
void UserOutCallCollector::Evaluate(const EndpointResolved& endpoint)
{
if (auto nodeling = IsUserOutNode(endpoint.first))
{
m_outCalls.insert(nodeling);
}
}
const AZStd::unordered_set<const ScriptCanvas::Nodes::Core::FunctionDefinitionNode*>& UserOutCallCollector::GetOutCalls() const
{
return m_outCalls;
}
}
}
|
//===-- TestDWARFCallFrameInfo.cpp ------------------------------*- C++ -*-===//
//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
#include "Plugins/Process/Utility/RegisterContext_x86.h"
#include "Plugins/SymbolFile/Symtab/SymbolFileSymtab.h"
#include "TestingSupport/SubsystemRAII.h"
#include "TestingSupport/TestUtilities.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/Section.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Symbol/DWARFCallFrameInfo.h"
#include "lldb/Utility/StreamString.h"
#include "llvm/Testing/Support/Error.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/raw_ostream.h"
using namespace lldb_private;
using namespace lldb;
class DWARFCallFrameInfoTest : public testing::Test {
SubsystemRAII<FileSystem, HostInfo, ObjectFileELF, SymbolFileSymtab>
subsystems;
protected:
void TestBasic(DWARFCallFrameInfo::Type type, llvm::StringRef symbol);
};
namespace lldb_private {
static std::ostream &operator<<(std::ostream &OS, const UnwindPlan::Row &row) {
StreamString SS;
row.Dump(SS, nullptr, nullptr, 0);
return OS << SS.GetData();
}
} // namespace lldb_private
static UnwindPlan::Row GetExpectedRow0() {
UnwindPlan::Row row;
row.SetOffset(0);
row.GetCFAValue().SetIsRegisterPlusOffset(dwarf_rsp_x86_64, 8);
row.SetRegisterLocationToAtCFAPlusOffset(dwarf_rip_x86_64, -8, false);
return row;
}
static UnwindPlan::Row GetExpectedRow1() {
UnwindPlan::Row row;
row.SetOffset(1);
row.GetCFAValue().SetIsRegisterPlusOffset(dwarf_rsp_x86_64, 16);
row.SetRegisterLocationToAtCFAPlusOffset(dwarf_rip_x86_64, -8, false);
row.SetRegisterLocationToAtCFAPlusOffset(dwarf_rbp_x86_64, -16, false);
return row;
}
static UnwindPlan::Row GetExpectedRow2() {
UnwindPlan::Row row;
row.SetOffset(4);
row.GetCFAValue().SetIsRegisterPlusOffset(dwarf_rbp_x86_64, 16);
row.SetRegisterLocationToAtCFAPlusOffset(dwarf_rip_x86_64, -8, false);
row.SetRegisterLocationToAtCFAPlusOffset(dwarf_rbp_x86_64, -16, false);
return row;
}
void DWARFCallFrameInfoTest::TestBasic(DWARFCallFrameInfo::Type type,
llvm::StringRef symbol) {
auto ExpectedFile = TestFile::fromYaml(R"(
--- !ELF
FileHeader:
Class: ELFCLASS64
Data: ELFDATA2LSB
Type: ET_DYN
Machine: EM_X86_64
Entry: 0x0000000000000260
Sections:
- Name: .text
Type: SHT_PROGBITS
Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
Address: 0x0000000000000260
AddressAlign: 0x0000000000000010
Content: 554889E5897DFC8B45FC5DC30F1F4000554889E5897DFC8B45FC5DC30F1F4000554889E5897DFC8B45FC5DC3
#0000000000000260 <eh_frame>:
# 260: 55 push %rbp
# 261: 48 89 e5 mov %rsp,%rbp
# 264: 89 7d fc mov %edi,-0x4(%rbp)
# 267: 8b 45 fc mov -0x4(%rbp),%eax
# 26a: 5d pop %rbp
# 26b: c3 retq
# 26c: 0f 1f 40 00 nopl 0x0(%rax)
#
#0000000000000270 <debug_frame3>:
# 270: 55 push %rbp
# 271: 48 89 e5 mov %rsp,%rbp
# 274: 89 7d fc mov %edi,-0x4(%rbp)
# 277: 8b 45 fc mov -0x4(%rbp),%eax
# 27a: 5d pop %rbp
# 27b: c3 retq
# 27c: 0f 1f 40 00 nopl 0x0(%rax)
#
#0000000000000280 <debug_frame4>:
# 280: 55 push %rbp
# 281: 48 89 e5 mov %rsp,%rbp
# 284: 89 7d fc mov %edi,-0x4(%rbp)
# 287: 8b 45 fc mov -0x4(%rbp),%eax
# 28a: 5d pop %rbp
# 28b: c3 retq
- Name: .eh_frame
Type: SHT_X86_64_UNWIND
Flags: [ SHF_ALLOC ]
Address: 0x0000000000000290
AddressAlign: 0x0000000000000008
Content: 1400000000000000017A5200017810011B0C0708900100001C0000001C000000B0FFFFFF0C00000000410E108602430D0600000000000000
#00000000 0000000000000014 00000000 CIE
# Version: 1
# Augmentation: "zR"
# Code alignment factor: 1
# Data alignment factor: -8
# Return address column: 16
# Augmentation data: 1b
#
# DW_CFA_def_cfa: r7 (rsp) ofs 8
# DW_CFA_offset: r16 (rip) at cfa-8
# DW_CFA_nop
# DW_CFA_nop
#
#00000018 000000000000001c 0000001c FDE cie=00000000 pc=ffffffffffffffd0..ffffffffffffffdc
# DW_CFA_advance_loc: 1 to ffffffffffffffd1
# DW_CFA_def_cfa_offset: 16
# DW_CFA_offset: r6 (rbp) at cfa-16
# DW_CFA_advance_loc: 3 to ffffffffffffffd4
# DW_CFA_def_cfa_register: r6 (rbp)
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
- Name: .debug_frame
Type: SHT_PROGBITS
AddressAlign: 0x0000000000000008
Content: 14000000FFFFFFFF03000178100C070890010000000000001C0000000000000070020000000000000C00000000000000410E108602430D0614000000FFFFFFFF040008000178100C07089001000000001C0000003800000080020000000000000C00000000000000410E108602430D06
#00000000 0000000000000014 ffffffff CIE
# Version: 3
# Augmentation: ""
# Code alignment factor: 1
# Data alignment factor: -8
# Return address column: 16
#
# DW_CFA_def_cfa: r7 (rsp) ofs 8
# DW_CFA_offset: r16 (rip) at cfa-8
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
#
#00000018 000000000000001c 00000000 FDE cie=00000000 pc=0000000000000270..000000000000027c
# DW_CFA_advance_loc: 1 to 0000000000000271
# DW_CFA_def_cfa_offset: 16
# DW_CFA_offset: r6 (rbp) at cfa-16
# DW_CFA_advance_loc: 3 to 0000000000000274
# DW_CFA_def_cfa_register: r6 (rbp)
#
#00000038 0000000000000014 ffffffff CIE
# Version: 4
# Augmentation: ""
# Pointer Size: 8
# Segment Size: 0
# Code alignment factor: 1
# Data alignment factor: -8
# Return address column: 16
#
# DW_CFA_def_cfa: r7 (rsp) ofs 8
# DW_CFA_offset: r16 (rip) at cfa-8
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
# DW_CFA_nop
#
#00000050 000000000000001c 00000038 FDE cie=00000038 pc=0000000000000280..000000000000028c
# DW_CFA_advance_loc: 1 to 0000000000000281
# DW_CFA_def_cfa_offset: 16
# DW_CFA_offset: r6 (rbp) at cfa-16
# DW_CFA_advance_loc: 3 to 0000000000000284
# DW_CFA_def_cfa_register: r6 (rbp)
Symbols:
- Name: eh_frame
Type: STT_FUNC
Section: .text
Value: 0x0000000000000260
Size: 0x000000000000000C
Binding: STB_GLOBAL
- Name: debug_frame3
Type: STT_FUNC
Section: .text
Value: 0x0000000000000270
Size: 0x000000000000000C
Binding: STB_GLOBAL
- Name: debug_frame4
Type: STT_FUNC
Section: .text
Value: 0x0000000000000280
Size: 0x000000000000000C
Binding: STB_GLOBAL
...
)");
ASSERT_THAT_EXPECTED(ExpectedFile, llvm::Succeeded());
auto module_sp =
std::make_shared<Module>(ModuleSpec(FileSpec(ExpectedFile->name())));
SectionList *list = module_sp->GetSectionList();
ASSERT_NE(nullptr, list);
auto section_sp = list->FindSectionByType(type == DWARFCallFrameInfo::EH
? eSectionTypeEHFrame
: eSectionTypeDWARFDebugFrame,
false);
ASSERT_NE(nullptr, section_sp);
DWARFCallFrameInfo cfi(*module_sp->GetObjectFile(), section_sp, type);
const Symbol *sym = module_sp->FindFirstSymbolWithNameAndType(
ConstString(symbol), eSymbolTypeAny);
ASSERT_NE(nullptr, sym);
UnwindPlan plan(eRegisterKindGeneric);
ASSERT_TRUE(cfi.GetUnwindPlan(sym->GetAddress(), plan));
ASSERT_EQ(3, plan.GetRowCount());
EXPECT_EQ(GetExpectedRow0(), *plan.GetRowAtIndex(0));
EXPECT_EQ(GetExpectedRow1(), *plan.GetRowAtIndex(1));
EXPECT_EQ(GetExpectedRow2(), *plan.GetRowAtIndex(2));
}
TEST_F(DWARFCallFrameInfoTest, Basic_dwarf3) {
TestBasic(DWARFCallFrameInfo::DWARF, "debug_frame3");
}
TEST_F(DWARFCallFrameInfoTest, Basic_dwarf4) {
TestBasic(DWARFCallFrameInfo::DWARF, "debug_frame4");
}
TEST_F(DWARFCallFrameInfoTest, Basic_eh) {
TestBasic(DWARFCallFrameInfo::EH, "eh_frame");
}
|
/*
Copyright 2020 René Ferdinand Rivera Morell
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <sstream>
#include <iostream>
#include <lyra/lyra.hpp>
#include "mini_test.hpp"
int main(int, const char**)
{
using namespace lyra;
bfg::mini_test::scope test;
{
bool show_help = false;
std::string message;
// Ex: <exe> --repeat=10 "Hello world."
auto cli
= lyra::cli()
| help(show_help)
| lyra::arg(message, "++message++").help("**message**");
std::ostringstream help_text;
help_text << cli ;
test
(REQUIRE(help_text.str().find("**message**") != std::string::npos))
(REQUIRE(help_text.str().find("[<++message++>]") != std::string::npos));
}
{
bool show_help = false;
std::string message;
// Ex: <exe> --repeat=10 "Hello world."
auto cli
= lyra::cli()
| help(show_help)
| lyra::arg(message, "++message++").help("**message**").required();
std::ostringstream help_text;
help_text << cli ;
test
(REQUIRE(help_text.str().find("**message**") != std::string::npos))
(REQUIRE(help_text.str().find("[<++message++>]") == std::string::npos))
(REQUIRE(help_text.str().find("++message++") != std::string::npos));
}
return test;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.